@unbrained/pm-cli 2026.9.12 → 2026.9.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +42 -0
- package/dist/cli/command-namespaces.js +1 -1
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/error-guidance.js +1 -1
- package/dist/cli/extension-command-help.d.ts +2 -2
- package/dist/cli/extension-command-help.js +2 -2
- package/dist/cli/main.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +146 -146
- package/dist/cli-bundle/chunks/chunk-33PER336.js +236 -0
- package/dist/cli-bundle/chunks/{chunk-3ZJDGTYC.js → chunk-5JIJAWIF.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-A2Q64TGR.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-YU75JRTW.js → chunk-B6W5LIXK.js} +43 -43
- package/dist/cli-bundle/chunks/{chunk-GKY655T7.js → chunk-BY3ID7QI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7KF6HCRC.js → chunk-D5AJQU7F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7H33WPDF.js → chunk-DBHQIS6Z.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TAGDYARO.js → chunk-GQMILIC5.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2JAY4LFI.js → chunk-NYE6EREL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-67H4PKQ5.js → chunk-O7SRS7Y3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-X6POOZKD.js → chunk-XEV7BHH3.js} +29 -29
- package/dist/cli-bundle/chunks/{chunk-I6VQUHK6.js → chunk-ZYRN2OG3.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-KEZPDR6X.js → register-list-query-B2U36YWL.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-HEXA3ZDM.js → register-mutation-GX42CQYR.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-TEZT65JF.js → register-operations-ZV34KX5E.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-IIL74WUG.js → register-setup-W4OS7IZW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LWJBBM6X.js → chunk-6WZBO4VQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TTRB47KM.js → chunk-7BUJABHB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2BQ4JSJQ.js → chunk-C5NQVXKE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CMCSUANO.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IURELABV.js → chunk-CPQQIVDL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EIXGDI77.js → chunk-D4FQV6TY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YNBACVQ2.js → chunk-ENJH7CBZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KK7KSXUP.js → chunk-FHQLQOUZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PERRTPIY.js → chunk-FNLAQJES.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GGDO6VBT.js +30 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7EKXAUKF.js → chunk-KWP3QTN7.js} +53 -53
- package/dist/cli-bundle/focused-chunks/{chunk-SDQOOL34.js → chunk-LFGTCEHX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5PSYV3AT.js → chunk-N23WTRCC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5CRND7UA.js → chunk-O4EROPO3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-UFSMYVZF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MFVABYEU.js → chunk-ZFNRD7EN.js} +2 -2
- package/dist/cli-bundle/main.js +20 -20
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +28 -28
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +42 -42
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +8 -8
- package/dist/core/output/output.js +3 -3
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/telemetry/consent.d.ts +1 -1
- package/dist/core/telemetry/consent.js +2 -2
- package/dist/core/telemetry/policy.d.ts +10 -0
- package/dist/core/telemetry/policy.js +2 -0
- package/dist/core/telemetry/runtime.d.ts +43 -14
- package/dist/core/telemetry/runtime.js +5 -4
- package/dist/sdk/agent/command-suggestions.d.ts +6 -0
- package/dist/sdk/agent/command-suggestions.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.d.ts +2 -2
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +7 -3
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/completion.js +1 -1
- package/dist/sdk/governance/health.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/telemetry.d.ts +5 -0
- package/dist/sdk/telemetry.js +1 -1
- package/docs/AGENT_UX_CONTRACTS.md +10 -2
- package/docs/CLI_GRAMMAR.md +59 -0
- package/docs/COMMAND_NAMESPACES.md +7 -4
- package/docs/CONFIGURATION.md +48 -3
- package/docs/generated/AGENT_CAPABILITY_ROUTING.md +4 -4
- package/docs/generated/AGENT_COMMAND_SURFACE.md +11 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +12 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +2 -2
- package/marketplace.json +2 -2
- package/package.json +5 -5
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/extensions/guide-shell/index.ts +13 -26
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-DEGRLB6Y.js +0 -235
- package/dist/cli-bundle/chunks/chunk-PTX2JRFR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-BIOWOU6S.js +0 -30
- package/dist/cli-bundle/focused-chunks/chunk-GAKFECOQ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VWMP6W7Y.js +0 -20
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
import{Da as f_,Ea as Vo,Fa as Ho,J as p_,Ja as g_,Oa as h_,Xa as Yo,e as r_,i as Xn,j as __,q as wt,s as Er,t as Tr,ta as Bo,u as ln}from"./chunk-3ZJDGTYC.js";import{A as Hn,Aa as Yn,Ab as T_,B as br,Ba as Wo,Bb as A_,C as Se,E as kr,Ea as y_,H as Sr,I as s_,K as zo,L as o_,N as a_,Ob as C_,Ra as Jn,Ua as un,Wa as mn,Zc as R_,ad as O_,bb as v_,ga as c_,ha as d_,hb as w_,rb as b_,ub as k_,vb as Qn,yb as S_,yc as I_,z as Vn,za as l_,zb as E_,zc as x_}from"./chunk-7KF6HCRC.js";import{$c as il,$d as nn,$j as Q,$k as Ro,$m as cm,$n as Jm,Ac as Yi,Ag as Ol,Am as Fu,An as Om,Ba as yo,Bd as Pe,Bg as Ao,Bi as dr,Bk as au,Bm as $u,Bn as Lm,Cb as Un,Cd as ul,Ci as Kn,Cm as Uu,Cn as Nm,Dd as Rt,Df as bl,Di as zn,Dk as cu,Dm as ju,Dn as Dm,E as Ed,Ea as Pn,El as bu,Em as Gu,En as Mm,F as Td,Fa as De,Fd as nr,Fh as Fl,Fl as ku,Fm as qu,Fn as Pm,Ga as zi,Gd as en,Gi as an,Gk as xo,Gm as Ku,Gn as Fm,H as Ad,Ha as Wi,Hd as _e,Hi as cn,Hl as hr,Hm as zu,Hn as $m,Ia as Nd,Ib as Xd,Id as ir,Ig as Ll,Ii as Gl,Ik as du,Il as Su,Im as Wu,In as jo,J as Cd,Ja as Dd,Jc as el,Jm as Bu,Jn as Um,Ka as Md,Kb as Jd,Kd as So,Km as Vu,Kn as jm,L as Id,La as Pd,Le as vl,Ln as Go,M as Gi,Ma as Fd,Mb as xt,Mg as Nl,Mm as Hu,Mn as Gm,Mo as u_,N as Ct,Na as $d,Nj as Ql,Nm as $o,Nn as qm,O as m,Oa as Ud,Ob as Qd,Oe as Gn,Oi as yt,Om as Yu,On as Km,Oo as m_,Pa as vo,Pe as qn,Pi as ql,Pm as Xu,Pn as zm,Q as p,Qj as Zl,Qm as Ju,Qn as Wm,Rc as M,Rg as Co,Ri as lr,Rj as eu,Rm as Qu,Rn as vt,S as ne,Si as Kl,Sm as Zu,Sn as Bm,T as xd,Th as $l,Ti as ur,Tm as em,Tn as Vm,Ui as mr,Uj as tu,Um as tm,Un as Hm,Vi as _r,Vj as gr,Vm as nm,Vn as Ym,Wc as tl,Wj as nu,Wm as im,Xa as wo,Xc as nl,Xd as rr,Xi as pr,Xm as rm,Xn as Xm,Ya as Fn,Ym as sm,Z as Rd,Za as Ee,Zd as K,Ze as wl,Zm as om,_c as ot,_d as tn,_i as zl,_j as P,_m as am,ab as $,ad as Me,ak as be,al as Oo,an as dm,ao as yr,ba as R,bb as rt,bd as rl,be as sr,bf as To,bg as kl,bj as Wn,bl as Lo,bm as Mo,bn as Uo,bo as Qm,ca as Od,cb as Bi,cd as sl,ce as ml,cf as G,ck as dn,cl as No,cm as Eu,cn as lm,co as vr,da as go,db as Jt,dd as ol,de as _l,df as sn,dk as ke,dn as um,do as Zm,eb as $n,ec as ie,ek as Ot,el as lu,en as mm,eo as qo,f as Be,fa as qi,fb as It,fc as st,fe as pl,ff as on,fk as iu,fm as Tu,fn as _m,gc as Zd,ge as or,gk as Bn,gm as Po,gn as pm,go as e_,h as X,ha as me,hm as Lt,hn as fm,ho as t_,i as Ui,ib as x,id as ht,ih as Dl,ik as ru,il as Do,in as gm,j as Mn,jb as He,jd as Xi,je as ar,jh as Ml,ji as Ul,jk as le,jm as Au,jn as hm,jo as n_,kb as Ye,kd as Ji,ke as se,ki as jl,kn as ym,ko as wr,lb as Te,ld as al,le as Eo,lh as Pl,lk as Io,ll as uu,ln as vm,mb as jd,me as de,mg as Sl,mj as fr,mk as su,mn as wm,n as gt,nb as Gd,ne as rn,ng as El,nl as mu,o as Z,ob as Qt,oe as fl,og as Tl,ol as _u,om as Fo,p as ji,pb as Vi,pd as Qi,pg as Al,pj as Wl,pl as pu,q as W,qa as Ki,qb as qd,qd as Zi,qe as cr,qg as Cl,qj as Bl,ql as fu,qm as Cu,qn as bm,qo as Ko,r as ee,ra as ho,rb as Kd,rd as er,re as gl,rg as Il,rj as Vl,rm as Iu,rn as km,s as Ve,sb as bo,sd as cl,se as hl,sg as Xe,sj as Hl,sm as xu,sn as Sm,t as kd,tb as ko,td as tr,tg as xl,tm as Ru,tn as Em,u as Sd,ub as zd,ud as dl,ul as gu,um as Ou,un as Tm,uo as i_,va as Ld,vb as Wd,vd as J,vj as Yl,vl as hu,vm as Lu,vn as Am,wb as Bd,wd as Zt,wj as I,wk as ou,wl as yu,wm as Nu,wn as Cm,xb as Vd,xd as jn,xf as at,xj as Xl,xl as vu,xm as Du,xn as Im,yb as Hd,yc as Hi,yd as he,ye as yl,yj as Jl,ym as Mu,yn as xm,zb as Yd,zd as ll,zg as Rl,zl as wu,zm as Pu,zn as Rm}from"./chunk-DEGRLB6Y.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 L_(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 zw}from"node:crypto";import Ww 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 D_=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"],Bw=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Vw=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Ar=30,Cr=5e3,M_=4,Hw=50;function dt(e,t){if(!Vw.test(e))throw new N(`${t} must be a stable lowercase id`)}function Yw(e,t){if(!Number.isFinite(e)||e<0)throw new N(`${t} must be a finite non-negative number`)}function ei(e){let t=Bw.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 Jo(e,t){return ie(e)===ie(t)}function P_(e,t){if(t.polarity==="equals")return Jo(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 F_(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=>P_(i.observed,t)===(i.expected==="pass"))}function Xw(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!Jo(e.value,t.value)}function Jw(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 Xw(ei(e),ei(t))||n[t.enforcement]<n[e.enforcement]||i}function Qw(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 Zw(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 eb(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 Qo(e){dt(e.id,"measurement.id"),e.max_cost!==void 0&&Yw(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"&&Qw(i),i.kind==="dependency_kind"&&Zw(i),i.kind==="prose_edge_gap"&&eb(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 Zo(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(!F_(e))throw new N(`assertion ${e.id} negative control does not prove its bound`);return e}function tb(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 $_(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&&tb(e.provider_policy),e}function fn(e){if(e.version!==D_)throw new N(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(Qo(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(Zo(i),t.has(`assertion:${i.id}`))throw new N(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){$_(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 U_(e))if(!n.has(i))throw new N(`${r.join(", ")} references missing measurement ${i}`);return e}function ea(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)ea(n,t)}function U_(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=[];ea(i.source.expression,r);for(let s of r)n(s,`derived measurement ${i.id}`)}return t}function nb(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"&&ea(o.source.expression,n)}return r}function ti(){return{version:D_,measurements:[],assertions:[],gates:[]}}function ib(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 Jo(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function rb(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 sb(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&&rb(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 ob(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 ab(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 Xo(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function cb(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(Xo(o.id,a.id));for(let a of[o.parent,o.blocked_by])typeof a=="string"&&n.add(Xo(o.id,a));for(let a of ob(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 db(e,t){let n=cb(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=Xo(o.holder_id,d);if(n.linked_pairs.has(l)||ab(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 lb(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 ub(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 mb(e,t){let n=e.source;return n.kind==="items"?ib(n,t):n.kind==="dependency_kind"?sb(n,t):n.kind==="prose_edge_gap"?db(n,t):n.kind==="history"?lb(n,t):n.kind==="links"?ub(n,t):null}function j_(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 _b(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 G_(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 q_(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 K_(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 G_(e.operands,M_,o=>q_(o,t,n,i,r));return{value:_b(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 pb(e,t,n,i,r){Qo(e);let s=Date.now(),o,a=[],c=0;if(e.source.kind==="derived"){let u=await q_(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=mb(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=j_([...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:${zw("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 K_(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=pb(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 ta(e,t,n=[e]){return K_(e,t,n,[],{cache:new Map,charged:new Set})}function fb(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 gb(e,t,n={}){Zo(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:fb(t.value,i),verdict:r?"retired":P_(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:F_(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function hb(e,t,n,i){let r=nb(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 N_(e,t,n,i,r){try{return await ta(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 z_(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}`);hb(r,t,n,i.trigger);let s=await G_(r.assertion_ids,M_,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 N_(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 gb(d,await N_(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:j_(s.map(c=>c.cost),Math.max(0,...s.map(c=>c.cost.duration_ms)))}}function Ir(e){return Ww.join(e,"assurance.json")}async function W_(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 yb(e,t){e==="measurement"?Qo(t):e==="assertion"?Zo(t):$_(t)}async function ni(e,t){let n=structuredClone(Rr(await W_(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function na(e,t,n){let i=Rr(await W_(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={}){yb(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&&Jw(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
|
-
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function
|
|
3
|
-
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function
|
|
4
|
-
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function V_(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 H_(e,t={}){let n=t.limit??Hw;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(zn(e),Kn)).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 Y_(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=>Y_(`${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 X_(e,t,n,i={}){return ia(e,Nr(t,n).declarations,i)}async function J_(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 ta(o,i)).value,d=Y_(`${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 Q_(e,t,n={}){return ia(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 Z_(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 np from"node:fs/promises";import{createRequire as vb}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 ep(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 wb(e){return e.includes(`${Oe.sep}.pnpm${Oe.sep}`)?"pnpm":e.includes(`${Oe.sep}node_modules${Oe.sep}`)?"npm":"other"}async function tp(e){try{let t=JSON.parse(await np.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 ra(e){try{return await np.realpath(e)}catch{return Oe.resolve(e)}}async function ip(e,t,n=Ld(import.meta.url,["../../.."])){let i=await ra(t),r=await ra(Oe.join(n,"package.json")),s=await tp(r),o=new Map;s!==void 0&&o.set(r,{version:s,path:ep(r,i),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=vb(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await ra(l),_=await tp(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:ep(u,i),layout:wb(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 bb=Symbol("pm.mcp-mutation-transport"),kb=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 bb in e}function Pr(e,t){return Mr(e)?ll(t):Pe(e,t)}function aa(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 pP(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 ca(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 fP(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 gP(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 Sb=new Set(["tags","blockedBy","blocked_by","skills","fields"]),sp=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"]),Eb=new Set([...sp].filter(e=>e!=="file")),Tb=new Set(["files","files-discover","docs","test","test-all"]),op=new Set(["comments","notes","learnings"]);function Ab(e,t){if(!(!op.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 Cb=new Set(["claim","release","start-task","pause-task","close-task"]),Ib={"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"]},xb=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function ap(e,t=""){let n={},i=Tb.has(t),r=t==="files"||t==="files-discover"||t==="docs",s=op.has(t)?Eb:sp;for(let[o,a]of Object.entries(e)){if(Array.isArray(a)&&Sb.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 Rb(e,t,n){let i=O(e,"author");return i!==void 0?i:n!==void 0&&Cb.has(n)?O(e,"assignee")??O(t,"assignee"):void 0}function Ob(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function hP(e,t){let n=gn(e.options)?e.options:void 0,i=Rd(e.options),r={},s=c=>{i[c]!==void 0||e[c]===void 0||(r[c]=e[c])};for(let c of Ib[t??""]??[])s(c);for(let c of xb)s(c);t!==void 0&&Mr(e)&&Ab(t,i);let o=ap({...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,Ob(o,Rb(e,o,t)))}function yP(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 vP(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 Lb(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 wP(e){return!kb.has(Lb(e))}function bP(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function da(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function kP(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 SP(e,t){let n=Pr(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function oa(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:So(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 sa(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return da(e)}function Dr(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function EP(e){let t=sa(e.kind),n=sa(e.exemptIsolate),i=sa(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 cp(e){let t=m_(e);return e.ids!==void 0&&(t.ids=So(e.ids)),t}function TP(e){return{status:O(e,"filterStatus"),list:gn(e.list)?cp(e.list):oa(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 Nb=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 rp(e){let t={};for(let[n,i]of Object.entries(e))Nb.has(n)||(t[n]=i);return dp(t)}function dp(e){let t=ap(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 u_(t)}function AP(e){if(gn(e.list)||gn(e.update)){let t=gn(e.update)?e.update:rp(e),n=Pr(e,dp(t));return{status:re(e,"filterStatus"),list:gn(e.list)?cp(e.list):oa(e),update:ul(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:oa(e),update:Pr(e,rp(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 up}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 Db="2026-07-15T06:22:12.276Z",Mb=Date.parse(Db),Pb=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],lp=e=>typeof e=="string"?e:"",mp=e=>{let t=e??{},n=lp(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(lp(t.ts))>=Mb);return Pb[i][r]};function _p(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=mp(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 PP=(e,t,n=20,i=new Set)=>_p(e,t,n,i);function pp(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=pp(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=_p(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 Fb(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 $b(e){try{return pp(await ri.readFile(si.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function Ub(e){return(e.item_id===Kn||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function jb(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 mp(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:up("sha256").update(i).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function fp(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=Fb(t.all_actionable===!0?(await oi(e,0,!0)).actionable_events:i),o=await $b(e),a=new Map;for(let _ of s)if(Ub(_)||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(_=>jb(_,o,a.get(_.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=up("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 FP(e,t,n=50){return(await fp(e,t,n)).plan}function Gb(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:qb(e),all_actionable:t}}function qb(e){return e.map(t=>{let n=t.lastIndexOf(":"),i=t.slice(0,n).trim(),r=Number(t.slice(n+1)),s=i===Kn||/^[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 $P(e,t){let n=Gb(da(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Kb(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 Kb(e,t){let n=t.reviewer?.trim()??"",i=t.attributed_author?.trim()??"",r=t.reason?.trim()??"",s=await fp(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 zb}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 Wb="2026-08-09T16:15:18.000Z",hp=Symbol("pre-durable-disposition-eligible");function lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function la(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 gp(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 yp(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 Bb(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&&yp(e.item_path,t)}function vp(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=>gp(o)?[o.field]:[])):new Set;return la(t)&&la(n)&&la(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(gp)&&s.size===r.length&&t.length===s.size&&t.every(o=>s.has(o))}function Vb(e,t){return Bb(e,t)&&vp(e)}function Hb(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&&yp(e.item_path,t)&&vp(e)}function Yb(e){return e[hp]===!0}function wp(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:Vb(i,t),[hp]:Hb(i,t),...typeof e.ts=="string"&&go(e.ts)?{eventTimestamp:e.ts}:{}}])}function bp(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"||!go(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 kp(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=>Yb(o)&&o.eventTimestamp!==void 0&&qi(o.eventTimestamp,Wb)<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:zb("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 Xb(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 Sp(e,t,n){let i=Xb(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 Ep(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}=Sp(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 Tp(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 _=Sp(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 Jb=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 ua(e){if(typeof e!="string")return;let t=e.trim();for(let n of Jb)if(t===n.code||t.startsWith(`${n.code}:`))return n}function ma(e){let t={};for(let n of e){let i=ua(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function Ap(e){return Object.values(ma(e))}import{execFile as Qb}from"node:child_process";import{realpath as Zb}from"node:fs/promises";import Cp from"node:path";import{promisify as ek}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 tk=ek(Qb),nk=32*1024*1024,ik=1e4,rk=["search/eval-queries.json"];function _a(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function sk(e){return`'${e.replaceAll("'","'\\''")}'`}async function ok(e,t=Zb){return t(e).catch(()=>Cp.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 ok(e),i=_a(Cp.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=r_.map(s=>`${i}/${_a(s)}`);try{let{stdout:s}=await tk("git",["ls-files","-z","--",...r.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:nk,windowsHide:!0,timeout:ik}),o=new Set(rk.map(d=>`${i}/${d}`)),a=[...new Set(s.split("\0").filter(d=>d.length>0&&!o.has(_a(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=>sk(`:(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]="205d2dd3-72e4-5ed2-b4c9-cf5000ea8e5f")}catch{}})();var ak=new Set(pu),xp=25,yn=8,Nt=100,ck=Ae.join("runtime","telemetry","events.jsonl"),dk=Ae.join("runtime","telemetry","state.json"),lk=2500,uk=500,Rp=_u-3,mk=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function va(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 wa(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function vn(e){return e.trim().toLowerCase()}function ga(e,t){let n=vn(e),i=vn(t);return n.startsWith("builtin-")?!0:i==="beads"||i==="todos"}async function ba(e){try{return(await ut.stat(e)).isDirectory()}catch{return!1}}async function _k(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 pk(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 fk(e,t,n){let i=Ae.join(e,"history");if(!await ba(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 pk(_,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 ha(e,t){return Ae.relative(e,t).replaceAll("\\","/")}async function Op(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)=>ha(e,r).localeCompare(ha(e,s))),i}function gk(e){return!(typeof e=="object"&&e!==null&&"code"in e&&W(e))}async function hk(e,t,n){let i=await Op(e,t),r=[],s=[],o=[],a=[],c=ht(M());for(let d of i){let l=ha(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:Gd(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 yk(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){gk(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(...wp(g,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...bp(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 Lp(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 vk(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 wk(e,t,n,i,r){let s=await hk(e,t,n),o=await yk(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=kp(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}`),...Lp(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}`]:[],...vk({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,yn)},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 bk(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function kk(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:bk(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Sk(e,t){let n=ne(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Ek(e){let n=ne(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function Tk(e){return ne(e.reason)??ne(e.error)??ne(e.message)}function pa(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 Ak(e){let t=[],n=[],i=[];e.forEach((s,o)=>{let a=Sk(s.definition,o),c=Ek(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:Tk(s.definition)});return}n.push({layer:s.layer,name:s.name,id:a,status:c})}),t.sort(pa),n.sort(pa),i.sort(pa);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 Np(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=>wa(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=f_(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: ${Sd.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 Ck(e,t,n){let i=await h_(He(e)),r=await Hi({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),s=r.loaded.map(k=>kk(k)),o=await ip(r.loaded,He(e)),a=await Yi({...r,loaded:r.loaded}),[c,d]=await Promise.all([Bo(r.roots.project),Bo(r.roots.global)]);await g_(e,a.registrations.migrations);let l=Ak(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=>vn(k.name))),f=new Set(d.state.entries.map(k=>vn(k.name))),g=[...new Map(r.loaded.filter(k=>!(k.layer==="project"?_:f).has(vn(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=>ga(k.name,k.directory)).map(k=>`${k.layer}:${k.name}`).sort((k,b)=>k.localeCompare(b)),v=g.filter(k=>!ga(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=Vo(S),T=Ho(),A=Np(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 Ik(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 xk(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=>xk(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 Rk(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 Ok={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:Rk(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 Dp(e,t){let n=Ok[e.name];return n?n(e.details,t):e.details}function Lk(e){let t=z(e.warnings,yn);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:Dp(n,yn)})),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:yn},generated_at:e.generated_at}}function Ip(e){return e.details.skipped===!0}function Nk(e){let t=z(e.warnings,yn),n=e.checks.filter(Ip).map(i=>i.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(i=>!Ip(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:yn,omitted_checks:n},generated_at:e.generated_at}}function ya(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Ik(e,xp);return{values:n.values,truncated:n.truncated,total:e.length}}function hn(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Dk(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return ak.has(e)?e:null}function Kr(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 Mp(e){let t=0,n=0,i=0,r=0,s=0;for(let o of e.split(`
|
|
5
|
-
`)){let a=o.trim();if(a.length!==0){i+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,s=Math.max(s,d),d>=Rp&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:i,highRetryEntries:r,maxAttempts:s}}function Mk(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Pk(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function Fk(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await Pp(n)}}function $k(e,t,n){let i=[];if(t.invalidRows>0&&i.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return i;let r=n.last_successful_flush_at,s=n.last_failed_flush_at,o=s&&(!r||s>r),a=!r,c=t.validEntries>=uk;return(o||a||c)&&i.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&i.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),i}function Uk(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function jk(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>mu?[`telemetry_schema_version_behind:${t}`]:[]}function Gk(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,i=t.last_otel_success_at,r=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!r&&(!i||r>=i)?[`telemetry_otel_export_failing:${n}`]:[]}function qk(){return{telemetry_disabled:hn("PM_TELEMETRY_DISABLED")||hn("PM_NO_TELEMETRY"),pm_no_telemetry:hn("PM_NO_TELEMETRY"),telemetry_otel_disabled:hn("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:hn("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:Dk()}}function Kk(e,t){return e.telemetry.enabled&&t.validEntries>0}function zk(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Pp(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(lk)});return{probe_url:Kr(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let i of mk){let r=n.headers.get(i)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:Kr(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function Wk(e,t){let n=Ye(process.cwd()),i=Ae.join(n,ck),r=Ae.join(n,dk),s=await ee(i),o=s!==null,a=s?Buffer.byteLength(s,"utf8"):0,c=s?Mp(s):Mk(),d=await ee(r),{runtimeState:l,stateParseFailed:u}=Pk(d),_=e.telemetry.endpoint.trim(),f=Kr(_),g=await Fk(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...$k(e,c,l),...Uk(g),...jk(g),...Gk(e,l));let y=Kk(e,c),v=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:f,global_pm_root:n,queue_path:i,queue_exists:o,queue_entries:c.validEntries,queue_draining:zk(y,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:a,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Rp,queue_max_attempts:c.maxAttempts,runtime_state_path:r,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:v,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:g??{attempted:!1},env_overrides:qk()}},warnings:h}}async function Bk(e){let t;try{t=await Ep(e)}catch(i){let r=i instanceof Error?i.message:String(i);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:r,pm_root:e}},warnings:[`locks_scan_failed:${r}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function Vk(e){let t="metadata",n=e.items,i=await Yn(e.pmRoot,n,{cacheHitVerification:t}),r=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((v,w)=>v.localeCompare(w)),s=[],o=[];if(r.length>0){n=await Ot(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),i=await Yn(e.pmRoot,n),s=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((w,S)=>w.localeCompare(S));let v=new Set(s);o=r.filter(w=>!v.has(w))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:_,workspaceStateMismatches:f,workspaceStateMissing:g,workspaceStateUnreadable:h}=i,y=[...a.map(v=>`history_drift_missing_stream:${v}`),...c.map(v=>`history_drift_unreadable_stream:${v}`),...d.map(v=>`history_drift_hash_mismatch:${v}`),...l.map(v=>`history_drift_chain_mismatch:${v}`),...u.map(v=>`history_drift_version_skew:${v}`),...f.map(v=>`history_drift_workspace_state_mismatch:${v}`),...g.map(v=>`history_drift_workspace_state_missing:${v}`),...h.map(v=>`history_drift_workspace_state_unreadable:${v}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:r.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:r.length>0,reason:r.length>0?"cached_corruption_candidate":null,candidate_items:r,confirmed_items:s,resolved_false_positive_items:o,authoritative_item_source:r.length>0},drifted_items:_,counts:{drifted:_.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:g.length,workspace_state_unreadable:h.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:g,workspace_state_unreadable:h}},warnings:y}}function Hk(e,t){let n=Jl(e),i=su(n.settings),r=ou(n.settings,t),s=i.active?au(i.active.name,i.active.model):null;return{runtimeDefaults:n,providerResolution:i,vectorStoreResolution:r,runtimeEmbeddingIdentity:s,semanticRuntimeAvailable:!!(i.active&&r.active)}}function Yk(){return{refreshed:[],skipped:[],warnings:[]}}async function Xk(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?Yk():du(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function Jk(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&cu(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function Qk(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,i)=>n.localeCompare(i))}function Zk(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Fp(e,t){let n=t.providerResolution.active?.name??null,i=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:Io(n,e.search?.provider??null),vector_store_active:i,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:Io(i,e.vector_store?.adapter??null)}}function eS(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function tS(e,t,n){return e.enabled&&n.length>0&&t}async function nS(e,t,n,i,r){let s=Hk(t,e),o=await xo(e),a=s.semanticRuntimeAvailable?Wo(n,o.entries):[],c=await Xk({pmRoot:e,snapshot:s,refreshPolicy:i,staleBefore:a}),d=await xo(e),l=s.semanticRuntimeAvailable?Wo(n,d.entries):[],u=!s.runtimeDefaults.auto_ollama_defaults_applied,_=Jk({strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:s.runtimeEmbeddingIdentity}),f=Qk({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,embeddingIdentityChanged:_,staleAfter:l}),g=ya(a,r),h=ya(l,r),y=tS(i,s.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:s.semanticRuntimeAvailable,compatibility_mode_auto_defaults:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:s.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:s.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:eS(i),...Fp(t,s),embedding_identity_changed:_,embedding_identity_before:o.embedding??null,embedding_identity_runtime:s.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:r?"full":"summary",stale_items_summary_limit:xp,stale_items_before_total:g.total,stale_items_before:g.values,stale_items_before_truncated:g.truncated,refresh_attempted:y,refresh_skipped_reason:Zk(i,s.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:f}}function iS(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function $p(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new p("--check-only cannot be combined with --refresh-vectors",m.USAGE);if(n&&e.noRefresh===!0)throw new p("--no-refresh cannot be combined with --refresh-vectors",m.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var rS=new Set(["extensions","locks","search"]);function sS(e){let t=new Set(Ad.filter(r=>r.length>0)),n=new Set,i=new Set(Object.values(Cd));for(let r of e.folders)t.has(r)&&!i.has(r)||(t.delete(r),n.add(r));for(let r of rS)t.delete(r),n.add(r);return{requiredDirs:[...t].sort((r,s)=>r.localeCompare(s)),optionalDirs:[...n].sort((r,s)=>r.localeCompare(s)),optionalDirSet:n}}async function oS(e,t,n){let{requiredDirs:i,optionalDirs:r,optionalDirSet:s}=sS(t),o=[],a=[],c=[];for(let d of[...i,...r]){let l=Ae.join(e,d);c.push(...await Me({path:l,scope:"project"})),!await ba(l)&&(s.has(d)?a.push(d):o.push(d))}return{requiredDirs:i,optionalDirs:r,missingRequiredDirs:o,missingOptionalDirs:a,missingDirs:n?[...o,...a]:[...o],hookWarnings:c}}function Up(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,i=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||i)&&e.full!==!0,skipDrift:(e.skipDrift===!0||i)&&e.full!==!0,skipVectors:(e.skipVectors===!0||i)&&e.full!==!0}}async function aS(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?ke(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):Ot(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function fa(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function cS(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function dS(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function lS(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var ka=e=>e.unknown_event_count??0,Sa=e=>e.actionable_unknown_event_count??ka(e);function uS(e,t,n,i,r,s,o){let a=ka(i),c=Sa(i),d=a>0,l=c>0,u=r.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...d?{author_attribution:i}:{},...u?{stale_in_progress:r}:{},...s.length>0?{provenance_resolver_outcomes:s}:{},...o.length>0?{provenance_invalid_values:o}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function jp(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function mS(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function _S(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function pS(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function Gp(e){let t=new Map;for(let[r,s]of Object.entries(e.remediationSources))for(let o of s)t.has(o)||t.set(o,r);let n=new Map(e.checks.map(r=>[r.name,r]));return e.warnings.map(r=>{let s=t.get(r)??"integrity",o=ua(r)?.code??wa(r),a=n.get(s)?.details,d=(typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{})[o],l=va(r,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:r,code:o,check:s,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function fS(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function gS(e){for(let t of e.checks){let n=ma(e.remediationSources[t.name]);fS({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function hS(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],i=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),r=new Map;for(let o of e.pendingMergeReceipts){if(o.evidence_source!=="clone_local")continue;let a=r.get(o.item_id)??[];a.push(o),r.set(o.item_id,a)}let s=[];for(let o of n){if(i.has(o))continue;let a=r.get(o);if(!(!a||a.length===0))try{await v_(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),s.push(o)}catch{}}return[...new Set(s)].sort((o,a)=>o.localeCompare(a))}function yS(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(i=>i.startsWith("history_drift_hash_mismatch:")?!n.has(i.slice(i.indexOf(":")+1)):!0),...t.map(i=>`history_drift_merge_receipt:${i}`)].sort((i,r)=>i.localeCompare(r)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}function qp(e,t,n){let i=e.warning_count??e.warnings.length,r={...e,warning_count:i,warning_limit:Nt,warnings_truncated:i>Nt,warnings:e.warnings.slice(0,Nt),findings:(e.findings??[]).filter(o=>e.warnings.slice(0,Nt).includes(o.warning)||e.failed_because.includes(o.warning))},s=n?Nk(r):t.brief===!0?Lk(r):r;return{...s,warning_count:i,warning_limit:Nt,warnings_truncated:i>s.warnings.length,...s.projection?{projection:{...s.projection,warning_count:i,warnings_truncated:i>s.warnings.length}}:{}}}async function Kp(e,t={}){let n=x(process.cwd(),e.path);await P(n);let i=Te(n),{settings:r,warnings:s}=await Yl(n),o=[...new Set(s)],a=$(r,M()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=$p(t),_=await oS(n,a,c),f=iS(r),g=await Wk(r,{checkTelemetry:t.checkTelemetry===!0}),h=await Ck(n,r,!!e.noExtensions),y=Up(t),v=[],w=await aS({pmRoot:n,settings:r,typeRegistry:a,skipPolicy:y,itemReadWarnings:v}),S=w,E=$r(K(r.schema),w),T=[...f,...Ur(E)],A=y.skipDrift?{warnings:[]}:await dr({pmRoot:n,settings:r,itemIds:w.map(ce=>ce.id),commandLabel:"health"}),k=await fk(n,r.history.compact_policy,await _k(n)),b=await oi(n,20,t.verboseAuthorEvents===!0),L=Sa(b),q=L>0?[`history_unknown_author_events:${L}`]:[],F=jp(await lu(n,w,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),C=await y_(n),B=C.outcomes,we=C.invalid_values,ue=C.warnings,fe=await Bk(n),Le=y.skipIntegrity&&!l?{...fa("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await wk(n,a.type_to_folder,r.schema,l,w),Ke=y.skipDrift?fa("history_drift"):await Vk({pmRoot:n,items:S,settings:r,typeRegistry:a,itemReadWarnings:v}),ft=[...new Set(v)],it=await hS({gitWorkspaceRoot:Le.gitWorkspaceRoot,pendingMergeReceipts:Le.pendingMergeReceipts,historyDriftCheck:Ke,global:e});yS(Ke,it);let Ht=y.skipVectors?fa("vectorization"):await nS(n,r,S,u,t.verboseStaleItems===!0),ae=[cS(i,r,o),dS(_,c),lS(T,E),g.check,h.check,uS(w,r,k,b,F.scan,B,we),fe.check,Le.check,Ke.check,Ht.check],Ne=mS({directoryState:_,normalizedSettingsReadWarnings:o,settingWarnings:T,normalizedItemReadWarnings:ft,telemetryCheck:g,extensionCheck:h,historyPolicyWarnings:A.warnings,historySummary:k,authorAttributionWarnings:q,staleInProgressWarnings:F.warnings,provenanceWarnings:ue,locksCheck:fe,integrityCheck:Le,historyDriftCheck:Ke,vectorizationCheck:Ht}),Yt=pS({directoryState:_,normalizedSettingsReadWarnings:o,settingWarnings:T,normalizedItemReadWarnings:ft,telemetryCheck:g,extensionCheck:h,historyPolicyWarnings:A.warnings,historySummary:k,authorAttributionWarnings:q,staleInProgressWarnings:F.warnings,provenanceWarnings:ue,locksCheck:fe,integrityCheck:Le,historyDriftCheck:Ke,vectorizationCheck:Ht});gS({checks:ae,remediationSources:Yt,historyDriftedCount:_S(Ke),overThresholdCount:k.over_threshold.length});let D=Ne.filter(ce=>!va(ce,l)),ge=Gp({warnings:Ne,checks:ae,remediationSources:Yt,requireMergeDrivers:l}),je=new Set(ge.filter(ce=>ce.severity==="gate_failing").map(ce=>ce.check)),Xt=new Set(ge.map(ce=>ce.check));for(let ce of ae)ce.ok=!je.has(ce.name),Xt.has(ce.name)&&(ce.status="warn");let ze={ok:D.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&D.length>0?m.GENERIC_FAILURE:0},checks:ae,warnings:Ne,findings:ge,failed_because:D,generated_at:R()};return qp(ze,t,y.summaryMode)}var QF={buildHierarchyIntegrityWarnings:Lp,buildExtensionHealthTriageSummary:Np,buildHealthFindings:Gp,buildCapabilityContractMetadata:Ho,buildStaleInProgressHealthSummary:jp,buildVectorizationProviderDetails:Fp,collectUnknownCapabilityGuidance:Vo,isAdvisoryHealthWarning:va,isDirectory:ba,isExpectedUnmanagedExtension:ga,listItemDocumentPaths:Op,normalizeEndpointForDisplay:Kr,normalizeExtensionNameForMatch:vn,parseTelemetryQueue:Mp,probeTelemetryEndpointHealth:Pp,projectHealthResult:qp,resolveActionableUnknownAuthorEventCount:Sa,resolveHealthSkipPolicy:Up,resolveUnknownAuthorEventCount:ka,resolveVectorRefreshPolicy:$p,selectStaleItemDetail:ya,summarizeHealthCheckDetails:Dp,summarizeExtensionList:qr,summarizeRecordList:Qe,summarizeStringList:z,telemetryEnvFlagEnabled:hn,warningCode:wa};(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]="e2cd8850-491a-505c-8709-3dcdb758de75")}catch{}})();function vS(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function zp(e){return`${e.item_id} ${e.link_kind}`}function Wp(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=vS(r.classification,i.classification),r.owners.set(zp(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[zp(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(s=>{let o=t(s.item_id);return{id:s.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:s.link_kind}}).sort((s,o)=>{let a=s.id.localeCompare(o.id);return a!==0?a:s.field.localeCompare(o.field)})}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ccb0d064-940b-5e14-ae63-2803aced4ee7")}catch{}})();function Bp(e,t,n,i,r=40){let s=r===1/0?1/0:Number.isFinite(r)?Math.max(0,Math.floor(r)):40,o=new Map(t.map(d=>[d.path,d])),a={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=Wp(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let g=se(f.status,i)??f.status;i.terminal_statuses.has(g)?(u.push(f),g===i.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):l.push(f)}a.missing_linked_links_count+=d.items.length,a.active_missing_linked_links_count+=l.length,a.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(a.active_missing_linked_paths_count+=1);let _=o.get(d.path);return{...d,candidates:_?.candidates??[],candidates_truncated:_?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,s),items_truncated:d.items.length>s}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),a.missing_linked_path_rows_count=c.length,a.missing_linked_path_rows=c.slice(0,s),a.missing_linked_path_rows_truncated=c.length>s,a}import wn from"node:fs/promises";import bn 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]="9bcae2f2-3739-5ef8-b080-daaaf7df2681")}catch{}})();async function wS(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let s;try{s=await wn.readdir(bn.join(e,r))}catch{return}for(let o of s)for(let a of It)if(o.toLowerCase().endsWith(a)){i.push({relativePath:`${r}/${o}`,id:o.slice(0,-a.length)});break}})),i.sort((r,s)=>r.relativePath.localeCompare(s.relativePath))}function bS(e,t){let{id:n,relativePath:i,liveItemIds:r,out:s}=e,o=rn(t);if(o){s.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=kS(e,t);a!==null&&(a.op==="delete"&&r.has(n)&&s.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(s.repairReconciliations+=1))}function kS(e,t){let{id:n,relativePath:i,out:r}=e,s=null,o=!1,a=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of a){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");s=d}catch{return r.unparseable.push({id:n,path:i,line:c.number,detail:"history line is not a valid JSON object"}),null}if(s.op==="create"){if(o)return r.unparseable.push({id:n,path:i,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return s}function Ea(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function SS(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await wn.readdir(bn.join(e,"history"))}catch{return n}for(let r of i.sort((s,o)=>s.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await wn.readFile(bn.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Ea("history stream",o)});continue}bS({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},s)}return n}function Vp(e){let t=rn(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function ES(e){let t=[],n=0,i=null;try{i=await ee(Te(e))}catch(s){n+=1,t.push({path:"settings.json",detail:Ea("configuration file",s)})}if(i!==null){n+=1;let s=Vp(i);s!==null&&t.push({path:"settings.json",detail:s})}let r;try{r=await wn.readdir(bn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of r.sort((o,a)=>o.localeCompare(a))){if(!s.endsWith(".json"))continue;n+=1;let o;try{o=await wn.readFile(bn.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:Ea("configuration file",c)});continue}let a=Vp(o);a!==null&&t.push({path:`schema/${s}`,detail:a})}return{scanned:n,unparseable:t}}async function Hp(e,t,n,i={}){let r=await wS(e,n),s=new Set(r.map(u=>u.id)),o=new Map;for(let u of r){let _=o.get(u.id);_===void 0?o.set(u.id,[u.relativePath]):_.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,_])=>({id:u,paths:[..._].sort((f,g)=>f.localeCompare(g))})).sort((u,_)=>u.id.localeCompare(_.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let _=bn.join(e,u.relativePath);return cr(await wn.readFile(_,"utf8"),{format:_.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await SS(e,s),l=await ES(e);return{item_files_on_disk:r.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import AS from"node:fs/promises";import $e from"node:path";import CS from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var TS=/^[a-z][a-z0-9+.-]+:\/\//i;function ci(e){return TS.test(e.trim())}(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]="02743545-3a44-565d-932c-7fe736d17eb8")}catch{}})();var IS=["path","scope","note"],xS=["pattern","glob","path","scope","note"],RS=["path"],OS=["from","to"],LS=new Set(["note","scope"]);function Xp(e){let t=e??"project";if(!De.includes(t))throw new p(`Invalid scope "${e}". Valid scopes: ${De.join(", ")} (default: project).`,m.USAGE);return t}function Ta(e){if(e.startsWith("```")||e.includes(`
|
|
6
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),i=n.indexOf("=");return i>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(r=>r>=0&&r<i))?!1:n.includes("=")||Zt(e)}function
|
|
7
|
-
`)){let i=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];i&&t.set(i,(t.get(i)??0)+1)}return t}function HS(e){let t=e.split("\0"),n=new Map;for(let i=0;i+1<t.length;i+=2){let r=t[i]?.trim();if(!r)continue;let s=[...new Set(t[i+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,a)=>o.localeCompare(a));n.set(r,s)}return n}async function YS(e){let t=Qp.relative(e.workspaceRoot,Qp.resolve(e.workspaceRoot,e.sourcePath)),n=await Zp(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),i=await Zp(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:VS(n),commitItems:HS(i),available:!0}}function XS(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,i;for(let r of e.graph.incidentEdges(t)){let s=r.source===t,o=s?r.target:r.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let a=e.graph.registry().require(r.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,s?r.kind:a.inverse??r.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(i=n,e.found.push(c)):e.queue.push(c)}return i}function JS(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),i=[],r;for(;t.length>0;){let s=t.shift(),o=s.kinds.length;r!==void 0&&o>=r||o>=e.maxDepth||(r=XS({current:s,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:i})??r)}return i.sort((s,o)=>s.nodes.join("\0").localeCompare(o.nodes.join("\0"))),i}function QS(e,t,n){let i=a_(t);if(!i.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let r=JS({itemId:e,maxDepth:n,graph:i.graph,details:new Map(i.details.map(a=>[a.id,a]))}),s=r[0];if(!s)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(r.map(a=>a.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:s.nodes,kinds:s.kinds,alternative_decision_ids:o.slice(1)}}async function ZS(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await YS({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function eE(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function tE(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function tf(e){ef(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await ZS(e),i=tE(n),r=new Map;for(let s of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(s.item.id)),a=o.reduce((l,[,u])=>l+u,0),c=QS(s.item.id,e.corpus,t),d=eE({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});r.set(s.item.id,{score:a*100+s.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(s.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...s.files.map(l=>({kind:"linked_file",reference:l.path})),...o.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:s.item.value?.trim()||null,why_now:s.item.why_now?.trim()||null,outcome:s.item.outcome?.trim()||null,objective:s.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:r,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:i.length,unmapped_commit_count:n.commitLines.size-i.length,decision_depth:t}}}import nf from"node:fs/promises";import Ue 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]="573da024-c791-5ff2-b3ee-3529804bab43")}catch{}})();var nE=32768;function xa(e){return mt(Ue.normalize(e))}async function Br(e){try{return await nf.realpath(e)}catch{return Ue.resolve(e)}}function kn(e,t){let n=Ue.isAbsolute(e.path)?Ue.resolve(e.path):Ue.resolve(t,e.path);return`${xa(n)}::${e.scope}`}function Vr(e,t,n){if(typeof e=="string"){let i=e.trim();i.length>0&&n.push({field:t,value:i});return}if(Array.isArray(e)){e.forEach((i,r)=>Vr(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))Vr(r,t?`${t}.${i}`:i,n)}function iE(e){let t=[];return Vr(e.metadata,"metadata",t),Vr(e.body,"body",t),t}function rE(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function sE(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,i=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let r of e){let s=new Set,o=r.value.slice(0,nE);for(let[a,c]of[[n,r.value],[i,o]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=rE(d[0]);!l||s.has(l)||(s.add(l),t.push({field:r.field,value:l}))}}}return t}async function oE(e,t,n=t){let i=Ue.isAbsolute(e)?Ue.resolve(e):Ue.resolve(n,e),r;try{r=await nf.stat(i)}catch{return}if(!r.isFile())return;let[s,o]=await Promise.all([Br(t),Br(i)]);if(ho(s,o)){let a=Ue.relative(s,o);return!a||a.startsWith("..")||Ue.isAbsolute(a)?void 0:{path:xa(a),scope:"project"}}return{path:xa(i),scope:"global"}}async function aE(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>kn(c,t))),r=new Map,s=sE(iE(e)),o=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{o.set(c,await oE(c,t,n))}));let a=s.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=kn(d,t),u=r.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,r.set(l,u)}return[...r.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:i.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function rf(e,t,n){let i=await zr(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Wr(i,"files")}async function cE(e,t){let n=await Br(t),i=await Promise.all(e.map(async s=>{let o=s.trim();if(!o)throw new p("Files lookup paths must not be empty.",m.USAGE);if(!Ue.isAbsolute(o))return mt(o);let a=await Br(o);return ho(n,a)?mt(Ue.relative(n,a)):mt(a)})),r=[...new Set(i)].sort((s,o)=>s.localeCompare(o));if(r.length===0)throw new p("Files lookup requires at least one path.",m.USAGE);return r}function dE(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new p(`Files lookup ${i} must be a non-negative integer.`,m.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function sf(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function of(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let i=t.item.updated_at.localeCompare(e.item.updated_at);return i===0?e.item.id.localeCompare(t.item.id):i}function lE(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(mt(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,i)=>{let r=n.path.localeCompare(i.path);return r===0?n.scope.localeCompare(i.scope):r})})).filter(t=>t.files.length>0).sort(of)}async function uE(e){if(e.explain)return tf({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function mE(e){if([e.strictRead,e.noTruncate,e.explain,rl()].includes(!0))return null;let t=await gr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Zl({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function _E(e){let t=[],n=await dn(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),i=lE({metadata:n,paths:e.paths,scope:e.scope}),r=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&r.length>0)throw new p(`Files lookup could not read every item: ${r.join("; ")}`,m.GENERIC_FAILURE);let s=await uE({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:i,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(s?[...i].sort((c,d)=>{let l=s.explanations.get(d.item.id).score-s.explanations.get(c.item.id).score;return l!==0?l:of(c,d)}):i).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<i.length,truncated:e.offset+a.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:sf(c.item),files:c.files,...s?{traceability:s.explanations.get(c.item.id)}:{}})),...s?{traceability_receipt:s.receipt}:{}}}async function Z$(e,t){let n=x(process.cwd(),t.path),i=He(n);await P(n);let r=await cE(e.paths,i);if(e.lineRange&&r.length!==1)throw new p("Files lookup line attribution requires exactly one source path.",m.USAGE);let s=await I(n),o=$(s,M()),{offset:a,limit:c}=dE(e),d=await mE({pmRoot:n,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:r,total:d.total,count:d.matches.length,offset:a,limit:c,has_more:a+d.matches.length<d.total,truncated:a+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:sf(l.item),files:l.files}))}:_E({pmRoot:n,settings:s,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:i,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function eU(e,t,n){let i=x(process.cwd(),n.path),r=He(i);await P(i);let s=await I(i),o=$(s,M()),a=await Q(i,e,s.id_prefix,s.item_format,o.type_to_folder);if(!a)throw new p(`Item ${e} not found`,m.NOT_FOUND);let c=await be(a,{schema:s.schema}),d=await aE(c.document,r,process.cwd()),l=d.filter(b=>b.status==="addable"),u=d.filter(b=>b.status==="already_linked"),_=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!_||l.length===0){let b=c.document.metadata.files??[];return{id:a.id,files:b,changed:!1,apply:_,count:b.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let g=G(t.author,s.author_default),h=l.map(b=>({path:b.path,scope:b.scope,note:f})),y=[],v=new Set,w=await le({pmRoot:i,settings:s,id:e,op:"files_discover",author:g,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let L=[...b.metadata.files??[]],q=new Set(L.map(B=>kn(B,r)));y=[],v.clear();for(let[B,we]of h.entries()){let ue=kn(we,r);q.has(ue)||(L.push(we),q.add(ue),y.push(we),v.add(B))}let F=Ia(L),C=t.appendStable?F:Ca(F);return C.length>0?b.metadata.files=C:delete b.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==h.length?[`files_discover_skipped_existing:${h.length-y.length}`]:[]}}}),S=w.item.files??[],E=new Set(y.map(b=>kn(b,r))),T=S.filter(b=>E.has(kn(b,r))),A=l.filter((b,L)=>!v.has(L)),k=[...u,...A];return{id:w.item.id,files:S,changed:T.length>0,apply:!0,count:S.length,candidate_count:d.length,addable_count:l.length,added_count:T.length,skipped_existing_count:k.length,candidates:d,added:T,skipped_existing:k}}import{readFileSync as pE}from"node:fs";import Hr 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]="e69d7d9b-9ae8-5337-9ea3-a8e40a62d3af")}catch{}})();var fE=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Ra=new Set(["--pm-path","--path","--author"]),gE={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},hE=new Set(["-p","--package"]),yE=new Set(["-c","--call"]),Oa=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),La=new Set(["-C","--prefix","--userconfig","--cache"]),af=new Set(["--cwd"]),cf=new Set(["--cwd"]),vE=new Set(["exec","x"]),df=new Set(["run","run-script"]),lf=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Dt(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function Yr(e,t=process.cwd()){let n=Xr(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[i,...r]=n;if(li(i)||ui(i,t))return r;if(i==="node"&&r[0]&&ui(r[0],t))return r.slice(1);let s=i==="npx"||i==="bunx"?Mt(r):i==="pnpm"?Qr(r):i==="npm"?Zr(r):null;return s&&(li(s.command)||Da(s.command))?s.args:null}var Na=(e,t="pm")=>{let n=t.trim().toLowerCase(),i=n.length;for(;i>0&&n[i-1]==="-";)i-=1;let r=n.slice(0,i);if(r.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of Dt(s)){let c=Yr(a),d=c?Ma(c):null,l=d&&fE.has(d.subcommand)?bE(d.remaining,gE[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&o.add(l)}return[...o].sort((a,c)=>a.localeCompare(c))};function Xr(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Jr(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ra.has(n)){t+=2;continue}t+=1;continue}return n}}function li(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function wE(e){let t=e.trim();if(!t.startsWith("@")){let r=t.indexOf("@");return r===-1?t:t.slice(0,r)}let n=t.indexOf("/");if(n===-1)return t;let i=t.indexOf("@",n+1);return i===-1?t:t.slice(0,i)}function Da(e){let t=wE(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function ui(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let i=Hr.resolve(t,e);try{return JSON.parse(pE(Hr.join(Hr.dirname(Hr.dirname(i)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Mt(e){let t=0;for(;t<e.length;){let i=e[t];if(i==="--"){t+=1;break}if(!i.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(i);if(r){let s=r[1];return s?{command:s,args:e.slice(t+1)}:null}if(yE.has(i)){t+=1;break}t+=hE.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function bt(e,t){let n=0;for(;n<e.length;){let i=e[n];if(i==="--"){n+=1;continue}if(i.startsWith("-")){if(i.includes("=")){n+=1;continue}if(t.has(i)){n+=2;continue}n+=1;continue}return{subcommand:i,args:e.slice(n+1)}}return null}function Qr(e){let t=bt(e,Oa);return t?.subcommand!=="dlx"?null:Mt(t.args)}function Zr(e){let t=bt(e,La);return!t||!vE.has(t.subcommand)?null:Mt(t.args)}function Ma(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ra.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function bE(e,t=new Set){for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")return e[n+1];if(!i.startsWith("-"))return i;!i.includes("=")&&(Ra.has(i)||t.has(i))&&(n+=1)}}import{execFile as kE}from"node:child_process";import{readFile as SE}from"node:fs/promises";import mf from"node:path";import{promisify as EE}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]="eeb9bc22-b9e1-5449-9ad0-fbb1a14fb09d")}catch{}})();var TE=EE(kE),Pa=1,AE="linked-test-trust.json";function Fa(e){return mf.join(qd(e),AE)}function uf(){return{version:Pa,acknowledged:{}}}async function $a(e){try{let t=JSON.parse(await SE(Fa(e),"utf8"));return t.version!==Pa||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?uf():{version:Pa,acknowledged:t.acknowledged}}catch{return uf()}}async function _i(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await TE("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),i=n.trim();return i.length===0?void 0:i}catch{return}}function pi(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function CE(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Od(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function mi(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function IE(e,t,n,i){return e?.map(r=>r.command&&!r.provenance?{...r,provenance:{author:t,created_at:n,source_kind:"local_mutation",...i?{source_ref:i}:{}}}:r)}async function Sn(e,t,n){if(!e||e.length===0)return e;let i=pi();return IE(e,t,n,await _i(i))}function _f(e){return Zd(ie({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function Ua(e,t,n){let i=await $a(e);return pf(t,n,i)}function pf(e,t,n){let i=_f(e),r=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:i,trusted:!0,reason:"legacy"};let s=Object.hasOwn(n.acknowledged,i);return e.provenance_invalid===!0||!CE(e.provenance)?s?{fingerprint:i,trusted:!0,reason:"acknowledged",...mi(void 0,t)}:{fingerprint:i,trusted:!1,reason:"invalid_provenance",...mi(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r===void 0?{fingerprint:i,trusted:!0,reason:"local_mutation",...mi(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r!==void 0&&r===t?{fingerprint:i,trusted:!0,reason:"local_source_ref",source_ref:r,current_source_ref:t}:s?{fingerprint:i,trusted:!0,reason:"acknowledged",...mi(r,t)}:{fingerprint:i,trusted:!1,reason:"foreign_source_ref",...mi(r,t)}}async function ff(e,t,n){let i=await $a(e);return t.map(r=>pf(r,n,i))}async function gf(e,t,n){let i=await $a(e),r=t.filter(s=>typeof s.command=="string"&&s.command.length>0).map(_f);for(let s of r)i.acknowledged[s]={acknowledged_at:n};return await gt(mf.dirname(Fa(e))),await Ve(Fa(e),`${JSON.stringify(i,null,2)}
|
|
8
|
-
`),{acknowledged:r.length,fingerprints:r}}import Qa from"node:fs/promises";import{realpathSync as PE}from"node:fs";import{execFile as FE}from"node:child_process";import Ce from"node:path";import{promisify as $E}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]="55d5ac7a-9aa4-569e-9bb6-f504a0ac7421")}catch{}})();var xE=["metadata","resolution"],ja=["metadata","resolution","estimates","lifecycle"],RE="completed";function Ga(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function hf(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function yf(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=hf(n.close_reason)??RE;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${Ga(i)}`,gate:"resolution"})}return t}function vf(e){let t=[];for(let n of e){let i=hf(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${Ga(i)}`,gate:"metadata"})}return t}function wf(e,t){return e.map(n=>{let i=Hl(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function bf(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function kf(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${i} ${n.item_id} --remove ${Ga(n.path)}`})}return t}function Sf(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new p(`--fix-scope values must not be empty. Supported values: ${ja.join(", ")}.`,m.USAGE);return new Set(xE)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(ja.includes(r)){n.add(r);continue}throw new p(`Unknown --fix-scope value "${i}". Supported values: ${ja.join(", ")}.`,m.USAGE)}return n}function Ef(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function fi(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="40703093-d602-5e6b-92b6-6b5efe3613fe")}catch{}})();var OE=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function LE(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let i=OE.exec(n);if(!i)return null;let r=i[1],s=r.toUpperCase(),o=r.slice(0,r.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(_=>_.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(r.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${s}`)||d.includes(`ISSUE CODE \`${s}\``)||d.includes(`\`${s}\``)||d.includes(`[${s}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(o.toUpperCase())||l?s:null}function Tf(e){return typeof e=="string"&&e.trim().length>0}function Af(e,t={}){let n=new Map;for(let r of e){if(typeof r.title!="string"||Tf(r.duplicate_of))continue;let s=LE(r.title,{...t,evidenceText:r.body});if(s===null)continue;let o=n.get(s);o||(o=[],n.set(s,o)),o.some(a=>a.id===r.id)||o.push({id:r.id,title:r.title,parent:Tf(r.parent)?r.parent.trim():null})}let i=[];for(let[r,s]of n){if(s.length<2)continue;let o=new Set(s.map(d=>d.id.toLowerCase())),a=s.filter(d=>d.parent===null||!o.has(d.parent.toLowerCase()));if(a.length<2)continue;let c=[...a].sort((d,l)=>d.id.localeCompare(l.id));i.push({code:r,count:c.length,ids:c.map(d=>d.id),titles:c.map(d=>d.title)})}return i.sort((r,s)=>r.code.localeCompare(s.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b51a9fba-7bbe-573b-a708-5ffea6fa040f")}catch{}})();function Cf(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,s)=>r.localeCompare(s))){let r=t.get(i),s={};for(let o of[...r.keys()].sort((a,c)=>a.localeCompare(c)))s[o]=r.get(o);n[i]=s}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ede22770-cb10-5054-85a7-89bb2758c25f")}catch{}})();var If=3;function xf(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Rf(e,t,n=If){let i=Number.isFinite(n)&&n>=1?Math.floor(n):If,r=new Map;for(let s of t){let o=xf(s);if(o.length===0)continue;let a=r.get(o);a?a.push(s):r.set(o,[s])}return e.map(s=>{if(s.includes(",")||s.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:s,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(r.get(xf(s))??[]).filter(a=>a!==s).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:o.slice(0,i),candidates_truncated:o.length>i}})}function Of(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ae38c0a-7f43-5457-b9a5-d23491a371ea")}catch{}})();async function es(e){return e.includeBody?Ot(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):dn(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42402d5d-8074-591f-98b4-75f479509cb4")}catch{}})();var NE=5;async function ts(e,t,n){let i=await Yn(e,t),s=[["validate_history_drift_missing_streams",i.missingStreams.length],["validate_history_drift_unreadable_streams",i.unreadableStreams.length],["validate_history_drift_hash_mismatches",i.hashMismatches.length],["validate_history_drift_chain_mismatches",i.chainMismatches.length],["validate_history_drift_version_skews",i.versionSkews.length],["validate_history_drift_workspace_state_mismatches",i.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",i.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",i.workspaceStateUnreadable.length]].filter(([,d])=>d>0).map(([d,l])=>`${d}:${l}`),o=n?Number.POSITIVE_INFINITY:NE,a=i.driftedItems.slice(0,o),c=i.identityDiscontinuities??[];return{check:{name:"history_drift",status:c.length>0?"error":s.length===0?"ok":"warn",ok:c.length===0&&s.length===0,details:{identity_discontinuities:c.slice(0,o),identity_discontinuities_count:c.length,identity_discontinuities_truncated:c.length>o,checked_items:t.length,drifted_items_count:i.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<i.driftedItems.length,counts:{missing_streams:i.missingStreams.length,unreadable_streams:i.unreadableStreams.length,hash_mismatches:i.hashMismatches.length,chain_mismatches:i.chainMismatches.length,version_skews:i.versionSkews.length,workspace_state_mismatches:i.workspaceStateMismatches.length,workspace_state_missing:i.workspaceStateMissing.length,workspace_state_unreadable:i.workspaceStateUnreadable.length},workspace_state_mismatches:i.workspaceStateMismatches,workspace_state_missing:i.workspaceStateMissing,workspace_state_unreadable:i.workspaceStateUnreadable,version_skews:i.versionSkews.slice(0,o)}},warnings: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]="c357729b-f316-51e7-9768-fc7bb4600e06")}catch{}})();function ns(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],s=new Set([n]),o=a=>{for(let c of(t.get(a)??[]).filter(d=>i.has(d))){if(c===n&&r.length>1)return r.push(n),!0;if(!s.has(c)){if(s.add(c),r.push(c),o(c))return!0;r.pop(),s.delete(c)}}return!1};return o(n)?[...r]:[...e,n]}function DE(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function ME(e,t,n,i){for(let r of e.dependencies??[]){if(typeof r!="object"||r===null||typeof r.id!="string")continue;let s=i.resolve(r.kind);if(!s?.hierarchy)continue;let o=n.get(r.id.toLowerCase());o&&(s.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function qa(e,t=Se()){let n=new Map(e.map(r=>[r.id.toLowerCase(),r.id])),i=new Map(e.map(r=>[r.id,[]]));for(let r of[...e].sort((s,o)=>s.id.localeCompare(o.id))){let s=i.get(r.id),o=DE(r.parent,n);o&&s.push(o),ME(r,i,n,t)}for(let[r,s]of i)i.set(r,[...new Set(s)].sort());return i}function Ka(e,t,n=Se()){let i=kr(e,o=>t?sr(o,t):o==="closed"||o==="canceled",n),r=qa(e,n),s=i.cycles.map(o=>o.item_ids);return{cycle_count:s.length,active_cycle_count:i.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:i.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(s.flat())].sort(),cycle_sample_paths:s.map(o=>ns(o,r).join("->")),cardinality_violation_count:i.cardinality_violations.length,active_cardinality_violation_count:i.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:i.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:i.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:i.divergences.length,active_parent_divergence_count:i.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:i.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:i.divergences.map(o=>`${o.child_id}:scalar=${o.scalar_parent_id}:dependencies=${o.dependency_parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1d8059aa-0711-522b-a12e-f5469286542f")}catch{}})();function kt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function za(e){return kt(e).replace(/\/+$/,"")}function Ge(e){let t=ne(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return 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]="16aa1db1-b6f2-504b-aa4e-0e384ad1d7a5")}catch{}})();var UE=["src","tests","docs"],jE=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],GE=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),qE=["resolution","expected_result","actual_result"],KE=["default","tracked-all","tracked-all-strict"],Lf=["core","strict","custom"],ss=["off","warn","error"],Va=["author","acceptance_criteria","estimated_minutes","close_reason"],Mf=[...Va,"reviewer","risk","confidence","sprint","release"],Ha=Array.from(new Set(Mf)),zE={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},WE={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},BE={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},VE={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},HE={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},YE=32*1024*1024,XE=1e4,Ya=40,et=5,JE=4096,QE=255,ZE=$E(FE);function Pf(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||i===!1&&n.endsWith("_truncated")||(t[n]=typeof i=="object"&&i!==null?Pf(i):i);return t}function eT(e){return{...e,checks:e.checks.map(t=>({...t,details:Pf(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function as(e,t){return se(e,t)??e}function gi(e,t){return t.terminal_statuses.has(as(e,t))}function St(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function is(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function tT(e){let t=St(Id),n={blocked_reason:St(Gi.blocked_reason),resolution:St(Gi.resolution),actual_result:St(Gi.actual_result)},i=St(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:St(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:St(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:St(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:is(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:is(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:is(r.resolution,n.resolution)?"default":"settings",actual_result:is(r.actual_result,n.actual_result)?"default":"settings"}}}function Ff(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Lf.includes(t))return t;throw new p(`Unknown --metadata-profile value "${e}". Supported values: ${Lf.join(", ")}.`,m.USAGE)}function $f(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ss.includes(t))return t;throw new p(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ss.join(", ")}.`,m.USAGE)}function Uf(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ss.includes(t))return t;throw new p(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ss.join(", ")}.`,m.USAGE)}function nT(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>zE[n]).filter(n=>n!==void 0).sort((n,i)=>n.localeCompare(i))}function iT(e,t,n){let i=nT(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Va],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Mf],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:i.length>0?{profile:e,profile_source:t,required_fields:i,configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Va],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var rT=new Set(["acceptance_criteria","estimated_minutes"]);function jf(e,t,n,i){return!i&&rT.has(t)&&gi(e.status,n)?!1:t==="author"?!ne(e.author):t==="acceptance_criteria"?!ne(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?as(e.status,n)===n.close_status&&!ne(e.close_reason):t==="reviewer"?!ne(e.reviewer):t==="risk"?!ne(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!ne(e.confidence):t==="sprint"?!ne(e.sprint):!ne(e.release)}function Gf(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new p(`Unknown --scan-mode value "${e}". Supported values: ${KE.join(", ")}.`,m.USAGE)}function qf(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Ce.resolve(t);let n=Ce.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Ce.dirname(Ce.dirname(n));let r=Ce.resolve(process.cwd()),s=Nf(n),o=Nf(r),a=Ce.relative(s,o);return a.length===0||!a.startsWith("..")&&!Ce.isAbsolute(a)?n:r}function Nf(e){try{return PE.native(e)}catch{return Ce.resolve(e)}}function sT(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Za(e,t,n){let i=t.length>0?Ce.join(e,t):e,r;try{r=await Qa.readdir(i,{withFileTypes:!0})}catch(s){if(W(s))return;throw s}for(let s of r){if(s.name.startsWith("."))continue;let o=t.length>0?Ce.join(t,s.name):s.name;if(s.isDirectory()){if(GE.has(s.name))continue;await Za(e,o,n);continue}s.isFile()&&n.push(kt(o))}}async function Xa(e){let t=[];for(let n of UE)await Za(e,n,t);for(let n of jE){let i=Ce.join(e,n);try{(await Qa.stat(i)).isFile()&&t.push(kt(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function Kf(e){try{let{stdout:t}=await ZE("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:YE,windowsHide:!0,timeout:XE}),n=t.split("\0").map(i=>kt(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function oT(e,t){let n=new Set,i=za(Td);i.length>0&&n.add(i);let r=za(Ce.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((s,o)=>s.localeCompare(o))}function Df(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function aT(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await Kf(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await Xa(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await Xa(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function te(e,t=et){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Pt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=te(e,Ya);return{values:n.values,truncated:n.truncated,total:e.length}}var cT={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},dT={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function lT(e){let t=e.missing_fields.map(n=>`${cT[n]} "${dT[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function zf(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(o=>typeof o=="string"):Ap(t);if(r.length===0)return;let s=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...s?{fix_hints_truncated:!0}:{}}}function Wf(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var uT="validate_metadata_duplicate_issue_codes";function Bf(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:et,i=e.slice(0,n);return{rows:i.map(s=>({code:s.code,count:s.count,ids:s.ids,titles:s.titles,remediation_hint:`Items ${s.ids.join(", ")} share issue code "${s.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${uT}:${e.length}`]}}function mT(e,t,n){let i=Object.fromEntries(Ha.map(r=>[r,[]]));for(let r of e)for(let s of Ha)jf(r,s,t,n)&&i[s].push(r.id);return i}function _T(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let s=t[r];s.length>0&&i.push(`${WE[r]}:${s.length}`)}return i.push(...n),i}function Vf(e,t){let n={};for(let i of e.required_fields){let r=t[i],s=r?r.length:0,o=BE[i];n[o]=s}return n}function Hf(e,t,n){let i=[];for(let r of e.required_fields){let s=t[r];if(s)for(let o of s){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";i.push({item_type:c,field:r})}}return i}function pT(e,t,n,i){for(let r of t.required_fields){let s=n[r];if(!s||s.length===0)continue;let o=VE[r],a=HE[r];if(!o||!a)continue;let c=te(s,i?s.length:et);e[o]=c.values,e[a]=c.truncated}}function Yf(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:ne(n.get(r)?.resolution)})):[]}function Xf(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:ne(n.get(r)?.type)})):[]}function fT(e,t,n,i,r){let s=new Map(e.map(v=>[v.id,v])),o=t.profile==="strict",a=mT(e,n,o),c=Af(e,{configuredPrefixes:r}),d=Bf(c,i),l=_T(t,a,d.warnings),u=Vf(t,a),_=Hf(t,a,s),f=Cf(_),g={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...Ha],counts:u,missing_by_type:f,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(g.configured_custom_required_fields=[...t.configured_custom_fields]),pT(g,t,a,i);let h=Yf(t,a,s),y=Xf(t,a,s);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:g},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:y}}function gT(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(_=>i.has(as(_.status,t))),s=[],o=[];for(let _ of r){let f=qE.filter(g=>!ne(_[g]));f.length!==0&&(s.push({id:_.id,missing_fields:f}),o.push({id:_.id,missing_fields:f,close_reason:ne(_.close_reason)}))}let a=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:et,d=te(s.map(_=>`${_.id}:${_.missing_fields.join(",")}`),c),l=s.map(_=>lT(_)),u=te(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:r.length,missing_resolution_items:s.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function Jf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qf(e,t="pm",n=Jd()){let i=new Set(e.map(s=>s.id)),r=[...e].sort((s,o)=>s.id.localeCompare(o.id));return new Map(r.map(s=>{let o=new Set,a=Ge(s.blocked_by);a&&i.has(a)&&o.add(a),(s.dependencies??[]).filter(d=>{let l=Ge(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ge(d.id)).filter(d=>d!==void 0&&i.has(d)).forEach(d=>o.add(d));let c=Ge(s.definition_of_ready);return eg(c??"",t).filter(d=>i.has(d)).forEach(d=>o.add(d)),[s.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function Zf(e,t,n){let i=o_(e,n?l=>gi(l,n):void 0),r=i.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),s=i.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:et,a=te(r,o),c=te(s,o),d=te(i.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:r.length===0?"ok":"warn",ok:r.length===0,details:{checked_items:e.length,dangling_reference_count:r.length+s.length,active_dangling_reference_count:r.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:i.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:i.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function eg(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${Jf(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,s)=>r.localeCompare(s))}function tg(e){let t=0,n=new Map,i=new Map,r=[],s=new Set,o=[],a=l=>{n.set(l,t),i.set(l,t),t+=1,r.push(l),s.add(l);for(let _ of e.get(l)??[])n.has(_)?s.has(_)&&i.set(l,Math.min(i.get(l),n.get(_))):(a(_),i.set(l,Math.min(i.get(l),i.get(_))));if(i.get(l)!==n.get(l))return;let u=[];for(;r.length>0;){let _=r.pop();if(s.delete(_),u.push(_),_===l)break}u.sort((_,f)=>_.localeCompare(f)),o.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return o.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function ng(e,t="pm"){let n=Qf(e,t),i=tg(n),r=[...new Set(i.flat())].sort((o,a)=>o.localeCompare(a)),s=i.map(o=>ns(o,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:s}}function ig(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function os(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function rg(e,t){let n=os(e).split("/").filter(Boolean),i=os(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function hT(e,t){let n=os(t),i=os(e),r=t.endsWith("/")?t:`${t}/`,s=e.startsWith(r),o=n.length>0&&n===i,a=rg(e,t);return!s&&!o&&a===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function yT(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function vT(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(s=>(i==="docs"?s.docs??[]:s.files??[]).map(o=>({item:s,link:o}))).forEach(({item:s,link:o})=>{if(o.scope!=="project")return;let a=kt(o.path);if(a.length===0||a===e)return;let c=hT(e,a);c!==null&&yT(r,s,c.score)&&(r={item:s,score:c.score,confidence:c.confidence})}),r?{id:r.item.id,type:r.item.type,title:r.item.title,status:r.item.status,confidence:r.confidence}:null}function sg(e,t){return e.map(n=>{let i=ig(n),r=i==="docs_unowned"?"docs":"files",s=vT(n,i,t),o=s?.id??"<id>";return{path:n,classification:i,owner_candidate:s,remediation_hint:`pm ${r} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function og(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function wT(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=Ge(e[n]);return r?i.some(s=>r.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function bT(e,t,n,i,r){let s=Ge(t.parent),o=s?n.get(i.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!gi(o.status,r)}}function kT(e,t,n,i){let r=Ge(e.blocked_by),s=Ge(e.blocked_reason),o=s?.toLowerCase(),a=as(e.status,n),c=[];return t.has(a)?(!r&&!s&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&i.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function ST(e,t,n,i){let r=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!gi(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=wT(c,i);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=Ge(c.parent),u=l?r.get(s.get(l.toLowerCase())??l):void 0;if(u&&gi(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(bT(c,u,r,s,n))),t){let _=kT(c,o,n,i);_.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(_)].sort((f,g)=>f.localeCompare(g))})}}return a}function ET(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function rs(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Wa(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function TT(e,t,n,i,r){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=rs("validate_lifecycle_dependency_cycles",n,r.dependencyCycles),a=rs("validate_hierarchy_parent_cycle",i,r.activeHierarchyCycles),c=rs("validate_hierarchy_cardinality_violation",i,r.activeHierarchyCardinality),d=rs("validate_hierarchy_parent_divergence",i,r.activeHierarchyDivergence),l=Wa("validate_legacy_hierarchy_parent_cycle",i,r.legacyHierarchyCycles),u=Wa("validate_legacy_hierarchy_cardinality_violation",i,r.legacyHierarchyCardinality),_=Wa("validate_legacy_hierarchy_parent_divergence",i,r.legacyHierarchyDivergence);return[...s,...o?[o]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],..._?[_]:[]]}function ag(e){let t=kt(e);return t.length>JE||t.split(/[\\/]/).some(n=>n.length>QE)}async function AT(e,t){let n=Ce.isAbsolute(t)?t:Ce.resolve(e,t);if(ag(n))return!1;try{let i=await Qa.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return sT(i,["ENOENT","ENOTDIR"])}}async function CT(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(s=>({item:r,artifact:s,link_kind:"files"})),...(r.docs??[]).map(s=>({item:r,artifact:s,link_kind:"docs"}))]);for(let{item:r,artifact:s,link_kind:o}of i){if(s.scope!=="project")continue;if(ci(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let a=kt(s.path);a.length!==0&&(n.linkedProjectPaths.add(a),await AT(t,s.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:r.id,path:a,link_kind:o})))}return n}function IT(e,t,n,i,r,s){let o=i==="tracked-all-strict",a=o&&!r,c=r||o,d=c?[]:oT(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>Df(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Df(f,d)),_={};if(l.length>0){let f=Pt(l,s);_.pm_internals={count:l.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:_}}function cg(e,t,n,i,r,s,o,a="pm"){let c=ST(e,t,r,s);ET(c);let d=ng(c.activeItems,a),l=Ka(e,r),u=$r(r,e,o?Number.POSITIVE_INFINITY:et),_=[...TT(c,t,n,i,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...Ur(u)],f=o?Number.POSITIVE_INFINITY:et,g=te(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),f),h=te(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),f),y=te(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),f),v=te(d.cycle_item_ids,f),w=te(d.cycle_sample_paths,f),S=te(l.cycle_item_ids,f),E=te(l.cycle_sample_paths,f),T=te(l.cardinality_violation_rows,f),A=te(l.parent_divergence_rows,f),k=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&i==="error";return{check:{name:"lifecycle",status:k?"error":_.length===0?"ok":"warn",ok:!k&&_.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:g.values,active_closure_like_metadata_rows_truncated:g.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:v.values,dependency_cycle_item_ids_truncated:v.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:i,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:S.values,parent_cycle_item_ids_truncated:S.truncated,parent_cycle_sample_paths:E.values,parent_cycle_sample_paths_truncated:E.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:T.values,hierarchy_cardinality_violation_rows_truncated:T.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:A.values,hierarchy_parent_divergence_rows_truncated:A.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:_,terminalParentFixRows:c.terminalParentFixRows}}async function dg(e,t,n,i,r,s,o=K(Ct.schema)){let a=await CT(e,t),c=new Map(e.map(C=>[C.id,C])),d=[...new Set(a.missingLinkedPaths)].sort((C,B)=>C.localeCompare(B)),l=await aT(t,i),u=IT(l,n,t,i,r,s),_=u.candidateFiles.filter(C=>!a.linkedProjectPaths.has(C)),f=sg(_,e),g=Rf(d,u.candidateFiles),h=new Map(g.map(C=>[C.path,C.classification])),y=g.filter(C=>C.classification==="moved").length,v=a.staleLinkRows.map(C=>({...C,classification:h.get(C.path)??"deleted"})).sort((C,B)=>C.item_id.localeCompare(B.item_id)||C.path.localeCompare(B.path)||C.link_kind.localeCompare(B.link_kind)),w=[];u.strictModeForcesPmInternals&&w.push("validate_files_tracked_all_strict_forces_pm_internals"),_.length>0&&w.push(`validate_files_orphaned_paths:${_.length}`);let S=[...a.remoteLinkedPaths].sort((C,B)=>C.localeCompare(B)),E=Pt(S,s),T=Pt(d,s),A=Pt(_,s),k=Pt(f.map(C=>`${C.path}:${C.classification}:owner_candidate=${C.owner_candidate?.id??"unowned"}`),s),b=s?f:Pt(og(f),!1).values,L=Pt(Of(g),s),F=Bp(v,g,C=>c.get(C),o,s?1/0:Ya);return F.active_missing_linked_paths_count>0&&w.push(`validate_files_missing_linked_paths:${F.active_missing_linked_paths_count}`),{check:{name:"files",status:w.length===0?"ok":"warn",ok:w.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:s?"full":"summary",file_list_summary_limit:Ya,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:r,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:S.length,remote_linked_paths_total:E.total,remote_linked_paths:E.values,remote_linked_paths_truncated:E.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:T.total,missing_linked_paths:T.values,missing_linked_paths_truncated:T.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:g.filter(C=>C.classification==="deleted").length,missing_linked_paths_malformed_count:g.filter(C=>C.classification==="malformed").length,missing_linked_path_classifications:L.values,missing_linked_path_classifications_truncated:L.truncated,...F,orphaned_paths_count:_.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.truncated,orphaned_path_classifications:k.values,orphaned_path_classifications_truncated:k.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:b}},warnings:w,staleLinkPruneRows:v}}function lg(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function xT(e,t,n){return`${e}:${t}:${lg(n)}`}function RT(e,t){let n=[];return e.forEach(({item:i,linkedTest:r},s)=>{let o=t[s];if(o.trusted)return;let a=lg(r.command??"");n.push(`${i.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${a}`)}),n}async function ug(e,t,n,i){let r=new Set(e.map(T=>T.id.toLowerCase())),s=0,o=0,a=new Set,c=[],d=e.flatMap(T=>(T.tests??[]).map(A=>({item:T,linkedTest:A}))),l=await _i(pi()),u=await ff(i,d.map(({linkedTest:T})=>T),l),_=RT(d,u);for(let{item:T,linkedTest:A}of d){if(typeof A.command!="string"||A.command.trim().length===0)continue;s+=1;let k=Na(A.command,t);if(k.length!==0){o+=k.length;for(let b of k)a.add(b),r.has(b.toLowerCase())||c.push(xT(T.id,b,A.command))}}let f=[...new Set(c)].sort((T,A)=>T.localeCompare(A)),g=[...new Set(f.map(T=>T.split(":")[1]??""))].filter(T=>T.length>0).sort((T,A)=>T.localeCompare(A)),h=[];f.length>0&&h.push(`validate_command_references_stale_pm_ids:${f.length}`),_.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${_.length}`);let y=n?Number.POSITIVE_INFINITY:et,v=te(f,y),w=te(g,y),S=te([...a].sort((T,A)=>T.localeCompare(A)),y),E=te(_,y);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:s,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:S.values,unique_referenced_pm_ids_truncated:S.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:_.length,untrusted_linked_tests:E.values,untrusted_linked_tests_truncated:E.truncated,stale_pm_id_references_count:f.length,stale_pm_ids_count:g.length,stale_pm_ids:w.values,stale_pm_ids_truncated:w.truncated,stale_pm_id_reference_rows:v.values,stale_pm_id_reference_rows_truncated:v.truncated}},warnings:h}}function OT(e,t){let n=ar(e.map(c=>({ref:c.id,version:or(c)}))),i=[];n.outdated.length>0&&i.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&i.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:et,s=te(n.outdated,r),o=te(n.ahead,r),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:pl,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:i}}var Ja="pm validate auto-fix";async function mg(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:Ja};if(e.kind==="set_resolution"?i.resolution=e.value:e.kind==="set_close_reason"?i.closeReason=e.value:e.kind==="set_estimate"?i.estimatedMinutes=e.value:e.kind==="reparent"?i.parent=e.parent_id:i.unset=["parent"],!n.runUpdate)throw new p("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",m.USAGE);await n.runUpdate(e.item_id,i,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Ba(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function _g(e,t,n){let i=[],r=[],s=new Map;for(let o of e.filter(a=>Ba(a)===null))try{await mg(o,t,n),i.push(o)}catch(a){r.push({fix:o,error:a})}for(let o of e.filter(a=>Ba(a)!==null)){let a=Ba(o),c=s.get(a);c?c.push(o):s.set(a,[o])}for(let o of s.values()){let a=o[0];if(!a)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await rf(a.item_id,{remove:c,message:Ja},t):await Jp(a.item_id,{remove:c,message:Ja},t),i.push(...o)}catch(d){r.push(...o.map(l=>({fix:l,error:d})))}}return{applied:i,failed:r}}var bj={applyValidateFix:mg,applyValidateFixes:_g,attachValidateFixHints:zf,buildCommandReferencesCheck:ug,buildDependencyReferencesCheck:Zf,buildCloseReasonBackfillRows:Yf,buildFilesCheck:dg,buildLifecycleCheck:cg,buildLifecycleDependencyGraph:Qf,buildLifecycleParentGraph:qa,buildEstimateBackfillRows:Xf,buildMetadataCounts:Vf,buildMissingFieldOccurrences:Hf,buildOrphanedPathRows:sg,classifyOrphanedPath:ig,collectDefaultProjectFileCandidates:Xa,collectTrackedGitFileCandidates:Kf,detectLifecycleDependencyCycles:ng,detectLifecycleParentCycles:Ka,escapeRegExp:Jf,extractItemIds:eg,findLifecycleDependencyCycleComponents:tg,isMetadataFieldMissing:jf,linkedArtifactPathExceedsFilesystemLimits:ag,listFilesRecursive:Za,resolveDependencyCycleSeverity:$f,resolveParentCycleSeverity:Uf,resolveFileScanMode:Gf,resolveLifecycleDependencyCycleSamplePath:ns,resolveRequestedChecks:Wf,resolveValidateMetadataProfile:Ff,resolveWorkspaceRoot:qf,sharedDirectoryPrefixLength:rg,summarizeOrphanedPathRows:og,summarizeDuplicateIssueCodes:Bf,toMeaningfulString:Ge};function LT(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function NT(e,t,n,i){let r=await Hp(e,new Set(t.map(y=>y.id)),n,{schema:i.schema,extensionFieldNames:ht(M())}),s=[];r.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let o=s.length,a=await Gr(e);a.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Tr(e,Er(i));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await wt(e),l=d===null?null:await ln(d);l!==null&&l.status!=="ok"&&s.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await un(d??e,{includeLossless:!0,pmRoot:e}),_=u.receipts,{pendingDecisions:f,lossless:g}=mn(_);f.length>0&&s.push(`validate_merge_decisions_unreviewed:${f.length}`),LT(s,u.invalid_evidence_count);let h=o>0?"error":s.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...r,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:f.length,pending_merge_decision_items:[...new Set(f.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),lossless_merge_receipt_count:g.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(g.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:s}}function Ze(e,t,n){n&&zf(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function DT(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,i=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let r=await p_(e.pmRoot,e.items,i?1/0:et,e.sourceIncomplete);Ze(t,r,n)}if(e.requestedChecks.has("metadata")){let r=fT(e.items,e.metadataPolicy,e.statusRegistry,i,[e.settings.id_prefix]);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows,Ze(t,r,n)}if(e.requestedChecks.has("resolution")){let r=gT(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,Ze(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=cg(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,Ze(t,r,n),Ze(t,Zf(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await dg(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=r.staleLinkPruneRows,Ze(t,r,n)}return e.requestedChecks.has("command_references")&&Ze(t,await ug(e.items,e.settings.id_prefix,i,e.pmRoot),n),e.requestedChecks.has("history_drift")&&Ze(t,await ts(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&Ze(t,OT(e.items,i),n),e.requestedChecks.has("storage_integrity")&&Ze(t,await NT(e.pmRoot,e.items,$(e.settings,M()).type_to_folder,e.settings),n),t}function MT(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...vf(t.closeReasonBackfillRows)),i.push(...yf(t.resolutionBackfillRows)),i.push(...wf(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...bf(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...kf(t.staleLinkPruneRows)),i}async function PT(e,t,n,i,r,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=MT(e,t,n),{applicable:a,gated:c}=Ef(o,i),d=e.dryRun===!0,l=[],u=[];if(!d){let _=await _g(a,r,s);l.push(..._.applied.map(fi)),u.push(..._.failed.map(({fix:f,error:g})=>({...fi(f),error:g instanceof Error?g.message:String(g)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...i].sort((_,f)=>_.localeCompare(f)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(fi),applied_fixes:l,gated_fixes:c.map(_=>({...fi(_),gate_hint:`Withheld: re-run with --fix-scope ${_.gate} to apply.`})),failed_fixes:u}}async function pg(e,t,n={}){bl(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new p("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",m.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new p("--fix-scope requires --auto-fix.",m.USAGE);let r=Sf(e.fixScope),s=x(process.cwd(),t.path);await P(s);let o=await I(s),a=K(o.schema),c=$(o,M()),d=Wf(e),l=[],u=await es({includeBody:["history_drift","metadata","completeness"].some(q=>d.has(q)),pmRoot:s,settings:o,typeToFolder:c.type_to_folder,warnings:l}),_=l.length>0;if(d.has("history_drift")){let q=await oi(s);q.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${q.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",g=Ff(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),h=iT(g,f,o.validation.metadata_required_fields),y=tT(o),v=$f(e.dependencyCycleSeverity),w=Uf(e.parentCycleSeverity),S=Gf(e.scanMode),E=qf(s),T=await DT({requestedChecks:d,options:e,global:t,pmRoot:s,workspaceRoot:E,settings:o,items:u,statusRegistry:a,metadataPolicy:h,lifecyclePatternPolicy:y,dependencyCycleSeverity:v,parentCycleSeverity:w,fileScanMode:S,initialWarnings:[...new Set(l)],sourceIncomplete:_}),A=i?await PT(e,T,o,r,t,n):void 0,k=[...new Set(T.warnings)].sort((q,F)=>q.localeCompare(F)),L={ok:!T.checks.some(q=>q.status==="error"),has_warnings:k.length>0,checks:T.checks,warnings:k,...A!==void 0?{fixes:A}:{},generated_at:R(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?L:{...eT(L),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as FT}from"node:child_process";import{promisify as $T}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]="894154aa-88b8-5a3b-a03c-e3ef8a85f1c0")}catch{}})();var UT=$T(FT),jT=16,GT=3e4;function qT(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(s=>typeof s=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function KT(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let i=t.parameters??{},r=n.parameters??{};for(let s of Object.entries(r).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(i,s))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${s}`);for(let[s,o]of Object.entries(i)){let a=r[s];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${s}`);if(o===null||typeof o!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${s} must be ${a.type}`)}return{...i}}async function zT(e,t,n,i){let r=KT(e,t),s=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:r,trigger:i,pm_root:n,...el(n)}));s.catch(()=>{});let o;try{let a=await Promise.race([s,new Promise((c,d)=>{o=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??GT),o.unref?.()})]);return qT(e,t.key,a)}finally{clearTimeout(o)}}function gg(e,t,n,i){let r=e;for(let s of t.split(".")){if(typeof r!="object"||r===null||Array.isArray(r))throw new Je(`assurance field ${t} is not present`,{source_kind:n,field:t,...i?{check:i}:{}});r=r[s]}if(typeof r=="number"&&Number.isFinite(r)||Array.isArray(r)&&r.every(s=>typeof s=="string"))return r;throw new Je(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...i?{check:i}:{}})}function fg(e,t,n,i){let r=e.checks.find(o=>o.name===t);if(!r)throw new Je(`assurance check ${t} is not present`,{source_kind:i,field:n,check:t});return{value:n==="status"||n==="ok"?r.ok?0:1:gg(r.details,n,i,t),population_size:1,cost:e.checks.length}}async function WT(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await UT("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function BT(e,t){let n=new Array(t.length),i=0,r=Array.from({length:Math.min(jT,t.length)},async()=>{for(;i<t.length;){let s=i;i+=1;let o=t[s],a=await on(Qt(e,o.id),o.id);n[s]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(r),n.flat()}async function hi(e,t={}){let n=await I(e),i=$(n),r=K(n.schema),o=(t.strict_read===!0?(await C_(void 0,{status:"all",full:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await dn(e,n.item_format,i.type_to_folder,void 0,n.schema)).map(f=>({...f,id:f.id,status:f.status,type:f.type})),a={path:e},c=M(),d=Object.fromEntries((c?.assurance_providers??[]).map(f=>[f.definition.id,{cost_class:f.runtime_definition.cost_class,network:f.runtime_definition.network}])),l=new Map,u,_;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await WT(e,t.tree_id),items:o,history:t.include_history===!1?[]:await BT(e,o),terminal_statuses:[...r.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async f=>{if(f.kind==="graph"){let y=ie({operation:f.operation,parameters:f.parameters??{}}),v=l.get(y);v===void 0&&(v=l_(f.operation,void 0,void 0,{...f.parameters,full:!0},a),l.set(y,v));let w=await v;return{value:gg(w,f.field,f.kind),population_size:o.length,cost:o.length}}if(f.kind==="validate"){u??=pg({counts:!0},a);let y=await u;return fg(y,f.check,f.field,f.kind)}if(f.kind==="health"){_??=Kp(a,{checkOnly:!0,full:!0});let y=await _;return fg(y,f.check,f.field,f.kind)}let g=t.providers?.[f.provider];if(g)return g(f);let h=al(c,f.provider);if(!h)throw new TypeError(`assurance provider ${f.provider} is not registered`);return zT(h.runtime_definition,f,e,t.trigger??"sdk")}}}import{createHash as VT}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="538168d9-116c-5e72-81a4-a23e021c48f5")}catch{}})();function hg(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:i,limit:r}=wr({...t,change:{}});return{policy:n,...i===void 0?{}:{cursor:i},...r===void 0?{}:{limit:r},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function HT(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let i=n;if(i.fingerprint!==t||typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return i.offset}function YT(e,t,n,i,r,s){let o=Object.fromEntries(qo.map(f=>[f,0])),a=0,c=0,d=0,l=0,u=[],_=VT("sha256").update(r);for(let f of i){let g=e.membership.get(f),h=n.has(f),y=g.family_ids.length>0;y&&h&&(a+=1),y||(c+=1),h||(d+=1);let v=t.get(f)?.escape_class;v!==void 0&&qo.includes(v)&&(o[v]+=1,l+=1),_.update(ie([f,h,t.get(f)??null,g.id,g.family_ids])),(!s||!y||!h)&&u.push(f)}return{classCounts:o,coveredCount:a,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:_.digest("hex")}}function yg(e,t,n={}){n_(e);let i=n.limit??25;if(!Number.isSafeInteger(i)||i<1||i>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let r=new Set,s=new Map;for(let E of t){if(r.has(E.id))throw new TypeError(`Duplicate recurrence item ${E.id}`);r.add(E.id);let T=vr(E);T!==void 0&&s.set(E.id,T)}let o=Zm(e.families,s),a=[...o.membership.keys()].sort(),c=ie({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:_,classifiedCount:f,selected:g,fingerprint:h}=YT(o,s,r,a,c,n.uncoveredOnly===!0),y=HT(n.cursor,h);if(y>g.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let v=g.slice(y,y+i).map(E=>{let T=o.membership.get(E),A=r.has(E);return{item_id:E,lineage_id:T.id,lineage_item_count:T.item_ids.length,family_ids:T.family_ids,present:A,...A?T.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),w=y+v.length,S=a.length===0?null:d.production_defect/a.length;return{ok:u===0&&_===0,fingerprint:h,items:v,total:g.length,has_more:w<g.length,...w<g.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:w})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:a.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:_,classified_item_count:f,unclassified_item_count:a.length-f,class_counts:d,escape_rate:f===a.length?S:null,escape_rate_lower_bound:S},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:i},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as XT}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77425e45-ae19-569b-b196-e024f9e2729f")}catch{}})();var ec,vg=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],tc=["measurement","assertion","gate"];function JT(e){if(vg.includes(e))return e;throw Ki({command_path:"assurance",token:e,allowed:vg,display_name:"assurance action"})}function En(e,t,n){throw new p(t,m.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function QT(e){if(!e)return En("kind",`Assurance declaration kind is required. Expected: ${tc.join(", ")}`,"pm assurance list measurement");if(tc.includes(e))return e;throw new p(`Assurance declaration kind is required. Expected: ${tc.join(", ")}`,m.USAGE)}function wg(e){if(!e)return En("preset",`Assurance preset is required. Expected: ${ii.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(ii.includes(e))return e;throw new p(`Assurance preset is required. Expected: ${ii.join(", ")}`,m.USAGE)}function nc(e){return e.owner?.trim()?e.owner.trim():En("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function ZT(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(i){throw new p("assurance definition must be valid JSON",m.USAGE,{reason:i instanceof Error?i.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new p("assurance put requires a JSON object definition",m.USAGE);return n}async function eA(e){let[t,n,i]=await Promise.all([ni(e,"measurement"),ni(e,"assertion"),ni(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:i.items}}function bg(e,t){return t===!0?{id:e.id}:e}async function tA(e,t){let n=t.authorization_decision;if(!n)return[];let i=await hi(e,{include_history:!1,resolve_tree:!1}),r=i.items.find(o=>o.id===n),s=new Set(i.terminal_statuses);if(!r||r.type.toLowerCase()!=="decision"||!s.has(r.status))throw new p(`Assurance authorization ${n} must name a terminal Decision item`,m.USAGE);return[r.id]}async function nA(e,t){let n=ca(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>pn))throw new p(`assurance verdict limit must be an integer from 1 through ${pn}`,m.USAGE);let i=await H_(t,{gate_id:e.id??e.gate,limit:n});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function iA(e,t,n){if(e==="presets"){if(t.preset??t.id)return Nr(wg(t.preset??t.id),nc(t));let r=ii.map(s=>{let o=Nr(s,"pm-owner");return{id:s,title:o.title,description:o.description}});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return _n(()=>X_(n,wg(t.preset??t.id),nc(t),{author:t.author,message:t.message}));if(e==="derive"){let r=await J_(await hi(n,{resolve_tree:!1,trigger:"derive"}),nc(t)),s=t.apply?await _n(()=>Q_(n,r,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:r,count:r.length,...s?{applied:s}:{}}}if(!t.id)return En("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new p("assurance promote requires --enforcement warn|block",m.USAGE);let i=await na(n,"assertion",t.id);return _n(()=>Z_(n,i,t.enforcement,{author:t.author,message:t.message}))}async function rA(e,t,n){if(!e.id)return En("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let i=e.id;if(!e.trigger)throw new p("assurance run requires a trigger",m.USAGE);if(!ct.includes(e.trigger))throw new p(`Unknown assurance trigger ${e.trigger}. Expected: ${ct.join(", ")}`,m.USAGE);let r=e.trigger,[s,o]=await Promise.all([eA(t),hi(t,{...n.workspace,tree_id:e.tree,trigger:r})]),a=await L_(()=>z_(i,s,o,{trigger:r,dry_run:e.dry_run===!0}));return a.dry_run||await V_(t,a,{author:e.author,message:e.message}),a}function kg(e){throw e instanceof p?e:new p(e instanceof Error?e.message:"assurance risk request is invalid",m.USAGE)}function sA(e){if(e.limit!==void 0)throw new p(`assurance ${e.action} does not accept --limit; set limit inside the definition`,m.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new p(`assurance ${e.action} definition must be valid JSON`,m.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?hg(t):wr(t)}catch(n){return kg(n)}}function oA(e,t){let n=new Set;for(let[i,r]of t)e.item_fingerprints.get(i)!==r&&n.add(i);for(let i of e.item_fingerprints.keys())t.has(i)||n.add(i);return n}function aA(e,t,n){let i=ie(t.policy),r=ec?.pm_root===e?ec:void 0,s=new Map(n.map(d=>[d.id,XT("sha256").update(ie([Jm(d),vr(d)])).digest("hex")])),o=r?.policy_serialized===i?r:void 0,a=o?oA(o,s):new Set,c=e_(t.policy,o?n.filter(d=>a.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...a]}:{});return ec={pm_root:e,policy_serialized:i,item_fingerprints:s,index:c},c}async function cA(e,t){let n=sA(e),i=await hi(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?t_(aA(t,n,i.items),n.change,{cursor:n.cursor,limit:n.limit}):yg(n.policy,i.items,n)}catch(r){return kg(r)}}async function dA(e,t={},n={}){let i=JT(e.action),r=x(process.cwd(),t.path);if(i==="presets"||i==="apply"||i==="derive"||i==="promote")return iA(i,e,r);if(i==="verdicts")return nA(e,r);if(i==="run")return rA(e,r,n);if(["risk","lineages"].includes(i))return cA(e,r);let s=QT(e.kind);if(i==="list")return ni(r,s);if(!e.id)return En("id",`assurance ${i} requires an id`,`pm assurance ${i} ${s} <id>`);let o=e.id;if(i==="show")return na(r,s,o);if(i==="remove"){let l=await _n(()=>B_(r,s,o,{author:e.author,message:e.message}));return bg(l,e.idOnly)}let a=ZT(s,e.definition);if(a.id!==o)throw new p(`Assurance definition id ${a.id} does not match requested id ${o}`,m.USAGE);let c={author:e.author,message:e.message,...s==="assertion"?{authorized_decision_ids:await tA(r,a)}:{}},d=await _n(()=>Or(r,s,a,c));return bg(d,e.idOnly)}function n1(e,t,n){let i={...e,...t};return dA({action:O(i,"subcommand")??O(i,"assuranceAction")??O(i,"operation")??"",kind:O(i,"kind"),id:O(i,"id"),definition:i.definition,trigger:O(i,"trigger"),tree:O(i,"treeId")??O(i,"tree"),gate:O(i,"gate"),limit:ca(i.limit,"assurance verdict limit"),dry_run:i.dryRun===!0||i.dry_run===!0,fullChangedFields:i.fullChangedFields===!0,idOnly:i.idOnly===!0,author:O(i,"author"),message:O(i,"message"),preset:O(i,"preset"),owner:O(i,"owner"),apply:i.apply===!0,enforcement:O(i,"enforcement")},n)}import{readFile as lA}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a5fc27e-3f5a-59e0-998e-be5da72913dd")}catch{}})();function y1(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Pe(e,t)}function Sg(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new p(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function uA(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Ft(e,t){let n=e[t];return Array.isArray(n)?n:[]}function v1(e,t={}){let n=e.trim();if(!n)return"";let i=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&i&&!n.startsWith("```"))return n.slice(i[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let s=J(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function mA(e){return typeof e=="object"&&e!==null&&"code"in e}function Eg(e,t){if(!Rt(e))throw new p(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function _A(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new p(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let i=en(),r=Rt(e);if(e.add!==void 0)return{value:await i.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return Eg(e,"--stdin"),{value:await i.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new p("--file path cannot be empty",m.USAGE);if(s==="-")return Eg(e,"--file -"),{value:await i.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await lA(s,"utf8"),emptyFlag:"--file"}}catch(o){if(mA(o)&&ji(o))throw new p(`--file path not found: ${s}. Use --file - to read stdin.`,m.USAGE);let a=o instanceof Error?o.message:String(o);throw new p(`Failed to read --file path "${s}": ${a}. Use --file - to read stdin.`,m.USAGE)}}async function w1(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new p("Specify only one of --edit or --delete",m.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new p("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new p("--delete must be a positive integer",m.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new p("--edit must be a positive integer",m.USAGE);let n=await _A(e,t);if(e.edit!==void 0){if(!n)throw new p("--edit requires replacement text from --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function yi(e,t){throw e instanceof p&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new p(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Ag(e){return e==="comments"?"--stdin":"--add -"}function pA(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let i=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(i))return;let r=Ag(t.collectionKey),s=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new p(`--add value "${i}" looks like an option, not annotation text. Use ${r} to read stdin, or use text=${i} for literal dash-leading text.`,m.USAGE,{code:"annotation_flag_like_value",required:`Use ${r} for stdin input, pass plain text, or use text=${i} when the text really starts with "-".`,examples:[`${s} ${r}`,`${s} --add text=${i}`]})}function fA(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new p(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,m.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new p(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,m.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${Ag(e.collectionKey)}`]})}function gA(e,t,n,i,r,s){let o=Ft(e.metadata,t),a=r?o.findIndex(c=>c.author===n&&c.text===i):-1;return a>=0?{changedFields:[],entryIndex:a+1}:(o.push(s({created_at:R(),author:n,text:i})),e.metadata[t]=o,{changedFields:[t],entryIndex:o.length})}async function b1(e,t,n,i){fA(i,t);let r=x(process.cwd(),n.path);await P(r);let s=await I(r),o=$(s,M()),a=Wn(t.limit);if(i.input.mode==="list"){let g=await Q(r,e,s.id_prefix,s.item_format,o.type_to_folder);if(!g)throw new p(`Item ${e} not found`,m.NOT_FOUND);let h=await be(g,{schema:s.schema}),y=Ft(h.document.metadata,i.collectionKey);return cs(g.id,i.collectionKey,y,a,t.includeMeta===!0)}let c=G(t.author,s.author_default);if(i.input.mode==="delete"){let g=i.deleteOp??i.op,h;try{h=await le({pmRoot:r,settings:s,id:e,op:g,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,mutate(v){let w=Ft(v.metadata,i.collectionKey),S=Tg(i.input.index,w.length,i.collectionKey);return Sg(w[S],"deleted"),w.splice(S,1),v.metadata[i.collectionKey]=w,{changedFields:[i.collectionKey]}}})}catch(v){yi(v,i.conflictGuidance)}let y=Ft(h.item,i.collectionKey);return cs(h.item.id,i.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:i.input.index},t.fullHistory===!0)}let d=i.input.rawValue??i.input.value??"";pA(d,i);let l=i.parseText(i.input.value??"");if(!l.trim())throw new p(`${i.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(i.input.mode==="edit"){let g=i.editOp??i.op,h;try{h=await le({pmRoot:r,settings:s,id:e,op:g,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,mutate(v){let w=Ft(v.metadata,i.collectionKey),S=Tg(i.input.index,w.length,i.collectionKey),E=w[S];return Sg(E,"edited"),w[S]={...E,text:l,edited_at:R()},v.metadata[i.collectionKey]=w,{changedFields:[i.collectionKey]}}})}catch(v){yi(v,i.conflictGuidance)}let y=Ft(h.item,i.collectionKey);return cs(h.item.id,i.collectionKey,y,a,t.includeMeta===!0,{action:"edit",entryIndex:i.input.index,entry:y[i.input.index-1]},t.fullHistory===!0)}let u,_=0;try{u=await le({pmRoot:r,settings:s,id:e,op:i.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(g){let h=gA(g,i.collectionKey,c,l,t.ifAbsent===!0,i.createEntry);return _=h.entryIndex,{changedFields:h.changedFields}}})}catch(g){yi(g,i.conflictGuidance)}let f=Ft(u.item,i.collectionKey);return cs(u.item.id,i.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:_,entry:f[_-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Tg(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let i=n.replace(/s$/,""),r=`${i.charAt(0).toUpperCase()}${i.slice(1)}`,s=t===1?`1 ${i}`:`${t} ${n}`;throw new p(`${r} index ${e??"(missing)"} out of range (item has ${s})`,m.USAGE)}return e-1}function hA(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function cs(e,t,n,i,r,s,o=!1){let a=s===void 0||o?uA(n,s!==void 0&&o?void 0:i):s.entry===void 0?[]:[s.entry],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...s?.changedCount===void 0?{}:{changed:s.changedCount===1},...[r,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...i!==void 0?{limit:i}:{}}:{},...hA(t,s,c)}}(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]="f366dd76-73b4-55c4-8c63-2913d0a0c380")}catch{}})();async function Cg(e,t,n){return[...await Promise.resolve().then(()=>on(Qt(e,t),t)).catch(()=>[])].reverse().find(s=>s.patch.some(o=>o.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${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]="f2901314-4044-5a91-ad72-6b4bebde16c2")}catch{}})();var Ig="no_available_next_item";function yA(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function ic(e,t,n,i={}){let r=x(process.cwd(),n.path);await P(r);let s=await I(r),o=K(s.schema),a=G(i.author,s.author_default),c=To(a),d=null,l=!1,u=[],_=await le({pmRoot:r,settings:s,id:e,op:"claim",author:a,message:i.message,force:t,skipNoop:!0,async mutate(f){let h=f.metadata.assignee??"",y=f.metadata.claim_principal?.trim()||h;if(d=h.trim().length>0?h:null,sr(f.metadata.status,o)&&!t)throw new p(`Cannot claim terminal item ${f.metadata.id} without --force`,m.CONFLICT);if(d!==null&&y!==c){if(i.ifAvailable===!0)return l=!0,u.push(`claim_skipped_held_by:${d}`),{changedFields:[]};if(!t){let E=await Cg(r,f.metadata.id,h);throw new p(`Item ${f.metadata.id} is already ${E}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}u.push(`claim_takeover:${d}->${a}`)}let w={assignee:a,claim_principal:c},S=["assignee","claim_principal"].filter(E=>f.metadata[E]!==w[E]);return Object.assign(f.metadata,w),{changedFields:S,warnings:u}}});return l||await I_({pmRoot:r,settings:s,principal:c,itemId:_.item.id}),{item:_.item,changed_fields:_.changedFields,claimed_by:l&&d!==null?d:a,previous_assignee:d,forced:t,...l?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function L1(e,t,n={},i={}){let r=vA(n.maxAttempts),s=await I(x(process.cwd(),t.path)),o={...n,author:G(n.author,s.author_default)},a=await R_({...i,callerAuthor:o.author,limit:String(r)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return wA(c.slice(0,r),e,t,o)}function vA(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new p("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function wA(e,t,n,i={},r=ic){let s=0;for(let a of e){s+=1;try{let c=await r(a.id,t,n,i),d={...c,recommendation:a,attempts:s,available:!0};if(!c.skipped)return d}catch(c){if(!yA(c))throw c}}if(i.ifAvailable===!0)return{available:!1,item:null,claimed_by:G(i.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[Ig]};let o=s===0;throw new p(o?"No actionable items matched the selection filters":"No actionable item remained available to claim",o?m.NOT_FOUND:m.CONFLICT,{code:Ig,why:o?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[o?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function rc(e,t,n,i={}){let r=x(process.cwd(),n.path);await P(r);let s=await I(r),o=G(i.author,s.author_default),a=To(o),c=i.ownershipReleaseBypass===!0,d=null,l;try{l=await le({pmRoot:r,settings:s,id:e,op:"release",author:o,message:i.message,force:t,bypassAssigneeConflict:c,mutate(f){return d=f.metadata.assignee??null,!d&&!f.metadata.claim_principal?{changedFields:[]}:(delete f.metadata.assignee,delete f.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(f){yi(f,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await x_({pmRoot:r,principal:a,itemId:l.item.id});let u=K(s.schema),_=Eo(l.item.status,u)===Eo(u.in_progress_status,u);return{item:l.item,released_by:o,changed_fields:l.changedFields,previous_assignee:d,forced:t,..._?{warnings:["released_unclaimed_in_progress"],suggestions:[`${l.item.id} remains ${l.item.status} and unclaimed. If work is paused, run pm release ${l.item.id} --pause to move it to ${u.open_status}.`]}:{}}}(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]="e63a8049-309b-57f2-ba48-cd0a550c11ab")}catch{}})();var P1=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function bA(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let i=n.value?.trim();if(i)return{closeReason:i,source:n.source}}return{source:"none"}}function Rg(e,t){return sc(e,t,{operation:"close"})}function sc(e,t,n){let i=bA(e);if(!t||i.closeReason!==void 0)return i;let r=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new p("Close reason text is required because governance.require_close_reason is enabled",m.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:r,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function Og(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",i=e.blocked_by!==void 0,r=e.dependencies??[],s=r.filter(d=>d.kind==="blocked_by"),o=e.blocked_reason!==void 0,a=[];if(i&&(delete e.blocked_by,a.push("blocked_by")),o&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let d=r.filter(l=>l.kind!=="blocked_by");d.length>0?e.dependencies=d:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...s.map(d=>d.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[t.orderingEdges==="preserve"?`closed_preserved_predecessors:${e.id}:${c.join(",")}`:`closed_removed_predecessors:${e.id}:${c.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]="49e375b7-49a8-5b6f-89c8-be70d334b78f")}catch{}})();var kA=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function SA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new p(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,m.USAGE)}function Lg(e){let t=[];for(let n of kA){let i=e[n.key];(typeof i!="string"||i.trim().length===0)&&t.push(n)}return t}function Ng(e,t,n={}){let i=Lg(e);if(i.length===0)return;let r={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},s=i.map(a=>`--${a.key.replaceAll("_","-")}`),o=["--pm-path",t,"update",e.id,...i.flatMap((a,c)=>[s[c],r[a.key]?.trim()||"<value>"])];return{missing:s,suggested_retry:at(o),suggested_retry_args:o}}async function EA(e,t,n){let i=new Set,r=t;for(;typeof r=="string"&&r.trim().length>0;){let s=r.trim();if(s===n)return!0;if(i.has(s))return!1;i.add(s),r=(await e(s))?.duplicate_of}return!1}function TA(e){return typeof e!="string"||e.trim().length===0}async function AA(e,t,n,i){let r=n?.trim();if(!r)return;if(r===i)throw new p("An item cannot be closed as a duplicate of itself.",m.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=$(t,M()),o=new Map,a=async d=>{if(o.has(d))return o.get(d)??null;let l=await Q(e,d,t.id_prefix,t.item_format,s.type_to_folder);if(!l)return o.set(d,null),null;let{document:u}=await be(l,{schema:t.schema});return o.set(d,u.metadata),u.metadata},c=await a(r);if(!c)throw new p(`Duplicate target "${r}" was not found. Create or locate the canonical item first.`,m.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${i} "Duplicate of ${r}" --duplicate-of ${r}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await EA(a,c.duplicate_of,i))throw new p(`Circular duplicate reference detected. Target "${r}" points back to "${i}".`,m.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new p(`Duplicate target "${r}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,m.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${i} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function CA(e,t,n){return e.filter(i=>i.parent===t&&!de(i.status,n)).map(i=>i.id).sort((i,r)=>i.localeCompare(r))}function IA(e,t,n){let i=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),r=w_(e),s=t.trim().toLowerCase(),o=n.blocked_statuses;return e.filter(a=>o.has(a.status)).map(a=>({item:a,blockerIds:r.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let d=i.get(c);return d!==void 0&&de(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function xA(e,t,n,i,r,s){let o=IA(n,i,s),a=[];for(let c of o)try{let d=await le({pmRoot:e,settings:t,id:c.id,op:"update",author:r,message:`Auto-unblocked after blocker ${i} closed`,mutate(l){let u=l.metadata.dependencies??[],_=u.filter(g=>{let h=g.id.trim().toLowerCase();return g.kind!=="blocked_by"||!c.blocker_ids.includes(h)});l.metadata.status=s.open_status,delete l.metadata.blocked_by,delete l.metadata.blocked_reason,l.metadata.unblock_note=`Auto-unblocked after blocker ${i} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,_.length>0?l.metadata.dependencies=_:delete l.metadata.dependencies;let f=["status","blocked_by","blocked_reason","unblock_note"];return _.length!==u.length&&f.push("dependencies"),{changedFields:f}}});a.push(`auto_unblocked:${d.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(d){let l=d instanceof Error?d.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${l}`)}return a}function RA(e,t){let n=[],i=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:r,key:s}of i){if(typeof r!="string")continue;let o=r.trim();o.length!==0&&(e[s]=o,n.push(s))}return n}function OA(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],i=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:r,value:s}of i)TA(e[r])&&(e[r]=s,n.push(r));return n}function LA(e,t,n,i){let r=[];if(t!=="off"){let s=Lg(e);if(s.length>0){let o=s.map(a=>a.label);if(t==="strict"){let a=s.map(d=>`--${d.key.replaceAll("_","-")}`),c=["--pm-path",i,"update",e.id,...a.flatMap(d=>[d,"<value>"])];throw new p(`Cannot close item ${e.id}: missing ${o.join(", ")}. Populate fields or use --validate-close warn.`,m.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:at(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}r.push(`close_validation_missing_fields:${e.id}:${o.join(",")}`)}if(n.length>0){if(t==="strict")throw new p(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,m.USAGE);r.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return r}return n.length>0&&r.push(`closed_with_active_children:${e.id}:${n.join(",")}`),r}function NA(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function DA(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function MA(e,t){if(de(e.status,t.statusRegistry)&&!t.force)throw new p(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,m.CONFLICT,{recovery:Ng(e,t.pmRoot,t.options)});let n=RA(e,t.options),i=OA(e,t.duplicateOf),r=LA(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let o=["status","closed_at",...s?["completed_at"]:[],...NA(e,t.closeReason),...n];if(uu(e)&&(e.plan_mode="completed",o.push("plan_mode")),t.duplicateOf!==void 0){o.push("duplicate_of");for(let c of i)o.includes(c)||o.push(c)}o.push(...DA(e));let a=Og(e,t.lifecyclePolicy);return o.push(...a.changedFields),r.push(...a.warnings),{changedFields:o,...r.length>0?{warnings:r}:{}}}async function PA(e,t,n,i){let r=x(process.cwd(),i.path);await P(r);let s=await I(r),o=K(s.schema),a=G(n.author,s.author_default),c=$(s,M()).type_to_folder,d=await Q(r,e,s.id_prefix,s.item_format,c);if(!d)throw await Bn(r,e,s.id_prefix,c);let l=await AA(r,s,n.duplicateOf,d.id),u={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},_=Rg({explicit:t,duplicateOf:l,resolution:n.resolution,message:n.message},u.requireCloseReason).closeReason,f=SA(n.validateClose)??s.governance.close_validation_default,g=await ke(r,s.item_format,c,void 0,s.schema),h=CA(g,d.id,o),y=R(),v=n.completedAt===void 0?y:me(n.completedAt,new Date(y),"completed-at"),w=await le({pmRoot:r,settings:s,id:d.id,op:"close",author:a,message:n.message,force:n.force,mutate(E){return MA(E.metadata,{pmRoot:r,statusRegistry:o,force:n.force,options:n,duplicateOf:l,validateCloseMode:f,activeChildIds:h,closeReason:_,closedAt:y,completedAt:v,lifecyclePolicy:u})}}),S=f==="warn"?Ng(w.item,r):void 0;return{item:w.item,changed_fields:w.changedFields,...S?{recovery:S}:{},warnings:[...w.warnings,...await xA(r,s,g,d.id,a,o)]}}function ds(e,t,n,i){return PA(e,t,n,i)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="874a21db-ed3b-5b4f-a913-bf87103172e7")}catch{}})();function Dg(e){return[...e].sort().join("\0")}function FA(e,t,n){let i=e.successors.get(t);i?i.push(n):e.successors.set(t,[n]);let r=e.predecessors.get(n);r?r.push(t):e.predecessors.set(n,[t])}function Mg(e,t,n,i,r){let s=t.resolve(r);if(s?.ordering!==!0)return;let o=s_(i),a=o===void 0?void 0:e.canonicalIds.get(o.toLowerCase());if(a===void 0)return;let c=(s.precedence??"source_before_target")==="source_before_target";FA(e,c?n:a,c?a:n)}function $A(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},i=e.filter(r=>typeof r?.id=="string"&&r.id.trim().length>0);for(let r of i){let s=r.id.trim();n.canonicalIds.set(s.toLowerCase(),s)}for(let r of i){let s=r.id.trim();Mg(n,t,s,r.blocked_by,"blocked_by");for(let o of r.dependencies??[])typeof o!="object"||o===null||Mg(n,t,s,o.id,typeof o.kind=="string"?o.kind:"related")}for(let r of[n.successors,n.predecessors])for(let s of r.values())s.sort();return n}function UA(e,t){let n=new Set([t]),i=[t];for(;i.length>0;){let r=i.pop();for(let s of[e.successors,e.predecessors])for(let o of s.get(r)??[])n.has(o)||(n.add(o),i.push(o))}return n}function jA(e,t){let n=new Map;for(let i of t){let r=(e.successors.get(i)??[]).filter(s=>t.has(s));r.length>0&&n.set(i,r)}return n}function Pg(e,t,n){let i=$A(e,t),r=i.canonicalIds.get(n.trim().toLowerCase());if(r===void 0)return{cycles:[],successors:new Map,canonical:n};let s=jA(i,UA(i,r));return{cycles:c_(s).filter(o=>o.includes(r)),successors:s,canonical:r}}function GA(e,t,n){let i=new Set(t),r=i.has(n)?n:t[0];if(e.get(r)?.includes(r))return[r,r];for(let s of e.get(r)??[]){if(!i.has(s))continue;let o=qA(e,i,r,s);if(o)return o}return[...t,t[0]]}function qA(e,t,n,i){let r=[[i]],s=new Set([n,i]);for(;r.length>0;){let o=r.shift(),a=o.at(-1);for(let c of e.get(a)??[]){if(c===n)return[n,...o,n];!t.has(c)||s.has(c)||(s.add(c),r.push([...o,c]))}}}function ls(e,t,n){let i=Se(),r=Pg(e,i,n),s=Pg(t,i,n),o=new Set(r.cycles.map(Dg)),a=new Set(zo(e,void 0,i).map(d=>`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`));return[...zo(t,void 0,i).filter(d=>d.holder_id.toLowerCase()===n.trim().toLowerCase()&&!a.has(`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`)).map(d=>`ordering_storage_contradiction_created:${d_(d)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...s.cycles.filter(d=>!o.has(Dg(d))).map(d=>`ordering_cycle_created:${GA(s.successors,d,s.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}(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]="4e54ed7b-3bab-51a2-912b-1284eaf8187a")}catch{}})();var us=1e6;function oc(e,t=us,n=.8,i=!1){let r=new Set,s=(l,u)=>{if(r.add(`${l}:${u}`),r.size>t)throw new p(`Duplicate sweep exceeded ${t} candidate pairs; narrow it with statuses or since.`,m.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the duplicate query or increase its similarity threshold. No partial result was returned."})};if(i||n===0){for(let l=0;l<e.length;l+=1)for(let u=0;u<l;u+=1)s(u,l);return r}let o=new Map;for(let{prepared:l}of e)for(let u of l.tokens)o.set(u,(o.get(u)??0)+1);let a=new Map,c=new Map,d=new Map;for(let[l,{prepared:u}]of e.entries()){let _=[...u.tokens].sort((h,y)=>o.get(h)-o.get(y)||h.localeCompare(y)),f=_.length-Math.ceil(n*_.length-1e-12)+1,g=[{index:a,keys:[u.normalized],lengthFilter:!1},{index:c,keys:n<=.99?u.issueCodes:[],lengthFilter:!1},{index:d,keys:_.length===0?[""]:_.slice(0,f),lengthFilter:!0}];for(let h of g)KA(e,l,h,n,s)}return r}function KA(e,t,n,i,r){let s=e[t].prepared.tokens.length;for(let o of n.keys){let a=n.index.get(o)??[];for(let c of a){let d=e[c].prepared.tokens.length;n.lengthFilter&&Math.min(d,s)/Math.max(d,s)+1e-12<i||r(c,t)}a.push(t),n.index.set(o,a)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d07624c-8663-5aba-8018-1b2c47997bef")}catch{}})();var zA=3,Fg=20,WA=.8,BA=100,$g=1e3;function Ug(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`,`likely_duplicate_recovery:${e.recovery.action}:${e.recovery.item_id}`]}async function VA(e,t){let n=e.items[0],i=x(t.cwd??process.cwd(),t.pmRoot),r=K((await I(i)).schema);return de(n.status,r)?{action:"reopen",item_id:n.id,command:`pm item reopen ${n.id} "<recurrence reason>"`,args:["item","reopen",n.id,"<recurrence reason>"]}:{action:"reuse",item_id:n.id,command:`pm get ${n.id} --full`,args:["get",n.id,"--full"]}}function ac(e){let t=e.limit??zA,n=e.threshold??WA;if(!Number.isSafeInteger(t)||t<0||t>Fg)throw new p(`Similarity limit must be an integer from 0 to ${Fg}.`,m.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new p("Similarity threshold must be a number from 0 to 1.",m.USAGE);return{limit:t,threshold:n}}function jg(e){let t=e.limit??BA;if(!Number.isSafeInteger(t)||t<0||t>$g)throw new p(`Duplicate cluster limit must be an integer from 0 to ${$g}.`,m.USAGE);let n=e.since===void 0?void 0:new Date(e.since);if(n&&Number.isNaN(n.getTime()))throw new p("Duplicate cluster --since must be a valid ISO timestamp.",m.USAGE);return{limit:t,since:n}}async function HA(e,t){let n=x(e.cwd??process.cwd(),e.pmRoot),i=await I(n),r=$(i),s=e.statuses?.map(u=>u.trim().toLowerCase()).filter(Boolean);if(e.statuses!==void 0&&s?.length===0)throw new p("Duplicate cluster statuses must include at least one lifecycle status or all.",m.USAGE);let o=K(i.schema),a=s?.map(u=>{if(u==="all")return u;let _=se(u,o);if(!_)throw new p(`Unknown duplicate-cluster status "${u}". Allowed: all, ${o.definitions.map(f=>f.id).join(", ")}.`,m.USAGE);return _}),c=a?.includes("all")===!0;if(c&&a?.some(u=>u!=="all"))throw new p('The "all" status cannot be combined with other statuses.',m.USAGE);let d=c?void 0:a,l=d?new Set(d):void 0;return{items:(await ke(n,i.item_format,r.type_to_folder,void 0,i.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())),statuses:d}}var _G={buildDuplicateClusters:qg,collectDuplicateCandidatePairs:oc,createDuplicateUnionFind:Gg};function Gg(e){let t=Array.from({length:e},(i,r)=>r);return{parent:t,findRoot:i=>{let r=i;for(;t[r]!==r;)r=t[r];for(;t[i]!==i;){let s=t[i];t[i]=r,i=s}return r}}}function YA(e,t,n,i){let r=[];for(let s of t){let[o,a]=s.split(":").map(u=>Number.parseInt(u,10)),c=No(e[o].prepared,e[a].prepared);if(c.score<n)continue;let d=i.findRoot(o),l=i.findRoot(a);d!==l&&(i.parent[l]=d),r.push({left_id:e[o].item.id,right_id:e[a].item.id,...c})}return r}function qg(e,t,n,i){let r=new Map;for(let a of e.keys()){let c=n.findRoot(a),d=r.get(c)??[];d.push(a),r.set(c,d)}let s=new Map(e.map(({item:a},c)=>[a.id,n.findRoot(c)])),o=new Map;for(let a of t){let c=s.get(a.left_id),d=o.get(c)??[];d.push(a),o.set(c,d)}return[...r.values()].filter(a=>a.length>1).map(a=>{let c=(o.get(n.findRoot(a[0]))??[]).sort((d,l)=>l.score-d.score||d.left_id.localeCompare(l.left_id)||d.right_id.localeCompare(l.right_id));return{id:e[a[0]].item.id,items:a.map(d=>{let l=e[d].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((a,c)=>c.max_score-a.max_score||a.id.localeCompare(c.id)).slice(0,i)}function XA(e,t,n,i,r){return t.filter(s=>!n.has(s.id)).map(s=>({id:s.id,title:s.title,status:s.status,type:s.type,...Lo(e,s.title)})).filter(s=>s.score>=i).sort((s,o)=>o.score-s.score||s.id.localeCompare(o.id)).slice(0,r)}async function JA(e,t={}){let n=e.title.trim();if(n.length===0)throw new p("Similarity candidate title must not be empty.",m.USAGE);let{limit:i,threshold:r}=ac(t),s=x(t.cwd??process.cwd(),t.pmRoot),o=await I(s),a=$(o),c=await gr(s,Object.values(a.type_to_folder)),d=Ro(n),l=c&&d.length>0?await eu({pmRoot:s,expectedSourceCursor:c.source_cursor,query:d.map(f=>`"${f.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(i*10,50)}):null,u=l===null?await ke(s,o.item_format,a.type_to_folder,void 0,o.schema):l.items,_=XA(n,u,new Set(e.excludeIds??[]),r,i);return{items:_,count:_.length,threshold:r,source:l?"persistent_index":"metadata_fallback"}}function QA(e,t={}){let{threshold:n}=ac({...t,limit:void 0}),{limit:i}=jg(t),r=new Set;for(let l of e){if(!l.id.trim()||r.has(l.id))throw new p("Duplicate analysis requires unique non-empty item ids.",m.USAGE);r.add(l.id)}let s=[...e].sort((l,u)=>l.id.localeCompare(u.id)).map(l=>({item:l,prepared:Oo(l.title)})),o=oc(s,us,n,t.exhaustive===!0),a=Gg(s.length),c=YA(s,o,n,a),d=qg(s,c,a,i);return{clusters:d,count:d.length,threshold:n,cost:{item_count:s.length,algorithm:t.exhaustive===!0||n===0?"exhaustive":"prefix_exact",possible_pairs:s.length*(s.length-1)/2,pair_limit:us,recall_guarantee:"exact",candidate_pairs:o.size,scored_pairs:o.size}}}async function Kg(e={}){ac({...e,limit:void 0});let{since:t}=jg(e),{items:n,statuses:i}=await HA(e,t);return{...QA(n,e),source:"metadata_scan",filters:{statuses:i??null,since:e.since??null}}}async function cc(e,t){if(t.mode==="off")return;let n=await JA(e,t);if(n.count===0)return;let i=await VA(n,t),r=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!r){let s=n.items.map(a=>`${a.id} (${a.status}): ${a.title}`).join("; "),o=i.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new p(`Likely duplicate item(s) found: ${s}. ${o} or pass --allow-duplicate with explicit intent.`,m.CONFLICT,{code:"likely_duplicate",required:`${o}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:i.command,suggested_retry_args:i.args}})}return{mode:t.mode,bypassed:r,result:n,recovery:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="70971b2a-c025-50a8-918f-871fc8adfd2a")}catch{}})();var _t=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],ZA=new Set(_t);function zg(e){return Qi(e,_t)}function ms(e,t){let n={},i=[];for(let[r,s]of Object.entries(e)){let o=r.toLowerCase();if(!ZA.has(o)){i.push(r);continue}if(Object.hasOwn(n,o))throw new p(`${t} provides key "${r}" more than once after case normalization`,m.USAGE);n[o]=s}if(i.length>0)throw new p(`${t} does not recognize key${i.length>1?"s":""} ${i.map(r=>`"${r}"`).join(", ")}. Allowed keys: ${_t.join(", ")}.`,m.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new p(`${t} command and cmd must match when both are provided`,m.USAGE);let{cmd:r,...s}=n;return{...s,command:s.command??r}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="800bdce7-d4d2-5702-9ceb-d83ac4a95fb0")}catch{}})();var jt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Xn,__,"FORCE_COLOR"]),fs=/^[A-Za-z_][A-Za-z0-9_]*$/,Ut=["schema","tracker","auto"],Wg=["source","isolated","snapshot"];function vi(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new p(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new p(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,m.USAGE);let o=r.slice(0,s).trim(),a=r.slice(s+1);if(!fs.test(o))throw new p(`${t} env_set key "${o}" is invalid`,m.USAGE);if(jt.has(o.toUpperCase()))throw new p(`${t} env_set key "${o}" is reserved for sandbox safety`,m.USAGE);i[o]=a}return Object.keys(i).length>0?i:void 0}function wi(e,t){if(!e)return;let n=Do(e,{separators:/[;,\n]/});if(n.length===0)throw new p(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let i of n){if(!fs.test(i))throw new p(`${t} env_clear key "${i}" is invalid`,m.USAGE);if(jt.has(i.toUpperCase()))throw new p(`${t} env_clear key "${i}" is reserved for sandbox safety`,m.USAGE)}return n}function gs(e,t,n){if(!e)return;let i=e.trim().toLowerCase();if(i==="true"||i==="1"||i==="yes")return!0;if(i==="false"||i==="0"||i==="no")return!1;throw new p(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function hs(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Ut.includes(n))return n;throw new p(`${t} pm_context_mode must be one of: ${Ut.join(", ")}`,m.USAGE)}function Gt(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Wg.includes(n))return n;throw new p(`${t} workspace_context_mode must be one of: ${Wg.join(", ")}`,m.USAGE)}function qt(e){if(!e)return;let t=Do(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Tn(e,t,n){let i=qt(e);if(!(!i||i.length===0)){for(let r of i)try{new RegExp(r,"m")}catch(s){throw new p(`${t} ${n} includes invalid regex "${r}": ${s instanceof Error?s.message:String(s)}`,m.USAGE)}return i}}function ys(e,t){if(!e)return;let n=_e(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new p(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function vs(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new p(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new p(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let o=r.slice(0,s).trim(),a=r.slice(s+1).trim();if(o.length===0||a.length===0)throw new p(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);i[o]=a}return Object.keys(i).length>0?i:void 0}function ws(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new p(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new p(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let o=r.slice(0,s).trim(),a=r.slice(s+1).trim();if(o.length===0||a.length===0)throw new p(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new p(`${t} assert_json_field_gte value for "${o}" must be numeric`,m.USAGE);i[o]=c}return Object.keys(i).length>0?i:void 0}var eC=new Set(_t);function bs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tC(e,t){let n={},i=[];for(let[r,s]of Object.entries(e)){let o=r.toLowerCase();if(!eC.has(o)){i.push(r);continue}if(Object.hasOwn(n,o))throw t(`provides key "${r}" more than once after case normalization`);n[o]=s}if(i.length>0)throw t(`does not recognize key${i.length>1?"s":""} ${i.map(r=>`"${r}"`).join(", ")}. Allowed keys: ${_t.join(", ")}.`);return n}function $t(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i!==void 0){if(typeof i!="string")throw n(`field "${t}" must be a JSON string`);return i}}function _s(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i===void 0)return;let r=typeof i=="string"?[i]:i;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=r.filter(o=>o.length>0);return s.length>0?s:void 0}function Bg(e,t,n){let i=_s(e,t,n);if(i){for(let r of i)try{new RegExp(r,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${r}": ${s instanceof Error?s.message:String(s)}`)}return i}}function ps(e,t,n){let i=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(i))throw n(`field "${t}" must be a finite number (or numeric string)`);return i}function nC(e,t){let n=e.timeout_seconds,i=e.timeout;if(n===void 0&&i===void 0)return;let r=n===void 0?void 0:ps(n,"timeout_seconds",t),s=i===void 0?void 0:ps(i,"timeout",t);if(r!==void 0&&s!==void 0&&r!==s)throw t("timeout and timeout_seconds must match when both are provided");let o=r??s;if(!Number.isInteger(o)||o<=0)throw t("timeout_seconds must be a positive integer");return o}function iC(e,t){let n=$t(e,"scope",t);if(n===void 0)return"project";if(!De.includes(n))throw t(`field "scope" must be one of: ${De.join(", ")}`);return n}function rC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!bs(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${r}" must be a string`);if(!fs.test(r))throw t(`field "env_set" key "${r}" is invalid`);if(jt.has(r.toUpperCase()))throw t(`field "env_set" key "${r}" is reserved for sandbox safety`);i[r]=s}return Object.keys(i).length>0?i:void 0}function sC(e,t){let n=_s(e,"env_clear",t);if(n){for(let i of n){if(!fs.test(i))throw t(`field "env_clear" key "${i}" is invalid`);if(jt.has(i.toUpperCase()))throw t(`field "env_clear" key "${i}" is reserved for sandbox safety`)}return n}}function oC(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i!==void 0){if(typeof i!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return i}}function aC(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let i=ps(n,"assert_stdout_min_lines",t);if(!Number.isInteger(i)||i<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return i}function cC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!bs(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(r.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${r}" must be a string, number, or boolean`);i[r]=String(s)}return Object.keys(i).length>0?i:void 0}function dC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!bs(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(r.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');i[r]=ps(s,`assert_json_field_gte.${r}`,t)}return Object.keys(i).length>0?i:void 0}function lC(e,t,n){let i=_=>new p(`${n} ${t} ${_}`,m.USAGE);if(!bs(e))throw i(`must be a JSON object with linked-test fields. Allowed keys: ${_t.join(", ")}.`);let r=tC(e,i),s=$t(r,"command",i),o=$t(r,"cmd",i);if(s!==void 0&&o!==void 0&&s!==o)throw i("command and cmd must match when both are provided");let a=s??o;if(a===void 0||a.trim().length===0)throw i('requires a non-empty "command" string');let c=$t(r,"path",i),d=$t(r,"pm_context_mode",i);if(d!==void 0&&!Ut.includes(d))throw i(`field "pm_context_mode" must be one of: ${Ut.join(", ")}`);let l=Gt($t(r,"workspace_context_mode",i),`${n} ${t}`),u=$t(r,"note",i);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:iC(r,i),timeout_seconds:nC(r,i),pm_context_mode:d,workspace_context_mode:l,env_set:rC(r,i),env_clear:sC(r,i),shared_host_safe:oC(r,"shared_host_safe",i),assert_stdout_contains:_s(r,"assert_stdout_contains",i),assert_stdout_regex:Bg(r,"assert_stdout_regex",i),assert_stderr_contains:_s(r,"assert_stderr_contains",i),assert_stderr_regex:Bg(r,"assert_stderr_regex",i),assert_stdout_min_lines:aC(r,i),assert_json_field_equals:cC(r,i),assert_json_field_gte:dC(r,i),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function Vg(e,t){let n=e.trim();if(n.length===0)throw new p(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let i;try{i=JSON.parse(n)}catch(s){throw new p(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,m.USAGE)}let r=Array.isArray(i)?i:[i];if(r.length===0)throw new p(`${t} array must include at least one linked-test entry object`,m.USAGE);return r.map((s,o)=>lC(s,r.length>1?`entry ${o+1}`:"entry",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]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var uC={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function mC(e){return uC[e]}function dc(e){return mC(e)!==void 0}(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]="4db3d1b3-68f3-5f74-b6f0-9847b3b00fc0")}catch{}})();var _C="hierarchy-integrity";async function ks(e){let t=e.required?await sn(e.pmRoot,_C,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await 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]="c45ead8e-c9ed-5b59-84e5-b8e077e84010")}catch{}})();function Ss(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Es(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ts(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Nd.includes(t))return t;let n=_e(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new p("Confidence must be an integer 0..100 or one of low|med|medium|high",m.USAGE);return n}function As(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new p("Regression must be one of true|false|1|0",m.USAGE)}(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]="add1928e-08d1-5ead-9a4e-0f1a9b6580fc")}catch{}})();var pC=new Set(["none","null"]);function Cs(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function qe(e){return e===void 0?!1:pC.has(e.trim().toLowerCase())}function Is(e,t,n){if(!qe(e))return;let i=n?` ${n}`:"";throw new p(`${t} no longer accepts "none" or "null".${i}`.trim(),m.USAGE)}function Ie(e,t,n){if(!e||e.length===0||!e.some(s=>qe(s)))return;let r=n?` ${n}`:"";throw new p(`${t} no longer accepts "none" or "null".${r}`.trim(),m.USAGE)}function xs(e,t){for(let n of t){let i=e[n.optionKey];if(!Array.isArray(i)||i.length===0)continue;if(!i.every(a=>typeof a=="string"))throw new p(`${n.valueFlag} entries must be strings.`,m.USAGE);let r=i;if(!r.some(a=>qe(a)))continue;if(r.filter(a=>!qe(a)).length>0)throw new p(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,m.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(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]="ca230957-d5a6-5f20-94b5-e1eeca8ca714")}catch{}})();var fC=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Hg(e,t,n,i){if(fC.has(t.trim().toLowerCase())||n!==i.open_status)return;let r=tn("in_progress",i);if(!(r===void 0||r===i.open_status))return{command:`pm claim ${e} --start`,to_status:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0562fd00-217b-5e1f-8004-df4574f8b796")}catch{}})();var lc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],uc=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],Yg=[...lc,...uc],Rs=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function Os(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let i of e.raw){let r=i.trim().toLowerCase();if(!r)throw new p("--unset values must not be empty",m.USAGE);if(qe(r))throw new p('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',m.USAGE);let s=e.resolveDefinition(r);if(!s)throw new p(`Unsupported --unset field "${i}". Supported fields: ${e.supportedFields}`,m.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function Ls(e,t,n){let i=e.trim().toLowerCase();if(!n)return;let r=n.command_to_fields?.get(t)??[];for(let s of r){if(s.allow_unset===!1)continue;let o=new Set;if(typeof s.key=="string"&&s.key.length>0&&o.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&o.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(o.add(s.cli_flag.replaceAll("-","_").toLowerCase()),o.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let a of s.cli_aliases)typeof a!="string"||a.length===0||(o.add(a.replaceAll("-","_").toLowerCase()),o.add(a.toLowerCase()));if(o.has(i))return{optionKey:s.key,metadataKey:s.metadata_key}}}(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]="49f970c3-e408-52d5-bb4d-8cea0c7f8ef4")}catch{}})();function Jg(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new p(`${t} must be one of true|false|1|0|yes|no`,m.USAGE)}function mc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function xe(e,t,n,i=n){if(!t.includes(e))throw new p(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,m.USAGE,{field:i,required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var Qg=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function gC(e,t){return t==="defined"?e!==void 0:!!e}function Xg(e,t,n){if(!gC(e,n))return;let i=_e(e,`event ${t}`);if(!Number.isInteger(i)||i<1)throw new p(`--event ${t} must be an integer >= 1`,m.USAGE);return i}function hC(e,t,n){let i=e?me(e,n,"event.recur_until"):void 0;if(i&&i<t)throw new p("--event recur_until must be at or after start",m.USAGE);return i}function yC(e){return Array.from(new Set(mc(e).map(t=>xe(t.toLowerCase(),Ud,"event weekday")))).sort((t,n)=>vo(t)-vo(n))}function vC(e){return Array.from(new Set(mc(e).map(t=>{let n=_e(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new p("--event recur_by_month_day values must be integers 1..31",m.USAGE);return n}))).sort((t,n)=>t-n)}function wC(e,t){return Array.from(new Set(mc(e).map(n=>me(n,t,"event.recur_exdates")))).sort((n,i)=>n.localeCompare(i))}function Zg(e,t,n,i){let r=e.recur_freq?.trim(),s=e.recur_interval?.trim(),o=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![r,s,o,a,c,d,l].some(S=>S!==void 0))return;if(!r)throw new p("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",m.USAGE);let _=xe(r.toLowerCase(),$d,"event recurrence frequency"),f=Xg(s,"recur_interval",i),g=Xg(o,"recur_count",i),h=hC(a,t,n),y=yC(c),v=vC(d),w=wC(l,n);return{freq:_,interval:f,count:g,until:h,by_weekday:y.length>0?y:void 0,by_month_day:v.length>0?v:void 0,exdates:w.length>0?w:void 0}}(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]="e2e87672-508a-5aef-b728-42e40544cf3c")}catch{}})();function bi(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new p(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,m.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function ki(e,t,n=Se()){for(let i of t??[])try{Qd(e,i.id,i.kind,n)}catch(r){throw new p(xd(r),m.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${i.id} (${i.kind}) violates the active relationship-kind policy`})}}async function eh(e,t){return(await be(e,{schema:t})).document.metadata.created_at}async function bC(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await Q(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:eh(n,t.schema)}function kC(e){let t=e.registry.require(e.dependency.kind);return new p(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,m.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function SC(e){let t=e.dependencies.filter(r=>e.registry.resolve(r.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(r.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:r,located:s})=>s===null?[]:[[r,s]])),i=new Map(await Promise.all([...new Set(t.map(({id:r})=>r))].map(async r=>[r,await eh(n.get(r),e.context.schema)])));for(let r of e.holders){let s=await bC(r,e.context);if(s!==void 0)for(let o of t){let a=i.get(o.id),c=Date.parse(s),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw kC({holder:r,dependency:o,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function Ns(e){let t=e.registry??Se(),n=(e.dependencies??[]).filter(o=>!Qm(o.source_kind)),i=[...new Set(n.map(o=>o.id))],r=await Promise.all(i.map(async o=>({target:o,located:await Q(e.pmRoot,o,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=r.filter(({located:o})=>o===null).map(({target:o})=>o).sort((o,a)=>o<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new p(`Dependency target${s.length===1?"":"s"} not found: ${s.join(", ")}`,m.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:s,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${s.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await SC({dependencies:n,missingTargets:s,resolutions:r,holders:e.holders??[],registry:t,context:e}),s.map(o=>`dependency_target_unresolved:${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]="ae7fdf9b-e2d5-511e-90db-cf0bc121628d")}catch{}})();var th="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",EC="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",TC=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,AC=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,ih=1e3,_c=60*ih,CC=60*_c;function nh(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new p(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,m.USAGE);return n.toISOString()}function IC(e,t){let n=new Date(e),i=t.trim(),r=TC.exec(i);if(r){let a=r[1]==="-"?-1:1,c=Number.parseInt(r[2],10)*a;return nh(n.getTime()+c*_c,i)}let s=AC.exec(i);if(s){let[,a,c,d,l]=s;if(c||d||l){let _=a==="-"?-1:1,f=Number.parseInt(c??"0",10),g=Number.parseInt(d??"0",10),h=Number.parseInt(l??"0",10),y=f*CC+g*_c+h*ih;return nh(n.getTime()+_*y,i)}}let o=i.startsWith("+")||i.startsWith("-")?i:`+${i}`;return me(o,n,"event.duration")}function rh(e,t,n,i){if(t&&n)throw new p(EC,m.USAGE);if(n){let s=IC(e,n);if(s<e)throw new p(th,m.USAGE);return s===e?void 0:s}if(!t)return;let r=me(t,i,"event.end");if(r<e)throw new p(th,m.USAGE);if(r!==e)return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dfce9924-8453-5ded-a5df-47477caa9fe7")}catch{}})();var xC=["at","date","text","title"],RC=["start","date","end","duration","title","description","location","timezone","all_day",...Qg],OC=["key","value"];function sh(e,t){return t==="trimmed"?e?.trim():e}function LC(e,t){return t==="defined"?e!==void 0:!!e}function Ds(e,t,n){return e.map(i=>{let r=J(i,"--reminder");he(r,"--reminder",xC);let s=sh(r.at??r.date,n.valueMode),o=sh(r.text??r.title,n.valueMode);if(!s||!o)throw new p("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",m.USAGE);let a=o.trim();if(!a)throw new p("--reminder text must not be empty",m.USAGE);return{at:me(s,t,"reminder.at"),text:a}})}function Ms(e,t,n){return e.map(i=>{let r=J(i,"--event");he(r,"--event",RC);let s=(r.start??r.date)?.trim();if(!s)throw new p("--event requires start=<iso|relative> or date=<iso|relative>",m.USAGE);let o=me(s,t,"event.start"),a=r.end?.trim(),c=r.duration?.trim(),d=rh(o,a,c,t),l=r.title,u=r.description,_=r.location,f=r.timezone,g=l?.trim(),h=u?.trim(),y=_?.trim(),v=f?.trim(),w=[["title",l,g],["description",u,h],["location",_,y],["timezone",f,v]];for(let[A,k,b]of w)if(k!==void 0&&!b)throw new p(`--event ${A} must not be empty`,m.USAGE);let S=r.all_day?.trim(),E=Zg(r,o,t,n.recurrenceEmptyNumericGuard),T=LC(S,n.allDayEmptyGuard)?Jg(S,"--event all_day"):void 0;return{start_at:o,end_at:d,title:g,description:h,location:y,all_day:T,timezone:v,recurrence:E}})}function Ps(e){let t={};for(let n of e){let i=n.trim();if(i.length===0)throw new p("--type-option values must not be empty",m.USAGE);let r,s;if(i.includes(",")||i.includes(`
|
|
9
|
-
`)||i.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(i)){let a=J(i,"--type-option");he(a,"--type-option",OC),r=a.key?.trim(),s=a.value?.trim()}else{let a=i.indexOf("="),c=i.indexOf(":"),d=a;if(a<=0&&c>0&&(d=c),d<=0||d===i.length-1)throw new p("--type-option requires key=value or key=<name>,value=<value> entries",m.USAGE);r=i.slice(0,d).trim(),s=i.slice(d+1).trim()}if(!r||!s)throw new p("--type-option requires key and value",m.USAGE);t[r]=s}return Object.fromEntries(Object.entries(t).sort((n,i)=>n[0].localeCompare(i[0])))}(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]="ad3f992c-db2e-5276-a8ae-5d5d4ec8ae68")}catch{}})();var NC=["strict","progressive"],DC=["lightweight"],dh=new Set(["Reminder","Meeting","Event"]),MC=new Set(["author","created_at","text"]),fc=[...Yg,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...Rs],PC=(()=>{let e=new Map;for(let t of fc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Fs=new Map(fc.map(e=>[e.optionKey,e.canonical])),FC=fc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function $C(e,t){let n=se(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new p(`Invalid status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n}function UC(e,t){let n=e.default_status;if(n!==void 0){let i=se(n,t);if(i)return i}return t.open_status}function pc(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`Invalid created_at timestamp "${e}"`,m.USAGE);return new Date(n).toISOString()}var jC=Cs();function lh(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=r=>{let s=t.unset?[...t.unset]:[];s.includes(r)||s.push(r),t.unset=s};qe(t.template)&&(t.template=void 0);let i=new Set([...Fs.keys(),"rank"]);for(let r of i){let s=t[r];if(typeof s!="string"||!qe(s))continue;let o=r==="rank"?"order":Fs.get(r)??r;n(o),t[r]=void 0}return Pe(e,xs(t,jC))}function ye(e){if(e!==void 0)return e}function GC(e,t){return Os({raw:e,supportedFields:FC,resolveDefinition:n=>PC.get(n)??Ls(n,"create",t)})}var oh=["id","kind","type","author","created_at","source_kind"],$s=["path","scope","note"];function qC(e,t,n,i){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let o=s.trim(),a=Us(o,oh);bi(o,a);let c=a?J(s,"--dep"):{id:o,kind:"related"};a&&he(c,"--dep",oh);let d=ye(c.id),l=KC(ye(c.kind??c.type));if(!d||!l)throw new p("--dep requires id and kind, or a bare item id to create a related dependency",m.USAGE);if(d.trim().toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,m.USAGE);let u=Vn(ye(c.source_kind)),_=ye(c.author);return{id:Hn(d,n,u),kind:xe(l,Pn,"dependency kind","kind"),created_at:pc(c.created_at,t),author:_??i,source_kind:u??"cli:create:dep",author_source:_?"asserted":"detected"}}),explicitEmpty:!1})}function KC(e){return typeof e=="string"?xt(e)??e.trim():e}function Us(e,t){return Qi(e,t)?!0:Zt(e)}function zt(e,t,n,i){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Ie(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(o=>{let a=o.trim(),c=()=>{if(a.length===0)throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:n,author:i,text:a}},d;try{d=J(o,e)}catch(_){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw _}if(Object.keys(d).filter(_=>!MC.has(_)).length>0)return{created_at:pc(d.created_at,n),author:ye(d.author)??i,text:a};let u=d.text??"";if(u==="")throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:pc(d.created_at,n),author:ye(d.author)??i,text:u}}),explicitEmpty:!1})}function gc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let i=n.trim(),r=Us(i,$s);jn(i,"--file","file path",r);let s=r?J(n,"--file"):{path:i};if(r&&he(s,"--file",$s),!s.path)throw new p("--file requires path=<value> or a bare file path",m.USAGE);return{path:s.path,scope:xe(s.scope??"project",De,"file scope"),note:ye(s.note)}}),explicitEmpty:!1})}function hc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let i=n.trim(),r=Us(i,_t);jn(i,"--test","test command",r);let s=r?ms(J(n,"--test"),"--test"):{command:i},o=ye(s.command),a=ye(s.path);if(!o)throw new p("--test requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);let c=ye(s.timeout_seconds),d=ye(s.timeout);if(c&&d&&c!==d)throw new p("--test timeout and timeout_seconds must match when both are provided",m.USAGE);let l=c??d;return{command:o,path:a,scope:xe(s.scope??"project",De,"test scope"),timeout_seconds:l?_e(l,"timeout_seconds"):void 0,pm_context_mode:hs(s.pm_context_mode,"--test"),workspace_context_mode:Gt(s.workspace_context_mode,"--test"),env_set:vi(s.env_set,"--test"),env_clear:wi(s.env_clear,"--test"),shared_host_safe:gs(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:qt(s.assert_stdout_contains),assert_stdout_regex:Tn(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:qt(s.assert_stderr_contains),assert_stderr_regex:Tn(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:ys(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:vs(s.assert_json_field_equals,"--test"),assert_json_field_gte:ws(s.assert_json_field_gte,"--test"),note:ye(s.note)}}),explicitEmpty:!1})}function yc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let i=n.trim(),r=Us(i,$s),s=r?J(n,"--doc"):{path:i};if(r&&he(s,"--doc",$s),!s.path)throw new p("--doc requires path=<value> or a bare doc path",m.USAGE);return{path:s.path,scope:xe(s.scope??"project",De,"doc scope"),note:ye(s.note)}}),explicitEmpty:!1})}function zC(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Ds(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function WC(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--event","Use --clear-events to clear linked events."),{values:Ms(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function BC(e,t,n,i=[]){let r=[...Ed.filter(s=>e[s]!==void 0),...i.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(r))}function VC(e,t){let n=e??"";if(t.length===0)return n;let i=`explicit_unset=${t.join(",")}`;return n?`${n} | ${i}`:i}function ah(e,t,n){let i=Fn("create",e);if(!i)throw new p(`Unsupported ${n} entry "${e}" for type "${t}"`,m.CONFLICT);return i}function HC(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function uh(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function YC(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let i of e.required_create_fields)n.add(ah(i,e.name,"required_create_fields"));for(let i of e.required_create_repeatables)n.add(ah(i,e.name,"required_create_repeatables"));return n}function XC(e,t,n,i){for(let r of e)if(!(!uh(t,r)&&!n.has(r)))throw new p(`Option ${Ee("create",r)} is disabled for type "${i}" by command_option_policies`,m.USAGE)}function JC(e,t,n){if(t!=="strict")return;let i=e.filter(s=>n.has(s)&&!dc(s));if(i.length===0)return;let r=[...new Set(i.map(s=>Ee("create",s)))].sort((s,o)=>s.localeCompare(o));throw new p(`Strict create mode requires concrete values for ${r.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,m.USAGE)}function QC(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Ps(e),explicitEmpty:!1})}async function ZC(e){return await nr(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function eI(e){return Rt(e)?await ZC(e):e}function tI(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new p(`Invalid --create-mode value "${e}". Allowed: ${NC.join(", ")}`,m.USAGE)}function nI(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new p("--schedule-preset must not be empty",m.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new p(`Invalid --schedule-preset value "${e}". Allowed: ${DC.join(", ")}`,m.USAGE)}function iI(e,t,n){let i=tI(e,n);if(t===void 0)return i;if(typeof e=="string"&&e.trim().length>0&&i==="strict")throw new p("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",m.USAGE);return"progressive"}function rI(e,t,n,i){let r=e.name,s=HC(t),o=YC(e,n),a=Jt(e,"create",o);if(a.errors.length>0)throw new p(a.errors.join("; "),m.CONFLICT);XC(a.disabled,s,i,r),JC(a.required,n,i);let c=l=>l==="status"&&e.default_status!==void 0||i.has(l)&&dc(l)?!0:uh(s,l),d=a.required.filter(l=>!c(l));return[...new Set(d.map(l=>Ee("create",l)))].sort((l,u)=>l.localeCompare(u))}var mh=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function sI(e,t){let n=[];for(let i of e){let r=i.match(mh);r&&r[2]===t&&n.push(r[1])}return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}function oI(e,t){return e.filter(n=>{let i=n.match(mh);return!i||i[2]!==t})}function aI(e,t,n,i){let r=oI(e,t);if(r.length===0)return;let s=_h(n,[],[],i.open_status);throw new p(r.join("; "),m.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function cI(e,t){let i=e.options.find(r=>r.key===t)?.values[0];return typeof i=="string"&&i.trim().length>0?i:"<value>"}function dI(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function _h(e,t,n,i){let r=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],o=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of o)a.has(c)||(r.push(...dI(c,e.name,i)),a.add(c));for(let c of n){let d=cI(e,c);r.push("--type-option",`${c}=${d}`)}return r.join(" ")}function vc(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new p("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",m.USAGE):new p('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',m.USAGE):new p(`Missing required option ${t}`,m.USAGE);return n}function lI(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=Array.isArray(r)?[...r]:r;for(let[i,r]of Object.entries(t))r!==void 0&&(n[i]=Array.isArray(r)?[...r]:r);return n}function uI(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function mI(){let e=M();return e?e.commands.some(t=>t.action==="templates-show"||uI(t.command)==="templates show"):!1}function _I(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new p(`Templates package returned invalid payload for template "${t}". Expected an options object.`,m.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new p(`Templates package returned invalid options for template "${t}".`,m.GENERIC_FAILURE);let i={};for(let[r,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){i[r]=s;continue}if(Array.isArray(s)&&s.every(o=>typeof o=="string")){i[r]=[...s];continue}throw new p(`Templates package returned unsupported option value for "${r}" in template "${t}".`,m.GENERIC_FAILURE)}return i}async function pI(e,t,n){if(!mI())throw new p("--template requires the templates package. Install it first (for example: pm install templates --project).",m.USAGE);let i=await ol({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!i.handled){let r=i.warnings.length>0?` (${i.warnings.join(", ")})`:"";throw new p(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${r}`,m.USAGE)}return _I(i.result,e)}function V(e,t,n){return e.has(t)||n===void 0?void 0:ye(n)}function Kt(e,t,n,i){return e.has(t)||n===void 0?void 0:i(n)}var fI=new Set(["milestone","meeting","reminder","event"]);function ph(e,t,n,i){let r=t!==void 0,s=n!==void 0&&n.length>0,o=i!==void 0&&i.length>0;return fI.has(e.toLowerCase())&&!r&&!s&&!o}function gI(e,t,n,i,r){let s=[];return e.toLowerCase()==="event"&&(r===void 0||r.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),ph(e,n,i,r)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function hI(e,t,n,i){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let r=await vl(i);return r===void 0?{parent:e,parentSource:void 0}:{parent:r,parentSource:"focus"}}async function yI(e,t,n,i,r,s){let o=br(lr(r),t.id_prefix);if(yr(o))return{parent:o,warnings:[]};if(mr(i,o,t.id_prefix),await Q(e,o,t.id_prefix,t.item_format,n.type_to_folder))return{parent:o,warnings:[]};let c=yt(o,t.id_prefix);return{parent:o,warnings:ur(c,s).warnings}}async function vI(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await yI(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function wI(e){if(e.explicitId===void 0)return ql(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new p("--id must be a string",m.USAGE);let t=e.explicitId.trim();if(t.length===0||Kl(t))throw new p("--id must not be empty or use a placeholder token",m.USAGE);let n=yt(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new p("--id must contain only letters, numbers, and dashes after normalization",m.USAGE);return n}function ch(e,t,n,i,r){let s=V(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let o=pr(i,s,r);return{value:o.value,warnings:o.warnings}}async function bI(e){let{pmRoot:t,settings:n,typeRegistry:i,statusRegistry:r,blockedBy:s,status:o,statusExplicit:a,nowValue:c,author:d}=e,l=e.dependencyValues;if(s===void 0)return{dependencyValues:l,status:o};let u=yt(s,n.id_prefix),_=await Q(t,u,n.id_prefix,n.item_format,i.type_to_folder);if(!_)return{dependencyValues:l,status:o};if((l??[]).some(h=>h.id===_.id&&h.kind==="blocked_by")||(l=[...l??[],{id:_.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:l,status:o};let g=r.blocked_statuses.has("blocked")?"blocked":[...r.blocked_statuses].sort((h,y)=>h.localeCompare(y))[0]??r.open_status;return{dependencyValues:l,status:g}}function kI(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let r=t.governance.create_default_type?.trim();if(r&&r.length>0&&rt(r,n)){e.type=r;return}rt("Task",n)&&(e.type="Task")}function SI(e,t){return e.options.filter(n=>Fn("create",n.key)===void 0).flatMap(n=>{let i=t[n.key];if(i===void 0)return[];if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")return[n];throw new p(`Template custom type option "${n.key}" must be a string, number, or boolean value`,m.USAGE)})}async function EI(e,t,n,i,r){let s=e,o=[];if(s.template!==void 0){let g=s.template.trim();if(g.length===0)throw new p("--template must not be empty. Omit --template to disable template usage.",m.USAGE);let h=await pI(g,t,n);s=lh(lI(h,s))}if(s.type===void 0&&kI(s,i,r),s.type===void 0)throw new p("Missing required option --type <value>",m.USAGE);let a=rt(s.type,r);if(!a){let g=zl(s.type),h=g?rt(g,r):void 0;if(h)o.push(`type_coercion:${s.type.trim()}:${h}`),s.type=h,a=h;else throw new p(fr(s.type,r.types,rr(n,i.schema)),m.USAGE)}let c=Bi(a,r);if(!c)throw new p(`Invalid type value "${s.type}"`,m.USAGE);let d=c.name,l=SI(c,s),u=l.map(g=>`${g.key}=${String(s[g.key])}`);if(u.length>0){s.typeOption=[...u,...s.typeOption??[]];for(let g of l)delete s[g.key]}let _=nI(s.schedulePreset);if(_!==void 0&&!dh.has(d))throw new p(`--schedule-preset ${_} is only supported for Reminder, Meeting, or Event types`,m.USAGE);let f=iI(s.createMode,_,i.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:d,schedulePreset:_,createMode:f,warnings:o}}function TI(e,t){let n=new Set(t.metadataKeys),i=new Set(t.optionKeys),r=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of r)if(s.enabled){if(s.values&&s.values.length>0)throw new p(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,m.USAGE);n.add(s.metadataKey),i.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:i}}function AI(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[i,r]of Object.entries(n)){if(!r||!t.optionKeys.has(i))continue;let s=Fs.get(i)??i;throw new p(`Cannot combine --unset ${s} with ${Ee("create",i)}`,m.USAGE)}}function CI(e){let t=(n,i)=>{let r=Fs.get(i),s=r?`Use --unset ${r} to clear this field.`:void 0;Is(n,Ee("create",i),s)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function II(e,t,n){for(let i of Object.keys(e))if(n.metadataKeys.has(i))throw new p(`Cannot combine --unset ${i.replaceAll("_","-")} with --field ${i}=...`,m.USAGE);for(let i of Object.keys(t.values??{}))if(n.metadataKeys.has(i))throw new p(`Cannot combine --unset ${i.replaceAll("_","-")} with its value flag`,m.USAGE)}var xI={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function RI(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:i,missingRequiredTypeOptionKeys:r,openStatus:s,type:o,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(g=>{let h=g.type==="boolean"?"<true|false>":g.type==="array"?"<json-array>":g.type==="object"?"<json-object>":g.type==="number"?"<number>":g.type==="string_array"||g.repeatable?"<value>":"<string>";return{example:`--${g.cli_flag} ${h}`,description:`--${g.cli_flag} maps to ${g.metadata_key} (${g.type}${g.repeatable?", repeatable":""})`}}),l=[_h(n,i,r,s),...d.map(g=>g.example)].join(" "),u=[`Run "pm create --help --type ${o}" for type-aware required option guidance.`,...t.filter(g=>g==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+o+").")];a==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),dh.has(o)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(g=>g.description).join("; ")}.`);let _=[...new Set(t.flatMap(g=>{let h=g.split(" ",1)[0],y=xI[h];return y?[y]:[]}))];_.length>0&&u.push(`If the truthful value is an empty collection, use ${_.join(", ")} instead of inventing metadata.`);let f=t.length===1?`Missing required option ${t[0]} for type "${o}"`:`Missing required options ${t.join(", ")} for type "${o}"`;throw new p(f,m.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${o}" in one invocation.`,examples:[..._.map(g=>`pm create --type ${o} ${g} ...`),l],nextSteps:u,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[..._,...t,"--create-mode progressive"]}:void 0})}function OI(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Zi(t.tags):[];return tr(n,t.addTags)}function LI(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new p("--order and --rank must match when both are provided",m.USAGE);let n=t.order??t.rank,i=Kt(e,"order",n,r=>_e(r,"order"));if(i!==void 0&&!Number.isInteger(i))throw new p("Order must be an integer",m.USAGE);return i}function NI(e,t,n,i,r,s){if(i.completedAt!==void 0&&e!==t.close_status)throw new p("--completed-at requires a terminal create status.",m.USAGE);let o=e!==t.close_status?void 0:i.completedAt===void 0?s:me(i.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:o,warnings:[]};let a=n.governance.require_close_reason?{explicit:i.closeReason??i.message,resolution:r}:{explicit:i.closeReason};return{closeReason:sc(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:o,warnings:[]}}async function DI(e){let{pmRoot:t,type:n,id:i,settings:r,typeRegistry:s,author:o,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:_,similarityCandidate:f,allowDuplicate:g}=e,h=jd(t,n,i,r.item_format,s.type_to_folder),y=Qt(t,i),v=Se(),w=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(A=>v.resolve(A.kind)?.hierarchy),S=await ks({pmRoot:t,author:o,ttlSeconds:r.locks.ttl_seconds,waitMs:r.locks.wait_ms,required:w}),E=w,T=[];try{let A=await sn(t,i,r.locks.ttl_seconds,o,!1,r.governance.force_required_for_stale_lock,r.locks.wait_ms);try{let k=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await ke(t,r.item_format,s.type_to_folder,void 0,r.schema):void 0;if(await Q(t,i,r.id_prefix,r.item_format,s.type_to_folder))throw new p(`Item "${i}" already exists`,m.CONFLICT);if(k){let C=K(r.schema);Sr(k,[...k,c.metadata],i,B=>de(B,C),v)}let L=await Ql({pmRoot:t,settings:r,operation:"create",author:o,before:null,after:c});await il({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:iu({pmRoot:t,settings:r,typeToFolder:s.type_to_folder})});let q=await tu(t,o,{required:r.governance.duplicate_detection_mode==="strict"&&g!==!0}),F=[];try{r.governance.duplicate_detection_mode==="strict"&&g!==!0&&await cc(f,{pmRoot:t,mode:"strict",threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:!1}),await Ve(h,gl(c,{format:r.item_format,schema:r.schema,extensionFieldNames:a}));try{let C=Ul({nowIso:_,author:o,op:"create",before:d,after:c,message:l,context:L.decisions.length===0?void 0:{workflow_policies:L.decisions}});await jl(y,C)}catch(C){throw await kd(h),C}E&&(await S(),E=!1),F=await nu({pmRoot:t,preferredFormat:r.item_format,typeToFolder:s.type_to_folder,schema:r.schema,itemPath:h,document:c})}finally{await q()}T=[...L.warnings,...k?ls(k,[...k,c.metadata],i):[],...F,...await ot({path:h,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await ot({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],tl({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:nl(c.metadata,u),changed_fields:u})}finally{await A()}}finally{E&&await S()}return T}async function wc(e,t){let n=lh(await eI(e)),i=x(process.cwd(),t.path);await P(i);let r=await I(i),s=K(r.schema),o=nn(r.schema),a=$(r,M()),c=await EI(n,t,i,r,a);n=c.resolvedOptions;let{typeDefinition:d,type:l,createMode:u}=c,_=GC(n.unset,o),{explicitUnsets:f,clearOptionKeys:g}=TI(n,_);AI(n,_),CI(n);let h=rI(d,n,u,g),y=R(),v=G(ye(n.author),r.author_default),w=qC(n.dep,y,r.id_prefix,v),S=zt("--comment",n.comment,y,v),E=zt("--note",n.note,y,v),T=zt("--learning",n.learning,y,v),A=gc(n.file),k=hc(n.test);k.values=await Sn(k.values,v,y);let b=yc(n.doc),L=zC(n.reminder,y),q=WC(n.event,y),F=QC(n.typeOption),C=$n(l,F.values,a),B=M(),we=ht(B),ue=Xi(n.field,B),fe=ml(n,o,l),Le=new Set(fe.missing_required_flags),Ke=o.definitions.filter(Y=>Le.has(`--${Y.cli_flag}`));II(ue,fe,_);let ft=sI(C.errors,l),it=ft.map(Y=>`--type-option ${Y}=<value>`),Ht=[...new Set([...h,...it,...fe.missing_required_flags])].sort((Y,fo)=>Y.localeCompare(fo));RI({combinedMissingFlags:Ht,typeDefinition:d,missingRequiredCreateFlags:h,missingRequiredTypeOptionKeys:ft,openStatus:s.open_status,type:l,createMode:u,missingRequiredRuntimeFields:Ke}),aI(C.errors,l,d,s);let ae=await wI({pmRoot:i,settings:r,typeRegistry:a,explicitId:n.id}),Ne=n.status!==void 0?$C(n.status,s):UC(d,s),Yt=n.priority!==void 0?_r(n.priority):2,D=_.metadataKeys,ge=OI(D,n),je=Kt(D,"deadline",n.deadline,Y=>me(Y,new Date(y),"deadline")),Xt=Kt(D,"estimated_minutes",n.estimatedMinutes,Y=>ir(Y,"estimated-minutes")),ze=V(D,"acceptance_criteria",n.acceptanceCriteria),ce=V(D,"definition_of_ready",n.definitionOfReady),We=LI(D,n),co=V(D,"goal",n.goal),Pi=V(D,"objective",n.objective),dw=V(D,"value",n.value),lw=V(D,"impact",n.impact),uw=V(D,"outcome",n.outcome),mw=V(D,"why_now",n.whyNow),_w=V(D,"assignee",n.assignee),pw=D.has("author")?void 0:ye(n.author)??v,fw=V(D,"parent",n.parent),ld=await hI(fw,n,D,i),lo=ld.parent,gw=ld.parentSource,hw=V(D,"reviewer",n.reviewer),yw=Kt(D,"risk",n.risk,Y=>xe(Ss(Y),zi,"risk")),vw=Kt(D,"confidence",n.confidence,Y=>Ts(Y)),ww=n.allowMissingParent===!0&&r.validation.parent_reference==="strict_error"?"warn":r.validation.parent_reference,ud=r.validation.sprint_release_format,At=[...c.warnings,...gI(l,ae,je,L.values,q.values)],md=await vI({itemId:ae,parent:lo,pmRoot:i,settings:r,typeRegistry:a,policy:ww});lo=md.parent,At.push(...md.warnings);let _d=ch(D,"sprint",n.sprint,"sprint",ud),bw=_d.value;At.push(..._d.warnings);let pd=ch(D,"release",n.release,"release",ud),kw=pd.value;At.push(...pd.warnings);let fd=V(D,"blocked_by",n.blockedBy),gd=await bI({pmRoot:i,settings:r,typeRegistry:a,statusRegistry:s,blockedBy:fd,dependencyValues:w.values,status:Ne,statusExplicit:n.status!==void 0,nowValue:y,author:v}),uo=gd.dependencyValues;ki(ae,uo),At.push(...await Ns({pmRoot:i,dependencies:uo,idPrefix:r.id_prefix,itemFormat:r.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:ae,createdAt:y}],schema:r.schema})),Ne=gd.status;let Sw=V(D,"blocked_reason",n.blockedReason),Ew=V(D,"unblock_note",n.unblockNote),Tw=V(D,"reporter",n.reporter),Aw=Kt(D,"severity",n.severity,Y=>xe(Es(Y),Wi,"severity")),Cw=V(D,"environment",n.environment),Iw=V(D,"repro_steps",n.reproSteps),hd=V(D,"resolution",n.resolution),xw=V(D,"expected_result",n.expectedResult),Rw=V(D,"actual_result",n.actualResult),Ow=V(D,"affected_version",n.affectedVersion),Lw=V(D,"fixed_version",n.fixedVersion),Nw=V(D,"component",n.component),Dw=Kt(D,"regression",n.regression,Y=>As(Y)),Mw=V(D,"customer_impact",n.customerImpact),mo=vc(n.title,"--title"),_o=n.description??"",Fi=n.body??"",yd=await cc({title:mo,description:_o,body:Fi},{pmRoot:i,mode:r.governance.duplicate_detection_mode,threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});At.push(...Ug(yd));let po=NI(Ne,s,r,n,hd,y),Pw=po.closeReason,Fw=Ne===s.close_status?y:void 0,$w=po.completedAt;At.push(...po.warnings);let $i=fl({id:ae,title:mo,description:_o,type:l,type_options:C.normalized,status:Ne,closed_at:Fw,completed_at:$w,close_reason:Pw,priority:Yt,tags:ge,created_at:y,updated_at:y,deadline:je,assignee:_w,author:pw,estimated_minutes:Xt,acceptance_criteria:ze,definition_of_ready:ce,order:We,goal:co,objective:Pi,value:dw,impact:lw,outcome:uw,why_now:mw,parent:lo,reviewer:hw,risk:yw,confidence:vw,sprint:bw,release:kw,blocked_by:fd,blocked_reason:Sw,unblock_note:Ew,reporter:Tw,severity:Aw,environment:Cw,repro_steps:Iw,resolution:hd,expected_result:xw,actual_result:Rw,affected_version:Ow,fixed_version:Lw,component:Nw,regression:Dw,customer_impact:Mw,dependencies:uo,comments:S.values,notes:E.values,learnings:T.values,files:A.values,tests:k.values,docs:b.values,reminders:L.values,events:q.values,...ue,...fe.values});try{Ji($i,B)}catch(Y){throw new p(Y instanceof Error?Y.message:"Invalid extension item field values",m.USAGE)}let Uw=hl({metadata:$i,body:Fi},{schema:r.schema,extensionFieldNames:we}),jw={metadata:{},body:""},vd=[...f].sort((Y,fo)=>Y.localeCompare(fo)),Gw=VC(n.message,vd),wd=BC($i,Fi,vd,[...Object.keys(ue),...Object.keys(fe.values??{})]),qw=await DI({pmRoot:i,type:l,id:ae,settings:r,typeRegistry:a,author:v,extensionFieldNames:we,afterDocument:Uw,beforeDocument:jw,historyMessage:Gw,changedFields:wd,nowValue:y,similarityCandidate:{title:mo,description:_o,body:Fi},allowDuplicate:n.allowDuplicate}),bd=structuredClone($i);u==="strict"&&f.has("dependencies")&&(bd.dependencies=[]);let Kw=Hg(ae,l,Ne,s);return ph(l,je,L.values,q.values)&&$l(`[pm] warning: ${l} '${ae}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${ae} --deadline <ISO>' or 'pm update ${ae} --event "start=<ISO>,end=<ISO>"'.`),{item:bd,changed_fields:wd,warnings:[...At,...qw],...Object.fromEntries([["parent_source",gw],["next_transition",Kw],["similarity_advisory",yd]].filter(Y=>Y[1]!==void 0))}}(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]="80ec599f-7198-5b07-bca2-253f85c137b7")}catch{}})();var Ec=[...lc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...uc,...Rs],MI=(()=>{let e=new Map;for(let t of Ec)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),js=new Map(Ec.map(e=>[e.optionKey,e.canonical])),PI=Ec.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),FI=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),$I=Cs({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function kh(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=r=>{let s=t.unset?[...t.unset]:[];s.includes(r)||s.push(r),t.unset=s},i=new Set([...js.keys(),"rank"]);for(let r of i){let s=t[r];if(typeof s!="string"||!qe(s))continue;let o=r==="rank"?"order":js.get(r)??r;n(o),t[r]=void 0}return Pe(e,xs(t,$I))}function Sh(e,t,n=[]){return Os({raw:e,supportedFields:PI,resolveDefinition:i=>{let r=n.find(o=>{let a=o.toLowerCase();return a===i||a.replaceAll("_","-")===i||a.replaceAll("-","_")===i});return MI.get(i)??Ls(i,"update",t)??(r?{optionKey:"field",metadataKey:r}:void 0)}})}var fh=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function gh(e){let t=e.disallowedFlags.flatMap(i=>{let r=fh.get(i);return r?[r(e.id)]:[]}),n=e.disallowedFlags.flatMap(i=>{let r=fh.get(i);return r?[`Replace ${i} with: ${r(e.id)}`]:[]});return new p(e.message,m.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function UI(e,t,n){let i=t.ownershipMetadataBypass===!0,r=t.ownershipDependencyBypass===!0;if(!i&&!r)return;if(i&&r)throw new p("Choose only one package-provided ownership bypass mode.",m.USAGE);let s=(c,d,l)=>{c&&l.push(d)};if(r){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new p("The dependency ownership bypass requires at least one --dep value",m.USAGE);if(c.length>0)throw gh({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let o=[];s(t.status!==void 0,"--status",o),s(t.closeReason!==void 0,"--close-reason",o),s(t.assignee!==void 0,"--assignee",o),s(t.parent!==void 0,"--parent",o),s(t.blockedBy!==void 0,"--blocked-by",o),s(t.blockedReason!==void 0,"--blocked-reason",o),s(t.unblockNote!==void 0,"--unblock-note",o),s(t.dep!==void 0,"--dep",o),s(t.depRemove!==void 0,"--dep-remove",o),s(t.replaceDeps===!0,"--replace-deps",o),s(t.replaceTests===!0,"--replace-tests",o),s(t.replaceFiles===!0,"--replace-files",o),s(t.replaceDocs===!0,"--replace-docs",o),s(t.note!==void 0,"--note",o),s(t.learning!==void 0,"--learning",o),s(t.test!==void 0,"--test",o),s(t.reminder!==void 0,"--reminder",o),s(t.event!==void 0,"--event",o),s(t.clearDeps===!0,"--clear-deps",o),s(t.clearComments===!0,"--clear-comments",o),s(t.clearNotes===!0,"--clear-notes",o),s(t.clearLearnings===!0,"--clear-learnings",o),s(t.clearFiles===!0,"--clear-files",o),s(t.clearTests===!0,"--clear-tests",o),s(t.clearDocs===!0,"--clear-docs",o),s(t.clearReminders===!0,"--clear-reminders",o),s(t.clearEvents===!0,"--clear-events",o);let a=[...n].filter(c=>FI.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(o.push(...a),o.length>0)throw gh({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${o.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:o})}function jI(e,t){let n=se(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new p(`Invalid --status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n}function GI(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Bl({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=se(e.fromStatus,e.statusRegistry)??e.fromStatus,i=se(e.toStatus,e.statusRegistry)??e.toStatus,r=`Disallowed transition for type "${e.typeName}": ${n} -> ${i}. Allowed transitions: ${Vl(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new p(r,m.USAGE);return`workflow_transition_not_allowed: ${r}`}function qI(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:Eh(e)}function Eh(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new p(`Invalid dependency created_at timestamp "${e}"`,m.USAGE);return new Date(t).toISOString()}function An(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var KI=["id","kind","type","author","created_at","source_kind"],zI=["id","kind","type","author","created_at","source_kind"];function Th(e){return e.startsWith("```")||e.includes(`
|
|
10
|
-
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Zt(e)}function Ah(e){return typeof e=="string"?xt(e)??e.trim():e}function WI(e,t,n,i){return e?(Ie(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let o=s.trim(),a=Th(o);bi(o,a);let c=a?J(s,"--dep"):{id:o,kind:"related"};a&&he(c,"--dep",KI);let d=c.id?.trim(),l=Ah((c.kind??c.type)?.trim());if(!d||!l)throw new p("--dep requires id and kind, or a bare item id to add a related dependency",m.USAGE);if(d.toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,m.USAGE);let u=Vn(An(c.source_kind)),_=An(c.author);return{id:Hn(d,t,u),kind:xe(l,Pn,"dependency kind","kind"),created_at:qI(c.created_at,n),author:_??i,source_kind:u??"cli:update:dep",author_source:_?"asserted":"detected"}})}):{additions:[]}}function BI(e,t){return e?(Ie(e,"--dep-remove"),e.map(n=>{let i=n.trim();if(!i)throw new p("--dep-remove requires id or key/value selectors",m.USAGE);let r=Th(i);if(bi(i,r,"--dep-remove"),r){let s=J(i,"--dep-remove");he(s,"--dep-remove",zI);let o=s.id?.trim();if(!o)throw new p("--dep-remove key/value form requires id=<value>",m.USAGE);if(o.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${o}"`,m.USAGE);let a=Ah(An(s.kind??s.type)),c=Vn(An(s.source_kind)),d=An(s.author),l=An(s.created_at);return{id:Hn(o,t,c),kind:a?xe(a,Pn,"dependency kind","kind"):void 0,source_kind:c,author:d,created_at:l?Eh(l):void 0}}if(i.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${i}"`,m.USAGE);return{id:yt(i,t)}})):[]}function Gs(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function VI(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",i=e.created_at?.trim()??"",r=Date.parse(i),s=Number.isFinite(r)?new Date(r).toISOString():i;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function HI(e,t,n,i){let r=[...e??[]],s=!1;if(t===void 0){let o=r.filter(a=>a.kind!=="blocked_by");return o.length!==r.length&&(r=o,s=!0),s?{dependencies:r.length>0?r:void 0,changed:!0}:{dependencies:e,changed:!1}}return r.some(o=>o.kind==="blocked_by"&&o.id===t)||(r.push({id:t,kind:"blocked_by",created_at:n,author:i,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:r.length>0?r:void 0,changed:!0}:{dependencies:e,changed:!1}}async function YI(e,t,n,i,r,s){if(e===void 0||t)return{};let o=e.trim();if(o.length===0)return{};let a=await Q(n,yt(o,i),i,r,s);return a?{id:a.id}:{unresolved:o}}function XI(e,t,n,i,r){let s=HI(e.dependencies,t,n,i);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,r.includes("dependencies")||r.push("dependencies"))}function JI(e){return`${e.path}::${e.scope}`}function QI(e){return`${e.path}::${e.scope}`}function ZI(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function Ch(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function hh(e,t){let n=Fn("update",e);if(!n)throw new p(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,m.CONFLICT);return n}function e0(e,t,n){let i=new Set,r=(s,o)=>{o&&i.add(s)};if(r("title",e.title!==void 0),r("description",e.description!==void 0),r("body",e.body!==void 0),r("status",e.status!==void 0),r("closeReason",e.closeReason!==void 0),r("priority",e.priority!==void 0),r("type",e.type!==void 0),r("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),r("deadline",e.deadline!==void 0),r("estimatedMinutes",e.estimatedMinutes!==void 0),r("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),r("definitionOfReady",e.definitionOfReady!==void 0),r("order",e.order!==void 0||e.rank!==void 0),r("goal",e.goal!==void 0),r("objective",e.objective!==void 0),r("value",e.value!==void 0),r("impact",e.impact!==void 0),r("outcome",e.outcome!==void 0),r("whyNow",e.whyNow!==void 0),r("author",e.author!==void 0),r("message",e.message!==void 0),r("assignee",e.assignee!==void 0),r("parent",e.parent!==void 0),r("reviewer",e.reviewer!==void 0),r("risk",e.risk!==void 0),r("confidence",e.confidence!==void 0),r("sprint",e.sprint!==void 0),r("release",e.release!==void 0),r("blockedBy",e.blockedBy!==void 0),r("blockedReason",e.blockedReason!==void 0),r("unblockNote",e.unblockNote!==void 0),r("reporter",e.reporter!==void 0),r("severity",e.severity!==void 0),r("environment",e.environment!==void 0),r("reproSteps",e.reproSteps!==void 0),r("resolution",e.resolution!==void 0),r("expectedResult",e.expectedResult!==void 0),r("actualResult",e.actualResult!==void 0),r("affectedVersion",e.affectedVersion!==void 0),r("fixedVersion",e.fixedVersion!==void 0),r("component",e.component!==void 0),r("regression",e.regression!==void 0),r("customerImpact",e.customerImpact!==void 0),r("dep",e.dep!==void 0),r("depRemove",e.depRemove!==void 0),r("dep",e.replaceDeps===!0),r("comment",e.comment!==void 0),r("note",e.note!==void 0),r("learning",e.learning!==void 0),r("file",e.file!==void 0),r("test",e.test!==void 0),r("test",e.replaceTests===!0),r("file",e.replaceFiles===!0),r("doc",e.replaceDocs===!0),r("doc",e.doc!==void 0),r("reminder",e.reminder!==void 0),r("event",e.event!==void 0),r("typeOption",e.typeOption!==void 0),r("field",e.field!==void 0),r("force",e.force===!0),r("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),r("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),r("dep",e.clearDeps===!0),r("comment",e.clearComments===!0),r("note",e.clearNotes===!0),r("learning",e.clearLearnings===!0),r("file",e.clearFiles===!0),r("test",e.clearTests===!0),r("doc",e.clearDocs===!0),r("reminder",e.clearReminders===!0),r("event",e.clearEvents===!0),r("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=Sh(e.unset,t,n);for(let o of s.optionKeys)r(o,!0)}return i}function t0(e,t,n,i,r){let s=Bi(e,n);if(!s)throw new p(`Invalid type value "${e}"`,m.USAGE);let o=Jt(s,"update",[]);if(o.errors.length>0)throw new p(o.errors.join("; "),m.CONFLICT);let a=e0(t,i,r);for(let c of o.disabled)if(a.has(hh(c,e)))throw new p(`Option ${Ee("update",c)} is disabled for type "${e}" by command_option_policies`,m.USAGE);for(let c of o.required)if(!a.has(hh(c,e)))throw new p(`Missing required option ${Ee("update",c)} for type "${e}"`,m.USAGE)}var n0=new Set(["order","rank"]),i0=wo.filter(e=>!n0.has(e)),Ih=["tags","closeReason",...i0],r0=["title","description","body","status","closeReason","completedAt","priority","type",...wo,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],s0=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>me(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>ir(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],o0=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>xe(Ss(e),zi,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Ts(e)}],a0=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>xe(Es(e),Wi,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>As(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Sc(e,t,n){for(let i of e){let r=t[i.optionKey],s=n.clearItemMetadataKeys.has(i.metadataKey);if(!(r===void 0&&!s)){if(s){delete n.metadataRecord[i.metadataKey],n.changedFields.push(i.metadataKey);continue}if(typeof r!="string")throw new p(`${Ee("update",String(i.optionKey))} must be a string value`,m.USAGE);n.metadataRecord[i.metadataKey]=i.transform?i.transform(r,n):r.trim(),n.changedFields.push(i.metadataKey)}}}async function c0(e){return kh(await nr(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function d0(e){return Rt(e)?await c0(e):kh(e)}function l0(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function bc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new p(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,m.USAGE);if(e.enabled&&e.clearEnabled)throw new p(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,m.USAGE)}function u0(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new p("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",m.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new p("--replace-deps requires at least one --dep entry",m.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new p("--replace-deps cannot be combined with --dep-remove",m.USAGE);bc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),bc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),bc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function m0(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new p(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,m.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function _0(e){let t={};for(let n of Ih)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function p0(e,t){let n=_0(e);for(let[i,r]of Object.entries(n)){if(!r||!t.optionKeys.has(i))continue;let s=js.get(i)??i;throw new p(`Cannot combine --unset ${s} with ${Ee("update",i)}`,m.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --add-ac",m.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --remove-ac",m.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new p("Cannot combine --unset tags with --remove-tags",m.USAGE)}}function f0(e){let t=(n,i)=>{let r=js.get(i),s=r?`Use --unset ${r} to clear this field.`:void 0;Is(n,Ee("update",i),s)};for(let n of Ih)t(e[n],String(n));t(e.order??e.rank,"order"),Ie(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Ie(e.event,"--event","Use --clear-events to clear linked events.")}function g0(e,t){let n={};for(let i of r0)n[String(i)]=e[i]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.runtimeFields=Object.keys(t).length>0,n}async function h0(e){let t=await Q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Bn(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await be(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function y0(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return ke(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function v0(e){e.before&&Sr(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>de(t,e.statusRegistry),Se())}function w0(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new p("--order and --rank must match when both are provided",m.USAGE)}async function b0(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=br(lr(e.options.parent),e.settings.id_prefix);if(yr(t))return{resolvedParentValue:t,warnings:[]};if(mr(e.id,t,e.settings.id_prefix),await Q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let i=yt(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:ur(i,e.parentReferencePolicy).warnings}}function k0(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function S0(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await Q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Bn(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await be(t,{schema:e.settings.schema}),i=e.options.type!==void 0?rt(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",r=GI({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:i,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return r?[r]:[]}async function E0(e){if(!e.fieldFlags.status||se(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),i=[],r=[];if(n.length>0){let a=Pe(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),c=await qs(e.id,a,e.global);r=c.changed_fields,i.push(...c.warnings)}let s=await ds(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),o=[...e.workflowTransitionWarnings,...i,...s.warnings,"auto_routed_from_update_to_close"];return{item:s.item,changed_fields:[...r,...s.changed_fields],warnings:o}}function T0(e,t,n,i){return t.title!==void 0&&(e.metadata.title=vc(t.title,"--title"),i.push("title")),t.description!==void 0&&(e.metadata.description=t.description,i.push("description")),t.body!==void 0&&(e.body=t.body,i.push("body")),se(e.metadata.status,n)??e.metadata.status}var A0=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function C0(e,t){for(let n of A0)e[n]!==void 0&&(delete e[n],t.push(n))}function I0(e,t,n,i,r){let s=jI(n,t.statusRegistry);if(e.metadata.status=s,r.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,r.push("closed_at","completed_at");return}!de(s,t.statusRegistry)&&de(i,t.statusRegistry)&&C0(e.metadata,r)}function x0(e,t,n,i){if(t.options.status!==void 0&&I0(e,t,t.options.status,n,i),t.options.completedAt!==void 0){if(!de(e.metadata.status,t.statusRegistry))throw new p("--completed-at can only be set on a terminal item",m.USAGE);e.metadata.completed_at=me(t.options.completedAt,new Date(t.nowIso),"completed-at"),i.push("completed_at")}}function R0(e,t,n,i){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let r=t.options.closeReason?.trim()??"";if(r.length===0)throw new p("--close-reason must not be empty",m.USAGE);e.metadata.close_reason=r}i.push("close_reason");return}t.options.status!==void 0&&de(n,t.statusRegistry)&&!de(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,i.push("close_reason"))}function O0(e,t,n,i){x0(e,t,n,i),R0(e,t,n,i)}function L0(e,t,n){let i=rt(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=_r(t.options.priority),n.push("priority")),t.options.type!==void 0){let r=rt(t.options.type,t.typeRegistry);if(!r)throw new p(fr(t.options.type,t.typeRegistry.types,rr(t.pmRoot,t.settings.schema)),m.USAGE);e.metadata.type=r,i=r,n.push("type")}return t0(i,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),N0(e,t,i,n),i}function N0(e,t,n,i){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let s=Ps(t.options.typeOption??[]),o=$n(n,s,t.typeRegistry);if(o.errors.length>0)throw new p(o.errors.join("; "),m.USAGE);e.metadata.type_options=o.normalized}i.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let r=$n(n,e.metadata.type_options,t.typeRegistry);if(r.errors.length>0)throw new p(`Current type options are incompatible with type "${n}". ${r.errors.join("; ")}. Use --clear-type-options to clear them.`,m.USAGE);e.metadata.type_options=r.normalized}function D0(e,t){let n=new Set(t.map(r=>Gs(r))),i=new Set;return e.filter(r=>{if(!n.has(Gs(r)))return!0;let s=VI(r);return i.has(s)?!1:(i.add(s),!0)})}function M0(e,t,n){let i=t.filter(r=>!e.some(s=>Ch(s,r)));if(i.length!==0)throw new p(`Dependency removal did not match ${i.length===1?"a stored edge":"stored edges"}.`,m.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:i,available_dependencies:e.map(r=>({id:r.id,kind:r.kind,source_kind:r.source_kind,author:r.author,created_at:r.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function P0(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let i=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){i=D0(i,t.dependencyUpdates.additions);let r=new Set(i.map(s=>Gs(s)));for(let s of t.dependencyUpdates.additions){let o=Gs(s);r.has(o)||(i.push(s),r.add(o))}}t.dependencyRemovals.length>0&&(M0(i,t.dependencyRemovals,e.metadata.id),i=i.filter(r=>!t.dependencyRemovals.some(s=>Ch(r,s)))),i.length===0?delete e.metadata.dependencies:e.metadata.dependencies=i,n.push("dependencies")}function F0(e,t,n){kc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),kc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),kc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function kc(e,t,n,i,r,s){n===void 0&&!r.has(t)||(r.has(t)||!i||i.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...i],s.push(t))}function $0(e,t,n){yh(e,"files",t.options.file,t.fileUpdates.values,JI,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),U0(e,t,n),yh(e,"docs",t.options.doc,t.docUpdates.values,QI,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function yh(e,t,n,i,r,s,o,a){if(!(n===void 0&&!o.has(t))){if(s)e.metadata[t]=i;else if(o.has(t)||!i||i.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>r(l)));for(let l of i){let u=r(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}a.push(t)}}function U0(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=vh(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=vh([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function vh(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let i of e){let r=ZI(i);n.has(r)||(t.push(i),n.add(r))}return t}function j0(e,t,n){let i=t.options.addTags,r=t.options.removeTags,s=Array.isArray(i)&&i.length>0||Array.isArray(r)&&r.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let o=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Zi(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=dl(tr(o,i),r),n.changedFields.push("tags")}Sc(s0,t.options,n),q0(e,t,n.changedFields)}function G0(e,t,n){let i=t.options.addAc,r=t.options.removeAc;if(!(Array.isArray(i)&&i.length>0)&&!(Array.isArray(r)&&r.length>0))return;let s=cl(er(e.metadata.acceptance_criteria),i,r);if(s.unmatchedRemovals.length>0)throw new p(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let o=s.criteria.join("; ");e.metadata.acceptance_criteria!==o&&(o===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=o,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function q0(e,t,n){let i=t.options.order??t.options.rank;if(!(i===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let r=_e(i??"","order");if(!Number.isInteger(r))throw new p("Order must be an integer",m.USAGE);e.metadata.order=r}n.push("order")}}function K0(e,t,n,i){z0(e,t,n.changedFields),W0(e,t,n.changedFields),Sc(o0,t.options,n),wh(e,t,"sprint",i,n.changedFields),wh(e,t,"release",i,n.changedFields),B0(e,t,n.changedFields),Sc(a0,t.options,n)}function z0(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let i=t.options.assignee?.trim()??"";if(i==="")throw new p("--assignee must not be empty. Use --unset assignee to clear it.",m.USAGE);e.metadata.assignee=i}n.push("assignee")}}function W0(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function wh(e,t,n,i,r){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=pr(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,i.push(...s.warnings)}r.push(n)}}function B0(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&XI(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function V0(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Ds(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=Ms(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function H0(e,t,n){bh(e,t.runtimeFieldRegistry.definitions.map(r=>r.metadata_key),t.clearItemMetadataKeys,n),bh(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[r,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(r)){let o=r.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(d=>d.metadata_key===r)?.cli_flag??o;throw new p(`Cannot combine --unset ${o} with --${c}`,m.USAGE)}st(e[r],s)||(e[r]=s,n.push(r))}let i=Xi(t.options.field,t.extensionRegistrations);for(let r of Object.keys(i))if(t.clearItemMetadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,m.USAGE);for(let[r,s]of Object.entries(i))st(e[r],s)||(e[r]=s,n.push(r))}function bh(e,t,n,i){for(let r of t)!n.has(r)||e[r]===void 0||(delete e[r],i.push(r))}function Y0(e,t){let n=structuredClone(e.metadata),i=e.body,r=[],s=[],o=T0(e,t.options,t.statusRegistry,r),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:r,nowValue:t.nowValue};O0(e,t,o,r),L0(e,t,r),P0(e,t,r),F0(e,t,r),$0(e,t,r),j0(e,t,c),G0(e,t,c),K0(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&ki(e.metadata.id,e.metadata.dependencies),se(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,r.includes("assignee")||r.push("assignee")),V0(e,t,r),H0(a,t,r);try{Ji(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(u){throw new p(u instanceof Error?u.message:"Invalid extension item field values",m.USAGE)}let d=e.metadata,l=[...new Set(r)].filter(u=>u==="body"?e.body!==i:!st(n[u],d[u]));return t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${er(n.acceptance_criteria).length}:${er(d.acceptance_criteria).length}`),{changedFields:l,warnings:s}}async function xh(e,t,n,i={}){t=await d0(t);let r=x(process.cwd(),n.path);await P(r);let s=await I(r),o=K(s.schema),a=nn(s.schema),c=M(),d=ht(c),l=$(s,c),u=s.governance.workflow_enforcement??"off",_=u==="off"?[]:Wl(s.schema),f=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],g=Sh(t.unset,a,d),h=new Set(g.optionKeys),y=new Set(g.metadataKeys);u0(t),m0({definitions:l0(t),options:t,clearOptionKeys:h,clearItemMetadataKeys:y}),UI(e,t,y),p0(t,g),f0(t);let v=G(t.author,s.author_default),w=new Date,S=w.toISOString(),E=WI(t.dep,s.id_prefix,S,v);ki(e,E.additions);let T=await Ns({pmRoot:r,dependencies:E.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:l.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),A=BI(t.depRemove,s.id_prefix),k=zt("--comment",t.comment,S,v),b=t.ownershipMetadataBypass===!0&&k.values?{...k,values:k.values.map(ge=>({...ge,author:v}))}:k,L=zt("--note",t.note,S,v),q=zt("--learning",t.learning,S,v),F=gc(t.file),C=hc(t.test);C.values=await Sn(C.values,v,S);let B=yc(t.doc),we=[],ue=await b0({id:e,options:t,unsetTargets:g,pmRoot:r,settings:s,typeRegistry:l,parentReferencePolicy:f}),fe=await YI(t.blockedBy,y.has("blocked_by"),r,s.id_prefix,s.item_format,l.type_to_folder),Le=fe.id,Ke=[...ue.warnings,...k0(fe)],ft=_l(t,a,t.runtimeFieldCommands),it=g0(t,ft);if(!Object.values(it).some(Boolean))return h0({pmRoot:r,id:e,settings:s,typeRegistry:l});we.push(...await S0({options:t,fieldFlags:it,workflowEnforcement:u,typeWorkflows:_,statusRegistry:o,typeRegistry:l,pmRoot:r,id:e,settings:s}));let ae=await E0({options:t,fieldFlags:it,statusRegistry:o,workflowTransitionWarnings:we,global:n,id:e});if(ae)return ae;w0(t);let Ne=Se(),Yt=it.parent&&!y.has("parent")||E.additions.some(ge=>Ne.resolve(ge.kind)?.hierarchy),D=await ks({pmRoot:r,author:v,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Yt});try{let ge=await y0({fieldFlags:it,clearedMetadataKeys:y,pmRoot:r,settings:s,typeToFolder:l.type_to_folder}),je,Xt,ze=await ru({pmRoot:r,settings:s,typeToFolder:l.type_to_folder,id:e,op:X0(t,i),author:v,message:t.message,resolveHistoryContext:()=>Xt,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:d,skipNoop:!0,mutate(We){je=J0({document:We,recurrenceReason:i.recurrenceReason,requestedStatus:t.status,statusRegistry:o}),Xt=je?{recurrence:je}:void 0,ge=ge?.map(Pi=>Pi.id===We.metadata.id?structuredClone(We.metadata):Pi);let co=Y0(We,{options:t,settings:s,typeRegistry:l,statusRegistry:o,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:d,clearItemMetadataKeys:y,dependencyUpdates:E,dependencyRemovals:A,commentUpdates:b,noteUpdates:L,learningUpdates:q,fileUpdates:F,testUpdates:C,docUpdates:B,resolvedParentValue:ue.resolvedParentValue,resolvedBlockedByDependencyId:Le,runtimeFieldUpdates:ft,nowValue:w,nowIso:S,author:v,pmRoot:r});return v0({before:ge,document:We,statusRegistry:o}),co}});await D();let ce=ge?ls(ge,ge.map(We=>We.id===ze.item.id?ze.item:We),ze.item.id):[];return{item:ze.item,changed_fields:ze.changedFields,warnings:[...we,...Ke,...T,...ce,...ze.warnings],...je===void 0?{}:{lifecycle_transition:je}}}finally{await D()}}function X0(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function J0(e){if(e.recurrenceReason===void 0)return;let t=se(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!de(t,e.statusRegistry))throw new p(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,m.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,i=se(n,e.statusRegistry)??n,r=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(o=>{let a=r[o];return typeof a=="string"?[[o,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:i,previous_terminal:s}}async function qs(e,t,n){return xh(e,t,n)}async function Yq(e,t,n,i){let r=await xh(e,t,n,{recurrenceReason:i});if(r.lifecycle_transition===void 0)throw new p(`Item ${e} did not produce the required recurrence receipt.`,m.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...r,lifecycle_transition:r.lifecycle_transition}}(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]="961c1918-75f9-5e5d-bbae-b333ca29534f")}catch{}})();function Rh(e){return tn("in_progress",e)??e.open_status}(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]="7f0e8f0f-bef3-5d61-b851-7582a03430b6")}catch{}})();async function Tc(e,t,n){try{return await n()}catch(i){let r=i instanceof p?i.context:{},s=new p(i instanceof Error?i.message:String(i),i instanceof p?i.exitCode:m.GENERIC_FAILURE,{...r,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${r.why?` ${r.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...r.nextSteps??[]]});throw s.cause=i,s}}async function dK(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new p("--start requires an explicit item id and cannot be combined with --next or --if-available",m.USAGE);let i=await I(x(process.cwd(),n.path)),r=Rh(K(i.schema)),s=await ic(e,t.force===!0,n,t),o=await Tc(e,"claim",()=>qs(e,aa(t,{status:r},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:e,action:"start_task",claim:s,update:o}}async function lK(e,t,n){let i=await I(x(process.cwd(),n.path)),r=K(i.schema).open_status,s=await qs(e,aa(t,{status:r},["assignee","pause"]),n),o=await Tc(e,"update",()=>rc(e,t.force===!0,n,t));return{id:e,action:"pause_task",update:s,release:o}}async function uK(e,t,n,i){let r=await ds(e,t,n,i),s=await Tc(e,"close",()=>rc(e,n.force===!0,i,n));return{id:e,action:"close_task",close:r,release: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]="86ee3f5f-ce07-59dc-a2ee-f4e0373a0345")}catch{}})();var Ac=[{exit_code:m.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:m.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:m.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:m.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:m.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:m.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:m.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:m.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],Oh=[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED],Q0=new Set(["close-many","update-many"]),Nh=Xe.map(e=>({command:e,exit_codes:Q0.has(e)?[...Oh,m.NO_EFFECT,m.PARTIAL_EFFECT]:[...Oh]})),Lh=new Map(Nh.map(e=>[e.command,e])),Z0=[m.SUCCESS,m.NO_EFFECT,m.PARTIAL_EFFECT];function fK(e){return Z0.includes(e)}function gK(e){return Ac.some(t=>t.exit_code===e)}function Dh(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return Lh.get(t)??Lh.get(t.split(" ")[0])}function hK(e,t=Xe,n=Nh){let i=new Map(n.map(d=>[d.command,d])),r=t.filter(d=>!i.has(d)),s=e.filter(d=>{let l=i.get(d.command)??i.get(d.command.split(" ")[0]);return l===void 0||!l.exit_codes.includes(d.exit_code)}),o=new Set(e.map(d=>d.exit_code)),c=[...new Set(n.flatMap(d=>d.exit_codes))].filter(d=>!o.has(d)).sort((d,l)=>d-l);return{ok:r.length===0&&s.length===0&&c.length===0,missing_commands:r,undeclared_observations:s,unreachable_exit_codes:c}}function yK(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:m.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:m.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS}}import Cc from"node:fs/promises";import Mh 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]="9189cea6-950f-5594-9321-b7590171297c")}catch{}})();var ex=1440*60*1e3,tx=new Set(["committed","compensated"]);function nx(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function ix(e,t,n,i,r){let s=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(s))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=i-s;return tx.has(t)?o>r?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function rx(e,t,n,i){let r=i.hooks?.onRead?await i.hooks.onRead(e):[],s=nx(await Cc.readFile(e,"utf8")),o=ix(t,s.status,s.updatedAt,i.nowMs,i.retentionMs);return o.entry.reason==="unparseable"&&r.push(`transaction_journal_unparseable:${n}`),o.remove&&!i.dryRun&&(await Cc.rm(e,{force:!0}),i.hooks?.onWrite&&r.push(...await i.hooks.onWrite(e))),{decision:o,warnings:r}}async function Ph(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),s=Math.max(0,t.retentionDays)*ex,o=Mh.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Cc.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(W(d))return a;throw d}for(let d of c){let l=Mh.join(o,d),u=`transactions/sdk/${d}`,_=await rx(l,u,d,{dryRun:n,hooks:i,nowMs:r,retentionMs:s});a.warnings.push(..._.warnings),a.scanned+=1;let{decision:f}=_;if(!f.remove){a.retained.push(u),a.entries.push(f.entry);continue}a.removed.push(u),a.entries.push(f.entry)}return a}import Cn from"node:fs/promises";import zs from"node:path";import Ks from"node:fs/promises";import Ic 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]="fe72275e-b195-5a7e-b963-a9f159f9c67c")}catch{}})();var sx=864e5;function ox(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function ax(e,t){let n;try{n=await Ks.readdir(e,{withFileTypes:!0})}catch(r){if(W(r))return[];throw r}let i=[];for(let r of n)if(r.isDirectory()){let s=Ic.join(e,r.name),o;try{o=await Ks.readdir(s)}catch(a){W(a)||t.push(`checkpoint_subdir_unreadable:${r.name}`);continue}for(let a of o)a.endsWith(".json")&&i.push(`${r.name}/${a}`)}else r.name.endsWith(".json")&&i.push(r.name);return i.sort()}async function Fh(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),s=Math.max(0,t.retentionDays)*sx,o=Ic.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await ax(o,a.warnings);for(let d of c){let l=Ic.join(o,d),u=`checkpoints/${d}`;a.scanned+=1,i?.onRead&&a.warnings.push(...await i.onRead(l));let _;try{_=await Ks.readFile(l,"utf8")}catch(v){if(W(v)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=ox(_),g=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(g)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=r-g,y={file:u,created_at:f,age_seconds:Math.floor(h/1e3),stale:h>s,reason:h>s?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await Ks.unlink(l)}catch(v){if(!W(v)){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}i?.onWrite&&a.warnings.push(...await i.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e2e3b62-5eb1-5773-96bf-866b26a59345")}catch{}})();var Si=["index","embeddings","runtime","locks","checkpoints","transactions"],cx=1440*60*1e3,dx=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function lx(e,t,n){let i=t.relativePath,r=zs.join(e,i),s=await Me({path:r,scope:"project"});try{let o=await Cn.stat(r);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...s,`not_a_file:${i}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...s,`not_a_directory:${i}`]};if(n)return{removed:!0,warnings:s};t.kind==="file"?await Cn.unlink(r):await Cn.rm(r,{recursive:!0,force:!0});let a=await ot({path:r,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...s,...a]}}catch(o){if(W(o))return{removed:!1,warnings:s};throw o}}async function ux(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],i=[],r=[],s=[],o=Date.now()-cx;for(let a of n){let c=zs.join(e,a.relativePath);if(!await Z(c))continue;let d=(await Cn.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=zs.posix.join(a.relativePath,l),_=zs.join(c,l);s.push(...await Me({path:_,scope:"project"}));let f=await Cn.stat(_).catch(g=>{if(!W(g))throw g});if(f){if(f.mtimeMs>o){r.push(u);continue}i.push(u),!t&&(await Cn.rm(_,{recursive:!0,force:!0}),s.push(...await ot({path:_,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:i,retained:r,warnings:s}}function mx(e){if(!e||e.length===0)return[...Si];let t=e.flatMap(i=>i.split(",")).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);if(t.length===0)throw new p(`--scope requires at least one value (${Si.join(",")})`,m.USAGE);let n=new Set;for(let i of t){if(!Si.includes(i))throw new p(`Invalid --scope value "${i}". Expected one or more of: ${Si.join(", ")}`,m.USAGE);n.add(i)}return Si.filter(i=>n.has(i))}function _x(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),i=e.removed.some(r=>r==="index/manifest.json"||r==="search/embeddings.jsonl"||r==="search/vectorization-status.json"||r==="search/lancedb"||r==="search/pending-refresh.json"||r==="search/pending-refresh.gate.lock");return n&&i&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(r=>r.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(r=>r.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function GK(e,t={}){let n=x(process.cwd(),e.path);await P(n);let i=await I(n),r=t.dryRun===!0,s=mx(t.scope),o=dx.filter(g=>s.includes(g.scope)),a=[],c=[],d=[];for(let g of o){let h=await lx(n,g,r);h.removed?a.push(g.relativePath):c.push(g.relativePath),d.push(...h.warnings)}if(s.includes("runtime")){let g=await ux(n,r);a.push(...g.removed),c.push(...g.retained),d.push(...g.warnings)}let l;if(s.includes("locks")){let g=await Tp(n,{dryRun:r,hooks:{onRead:h=>Me({path:h,scope:"project"}),onWrite:h=>ot({path:h,scope:"project",op:"gc:lock_remove"})}});a.push(...g.removed),c.push(...g.retained),d.push(...g.warnings),l={scanned:g.scanned,removed:g.removed.length,retained:g.retained.length}}let u;if(s.includes("transactions")){let g=i.checkpoints.retention_days,h=await Ph(n,{dryRun:r,retentionDays:g,hooks:{onRead:y=>Me({path:y,scope:"project"}),onWrite:y=>ot({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:g}}let _;if(s.includes("checkpoints")){let g=i.checkpoints.retention_days,h=await Fh(n,{dryRun:r,retentionDays:g,hooks:{onRead:y=>Me({path:y,scope:"project"}),onWrite:y=>ot({path:y,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),_={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:g}}d.push(...await sl({mode:r?"gc:dry-run":"gc",total_items:o.length}));let f=_x({dryRun:r,scopes:s,removed:a});return{ok:d.length===0,dry_run:r,scope:s,removed:a,retained:c,warnings:d,...l?{locks:l}:{},..._?{checkpoints:_}:{},...u?{transactions:u}:{},guidance:f,generated_at:R()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a196ae-61e1-528d-99a2-83eb9e11158b")}catch{}})();var px="1h",fx="now",gx="+1d";function Et(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function $h(e,t,n){let i={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return Pe(n,i)}async function Uh(e,t,n,i){let r=$h(e,t,n),s=[];return Et(s,"start",n.start??fx),n.end!==void 0?Et(s,"end",n.end):Et(s,"duration",n.duration??px),Et(s,"location",n.location),Et(s,"timezone",n.timezone),n.allDay===!0&&Et(s,"all_day","true"),r.event=[s.join(",")],wc(r,i)}function WK(e,t,n){return Uh("Meeting",e,t,n)}function BK(e,t,n){return Uh("Event",e,t,n)}function VK(e,t,n){let i=$h("Reminder",e,t),r=[];return Et(r,"at",t.at??gx),Et(r,"text",t.text??e),i.reminder=[r.join(",")],wc(i,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]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();import Ti from"node:crypto";import{cp as jh,lstat as hx,mkdir as Wt,readFile as In,readdir as Rc,rename as Kh,rm as Lc,writeFile as Ws}from"node:fs/promises";import U from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="91604cb2-8afd-585e-9c18-26e223df25bc")}catch{}})();var zh="https://schema.unbrained.dev/pm/workspace-snapshot/v1",dz=["create","list","inspect","restore","delete"],Wh=U.join("runtime","workspace-snapshots"),yx=new Set(["checkpoints","locks","runtime","search","transactions"]),vx=/^[a-z0-9][a-z0-9._-]*$/,Ei="sdk-workspace-transaction",xc={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Bh={renameEntry:Kh,removeEntry:async e=>{await Lc(e,{recursive:!0,force:!0})}},Oc=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,i){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(i*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await In(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==Ei||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await Ve(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
|
|
11
|
-
`)}};async function
|
|
12
|
-
`).filter(t=>t.trim().length>0).length}async function
|
|
13
|
-
`,"utf8"),await Wt(U.dirname(s),{recursive:!0})}),o=await
|
|
14
|
-
`,"utf8"),await
|
|
15
|
-
`)}var Az={commandForWorkspacePositionState:Zh,normalizeWorkspaceHistoryDrift:ey,selectWorkspacePositionState:Qh};(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]="c6f4f9d1-e167-5a06-a1a1-a32d3b3f4d9f")}catch{}})();var Ix=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file, or from stdin when set to -.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),xx=new Set(["--add","--body","--comment","--dep","--dep-remove","--description","--doc","--event","--field","--file","--learning","--note","--remove","--reminder","--test","--type-option"]),Rx=new Set(["append","comments","create","docs","files","learnings","notes","test","update","update-many"]),Ox=new Set(["close-many:--ids","comments:--file","create:--body-file","history-compact:--ids","learnings:--file","notes:--file","update:--body-file","update-many:--ids"]),Lx=new Set(["close-many:--ids","history-compact:--ids","update-many:--ids"]),Nx=["--allow-","--check-","--dry-run","--explain","--fail-","--fix-","--full","--has-","--include-","--json","--no-","--prune-","--quiet","--refresh-","--require-","--runtime-only","--schema-only","--skip-","--stream","--strict-","--summary","--today","--verbose"],Dx=new Set(["--activate","--active-only","--adopt","--adopt-all","--all","--all-actionable","--all-affected-ids","--all-day","--all-streams","--acknowledge-linked-tests","--append-stable","--auto-fix","--auto-pm-context","--availability-only","--background","--brief","--by-assignee","--by-priority","--by-tag","--catalog","--claim","--clear","--clear-comments","--clear-criteria","--clear-deps","--clear-docs","--clear-events","--clear-files","--clear-learnings","--clear-notes","--clear-reminders","--clear-tests","--clear-type-options","--cli-only","--closed","--compact","--completion","--count","--counts","--deactivate","--declarative","--defaults","--describe","--diff","--doctor","--empty-body","--explore","--field-utilization","--filter-empty-body","--flags-only","--follow","--force","--global","--highlight","--hybrid","--id-only","--if-available","--ignore-global","--include_unparented","--infer","--init","--install","--isolated","--lean","--list","--local","--manage","--markdown","--metadata-coverage","--next","--normalize-provenance","--only","--only-last","--output-row-contract","--override-linked-pm-context","--override-linked-workspace-context","--packages-only","--past","--phrase-exact","--profile","--progress","--project","--promote-to-item-dep","--provenance","--provenance-summary","--raw","--ready-only","--ready_only","--rebuild","--recent","--reload","--repair","--replace-deps","--replace-docs","--replace-files","--replace-tests","--required","--required-on-create","--run","--runtime-probe","--save-baseline","--scaffold","--semantic","--shared-host-safe","--storage","--title-exact","--token-accounting","--trace","--tree","--unbounded","--uninstall","--validate-paths","--verify","--watch","--with-packages"]),Mx=new Set(["--only-index"]),Px=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),Fx=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),$x=new Set(["--regression"]);function Ux(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:Ox.has(`${e}:${t}`)?["argv","file","stdin"]:t.endsWith("-file")?["argv","file"]:xx.has(t)&&Rx.has(e)?["argv","stdin"]:["argv"]}function jx(e,t){let n=Px.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,i=t.value_type==="boolean"||t.flag==="--stdin"||t.flag==="--stdin-json"||t.flag.startsWith("--filter-")&&(t.flag.endsWith("-missing")||t.flag.startsWith("--filter-has-")||t.flag.startsWith("--filter-no-"))||Nx.some(r=>t.flag.startsWith(r));return n||Mx.has(t.flag)||!Dx.has(t.flag)&&!i}function Gx(e,t){let n=Ui(e),i=jx(n,t),r=Ux(n,t.flag),s=t.description??Ix[t.flag]??`${i?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:s,takes_value:i,value_required:i&&!$x.has(t.flag)&&!Fx.has(`${n}:${t.flag}`),...i?{value_name:t.value_name??"value"}:{},value_type:i?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:r,...r.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{},...Lx.has(`${n}:${t.flag}`)?{file_token_prefix:"@"}:{}}}function ty(e,t){return t.map(n=>Gx(e,n))}function xz(e,t,n){let i=e.trim().toLowerCase(),r=[],s=new Map,o=0;for(let c of n)if(c.command.trim().toLowerCase()===i){if(o+=1,s.has(c.flag)){r.push({code:"duplicate_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} was observed more than once.`});continue}s.set(c.flag,c)}let a=new Set(t.map(({flag:c})=>c));for(let c of t){let d=s.get(c.flag);if(!d){r.push({code:"missing_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} has no executable option observation.`});continue}for(let[l,u]of[["takes_value","takes_value_mismatch"],["value_required","value_required_mismatch"],["repeatable","repeatable_mismatch"]])c[l]!==d[l]&&r.push({code:u,command:i,flag:c.flag,detail:`${i} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of s.values())a.has(c.flag)||r.push({code:"undeclared_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} is executable but absent from invocation contracts.`});return r.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:r.length===0,declared_count:t.length,observed_count:o,findings:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d931940-2d41-557a-8913-875848774ed0")}catch{}})();var qx=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate"]),Kx=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),zx=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),Wx=new Set(["extension","install","package","packages","upgrade"]);function Bx(e){let t=X(e.trim().toLowerCase());if(t==="ops")return"quality";for(let[n,i]of Object.entries(zx))if(i.has(t))return n;return Wx.has(t)?"extensions":"internal"}var xn=Object.freeze([...Xe.flatMap(e=>e==="item"?["item-reopen"]:[e,...Be.filter(t=>t.alias===e).map(t=>t.canonical)]).map(e=>({command:e,tier:qx.has(X(e))?"core":Kx.has(X(e))?"standard":"full",family:Bx(e)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"}]),Vx=xn,ny=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),Nz=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function Dz(e){let t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=ny.max_lines&&n<=ny.max_utf8_bytes}}var iy={core:0,standard:1,full:2,internal:3},Hx=new Map(Vx.map(({command:e,tier:t})=>[e,t]));function ry(e,t="standard"){return Hx.get(e.trim().toLowerCase())??t}function Mz(e){return sy(e,xn)}function sy(e,t){let n=iy[e];return t.filter(i=>i.tier!=="internal"&&iy[i.tier]<=n).map(i=>i.command)}function Pz(e){return oy(e,xn)}function oy(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}var Yx=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],Xx=new Set([...Mn.filter(e=>e.hidden).map(e=>e.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function Fz(e=xn){return Yx.map(t=>({family:t,commands:oy(t,e).filter(n=>e.find(i=>i.command===n)?.tier!=="internal"&&!Xx.has(n))})).filter(({commands:t})=>t.length>0)}var Jx=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function $z(e,t){return Qx(e,t,xn)}function Qx(e,t,n){if(t==="full")return[...e];let i=new Set(sy(t,n));return e.filter(r=>{let s=Jx[r];return s!==void 0&&i.has(s)})}var Uz=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),jz=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function Gz(){return Zx(xn)}function Zx(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:n,tier:i,family:r})=>`| \`${n}\` | ${i} | ${r} |`),""].join(`
|
|
16
|
-
`)}(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]="a2e77c4f-3899-518a-885f-ce5dd2090ac6")}catch{}})();var eR=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],tR=new Map(eR.map(e=>[e.exit_code,e.class]));function Bs(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function nR(e){if(!e)return[];let t=new Set,n=new Set;return e.map(i=>{let r=i.state.trim(),s=i.probe_id.trim(),o=Bs(i.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(r)||!/^[a-z][a-z0-9-]*$/.test(s)||o.length===0||t.has(r)||n.has(s))throw new TypeError("Invalid pm refusal state contract");return t.add(r),n.add(s),{state:r,probe_id:s,entrypoints:o,expected_exit_class:i.expected_exit_class}}).sort((i,r)=>i.state.localeCompare(r.state))}function iR(e,t,n,i,r){return![[1,2,3,4,5].includes(e.exit_code),e.meaning.trim().length>0,e.recovery.trim().length>0,t.length>0,n.length>0,/^[a-z][a-z0-9_]*$/.test(i),r.every(s=>/^[a-z][a-z0-9_]*$/.test(s)),tR.get(e.exit_code)===e.class].includes(!1)}function rR(e,t){let n=e,i=new Set;for(;n.canonical_code!==n.code;){if(i.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);i.add(n.code);let r=t.get(n.canonical_code);if(!r)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=r}return n}function sR(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let i=rR(n,t);if(i.exit_code!==n.exit_code||i.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let r=e.filter(s=>s.code!==i.code&&s.canonical_code===i.code).map(s=>s.code).sort();if(n.code===i.code?JSON.stringify(n.aliases)!==JSON.stringify(r):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function cy(e){let t=new Set,n=e.map(i=>{let r=i.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(r))throw new TypeError(`Invalid pm error code: ${JSON.stringify(i.code)}`);if(t.has(r))throw new TypeError(`Duplicate pm error code: ${r}`);t.add(r);let s=Bs(i.sources),o=Bs(i.emitting_commands),a=(i.canonical_code??r).trim(),c=Bs(i.aliases??[]),d=nR(i.owned_states);if(!iR(i,s,o,a,c))throw new TypeError(`Invalid pm error code contract: ${r}`);if(d.some(l=>l.expected_exit_class!==i.class))throw new TypeError(`Invalid pm refusal state exit class: ${r}`);return Object.freeze({...i,code:r,meaning:i.meaning.trim(),recovery:i.recovery.trim(),sources:s,emitting_commands:o,canonical_code:a,aliases:c,owned_states:d})});return sR(n),Object.freeze(n.sort((i,r)=>i.code.localeCompare(r.code)))}function Kz(e,t){let n=ay(e,t);return ay(n.canonical_code??n.code,t)}function ay(e,t){let n=e.trim(),i=t.find(r=>r.code===n);if(!i)throw new TypeError(`Unknown pm error code "${n}"`);return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ea8d1914-d35c-5fb6-a047-6f9e1aa9d22e")}catch{}})();var dy=[{code:"acceptance_criteria_mutation_conflict",meaning:"Acceptance criteria mutation conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"],canonical_code:"acceptance_criteria_mutation_conflict",aliases:[]},{code:"acceptance_criteria_remove_unmatched",meaning:"Acceptance criteria remove unmatched condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"],canonical_code:"acceptance_criteria_remove_unmatched",aliases:[]},{code:"acceptance_criteria_semicolon_forbidden",meaning:"Acceptance criteria semicolon forbidden condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"],canonical_code:"acceptance_criteria_semicolon_forbidden",aliases:[]},{code:"accepted_rejected_value",meaning:"Accepted rejected value condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"accepted_rejected_value",aliases:[]},{code:"alias_collision",meaning:"Alias collision condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"alias_collision",aliases:[]},{code:"alias_target_missing",meaning:"Alias target missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"alias_target_missing",aliases:[]},{code:"already_claimed_by",meaning:"Already claimed by condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"],canonical_code:"already_claimed_by",aliases:[]},{code:"ambiguous_option_combination",meaning:"Ambiguous option combination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"ambiguous_option_combination",aliases:[]},{code:"annotation_alias_conflict",meaning:"Annotation alias conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_alias_conflict",aliases:[]},{code:"annotation_flag_like_value",meaning:"Annotation flag like value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_flag_like_value",aliases:[]},{code:"annotation_if_absent_without_append",meaning:"Annotation if absent without append condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_if_absent_without_append",aliases:[]},{code:"annotation_message_without_text",meaning:"Annotation message without text condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_message_without_text",aliases:[]},{code:"annotation_transposed_subcommand",meaning:"Annotation transposed subcommand condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_transposed_subcommand",aliases:[]},{code:"append_empty_body",meaning:"Append empty body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"],canonical_code:"append_empty_body",aliases:[]},{code:"assurance_registry_invalid",meaning:"Assurance registry invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/assurance.ts"],emitting_commands:["*"],canonical_code:"assurance_registry_invalid",aliases:[]},{code:"bare_comma_entry_ambiguous",meaning:"Bare comma entry ambiguous condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"],canonical_code:"bare_comma_entry_ambiguous",aliases:[]},{code:"body_file_conflicts_with_body",meaning:"Body file conflicts with body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_conflicts_with_body",aliases:[]},{code:"body_file_missing_path",meaning:"Body file missing path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_missing_path",aliases:[]},{code:"body_file_unreadable",meaning:"Body file unreadable condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_unreadable",aliases:[]},{code:"budget_exceeded",meaning:"Budget exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"budget_exceeded",aliases:[]},{code:"bulk_ids_input_empty",meaning:"Bulk ids input empty condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts","sdk/history-compact.ts","sdk/history-mcp.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_empty",aliases:[],owned_states:[{state:"bulk_ids_stdin_contains_no_nonempty_ids",probe_id:"bulk-ids-stdin-empty",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_missing_path",meaning:"Bulk ids input missing path condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_missing_path",aliases:[],owned_states:[{state:"bulk_ids_file_token_omits_its_path",probe_id:"bulk-ids-file-path-missing",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_unreadable",meaning:"Bulk ids input unreadable condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_unreadable",aliases:[],owned_states:[{state:"bulk_ids_file_path_cannot_be_read",probe_id:"bulk-ids-file-unreadable",entrypoints:["update-many"],expected_exit_class:"not_found"}]},{code:"bundle_integrity_torn_install",meaning:"Bundle integrity torn install condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/bundle-integrity.ts"],emitting_commands:["*"],canonical_code:"bundle_integrity_torn_install",aliases:[]},{code:"capability_undeclared",meaning:"Capability undeclared condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"capability_undeclared",aliases:[]},{code:"capability_unused",meaning:"Capability unused condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"capability_unused",aliases:[]},{code:"child_projection_item_bound_exceeded",meaning:"Child projection item bound exceeded condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-children.ts"],emitting_commands:["*"],canonical_code:"child_projection_item_bound_exceeded",aliases:[]},{code:"close_reason_required",meaning:"Close reason required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"],canonical_code:"close_reason_required",aliases:[]},{code:"close_through_update",meaning:"Close through update condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"close_through_update",aliases:[]},{code:"close_validation_missing_fields",meaning:"Close validation missing fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"close_validation_missing_fields",aliases:[]},{code:"collected_zero_items",meaning:"Collected zero items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"collected_zero_items",aliases:[]},{code:"collection_transposed_subcommand",meaning:"Collection transposed subcommand condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"collection_transposed_subcommand",aliases:[]},{code:"command_failed",meaning:"Command failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"command_failed",aliases:[]},{code:"command_namespace",meaning:"Command namespace condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"],canonical_code:"command_namespace",aliases:[]},{code:"command_override_conflict",meaning:"Command override conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"command_override_conflict",aliases:[]},{code:"config_duplicate",meaning:"Config duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_duplicate",aliases:[]},{code:"config_key_unknown",meaning:"Config key unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_key_unknown",aliases:[]},{code:"config_value_invalid",meaning:"Config value invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_value_invalid",aliases:[]},{code:"conflicting_lifecycle_owner",meaning:"Conflicting lifecycle owner condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-operations.ts"],emitting_commands:["*"],canonical_code:"conflicting_lifecycle_owner",aliases:[]},{code:"context_signal_store_invalid",meaning:"Context signal store invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_invalid",aliases:[]},{code:"context_signal_store_stale",meaning:"Context signal store stale condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_stale",aliases:[]},{code:"context_signal_store_write_failed",meaning:"Context signal store write failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_write_failed",aliases:[]},{code:"context_takes_no_item_argument",meaning:"Context takes no item argument condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"context_takes_no_item_argument",aliases:[]},{code:"core_item_field_requires_dedicated_flag",meaning:"Core item field requires dedicated flag condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"core_item_field_requires_dedicated_flag",aliases:[]},{code:"create_positional_type_without_title",meaning:"Create positional type without title condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts"],emitting_commands:["*"],canonical_code:"create_positional_type_without_title",aliases:[]},{code:"dependency_edge_not_allowed",meaning:"Dependency edge not allowed condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_edge_not_allowed",aliases:[]},{code:"dependency_flag_value_invalid",meaning:"Dependency flag value invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_flag_value_invalid",aliases:[]},{code:"dependency_remove_no_match",meaning:"Dependency remove no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"dependency_remove_no_match",aliases:[]},{code:"dependency_target_not_found",meaning:"Dependency target not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_target_not_found",aliases:[]},{code:"dependency_temporal_order_invalid",meaning:"Dependency temporal order invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_temporal_order_invalid",aliases:[]},{code:"duplicate_canonical_flag",meaning:"Duplicate canonical flag condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_canonical_flag",aliases:[]},{code:"duplicate_command",meaning:"Duplicate command condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"duplicate_command",aliases:[]},{code:"duplicate_destination",meaning:"Duplicate destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_destination",aliases:[]},{code:"duplicate_edge",meaning:"Duplicate edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"],canonical_code:"duplicate_edge",aliases:[]},{code:"duplicate_observation",meaning:"Duplicate observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_observation",aliases:[]},{code:"duplicate_probe",meaning:"Duplicate probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"duplicate_probe",aliases:[]},{code:"duplicate_sweep_cost_limit",meaning:"Duplicate sweep cost limit condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/duplicate-candidates.ts"],emitting_commands:["duplicate-candidates"],canonical_code:"duplicate_sweep_cost_limit",aliases:[]},{code:"duplicate_target_circular",meaning:"Duplicate target circular condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_circular",aliases:[]},{code:"duplicate_target_is_duplicate",meaning:"Duplicate target is duplicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_is_duplicate",aliases:[]},{code:"duplicate_target_missing",meaning:"Duplicate target missing condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_missing",aliases:[]},{code:"duplicate_target_self",meaning:"Duplicate target self condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_self",aliases:[]},{code:"empty_corpus",meaning:"Empty corpus condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"empty_corpus",aliases:[]},{code:"empty_surface",meaning:"Empty surface condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"empty_surface",aliases:[]},{code:"error_code_mismatch",meaning:"Error code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"error_code_mismatch",aliases:[]},{code:"event_cursor_query_mismatch",meaning:"Event cursor query mismatch condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"event_cursor_query_mismatch",aliases:[]},{code:"event_index_unavailable",meaning:"Event index unavailable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"event_index_unavailable",aliases:[]},{code:"exit_code_mismatch",meaning:"Exit code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"exit_code_mismatch",aliases:[]},{code:"extension_command_activation_failed",meaning:"Extension command activation failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/commander-usage.ts"],emitting_commands:["*"],canonical_code:"extension_command_activation_failed",aliases:[]},{code:"extension_dependency_name_unsafe",meaning:"Extension dependency name unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_name_unsafe",aliases:[]},{code:"extension_dependency_spec_invalid",meaning:"Extension dependency spec invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_spec_invalid",aliases:[]},{code:"extension_dependency_version_unsafe",meaning:"Extension dependency version unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_version_unsafe",aliases:[]},{code:"extension_install_soft_failed",meaning:"Extension install soft failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"],canonical_code:"extension_install_soft_failed",aliases:[]},{code:"extension_install_source_contains_destination",meaning:"Extension install source contains destination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_install_source_contains_destination",aliases:[]},{code:"extension_item_field_reserved",meaning:"Extension item field reserved condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_reserved",aliases:[]},{code:"extension_item_field_type_conflict",meaning:"Extension item field type conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_type_conflict",aliases:[]},{code:"extension_item_field_unknown",meaning:"Extension item field unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_unknown",aliases:[]},{code:"extension_mutation_guard_failed",meaning:"Extension mutation guard failed condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_failed",aliases:[]},{code:"extension_mutation_guard_invalid_decision",meaning:"Extension mutation guard invalid decision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_invalid_decision",aliases:[]},{code:"extension_mutation_guard_invalid_denial",meaning:"Extension mutation guard invalid denial condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_invalid_denial",aliases:[]},{code:"extension_mutation_guard_timed_out",meaning:"Extension mutation guard timed out condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_timed_out",aliases:[]},{code:"extension_update_health_partial_coverage",meaning:"Extension update health partial coverage condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"extension_update_health_partial_coverage",aliases:[]},{code:"field_duplicate",meaning:"Field duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_duplicate",aliases:[]},{code:"field_invalid",meaning:"Field invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_invalid",aliases:[]},{code:"field_mcp_input_collision",meaning:"Field mcp input collision condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_mcp_input_collision",aliases:[]},{code:"github_source_entry_unbuilt",meaning:"Github source entry unbuilt condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/shared.ts"],emitting_commands:["*"],canonical_code:"github_source_entry_unbuilt",aliases:[]},{code:"hierarchy_cardinality_created",meaning:"Hierarchy cardinality created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_cardinality_created",aliases:[]},{code:"hierarchy_cycle_created",meaning:"Hierarchy cycle created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_cycle_created",aliases:[]},{code:"hierarchy_parent_divergence_created",meaning:"Hierarchy parent divergence created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_parent_divergence_created",aliases:[]},{code:"history_author_acknowledge_plan_conflict",meaning:"History author acknowledge plan conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_plan_conflict",aliases:[]},{code:"history_author_acknowledge_plan_fingerprint_required",meaning:"History author acknowledge plan fingerprint required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_plan_fingerprint_required",aliases:[]},{code:"history_author_acknowledge_preview_limit_invalid",meaning:"History author acknowledge preview limit invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_preview_limit_invalid",aliases:[]},{code:"history_author_acknowledge_required_values_missing",meaning:"History author acknowledge required values missing condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_required_values_missing",aliases:[]},{code:"history_author_acknowledge_selector_conflict",meaning:"History author acknowledge selector conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_selector_conflict",aliases:[]},{code:"history_author_acknowledge_selector_required",meaning:"History author acknowledge selector required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_selector_required",aliases:[]},{code:"history_author_acknowledge_target_not_actionable",meaning:"History author acknowledge target not actionable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_target_not_actionable",aliases:[]},{code:"history_author_acknowledge_target_unreadable",meaning:"History author acknowledge target unreadable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_target_unreadable",aliases:[]},{code:"history_baseline_unavailable",meaning:"History baseline unavailable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_baseline_unavailable",aliases:[]},{code:"history_drift_chain_mismatch",meaning:"History drift chain mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_chain_mismatch",aliases:["validate_history_drift_chain_mismatches"]},{code:"history_drift_hash_mismatch",meaning:"History drift hash mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_hash_mismatch",aliases:["validate_history_drift_hash_mismatches"]},{code:"history_drift_merge_receipt",meaning:"History drift merge receipt condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_merge_receipt",aliases:[]},{code:"history_drift_missing_stream",meaning:"History drift missing stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_missing_stream",aliases:["validate_history_drift_missing_streams"]},{code:"history_drift_unreadable_stream",meaning:"History drift unreadable stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_unreadable_stream",aliases:["validate_history_drift_unreadable_streams"]},{code:"history_drift_version_skew",meaning:"History drift version skew condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_version_skew",aliases:["validate_history_drift_version_skews"]},{code:"history_json_invalid",meaning:"History json invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"],canonical_code:"history_json_invalid",aliases:[]},{code:"history_merge_conflict_markers_detected",meaning:"History merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"],canonical_code:"merge_conflict_markers_detected",aliases:[]},{code:"history_replay_invalid",meaning:"History replay invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts","core/history/tombstone.ts"],emitting_commands:["*"],canonical_code:"history_replay_invalid",aliases:[]},{code:"history_salvage_refused",meaning:"History salvage refused condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history/salvage.ts"],emitting_commands:["*"],canonical_code:"history_salvage_refused",aliases:[]},{code:"history_stream_over_compact_threshold",meaning:"History stream over compact threshold condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_stream_over_compact_threshold",aliases:[]},{code:"history_target_out_of_range",meaning:"History target out of range condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_target_out_of_range",aliases:[]},{code:"history_timestamp_invalid",meaning:"History timestamp invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/event-index.ts","core/history/history.ts"],emitting_commands:["*"],canonical_code:"history_timestamp_invalid",aliases:[]},{code:"history_unknown_author_events",meaning:"History unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_unknown_author_events",aliases:["validate_history_unknown_author_events"]},{code:"history_version_mapping_unavailable",meaning:"History version mapping unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/version-address.ts"],emitting_commands:["*"],canonical_code:"history_version_mapping_unavailable",aliases:[]},{code:"history_version_pruned",meaning:"History version pruned condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_version_pruned",aliases:[]},{code:"host_environment_capacity_fault",meaning:"Host environment capacity fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_capacity_fault",aliases:[]},{code:"host_environment_operation_invalid",meaning:"Host environment operation invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_operation_invalid",aliases:[]},{code:"host_environment_permission_fault",meaning:"Host environment permission fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_permission_fault",aliases:[]},{code:"host_environment_resource_fault",meaning:"Host environment resource fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_resource_fault",aliases:[]},{code:"improvement_metric_contract_conflict",meaning:"Improvement metric contract conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"improvement_metric_contract_conflict",aliases:[]},{code:"improvement_observation_conflict",meaning:"Improvement observation conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"improvement_observation_conflict",aliases:[]},{code:"incomplete_allowed_values",meaning:"Incomplete allowed values condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"incomplete_allowed_values",aliases:[]},{code:"inconsistent_concept_kind",meaning:"Inconsistent concept kind condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"inconsistent_concept_kind",aliases:[]},{code:"init_existing_settings_requires_force",meaning:"Init existing settings requires force condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_existing_settings_requires_force",aliases:[]},{code:"init_gitignore_unwritable",meaning:"Init gitignore unwritable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace.ts"],emitting_commands:["*"],canonical_code:"init_gitignore_unwritable",aliases:[]},{code:"init_id_prefix_conflict",meaning:"Init id prefix conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_id_prefix_conflict",aliases:[]},{code:"init_id_prefix_path_like",meaning:"Init id prefix path like condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_id_prefix_path_like",aliases:[]},{code:"integrity_history_conflict_marker",meaning:"Integrity history conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_conflict_marker",aliases:["validate_storage_history_conflict_markers"]},{code:"integrity_history_invalid_json",meaning:"Integrity history invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_invalid_json",aliases:[]},{code:"integrity_history_unreadable",meaning:"Integrity history unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_unreadable",aliases:[]},{code:"integrity_item_ahead_format_version",meaning:"Integrity item ahead format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_ahead_format_version",aliases:["validate_format_version_ahead_items"]},{code:"integrity_item_conflict_marker",meaning:"Integrity item conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_conflict_marker",aliases:[]},{code:"integrity_item_outdated_format_version",meaning:"Integrity item outdated format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_outdated_format_version",aliases:["validate_format_version_outdated_items"]},{code:"integrity_item_parse_failed",meaning:"Integrity item parse failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_parse_failed",aliases:[]},{code:"integrity_item_unreadable",meaning:"Integrity item unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_unreadable",aliases:[]},{code:"invalid_argument_value",meaning:"Invalid argument value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/governance/assurance-mutation-error.ts","sdk/lifecycle/create.ts"],emitting_commands:["*","create"],canonical_code:"invalid_argument_value",aliases:[]},{code:"invalid_command_usage",meaning:"Invalid command usage condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"invalid_command_usage",aliases:[]},{code:"invalid_event_cursor",meaning:"Invalid event cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_cursor",aliases:[]},{code:"invalid_event_cursor_mode",meaning:"Invalid event cursor mode condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-list-query.ts","sdk/mutation-events.ts","sdk/runtime-extended-actions.ts"],emitting_commands:["*"],canonical_code:"invalid_event_cursor_mode",aliases:[]},{code:"invalid_event_follow_interval",meaning:"Invalid event follow interval condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_follow_interval",aliases:[]},{code:"invalid_event_limit",meaning:"Invalid event limit condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_limit",aliases:[]},{code:"invalid_event_since",meaning:"Invalid event since condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_since",aliases:[]},{code:"invalid_history_analytics_limit",meaning:"Invalid history analytics limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_limit",aliases:[]},{code:"invalid_history_analytics_minimum_sample",meaning:"Invalid history analytics minimum sample condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_minimum_sample",aliases:[]},{code:"invalid_history_analytics_since",meaning:"Invalid history analytics since condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_since",aliases:[]},{code:"invalid_improvement_ledger",meaning:"Invalid improvement ledger condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger-validation.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_ledger",aliases:[]},{code:"invalid_improvement_metric",meaning:"Invalid improvement metric condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_metric",aliases:[]},{code:"invalid_improvement_observation",meaning:"Invalid improvement observation condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation",aliases:[]},{code:"invalid_improvement_observation_limit",meaning:"Invalid improvement observation limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation_limit",aliases:[]},{code:"invalid_improvement_observation_timestamp",meaning:"Invalid improvement observation timestamp condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation_timestamp",aliases:[]},{code:"invalid_provenance_predicate",meaning:"Invalid provenance predicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"],canonical_code:"invalid_provenance_predicate",aliases:[]},{code:"invalid_query_cursor",meaning:"Invalid query cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/pagination.ts"],emitting_commands:["*"],canonical_code:"invalid_query_cursor",aliases:[]},{code:"invalid_read_output_session",meaning:"Invalid read output session condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output-session.ts"],emitting_commands:["*"],canonical_code:"invalid_read_output_session",aliases:[]},{code:"invalid_reproducible_process_environment",meaning:"Invalid reproducible process environment condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/reproducibility/process.ts"],emitting_commands:["*"],canonical_code:"invalid_reproducible_process_environment",aliases:[]},{code:"invalid_workspace_snapshot_target",meaning:"Invalid workspace snapshot target condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"invalid_workspace_snapshot_target",aliases:[]},{code:"item_already_active",meaning:"Item already active condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"item_already_active",aliases:[]},{code:"item_deleted",meaning:"Item deleted condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/tombstone.ts"],emitting_commands:["*"],canonical_code:"item_deleted",aliases:[]},{code:"item_document_encoding_invalid",meaning:"Item document encoding invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"],canonical_code:"item_document_encoding_invalid",aliases:[]},{code:"item_document_invalid",meaning:"Item document invalid condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_document_invalid",aliases:[]},{code:"item_document_roundtrip_failed",meaning:"Item document roundtrip failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_document_roundtrip_failed",aliases:[]},{code:"item_id_collision",meaning:"Item id collision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"],canonical_code:"item_id_collision",aliases:[]},{code:"item_identity_ambiguous",meaning:"Item identity ambiguous condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"],canonical_code:"item_identity_ambiguous",aliases:[]},{code:"item_identity_conflict",meaning:"Item identity conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/three-way.ts"],emitting_commands:["*"],canonical_code:"item_identity_conflict",aliases:[]},{code:"item_identity_reserved",meaning:"Item identity reserved condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/history.ts"],emitting_commands:["*"],canonical_code:"item_identity_reserved",aliases:[]},{code:"item_not_found",meaning:"Item not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"item_not_found",aliases:[]},{code:"likely_duplicate",meaning:"Likely duplicate condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/similarity.ts"],emitting_commands:["*"],canonical_code:"likely_duplicate",aliases:[]},{code:"linked_artifact_mutation_conflict",meaning:"Linked artifact mutation conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/linked-artifacts.ts"],emitting_commands:["*"],canonical_code:"linked_artifact_mutation_conflict",aliases:[]},{code:"linked_test_remove_no_match",meaning:"Linked test remove no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"linked_test_remove_no_match",aliases:[]},{code:"linked_test_value_not_quoted",meaning:"Linked test value not quoted condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"linked_test_value_not_quoted",aliases:[]},{code:"list_source_incomplete",meaning:"List source incomplete condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/list.ts"],emitting_commands:["list"],canonical_code:"list_source_incomplete",aliases:[]},{code:"local_package_archive_unsafe",meaning:"Local package archive unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"local_package_archive_unsafe",aliases:[]},{code:"local_source_not_found_bare_name",meaning:"Local source not found bare name condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"local_source_not_found_bare_name",aliases:[]},{code:"lock_conflict",meaning:"Lock conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"lock_conflict",aliases:[]},{code:"locks_stale_count",meaning:"Locks stale count condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"locks_stale_count",aliases:[]},{code:"locks_unreadable",meaning:"Locks unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"locks_unreadable",aliases:[]},{code:"malformed_plan_step_evidence",meaning:"Malformed plan step evidence condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"malformed_plan_step_evidence",aliases:[]},{code:"manifest_capabilities_absent",meaning:"Manifest capabilities absent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"manifest_capabilities_absent",aliases:[]},{code:"manifest_unknown_key",meaning:"Manifest unknown key condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/manifest-schema.ts"],emitting_commands:["*"],canonical_code:"manifest_unknown_key",aliases:[],owned_states:[{state:"author_workspace_manifest_declares_an_unknown_top_level_key",probe_id:"author-manifest-unknown-key",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"mcp_annotation_file_unavailable",meaning:"Mcp annotation file unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/runtime-input.ts"],emitting_commands:["*"],canonical_code:"mcp_annotation_file_unavailable",aliases:[]},{code:"mcp_stdin_unavailable",meaning:"Mcp stdin unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"mcp_stdin_unavailable",aliases:[]},{code:"mcp_task_not_found_or_not_authorized",meaning:"Mcp task not found or not authorized condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mcp/tasks.ts"],emitting_commands:["*"],canonical_code:"mcp_task_not_found_or_not_authorized",aliases:[]},{code:"merge_conflict_markers_detected",meaning:"Merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"merge_conflict_markers_detected",aliases:["history_merge_conflict_markers_detected"]},{code:"merge_decisions_unreviewed",meaning:"Merge decisions unreviewed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_decisions_unreviewed",aliases:[]},{code:"merge_git_config_unwritable",meaning:"Merge git config unwritable condition.",stability:"stable",exit_code:5,class:"dependency_failed",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_git_config_unwritable",aliases:[]},{code:"merge_receipt_evidence_invalid",meaning:"Merge receipt evidence invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts","sdk/merge/reconcile.ts"],emitting_commands:["*"],canonical_code:"merge_receipt_evidence_invalid",aliases:[]},{code:"merge_receipt_history_reference_missing",meaning:"Merge receipt history reference missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_receipt_history_reference_missing",aliases:[]},{code:"merge_receipts_pending",meaning:"Merge receipts pending condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_receipts_pending",aliases:[]},{code:"merge_reconcile_receipt_evidence_untrusted",meaning:"Merge reconcile receipt evidence untrusted condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-repair.ts"],emitting_commands:["*"],canonical_code:"merge_reconcile_receipt_evidence_untrusted",aliases:[]},{code:"merge_root_not_found",meaning:"Merge root not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_root_not_found",aliases:[]}];(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]="fec88380-eb4c-5be0-93fa-87a444fd7825")}catch{}})();var ly=[{code:"missing_allowed_values",meaning:"Missing allowed values condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_allowed_values",aliases:[]},{code:"missing_budget",meaning:"Missing budget condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_budget",aliases:[]},{code:"missing_cli_flag",meaning:"Missing cli flag condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/tool-option-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_cli_flag",aliases:[]},{code:"missing_destination",meaning:"Missing destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_destination",aliases:[]},{code:"missing_directory",meaning:"Missing directory condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"missing_directory",aliases:[]},{code:"missing_init_recovery",meaning:"Missing init recovery condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_init_recovery",aliases:[]},{code:"missing_lifecycle_target",meaning:"Missing lifecycle target condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension.ts"],emitting_commands:["*"],canonical_code:"missing_lifecycle_target",aliases:[]},{code:"missing_observation",meaning:"Missing observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_observation",aliases:[]},{code:"missing_observed_signature",meaning:"Missing observed signature condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_observed_signature",aliases:[]},{code:"missing_parameter_alias",meaning:"Missing parameter alias condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/tool-option-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_parameter_alias",aliases:[]},{code:"missing_positive_execution_receipt",meaning:"Missing positive execution receipt condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"missing_positive_execution_receipt",aliases:[]},{code:"missing_probe",meaning:"Missing probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_probe",aliases:[]},{code:"missing_required_argument",meaning:"Missing required argument condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","cli/schema/registration.ts","core/telemetry/observability.ts","sdk/governance/assurance-action.ts","sdk/history-redact.ts","sdk/invocation-author.ts"],emitting_commands:["*"],canonical_code:"missing_required_argument",aliases:[]},{code:"missing_required_option",meaning:"Missing required option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"],canonical_code:"missing_required_option",aliases:[]},{code:"missing_suggested_retry",meaning:"Missing suggested retry condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_suggested_retry",aliases:[]},{code:"missing_suggested_retry_args",meaning:"Missing suggested retry args condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_suggested_retry_args",aliases:[]},{code:"module_import_failed",meaning:"Module import failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"module_import_failed",aliases:[]},{code:"multi_target_github_install_ambiguous",meaning:"Multi target github install ambiguous condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"],canonical_code:"multi_target_github_install_ambiguous",aliases:[]},{code:"mutation_author_required",meaning:"Mutation author required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"],canonical_code:"mutation_author_required",aliases:[]},{code:"mutation_secret_guard_blocked",meaning:"Mutation secret guard blocked condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"],canonical_code:"mutation_secret_guard_blocked",aliases:[]},{code:"no_matching_tests",meaning:"No matching tests condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_matching_tests",aliases:[]},{code:"no_projects_matched_filters",meaning:"No projects matched filters condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_projects_matched_filters",aliases:[]},{code:"no_test_files_found",meaning:"No test files found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_test_files_found",aliases:[]},{code:"no_tests_found",meaning:"No tests found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_tests_found",aliases:[]},{code:"no_update_fields",meaning:"No update fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"no_update_fields",aliases:[]},{code:"no_version_bounds_declared",meaning:"No version bounds declared condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/manifest-schema.ts"],emitting_commands:["*"],canonical_code:"no_version_bounds_declared",aliases:[],owned_states:[{state:"author_workspace_manifest_omits_canonical_pm_version_bounds",probe_id:"author-manifest-version-bounds-missing",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"non_refusal_exit",meaning:"Non refusal exit condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"non_refusal_exit",aliases:[]},{code:"npm_pack_json_shape_unsupported",meaning:"Npm pack json shape unsupported condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_pack_json_shape_unsupported",aliases:[]},{code:"npm_package_archive_missing",meaning:"Npm package archive missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_archive_missing",aliases:[]},{code:"npm_package_archive_unsafe",meaning:"Npm package archive unsafe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_archive_unsafe",aliases:[]},{code:"npm_package_not_found",meaning:"Npm package not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_not_found",aliases:[]},{code:"ownership_conflict",meaning:"Ownership conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"ownership_conflict",aliases:[]},{code:"ownership_dependency_bypass_restricted_options",meaning:"Ownership dependency bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"ownership_dependency_bypass_restricted_options",aliases:[]},{code:"ownership_metadata_bypass_restricted_options",meaning:"Ownership metadata bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"ownership_metadata_bypass_restricted_options",aliases:[]},{code:"package_spec_empty",meaning:"Package spec empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"package_spec_empty",aliases:[]},{code:"package_upgrade_modes_mutually_exclusive",meaning:"Package upgrade modes mutually exclusive condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/upgrade.ts"],emitting_commands:["*"],canonical_code:"package_upgrade_modes_mutually_exclusive",aliases:[]},{code:"positional_shape_budget_exceeded",meaning:"Positional shape budget exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"positional_shape_budget_exceeded",aliases:[]},{code:"positional_signature_mismatch",meaning:"Positional signature mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"positional_signature_mismatch",aliases:[]},{code:"profile_name_empty",meaning:"Profile name empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_name_empty",aliases:[]},{code:"profile_name_not_normalized",meaning:"Profile name not normalized condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_name_not_normalized",aliases:[]},{code:"profile_summary_empty",meaning:"Profile summary empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_summary_empty",aliases:[]},{code:"profile_title_empty",meaning:"Profile title empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_title_empty",aliases:[]},{code:"project_runtime_history_epoch_incompatible",meaning:"Project runtime history epoch incompatible condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_history_epoch_incompatible",aliases:[]},{code:"project_runtime_stale_mutation",meaning:"Project runtime stale mutation condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_stale_mutation",aliases:[]},{code:"project_runtime_stale_read",meaning:"Project runtime stale read condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_stale_read",aliases:[]},{code:"projection_options_mutually_exclusive",meaning:"Projection options mutually exclusive condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"],canonical_code:"projection_options_mutually_exclusive",aliases:[]},{code:"provenance_value_domain_invalid",meaning:"Provenance value domain invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"provenance_value_domain_invalid",aliases:[]},{code:"read_output_cursor_command_mismatch",meaning:"Read output cursor command mismatch condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_command_mismatch",aliases:[]},{code:"read_output_cursor_invalid",meaning:"Read output cursor invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_invalid",aliases:[]},{code:"read_output_cursor_stale",meaning:"Read output cursor stale condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_stale",aliases:[]},{code:"recovery_kind_mismatch",meaning:"Recovery kind mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"recovery_kind_mismatch",aliases:[]},{code:"redundant_edge",meaning:"Redundant edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"],canonical_code:"redundant_edge",aliases:[]},{code:"refusal_allowed_values_mismatch",meaning:"Refusal allowed values mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_allowed_values_mismatch",aliases:[]},{code:"refusal_error_code_mismatch",meaning:"Refusal error code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_error_code_mismatch",aliases:[]},{code:"refusal_exit_code_mismatch",meaning:"Refusal exit code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_exit_code_mismatch",aliases:[]},{code:"refusal_mutated_state",meaning:"Refusal mutated state condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_mutated_state",aliases:[]},{code:"refusal_probe_missing",meaning:"Refusal probe missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_probe_missing",aliases:[]},{code:"refusal_recovery_failed",meaning:"Refusal recovery failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_recovery_failed",aliases:[]},{code:"reindex_already_running",meaning:"Reindex already running condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/reindex.ts"],emitting_commands:["*"],canonical_code:"reindex_already_running",aliases:[]},{code:"removed_canonical_spelling",meaning:"Removed canonical spelling condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"removed_canonical_spelling",aliases:[]},{code:"removed_compatibility_spelling",meaning:"Removed compatibility spelling condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"removed_compatibility_spelling",aliases:[]},{code:"reopen_reason_required",meaning:"Reopen reason required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"],canonical_code:"reopen_reason_required",aliases:[]},{code:"reopen_receipt_missing",meaning:"Reopen receipt missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"reopen_receipt_missing",aliases:[]},{code:"reopen_target_status_invalid",meaning:"Reopen target status invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"],canonical_code:"reopen_target_status_invalid",aliases:[]},{code:"reported_zero_passes",meaning:"Reported zero passes condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"reported_zero_passes",aliases:[]},{code:"reported_zero_tests",meaning:"Reported zero tests condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"reported_zero_tests",aliases:[]},{code:"reserved_item_field",meaning:"Reserved item field condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"reserved_item_field",aliases:[]},{code:"retry_failed",meaning:"Retry failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"retry_failed",aliases:[]},{code:"schema_migration_input_required",meaning:"Schema migration input required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/migration-gates.ts"],emitting_commands:["*"],canonical_code:"schema_migration_input_required",aliases:[]},{code:"semantic_spelling_collision",meaning:"Semantic spelling collision condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"semantic_spelling_collision",aliases:[]},{code:"settings_read_fs_error",meaning:"Settings read fs error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_fs_error",aliases:[]},{code:"settings_read_invalid_json",meaning:"Settings read invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_invalid_json",aliases:[]},{code:"settings_read_invalid_schema",meaning:"Settings read invalid schema condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_invalid_schema",aliases:[]},{code:"settings_read_merge_failed",meaning:"Settings read merge failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_merge_failed",aliases:[]},{code:"stale_budget",meaning:"Stale budget condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_budget",aliases:[]},{code:"stale_destination",meaning:"Stale destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_destination",aliases:[]},{code:"stale_observed_signature",meaning:"Stale observed signature condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_observed_signature",aliases:[]},{code:"status_duplicate",meaning:"Status duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"status_duplicate",aliases:[]},{code:"status_invalid",meaning:"Status invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"status_invalid",aliases:[]},{code:"status_lifecycle_role_required",meaning:"Status lifecycle role required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"status_lifecycle_role_required",aliases:[]},{code:"stdin_json_invalid",meaning:"Stdin json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"stdin_json_invalid",aliases:[]},{code:"stdin_json_unknown_key",meaning:"Stdin json unknown key condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"stdin_json_unknown_key",aliases:[]},{code:"structured_event_immutable",meaning:"Structured event immutable condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"structured_event_immutable",aliases:[]},{code:"structured_event_input_conflict",meaning:"Structured event input conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_input_conflict",aliases:[]},{code:"structured_event_json_empty",meaning:"Structured event json empty condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_json_empty",aliases:[]},{code:"structured_event_json_invalid",meaning:"Structured event json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_json_invalid",aliases:[]},{code:"structured_event_since_invalid",meaning:"Structured event since invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_since_invalid",aliases:[]},{code:"suggested_retry_args_mismatch",meaning:"Suggested retry args mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"suggested_retry_args_mismatch",aliases:[]},{code:"telemetry_endpoint_probe_failed",meaning:"Telemetry endpoint probe failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_endpoint_probe_failed",aliases:[]},{code:"telemetry_endpoint_probe_http_status",meaning:"Telemetry endpoint probe http status condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_endpoint_probe_http_status",aliases:[]},{code:"telemetry_otel_export_failing",meaning:"Telemetry otel export failing condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_otel_export_failing",aliases:[]},{code:"telemetry_queue_high_retries",meaning:"Telemetry queue high retries condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_high_retries",aliases:[]},{code:"telemetry_queue_invalid_rows",meaning:"Telemetry queue invalid rows condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_invalid_rows",aliases:[]},{code:"telemetry_queue_pending",meaning:"Telemetry queue pending condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_pending",aliases:[]},{code:"telemetry_schema_version_behind",meaning:"Telemetry schema version behind condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_schema_version_behind",aliases:[]},{code:"telemetry_state_invalid_json",meaning:"Telemetry state invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_state_invalid_json",aliases:[]},{code:"template_type_unknown",meaning:"Template type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"template_type_unknown",aliases:[]},{code:"terminal_plan_mutation",meaning:"Terminal plan mutation condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"terminal_plan_mutation",aliases:[]},{code:"terminal_state_conflict",meaning:"Terminal state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"terminal_state_conflict",aliases:[]},{code:"tracked_runtime_cache_files",meaning:"Tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"tracked_runtime_cache_files",aliases:["validate_storage_tracked_runtime_cache_files"]},{code:"tracker_not_initialized",meaning:"Tracker not initialized condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/store/tracker-preflight.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"tracker_not_initialized",aliases:[],owned_states:[{state:"selected_tracker_root_exists_without_settings",probe_id:"tracker-root-settings-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_missing",meaning:"Tracker root missing condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_missing",aliases:[],owned_states:[{state:"selected_tracker_root_does_not_exist",probe_id:"tracker-root-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_not_directory",meaning:"Tracker root not directory condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_not_directory",aliases:[],owned_states:[{state:"selected_tracker_root_is_a_regular_file",probe_id:"tracker-root-not-directory",entrypoints:["list"],expected_exit_class:"usage"}]},{code:"tracker_root_unreadable",meaning:"Tracker root unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_unreadable",aliases:[],owned_states:[{state:"selected_tracker_root_is_not_readable",probe_id:"tracker-root-unreadable",entrypoints:["list"],expected_exit_class:"generic_failure"}]},{code:"type_duplicate",meaning:"Type duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"type_duplicate",aliases:[]},{code:"type_invalid",meaning:"Type invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"type_invalid",aliases:[]},{code:"undeclared_observation",meaning:"Undeclared observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"undeclared_observation",aliases:[]},{code:"unexpected_refusal_probe",meaning:"Unexpected refusal probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"unexpected_refusal_probe",aliases:[]},{code:"unknown_command",meaning:"Unknown command condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_command",aliases:[]},{code:"unknown_context_intent",meaning:"Unknown context intent condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-intent-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_context_intent",aliases:[]},{code:"unknown_error",meaning:"Unknown error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"unknown_error",aliases:[]},{code:"unknown_field",meaning:"Unknown field condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_field",aliases:[]},{code:"unknown_field_projection",meaning:"Unknown field projection condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"],canonical_code:"unknown_field_projection",aliases:[]},{code:"unknown_item_type",meaning:"Unknown item type condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_item_type",aliases:[]},{code:"unknown_lifecycle_action",meaning:"Unknown lifecycle action condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/subcommand-recovery.ts"],emitting_commands:["*"],canonical_code:"unknown_subcommand",aliases:[]},{code:"unknown_noun",meaning:"Unknown noun condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_noun",aliases:[]},{code:"unknown_option",meaning:"Unknown option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"unknown_option",aliases:[],owned_states:[{state:"declared_option_is_rejected_on_the_selected_command_path",probe_id:"cross-command-unknown-option",entrypoints:["deps"],expected_exit_class:"usage"}]},{code:"unknown_plan_template",meaning:"Unknown plan template condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"unknown_plan_template",aliases:[]},{code:"unknown_provenance_dimension",meaning:"Unknown provenance dimension condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"],canonical_code:"unknown_provenance_dimension",aliases:[]},{code:"unknown_status",meaning:"Unknown status condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_status",aliases:[]},{code:"unknown_subcommand",meaning:"Unknown subcommand condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","sdk/agent/subcommand-recovery.ts"],emitting_commands:["*"],canonical_code:"unknown_subcommand",aliases:["unknown_lifecycle_action"],owned_states:[{state:"config_action_token_is_not_declared",probe_id:"config-unknown-action",entrypoints:["config"],expected_exit_class:"usage"},{state:"graph_command_token_is_not_declared",probe_id:"graph-unknown-subcommand",entrypoints:["graph"],expected_exit_class:"usage"},{state:"nested_command_token_is_not_declared_by_its_family",probe_id:"schema-unknown-subcommand",entrypoints:["schema"],expected_exit_class:"usage"},{state:"package_lifecycle_token_is_not_declared",probe_id:"package-unknown-action",entrypoints:["package"],expected_exit_class:"usage"}]},{code:"unsafe_init_recovery",meaning:"Unsafe init recovery condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"unsafe_init_recovery",aliases:[]},{code:"unsupported_update_option",meaning:"Unsupported update option condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"unsupported_update_option",aliases:[]},{code:"validate_command_references_stale_pm_ids",meaning:"Validate command references stale pm ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_command_references_stale_pm_ids",aliases:[]},{code:"validate_files_missing_linked_paths",meaning:"Validate files missing linked paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_missing_linked_paths",aliases:[]},{code:"validate_files_orphaned_paths",meaning:"Validate files orphaned paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_orphaned_paths",aliases:[]},{code:"validate_files_tracked_all_strict_forces_pm_internals",meaning:"Validate files tracked all strict forces pm internals condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_tracked_all_strict_forces_pm_internals",aliases:[]},{code:"validate_format_version_ahead_items",meaning:"Validate format version ahead items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_ahead_format_version",aliases:[]},{code:"validate_format_version_outdated_items",meaning:"Validate format version outdated items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_outdated_format_version",aliases:[]},{code:"validate_hierarchy_parent_cycle",meaning:"Validate hierarchy parent cycle condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_hierarchy_parent_cycle",aliases:[]},{code:"validate_hierarchy_parent_cycle_error",meaning:"Validate hierarchy parent cycle error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_hierarchy_parent_cycle_error",aliases:[]},{code:"validate_history_drift_chain_mismatches",meaning:"Validate history drift chain mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_chain_mismatch",aliases:[]},{code:"validate_history_drift_hash_mismatches",meaning:"Validate history drift hash mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_hash_mismatch",aliases:[]},{code:"validate_history_drift_missing_streams",meaning:"Validate history drift missing streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_missing_stream",aliases:[]},{code:"validate_history_drift_unreadable_streams",meaning:"Validate history drift unreadable streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_unreadable_stream",aliases:[]},{code:"validate_history_drift_version_skews",meaning:"Validate history drift version skews condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_version_skew",aliases:[]},{code:"validate_history_unknown_author_events",meaning:"Validate history unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_unknown_author_events",aliases:[]},{code:"validate_lifecycle_active_closure_like_metadata",meaning:"Validate lifecycle active closure like metadata condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_active_closure_like_metadata",aliases:[]},{code:"validate_lifecycle_active_terminal_parent",meaning:"Validate lifecycle active terminal parent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_active_terminal_parent",aliases:[]},{code:"validate_lifecycle_dependency_cycles",meaning:"Validate lifecycle dependency cycles condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_dependency_cycles",aliases:[]},{code:"validate_lifecycle_dependency_cycles_error",meaning:"Validate lifecycle dependency cycles error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_dependency_cycles_error",aliases:[]},{code:"validate_lifecycle_stale_blockers",meaning:"Validate lifecycle stale blockers condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_stale_blockers",aliases:[]},{code:"validate_merge_decisions_unreviewed",meaning:"Validate merge decisions unreviewed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_decisions_unreviewed",aliases:[]},{code:"validate_merge_fence_drift",meaning:"Validate merge fence drift condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_fence_drift",aliases:[]},{code:"validate_metadata_custom_profile_missing_required_fields",meaning:"Validate metadata custom profile missing required fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_custom_profile_missing_required_fields",aliases:[]},{code:"validate_metadata_duplicate_issue_codes",meaning:"Validate metadata duplicate issue codes condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_duplicate_issue_codes",aliases:[]},{code:"validate_metadata_missing_acceptance_criteria",meaning:"Validate metadata missing acceptance criteria condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_acceptance_criteria",aliases:[]},{code:"validate_metadata_missing_close_reason",meaning:"Validate metadata missing close reason condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_close_reason",aliases:[]},{code:"validate_metadata_missing_confidence",meaning:"Validate metadata missing confidence condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_confidence",aliases:[]},{code:"validate_metadata_missing_estimate",meaning:"Validate metadata missing estimate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_estimate",aliases:[]},{code:"validate_metadata_missing_release",meaning:"Validate metadata missing release condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_release",aliases:[]},{code:"validate_metadata_missing_reviewer",meaning:"Validate metadata missing reviewer condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_reviewer",aliases:[]},{code:"validate_metadata_missing_risk",meaning:"Validate metadata missing risk condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_risk",aliases:[]},{code:"validate_metadata_missing_sprint",meaning:"Validate metadata missing sprint condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_sprint",aliases:[]},{code:"validate_resolution_missing_fields",meaning:"Validate resolution missing fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_resolution_missing_fields",aliases:[]},{code:"validate_storage_duplicate_item_ids",meaning:"Validate storage duplicate item ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_duplicate_item_ids",aliases:[]},{code:"validate_storage_history_conflict_markers",meaning:"Validate storage history conflict markers condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_conflict_marker",aliases:[]},{code:"validate_storage_resurrected_items",meaning:"Validate storage resurrected items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_resurrected_items",aliases:[]},{code:"validate_storage_tracked_runtime_cache_files",meaning:"Validate storage tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"tracked_runtime_cache_files",aliases:[]},{code:"validate_storage_unparseable_config",meaning:"Validate storage unparseable config condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unparseable_config",aliases:[]},{code:"validate_storage_unparseable_history",meaning:"Validate storage unparseable history condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unparseable_history",aliases:[]},{code:"validate_storage_unreadable_items",meaning:"Validate storage unreadable items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unreadable_items",aliases:[]},{code:"vectorization_embedding_identity_changed",meaning:"Vectorization embedding identity changed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"vectorization_embedding_identity_changed",aliases:[]},{code:"vectorization_stale_items_remaining",meaning:"Vectorization stale items remaining condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"vectorization_stale_items_remaining",aliases:[]},{code:"visible_surface_ceiling_exceeded",meaning:"Visible surface ceiling exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"visible_surface_ceiling_exceeded",aliases:[]},{code:"workflow_duplicate_type",meaning:"Workflow duplicate type condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_duplicate_type",aliases:[]},{code:"workflow_policy_approval_history_invalid",meaning:"Workflow policy approval history invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_approval_history_invalid",aliases:[]},{code:"workflow_policy_audit_failed",meaning:"Workflow policy audit failed condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_audit_failed",aliases:[]},{code:"workflow_policy_input_unreadable",meaning:"Workflow policy input unreadable condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_input_unreadable",aliases:[]},{code:"workflow_policy_invalid",meaning:"Workflow policy invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_invalid",aliases:[]},{code:"workflow_policy_refused",meaning:"Workflow policy refused condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_refused",aliases:[]},{code:"workflow_policy_registry_invalid",meaning:"Workflow policy registry invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_registry_invalid",aliases:[]},{code:"workflow_status_unknown",meaning:"Workflow status unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_status_unknown",aliases:[]},{code:"workflow_transition_malformed",meaning:"Workflow transition malformed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_transition_malformed",aliases:[]},{code:"workflow_type_empty",meaning:"Workflow type empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_type_empty",aliases:[]},{code:"workflow_type_unknown",meaning:"Workflow type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_type_unknown",aliases:[]},{code:"workspace_history_chain_invalid",meaning:"Workspace history chain invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"],canonical_code:"workspace_history_chain_invalid",aliases:[]},{code:"workspace_history_state_conflict",meaning:"Workspace history state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"],canonical_code:"workspace_history_state_conflict",aliases:[]},{code:"workspace_root_pm_path",meaning:"Workspace root pm path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"workspace_root_pm_path",aliases:[]},{code:"workspace_snapshot_force_required",meaning:"Workspace snapshot force required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_force_required",aliases:[]},{code:"workspace_snapshot_manifest_mismatch",meaning:"Workspace snapshot manifest mismatch condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_manifest_mismatch",aliases:[]},{code:"workspace_snapshot_name_reserved_fingerprint",meaning:"Workspace snapshot name reserved fingerprint condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_name_reserved_fingerprint",aliases:[]},{code:"workspace_snapshot_not_found",meaning:"Workspace snapshot not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_not_found",aliases:[]},{code:"workspace_snapshot_permission_denied",meaning:"Workspace snapshot permission denied condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_permission_denied",aliases:[]},{code:"workspace_snapshot_resource_exhausted",meaning:"Workspace snapshot resource exhausted condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_resource_exhausted",aliases:[]},{code:"workspace_snapshot_storage_exhausted",meaning:"Workspace snapshot storage exhausted condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_storage_exhausted",aliases:[]},{code:"wrong_item_type",meaning:"Wrong item type condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"wrong_item_type",aliases:[]}];(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]="70a7dc18-ab34-5e17-83eb-f5fac0b7fdd9")}catch{}})();var uy=cy([...dy,...ly]);(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]="49e76519-d1f8-58ef-818f-927c563aa006")}catch{}})();var oR=["mutation_receipt","entity","collection","diagnostic","stream"],aR=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),cR=new Set(["close-many","update-many"]),dR=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),lR=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function Ai(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!oR.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function my(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return cR.has(n)?Ai({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):aR.has(n)?Ai({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):dR.has(n)?Ai({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):lR.has(n)?Ai({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):Ai({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var uR=Xe.map(e=>my(e)),mR=new Map(uR.map(e=>[e.command,e]));function _y(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=Ui(t).split(" "),i=mR.get(n);return i?{...i,command:t}:my(t)}function _R(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pR(e){return _R(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function Zz(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!pR(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}(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]="1979adcd-4a7f-5dc7-b5dd-6bfc15eed1af")}catch{}})();var fR=Ko("list").properties.outputSession,gR={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...fR},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},py={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},fy={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},oe={type:"string",description:"pm item id, for example pm-abc1."},hR=`Operation name (one of): ${Ao.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,yR={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},vR={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function j(e,t=[]){return{...fy,properties:{...fy.properties,...e},required:t}}var wR=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:j({action:{type:"string",enum:[...Ao],description:hR},id:oe,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...gR},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:j({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:j({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:j({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:j({query:{type:"string"},options:{type:"object"},...vR},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:j({options:{type:"object"},...yR})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:j({id:oe,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:j({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:j({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:j({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:oe,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:j({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:j({id:oe,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:j({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:j({id:oe,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:j({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:j({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:j({id:oe,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:j({subcommand:{type:"string",enum:[...xl]},id:oe,target:oe,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:j({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:j({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:j({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:j({...py,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...kl],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...yo]},description:`Lifecycle roles for add-status: ${yo.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:py}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:j({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:j({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:j({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],bR={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},kR=wR.map(e=>{let t=bR[e.name];if(!t)return e;let n=e.inputSchema.properties,i=e.inputSchema.required.map(String);return{...e,inputSchema:Ko(t,{properties:n,required:i})}});function gy(){return kR.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(i=>String(i)).sort((i,r)=>i.localeCompare(r)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(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]="15a7b743-b5c0-5228-854b-f4ab1394ffff")}catch{}})();var hy=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),SR=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Cy=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Hs=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),Ci=new Set(["search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),Iy=new Map([["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),xy=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),Ry=new Map([...xy.entries()].flatMap(([e,t])=>pt(t).map(n=>[n,e]))),Oy=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],$c=new Map(Oy.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),ER=10,TR=20,yy=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),Ly=[["init",Hu],["install",Xu],["uninstall",Ju],["explore",Qu],["manage",rm],["describe",Zu],["reload",sm],["doctor",om],["catalog",am],["adopt",cm],["adopt-all",em],["activate",tm],["deactivate",nm],["migrate",im]],AR=[...Ly.map(([e,t])=>e==="init"?[e,Yu]:[e,t]),["upgrade",Uo]],CR=[...Ly.map(([e,t])=>[`extension ${e}`,t]),...AR.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Wu],["config",Bu],["extension",Vu],["package",$o],["packages",$o],["install",dm],["create",Om],["item mutate",Lm],["item complete",Nm],["item reopen",Dm],["copy",Mm],["focus",Pm],["update",Fm],["update-many",$m],["upgrade",Uo],["calendar",jo],["cal",jo],["context",Go],["ctx",Go],["get",Gm],["search",Vm],["eval",Wm],["events",jm],["workspace",vt],["workspace position",[]],["workspace snapshot",vt],["workspace snapshot create",vt],["workspace snapshot list",vt],["workspace snapshot inspect",vt],["workspace snapshot restore",vt],["workspace snapshot delete",vt],["next",Bm],["aggregate",xu],["deps",Km],["graph",zm],["guide",qm],["reindex",lm],["history",Mu],["history-compact",ju],["history-attest",Gu],["history-redact",Fu],["history-repair",$u],["history-author-acknowledge",Uu],["merge",Pu],["schema",qu],["profile",Ku],["plan",zu],["restore",fm],["delete",gm],["close",um],["close-many",mm],["append",_m],["claim",pm],["release",hm],["start-task",ym],["pause-task",vm],["close-task",wm],["comments",Ru],["notes",Ou],["learnings",Lu],["files",Nu],["docs",Du],["test",bm],["test-all",km],["telemetry",Sm],["test-runs",Em],["gc",Tm],["stats",Am],["ops",[]],["duplicates",Cm],["validate",xm],["health",Im],["assurance",Rm],...Xm,["contracts",Hm],["completion",Ym],["activity",Um],...[...Cy].map(e=>[e,Iu])],Ii=new Map(CR);for(let{alias:e,canonical:t}of Be){let n=Ii.get(e);n!==void 0&&Ii.set(t,n)}function IR(e){let t=Ry.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function vy(e){let t=Be.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Xe.includes(e)?ve(e):e.startsWith("extension-")?ve(`extension ${e.slice(10)}`):e.startsWith("package-")?ve(`package ${e.slice(8)}`):e.startsWith("item-")?ve(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ve(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ve(`templates ${e.slice(10)}`):Hs.has(e)?xy.get(e)??ve(e):null}function xR(e,t){let n=X(t);return n!==t||Be.some(i=>i.alias===t)?e.action===n:e.command_path===null?!1:pt(e.command_path).some(i=>i===t?!0:i.startsWith(`${t} `)||t.startsWith(`${i} `))}function pt(e){return e.split("|").map(t=>ve(t)).filter(t=>t.length>0)}function RR(e,t){let n=new Set(t),i=new Set;for(let r of e)if(r.command_path)for(let s of pt(r.command_path)){let o=s.split(" ").filter(a=>a.length>0);if(o.length!==0)for(let a=o.length;a>0;a-=1){let c=o.slice(0,a).join(" ");if(n.has(c)){i.add(c);break}}}return[...i].sort((r,s)=>r.localeCompare(s))}function Vs(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function xi(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function OR(e,t){if(!t)return{...e};let i=xi(e).filter(r=>{let s=r.properties;if(typeof s!="object"||s===null)return!1;let o=s.action;return typeof o!="object"||o===null?!1:o.const===t});return{...e,oneOf:i}}function Mc(e,t){let i=xi(e).filter(r=>{let s=r.properties;if(typeof s!="object"||s===null)return!1;let o=s.action;if(typeof o!="object"||o===null)return!1;let a=o.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:i}}function ve(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Ny(e){return e.replace(/\s+/g,"-")}function tt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function wy(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let i of e){let r=tt(i);!r||n.has(r)||(n.add(r),t.push(r))}return t}function Pc(e,t,n){n&&(e[t]=!0)}function by(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function LR(e){let t=by(e.long,"long"),n=by(e.short,"short"),i=t??n;if(!i)return null;let r={flag:i};n&&t&&(r.short=n),Pc(r,"required",e.required===!0),Pc(r,"repeatable",e.repeatable===!0),Pc(r,"list",e.list===!0);let s=tt(e.description);s&&(r.description=s);let o=tt(e.value_name);o&&(r.value_name=o);let a=[tt(e.value_type),tt(e.type),o?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(r.value_type=a),r}function Dy(e){let t=new Map;for(let i of e){let r=ve(i.target_command);if(r.length===0)continue;let s=t.get(r)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},o=`${i.layer}:${i.name}`;s.sourceDedupe.has(o)||(s.sourceDedupe.add(o),s.sources.push({layer:i.layer,name:i.name}));for(let a of i.flags){let c=LR(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;s.dedupe.has(d)||(s.dedupe.add(d),s.flags.push(c))}t.set(r,s)}let n=new Map;for(let[i,r]of t.entries())n.set(i,{flags:r.flags,sources:r.sources.sort((s,o)=>{let a=s.layer.localeCompare(o.layer);return a!==0?a:(s.name??"").localeCompare(o.name??"")})});return n}function NR(e){let t=Dy(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let o=ve(s.command);if(o.length===0)continue;let a=tt(s.action)??Ny(o),c=Array.isArray(s.arguments)?s.arguments.map(d=>{let l=tt(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:tt(d.description)}:null}).filter(d=>d!==null):[];n.set(o,{command:o,action:a,source:{layer:s.layer,name:s.name},description:tt(s.description),intent:tt(s.intent),arguments:c,flags:t.get(o)?.flags??[],examples:wy(s.examples),failure_hints:wy(s.failure_hints)})}let i=new Set;for(let s of e.handlers)i.add(ve(s));for(let s of n.keys())i.add(s);for(let s of t.keys())i.add(s);let r=[];for(let s of[...i].sort((o,a)=>o.localeCompare(a))){let o=n.get(s);r.push(DR(s,o,t.get(s)?.flags??[]))}return r}function DR(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Ny(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function MR(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let i=t.replace(/-([a-z0-9])/g,(r,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return i.length>0?i:null}function PR(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function FR(e,t){let n=e.value_type??"boolean",i=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",r=e.repeatable===!0||e.list===!0;return{type:r?"array":i,...r?{items:{type:i}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function $R(e){let t=e.command.split("|").map(r=>r.trim()).filter(r=>r.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},i=["action"];for(let r of e.arguments)n[r.name]=PR(r,e.action),r.required&&i.push(r.name);for(let r of e.flags){let s=MR(r);!s||n[s]!==void 0||(n[s]=FR(r,e.action),r.required===!0&&i.push(s))}return{type:"object",properties:n,required:i,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function UR(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function jR(e){let t=new Map;for(let n of e){let i=t.get(n.action);if(!i){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}i.command=[...new Set([i.command,n.command])].sort((s,o)=>s.localeCompare(o)).join("|"),i.arguments=i.arguments.length>=n.arguments.length?i.arguments:n.arguments;let r=new Set(i.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let o=`${s.flag}|${s.short??""}`;if(!r.has(o))r.add(o),i.flags.push(s);else{let a=i.flags.find(c=>`${c.flag}|${c.short??""}`===o);a&&UR(a,s)}}i.examples=[...new Set([...i.examples,...n.examples])],i.failure_hints=[...new Set([...i.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,i)=>n.action.localeCompare(i.action))}async function GR(e,t=I){let n={mode:Ct.extensions.policy.mode,trust_mode:Ct.extensions.policy.trust_mode,default_sandbox_profile:Ct.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let i=x(process.cwd(),e.path);if(!await Z(Te(i)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let r=await t(i),s=await Hi({pmRoot:i,settings:r,cwd:process.cwd(),noExtensions:!1}),o=await Yi({...s,loaded:s.loaded});return{handlers:new Set(o.commands.handlers.map(c=>ve(c.command))),disabledReason:null,commandDefinitions:o.registrations.commands,flagRegistrations:o.registrations.flags,registrations:o.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function qR(e,t={}){let n=new Map;for(let i of Rl){let r=Hs.has(i);if(r&&!t.includePackageOwnedActions)continue;let s=vy(i);n.set(i,{action:i,provider:r?"extension":"core",requires_extension:r,command_path:s})}if(t.includePackageOwnedActions)for(let i of Hs)n.has(i)||n.set(i,{action:i,provider:"extension",requires_extension:!0,command_path:vy(i)});for(let i of e)n.has(i.action)||n.set(i.action,{action:i.action,provider:"extension",requires_extension:!0,command_path:Be.find(r=>r.alias===i.command)?.canonical??ve(i.command)});return[...n.values()].sort((i,r)=>(i.action??"").localeCompare(r.action??""))}function KR(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null};let n=e.command_path?pt(e.command_path):[],i=n.some(o=>t.handlers.has(o)||t.handlers.has(X(o))),r=n.map(o=>Iy.get(X(o))).find(o=>typeof o=="string"),s=t.disabledReason===null&&i;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(r?`optional_package_not_installed:${r}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:i,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function My(e){return Ii.get(e)??Cu}function zR(e){return Ci.has(X(e))?!1:Ii.has(e)}function WR(e){return Cy.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function ky(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function BR(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function VR(e){let t=new Map;for(let i of e.definitions){let r=ky(i.cli_flag);if(!r)continue;let s=i.cli_aliases.map(a=>BR(a)).find(a=>a!==null),o=i.cli_aliases.map(a=>ky(a)).filter(a=>a!==null&&a!==r);for(let a of i.commands){let c=t.get(a)??{flags:[],seen:new Set},d=s?{flag:r,short:s}:{flag:r},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of o){let _=`${u}|`;c.seen.has(_)||(c.seen.add(_),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[i,r]of t.entries())n.set(i,Fo(r.flags));return n}function Sy(e,t){let n=[],i=new Set;for(let r of[...e,...t]){let s=`${r.flag}|${r.short??""}`;i.has(s)||(i.add(s),n.push(r))}return Fo(n)}function HR(e,t,n,i){let r=new Map(t);for(let{alias:s,canonical:o}of Be){let a=t.get(o)??t.get(s);a&&(r.set(s,a),r.set(o,a))}return e.map(s=>{let o=zR(s),a=o?My(s):[],c=n.get(WR(s))??[],d=r.get(s),l=Sy(a,c),u=Sy(l,d?.flags??[]),_=a.length>0&&(d?.flags.length??0)>0?"mixed":o?"core":"extension";return{command:s,flags:u,...i?{canonical_command:Fc(s),visibility:ry(Fc(s)),positionals:Eu(s)?.slots??[],flag_invocations:ty(s,u)}:{},provider:_,extension_sources:d?.sources}}).sort((s,o)=>s.command.localeCompare(o.command))}function YR(e,t=Mn){let n=new Set(e),i=new Map;for(let r of Oy){let s=r.aliases.filter(o=>n.has(o));i.set(r.canonical,{canonical:r.canonical,aliases:s,contracts:[]})}for(let r of t){if(!n.has(r.canonical)||r.registration==="commander"&&!n.has(r.alias))continue;let s=i.get(r.canonical)??{canonical:r.canonical,aliases:[],contracts:[]};s.aliases.includes(r.alias)||s.aliases.push(r.alias),s.contracts.push(r),i.set(r.canonical,s)}return[...i.values()].map(({contracts:r,...s})=>r.length===0?s:{...s,contracts:r}).sort((r,s)=>r.canonical.localeCompare(s.canonical))}function XR(){return{create_string_options:bu,create_repeatable_options:ku,update_string_options:hr,update_repeatable_options:Su,list_string_options:gu,search_string_options:hu,calendar_string_options:yu,context_string_options:vu,activity_string_options:wu}}function Ey(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let i=Jt(e,"create",n),r=[...new Set(i.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(r.map(a=>Ee("create",a)))].sort((a,c)=>a.localeCompare(c)),o=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:r,required_flags:s,required_type_options:o,policy_errors:[...new Set(i.errors)].sort((a,c)=>a.localeCompare(c))}}function JR(e){let t={},n={};for(let i of[...e.types].sort((r,s)=>r.localeCompare(s))){let r=e.by_type[i];t[i]=Ey(r,"strict"),n[i]=Ey(r,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function QR(e,t){let n=xi(e);if(n.length===0)return e;let i=!1,r=n.map(s=>{let o=s.properties;if(typeof o!="object"||o===null)return s;let a=o.action;return typeof a!="object"||a===null||a.const!=="create"?s:(i=!0,{...s,"x-create-required-options":t})});return i?{...e,oneOf:r}:e}function ZR(e){let t=Vs(e.action)!==void 0||Vs(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,i=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,r=e.schemaOnly===!0,s=e.flagsOnly===!0,o=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=Vs(e.action),l=Vs(e.command),u=!i&&!c&&!r&&!s&&!o&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:i,schemaOnly:r,flagsOnly:s,availabilityOnly:o,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function eO(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new p("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function tO(e,t=I){try{return await t(e)}catch{return structuredClone(Ct)}}async function nO(e,t){let n=await tO(t),i=await GR(e),r=$(n,i.registrations??M()),s=nn(n.schema),o=NR(i);return{settings:n,runtimeProbe:i,typeRegistry:r,statusRegistry:K(n.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:VR(s),createRequiredOptionContracts:JR(r),extensionContracts:o,mergedExtensionContracts:jR(o),extensionFlagMap:Dy(i.flagRegistrations)}}function Ty(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Hs.has(e.selectedAction)||e.selectedCommand!==void 0&&Ci.has(X(e.selectedCommand)))}function iO(e,t){let n=qR(t,{includePackageOwnedActions:Ty(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let i=new Set(Ol);return n.filter(r=>!i.has(r.action))}return Ty(e)&&e.selectedCommand!==void 0&&Ci.has(X(e.selectedCommand))&&!n.some(i=>i.command_path===e.selectedCommand)&&n.push({action:IR(X(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function rO(e,t){let n=new Set(t.map(i=>i.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new p(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function sO(e,t){return[...new Set([...Xe.filter(n=>!Ci.has(X(n))),...[...Ii.keys()].filter(n=>!Ci.has(X(n))),...e.flatMap(n=>n.command_path?pt(n.command_path):[]),...t.flatMap(n=>n.command.split("|").flatMap(i=>{let r=Be.find(s=>s.alias===i||s.canonical===i);return r===void 0?[i]:[r.alias,r.canonical]}))])].map(n=>ve(n)).filter(n=>n.length>0).sort((n,i)=>n.localeCompare(i))}function oO(e,t){let n=t.slice(0,ER),i=t.length-n.length,r=i>0?`${n.join(", ")}, and ${i} more`:n.join(", "),s=t.slice(0,TR),o=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new p(`Command "${e}" is a command namespace. Choose a concrete child command: ${r}.`,m.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:o,nextSteps:[`Retry with a child command, for example: ${o[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function aO(e,t){return new p(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,m.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function cO(e){return new p(`Unknown command: "${e}".`,m.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function dO(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let i=t.filter(s=>s.startsWith(`${e.selectedCommand} `));if(i.length>0)throw oO(e.selectedCommand,i);let r=Iy.get(X(e.selectedCommand));throw r?aO(e.selectedCommand,r):cO(e.selectedCommand)}function lO(e,t){let n=iO(e,t.mergedExtensionContracts);rO(e,n);let i=sO(n,t.mergedExtensionContracts);dO(e,i);let r=e.selectedCommand?Ry.get(X(e.selectedCommand)):void 0,s=e.selectedCommand?n.filter(d=>r?d.action===r:xR(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.some(d=>d.action===e.selectedAction))throw new p(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let o=e.selectedAction?s.filter(d=>d.action===e.selectedAction):s,a=[...new Map(o.map(d=>KR(d,t.runtimeProbe)).map(d=>[r?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:i,commandScopedDescriptors:s,scopedActionDescriptors:o,selectedPackageOwnedAction:r,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function uO(e){return new Set(xi(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let i=n.action;if(typeof i!="object"||i===null)return null;let r=i.const;return typeof r=="string"?r:null}).filter(t=>t!==null))}function mO(e){let t=i_,n=xi(t),i=uO(t),r=e.filter(s=>!i.has(s.action)).map(s=>$R(s));return r.length>0?{...t,oneOf:[...n,...r]}:t}function Ay(e,t,n){let i=new Set(t.actionDescriptors.map(s=>s.action)),r=e.selectedAction?OR(n,e.selectedAction):e.selectedCommand?Mc(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):Mc(n,i);return e.runtimeOnly&&!e.selectedAction?Mc(r,new Set(t.actions)):r}function _O(e,t,n){let i=mO(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?QR(Ay(e,n,i),t.createRequiredOptionContracts):Ay(e,n,i);return{mergedSchema:i,filteredSchema:s}}function pO(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?RR(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function fO(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Mn.filter(i=>i.hidden&&(i.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(i=>i.alias));if(e.summary&&!e.fullOutput)for(let i of $c.keys())n.add(i);return t.filter(i=>!n.has(i))}function Fc(e){let t=Be.find(i=>i.alias===e||i.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":$c.get(n)??n}var gO=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),hO=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function yO(e,t){let n=yy.get(X(e))??(e.includes(" ")?void 0:yy.get(Fc(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let i=t.find(d=>pt(d.command).some(l=>X(l)===X(e)));if(i?.intent!==null&&i?.intent!==void 0)return{intent:i.intent,intent_source:"command"};if(i?.description!==null&&i?.description!==void 0)return{intent:i.description,intent_source:"description"};let r=e.split(" "),s=r.at(-1),o=r.slice(0,-1).join(" "),a=gO.get(s),c=hO.get(e)??o;return{intent:a===void 0||o.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function vO(e,t=[],n={}){let i=n.includeFormatBudgets??!0,r=n.includeIntentProvenance??!0;return[...new Set(e.map(ve))].filter(s=>s.length>0).sort((s,o)=>s.localeCompare(o)).map(s=>{let o=Co(s,{generateFallback:!0}),a=s.split(" ")[0],c=$c.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...My(s).map(_=>_.flag),...t.filter(_=>pt(_.command).some(f=>X(f)===X(s))).flatMap(_=>_.flags.map(f=>f.flag))]),l=(hy.get(X(s))??hy.get(c)??SR).filter(_=>d.has(_)),u=yO(s,t);return{command:s,intent:u.intent,...r||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:o.default_max_estimated_tokens,...i?{default_max_estimated_tokens_by_format:{...o.default_max_estimated_tokens_by_format}}:{}}})}function wO(e){return e.map(t=>({budget:Co(t,{generateFallback:!0}),envelope:_y(t)}))}function bO(e){let t=new Map;for(let n of e){let i=Dh(n),r=i===void 0?[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED]:i.exit_codes,s=r.join(","),o=t.get(s)??{commands:[],exit_codes:r};o.commands.push(n),t.set(s,o)}return[...t.values()]}function kO(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(i=>pt(i.command).some(r=>X(r)===X(e.selectedCommand)));if(e.selectedAction){let i=new Set(n);return t.extensionContracts.filter(r=>pt(r.command).some(s=>i.has(s)))}return t.extensionContracts}function SO(e,t,n,i){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:i,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function EO(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=yl);let i=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(r=>r.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([r])=>i===void 0||r===i).map(([r,s])=>[r,[...new Set(s.map(o=>`--${o.cli_flag}`))].sort((o,a)=>o.localeCompare(a))]))},!(i!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Sl],services:[...El],policy_modes:[...Tl],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Il],trust_modes:[...Al],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Cl],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Dd],create_modes:[...Md],close_validation_modes:[...Pd],workflow_enforcement_modes:[...Fd]},e.relationship_kind_contracts=[...Xd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(r=>r.definitions)].sort((r,s)=>r.kind.localeCompare(s.kind)).map(r=>({canonical:r.kind,aliases:[...r.aliases??[]],...r.inverse===void 0?{}:{inverse:r.inverse},ordering:r.ordering,hierarchy:r.hierarchy})))}function TO(e,t,n,i){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=i;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=i}}function AO(e,t,n,i,r){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=HR(i,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let s=new Set(i);e.list_projections=Object.entries(A_).filter(([o])=>s.has(o)).map(([o,a])=>({command:o,default:a,brief_fields:[...T_],compact_fields:[...E_]}))}e.command_aliases=t.fullOutput?r:r.map(({canonical:s,aliases:o})=>({canonical:s,aliases:o})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function CO(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=XR();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function IO(e,t,n,i){e.command_summaries=vO(t,n,{includeFormatBudgets:i.includeFormatBudgets,includeIntentProvenance:i.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Ll],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...i.includeProjectionModeMatrix?{commands:[...new Set(t.map(ve))].filter(r=>Ml(r)!==void 0).sort((r,s)=>r.localeCompare(s)).map(r=>({command:r,modes:[...Pl(r).keys()]}))}:{}},e.grammar_contracts={nouns:Lt.nouns,shared_verbs:Lt.shared_verbs,scope_before_verb:Lt.scope_before_verb,visible_top_level_ceiling:Lt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Lt.ceiling_raise_requires_pm_item,positional_shape_budget:Lt.positional_shape_budget,positional_shape_count:new Set(Po.map(({slots:r})=>Au(r))).size,positional_action_count:Mo.length,positional_action_parents:[...new Set(Mo.map(({parent:r})=>r))].sort((r,s)=>r.localeCompare(s)),...i.includePositionalSignatures?{positional_signatures:Po}:{}}}async function S2(e,t){let n=ZR(e);eO(n);let i=x(process.cwd(),t.path),r=await nO(t,i),s=lO(n,r),o=_O(n,r,s),a=pO(n,s),c=fO(n,a),d=SO(n,o,s,c),l=kO(n,r,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&IO(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return d;let _=YR(s.commandCatalog);return n.flagsOnly&&!n.fullOutput||EO(d,r,n),TO(d,n,o,l),AO(d,n,r,c,_),CO(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...Zn],gate_triggers:[...ct]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=Tu),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=gy(),d.context_intents=Fl(),d.read_output_dimensions=Dl,d.error_codes=uy,d.command_output_contracts=wO(c),d.diagnostic_output_contracts=Nl,d.command_exit_contracts={vocabulary:Ac,command_sets:bO(c)}),d}import{createHash as RO}from"node:crypto";import{execFile as OO}from"node:child_process";import $y from"node:path";import{promisify as LO}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]="39d2b5aa-c6f3-57ac-adb4-e775bc838828")}catch{}})();var Py=1;function xO(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Uc(e){if(e===null)return{format_version:Py,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new p("Improvement ledger contains invalid JSON.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Py||!Array.isArray(t.observations))throw new p("Improvement ledger has an unsupported shape or format version.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let i of n)if(!xO(i))throw new p("Improvement ledger contains an invalid observation.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return 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]="c800f76b-2867-51f5-80d6-fb7b1c61f9e4")}catch{}})();var NO=LO(OO),DO=50,Fy=1e3,MO=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Uy(e){let t=e.trim().toLowerCase();if(!MO.test(t))throw new p(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,m.USAGE,{code:"invalid_improvement_metric"});return t}function PO(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new p("Improvement direction must be higher, lower, or target.",m.USAGE,{code:"invalid_improvement_observation"});return t}function Ri(e,t){let n=e?.trim();if(n){if(n.length>256)throw new p(`${t} must not exceed 256 characters.`,m.USAGE,{code:"invalid_improvement_observation"});return n}}function FO(e){let t=e??DO;if(!Number.isSafeInteger(t)||t<0||t>Fy)throw new p(`Improvement observation limit must be an integer from 0 to ${Fy}.`,m.USAGE,{code:"invalid_improvement_observation_limit"});return t}function jy(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`${t} must be an ISO timestamp.`,m.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function $O(e,t,n){if(!Number.isFinite(n.value))throw new p("Improvement observation value must be finite.",m.USAGE,{code:"invalid_improvement_observation"});let i=Uy(n.metric),r=PO(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||r==="target"&&n.threshold===void 0)throw new p("Target-directed observations require a finite threshold.",m.USAGE,{code:"invalid_improvement_observation"});let s=await jO(e,n.revision),o=Ri(n.source,"source"),a=Ri(n.itemId,"itemId"),c=Ri(n.unit,"unit"),d=Ri(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,i,o??"manual",a??"workspace"].join(":")),l={metric:i,value:n.value,direction:r,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:jy(n.observedAt??R(),"observedAt"),...s,author:G(n.author,t.author_default),...a===void 0?{}:{item_id:a},...o===void 0?{}:{source:o},...d===void 0?{}:{idempotency_key:d}};return{id:RO("sha256").update(ie(l)).digest("hex").slice(0,24),...l}}function UO(e,t){let n=t.idempotency_key?e.observations.find(r=>r.idempotency_key===t.idempotency_key):e.observations.find(r=>r.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new p(`Improvement observation retry key already records a different value for ${t.metric}.`,m.CONFLICT,{code:"improvement_observation_conflict"});return n}let i=e.observations.find(r=>r.metric===t.metric);if(i&&(i.direction!==t.direction||i.unit!==t.unit||t.direction==="target"&&i.threshold!==t.threshold))throw new p(`Metric ${t.metric} is already declared with direction ${i.direction} and unit ${i.unit??"<none>"}.`,m.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function jO(e,t){let n=Ri(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await NO("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:He(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function GO(e){let t=e[0],n=e[e.length-1],i=n.value-t.value,r=n.direction==="higher"?i>0:n.direction==="lower"?i<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:i,improved:r,sample_count:e.length}}async function Gy(e,t={}){let n=x(process.cwd(),t.path);await P(n);let i=await I(n),r=await $O(n,i,e),s=$y.join(n,"improvement-ledger.json"),o=await cn({pmRoot:n,filePath:s,op:"improvement_observe",author:r.author,lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,message:e.message??`Record ${r.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Uc(a),d=UO(c,r);return d?{raw:a,result:d}:(c.observations.push(r),c.observations.sort((l,u)=>l.observed_at.localeCompare(u.observed_at)||l.metric.localeCompare(u.metric)||l.id.localeCompare(u.id)),{raw:`${ie(c)}
|
|
17
|
-
`,result:r})}});return{changed:o.changed,observation:o.result,ledger_path:"improvement-ledger.json"}}async function qy(e={}){let t=x(e.cwd??process.cwd(),e.pmRoot);await P(t);let n=e.metric===void 0?void 0:Uy(e.metric),i=e.since===void 0?void 0:jy(e.since,"since"),r=FO(e.limit),o=Uc(await ee($y.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(i===void 0||c.observed_at>=i)),a=new Map;for(let c of o){let d=a.get(c.metric)??[];d.push(c),a.set(c.metric,d)}return{observations:[...o].reverse().slice(0,r),total:o.length,truncated:o.length>r,trends:[...a].map(([,c])=>GO(c)).sort((c,d)=>c.metric.localeCompare(d.metric)),source:"audited_workspace_singleton"}}(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]="2e7a7f40-523d-590f-8aea-90b65535506e")}catch{}})();function qO(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function KO(e,t,n){let i=t,r=new Set([e.id]);for(;i!==void 0&&!r.has(i.id);)r.add(i.id),i=i.parent_id?n.get(i.parent_id):void 0;return i===void 0}function zO(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((i,r)=>i.entries[0].ts.localeCompare(r.entries[0].ts)||i.id.localeCompare(r.id)),t.push(...n.map(i=>i.children))}}function Ky(e=qn,t=Gn){return t.map(n=>{let i=e.filter(r=>((n==="model"?r.model_environment_keys:r.provenance_environment_keys?.[n])?.length??0)>0||r.provenance_resolvers?.[n]!==void 0).map(r=>r.harness).sort();return{dimension:n,harnesses:i,covered:i.length>0}})}function W2(e,t=1){let n=new Map;for(let i of e){if(!i.agent_harness)continue;let r=n.get(i.agent_harness)??{harness:i.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};r.entries+=1,i.agent_model||i.agent_provenance?.model&&i.agent_provenance.model.value.length>0?r.observed+=1:i.agent_provenance?.model===null?r.unavailable+=1:r.legacy_missing+=1,n.set(i.agent_harness,r)}return[...n.values()].map(i=>{let r=i.observed+i.unavailable;return{...i,coverage:r===0?null:i.observed/r,inert:r>=t&&i.observed===0}}).sort((i,r)=>i.harness.localeCompare(r.harness))}function zy(e,t=Gn,n=1){let i=new Map;for(let r of e)if(r.agent_harness)for(let s of t){let o=`${r.agent_harness}\0${s}`,a=i.get(o)??{harness:r.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=r.agent_provenance?.[s];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,i.set(o,a)}return[...i.values()].map(r=>{let s=r.observed+r.unavailable;return{...r,coverage:s===0?null:r.observed/s,inert:s>=n&&r.observed===0}}).sort((r,s)=>r.harness.localeCompare(s.harness)||r.dimension.localeCompare(s.dimension))}function B2(e,t={}){let n=t.minimumCoverage??.8,i=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(i),i>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let r=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let l=`${c.agent_harness}\0${d}`,u=r.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let _=c.agent_provenance?.[d];_?.value&&(u.observed+=1,u.by_source[_.source]=(u.by_source[_.source]??0)+1),r.set(l,u)}let s=[...r.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[l])=>d.localeCompare(l)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),o=s.filter(c=>c.entries>=i),a=o.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:o.length>0&&a.length===0,minimum_coverage:n,minimum_entries:i,rows:s,failures:a}}function V2(e){let t=[...e].sort((s,o)=>s.ts.localeCompare(o.ts)||s.author.localeCompare(o.author)||s.op.localeCompare(o.op)||s.before_hash.localeCompare(o.before_hash)||s.after_hash.localeCompare(o.after_hash)),n=new Map,i=new Map;for(let s of t){let o=s.agent_episode,a=qO(s),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(s);continue}let l={id:a.id,...o?.label===void 0?{}:{label:o.label},...o?.parent_id===void 0?{}:{parent_id:o.parent_id},source:a.source,entries:[s],children:[]};n.set(c,l),o!==void 0&&i.set(a.id,l)}let r=[];for(let s of n.values()){let o=s.parent_id?i.get(s.parent_id):void 0;o&&KO(s,o,i)?o.children.push(s):r.push(s)}return zO(r),r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0eeefcd-2202-55c6-94e9-0372fcfe0c87")}catch{}})();var WO=1e4,Wy=1e5,BO=1e3,VO=30,HO=["append","comment","docs","file","learning","note","test_run"];function YO(e){let t=e??WO;if(!Number.isSafeInteger(t)||t<1||t>Wy)throw new p(`History analytics event limit must be an integer from 1 to ${Wy}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return t}function By(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new p("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function XO(e){let t=e?.trim();if(!t)return new Date(Date.now()-VO*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let r=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(r)||r<1)throw new p("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-r*s).toISOString()}let i=Date.parse(t);if(!Number.isFinite(i))throw new p("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(i).toISOString()}async function Ys(e,t){let n=YO(t.eventLimit),i=XO(t.since),r=[],s=i,o=!1;for(;r.length<n;){let a=await O_({pmRoot:e,since:s,limit:Math.min(BO,n-r.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(r.push(...c),o=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:r,receipt:{since:i,events:r.length,truncated:o,...o?{next_cursor:s}:{},source:"history_event_index"}}}function JO(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function QO(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function ZO(e){return HO.some(t=>e.startsWith(t))}function Vy(e,t){let n=e.get(t);if(n)return n;let i={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,i),i}function eL(e,t,n){let i=new Map,r=new Map,s=new Map;for(let o of t){let a=JO(o.entry,e),c=QO(o.entry),d=r.get(o.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&r.set(o.item_id,l),!a)continue;let u=Vy(i,a);u.events+=1,ZO(o.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,s.set(o.item_id,a)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:i,lastCloseValue:s}}function tL(e,t,n){for(let i of n){if(i.type!=="Issue")continue;let r=new Set((i.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of r){let o=t.get(s);o&&(Vy(e,o).defectEscapes+=1)}}}function nL(e,t,n,i){let r=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:r==="available"?t.closes/i:null,rework_rate:r==="available"?t.reopens/t.closes:null,defect_escape_rate:r==="available"?t.defectEscapes/t.closes:null,sample_status:r}}function iL(e,t,n,i,r,s){let{buckets:o,lastCloseValue:a}=eL(e,t,i);return tL(o,a,n),{dimension:e,status:o.size===0?"unavailable":"available",rows:[...o].map(([c,d])=>nL(c,d,r,s)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function rL(e,t){let n=e[0]?.entry.ts??t,i=e[e.length-1]?.entry.ts??n,r=Date.parse(n),s=Date.parse(i);return!Number.isFinite(r)||!Number.isFinite(s)?1:Math.max(1,(s-r)/864e5)}function sL(e,t,n){let i=Ky(t),r=zy(e,Gn,n),s=r.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),o=i.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:i,observations:r,inert:s,undeclared:o,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...o.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function eW(e,t=qn,n={}){return jc(await Ys(e,n),t,n)}function jc(e,t=qn,n={}){let i=By(n.minimumSample);return{...sL(e.events.map(r=>r.entry),t,i),window:e.receipt}}async function tW(e,t,n,i={}){return Gc(await Ys(e,i),t,n,i)}function Gc(e,t,n,i={}){let r=By(i.minimumSample),s=rL(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(o=>iL(o,e.events,t,n,r,s)),minimum_sample:r,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(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]="c81415a5-81fa-57ed-936f-236841e5f066")}catch{}})();var oL=32;function aL(e){let t=[];for(let n of e??[]){let i=[];for(let r of n.split(",")){let s=r.slice(0,r.indexOf("=")).trim();i.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(i.join(",")),i=[]),i.push(r)}t.push(i.join(","))}return t}function Oi(e,t){let n=aL(e).map(r=>{let[s,...o]=r.split(","),a=s.indexOf("="),c=s.slice(0,a).trim(),d=s.slice(a+1).trim(),l=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(l))throw new p(`Invalid --measure "${r}"; expected name=value[,unit=...][,threshold=...]`,m.USAGE);let u,_;for(let f of o){let g=f.indexOf("="),h=f.slice(0,g).trim(),y=f.slice(g+1).trim();if(h==="unit"&&y.length>0)u=y;else if(h==="threshold"&&y.length>0&&Number.isFinite(Number(y)))_=Number(y);else throw new p(`Invalid --measure attribute "${f}"`,m.USAGE)}return{name:c,value:l,unit:u,threshold:_,recorded_at:t}});return[...new Map(n.map(r=>[r.name,r])).values()].sort((r,s)=>r.name.localeCompare(s.name)).slice(0,oL)}function Hy(e,t,n){return e.flatMap(i=>(i.measurements??[]).filter(r=>r.name===t&&r.value<n).map(r=>({...r,run_id:i.run_id})))}function Yy(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,o)=>o.recorded_at.localeCompare(s.recorded_at)),i=n[0],r=n[1];return{name:t,latest:i?.value??null,previous:r?.value??null,delta:i!==void 0&&r!==void 0?i.value-r.value:null,unit:i?.unit}}import dL from"node:fs/promises";import Jy 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]="60090339-2f94-5f22-be47-518498838b92")}catch{}})();function Xs(e,t,n,i,r,s="min"){let o=r==="min"?e-t:t-e,a=s==="min"?n.localeCompare(i??n):(i??n).localeCompare(n);return o<0||o===0&&i!==null&&a<0}function cL(e,t){let n=Buffer.byteLength(t,"utf8"),i=0,r=null,s=null,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;i+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,_=Date.parse(u);Number.isNaN(_)||(Xs(_,o,u,r,"min")&&(o=_,r=u),Xs(_,a,u,s,"max","max")&&(a=_,s=u))}return{id:e,bytes:n,lines:i,oldest_ts:r,newest_ts:s}}function Xy(e,t){let n=t?.topN??5,i=Math.max(0,Math.floor(n)),r=e.map(({id:f,raw:g})=>cL(f,g)),s=0,o=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let f of r){if(s+=f.lines,o+=f.bytes,f.oldest_ts!==null){let g=Date.parse(f.oldest_ts);Xs(g,d,f.id,a?.id??null,"min")&&(d=g,a={id:f.id,ts:f.oldest_ts})}if(f.newest_ts!==null){let g=Date.parse(f.newest_ts);Xs(g,l,f.id,c?.id??null,"max")&&(l=g,c={id:f.id,ts:f.newest_ts})}}let u=i===0?[]:[...r].sort((f,g)=>g.bytes-f.bytes||f.id.localeCompare(g.id)).slice(0,i),_=i===0?[]:[...r].sort((f,g)=>g.lines-f.lines||f.id.localeCompare(g.id)).slice(0,i);return{total_streams:e.length,total_lines:s,total_bytes:o,largest_by_bytes:u,deepest_by_lines:_,oldest_entry:a,newest_entry:c}}(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]="a567e72a-faff-580d-b9ae-e2ebfa492b89")}catch{}})();function lL(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function uL(e,t,n,i,r){let s=Qn(e,"type",i),o=new Set(s.rows.map(_=>_.key)),a=t.filter(_=>!o.has(_)),d=(r?[...s.rows,...a.map(_=>({label:_,key:_,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(_=>({type:_.key??_.label,total:_.total,open:_.buckets.open,in_progress:_.buckets.in_progress,blocked:_.buckets.blocked,draft:_.buckets.draft,closed:_.buckets.closed,canceled:_.buckets.canceled,other:_.buckets.other})),l=lL([...n]);for(let _ of e)l[_.status]+=1;let u=Object.fromEntries(Object.entries(l).filter(([,_])=>r||_>0));return{byType:d,byStatus:u,omitted:r?0:a.length+Object.values(l).filter(_=>_===0).length}}function mL(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function _L(e){let t=Jy.join(e,"history");if(!await Z(t))return[];await Me({path:t,scope:"project"});let n=(await dL.readdir(t)).filter(r=>r.endsWith(".jsonl")).sort((r,s)=>r.localeCompare(s)),i=[];for(let r of n){let s=Jy.join(t,r),o=await ee(s);o!==null&&(await Me({path:s,scope:"project"}),i.push({id:r.slice(0,-6),raw:o}))}return i}async function pL(e,t){let n=[],i=R();for(let r of Oi(t.observe,i))n.push(await Gy({metric:r.name,value:r.value,direction:t.direction,unit:r.unit,threshold:r.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:i,author:t.author,message:t.message},e));return n}function fL(e,t,n){let i={};return t.byAssignee&&(i.assignee=Qn(e,"assignee",n)),t.byTag&&(i.tag=Qn(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(i.priority=Qn(e,"priority",n)),i}async function gL(e,t,n,i,r){let s={since:r.since,eventLimit:r.eventLimit,minimumSample:r.minimumSample},o=r.provenanceCoverage||r.fleetAttribution?await Ys(e,s):void 0;return{provenanceCoverage:r.provenanceCoverage&&o?jc(o,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:r.fleetAttribution&&o?Gc(o,t,i,s):void 0}}function hL(e,t,n,i,r){let s=Object.keys(r.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:i,...r.metadataCoverage?{metadata_coverage:r.metadataCoverage}:{},...s?{breakdowns:r.breakdowns}:{},...r.storage?{storage:r.storage}:{},...r.fieldUtilization?{field_utilization:r.fieldUtilization}:{},...r.improvementLedger?{improvement_ledger:r.improvementLedger}:{},...r.recordedObservations.length>0?{recorded_observations:r.recordedObservations}:{},...r.provenanceCoverage?{provenance_coverage:r.provenanceCoverage}:{},...r.fleetAttribution?{fleet_attribution:r.fleetAttribution}:{},generated_at:R()}}async function EW(e,t={}){let n=x(process.cwd(),e.path);await P(n);let i=await I(n),r=await pL(e,t),s=$(i,M()),o=K(i.schema),a=t.fieldUtilization?await Ot(n,i.item_format,s.type_to_folder,void 0,i.schema):await ke(n,i.item_format,s.type_to_folder,void 0,i.schema);await dr({pmRoot:n,settings:i,itemIds:a.map(S=>S.id),commandLabel:"stats"});let c=b_(o),d=uL(a,s.types,o.definitions.map(S=>S.id),c,t.includeEmpty===!0),l=await _L(n),u=0;for(let S of l)u+=mL(S.raw);let _=t.storage?Xy(l):void 0,f=t.metadataCoverage?k_(a,c):void 0,g=fL(a,t,c),h=t.fieldUtilization?S_(a):void 0,y=t.measurements===!0||r.length>0?await qy({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:v,fleetAttribution:w}=await gL(n,a,i,o.terminal_statuses,t);return hL({items:a.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:f,breakdowns:g,storage:_,fieldUtilization:h,improvementLedger:y,recordedObservations:r,provenanceCoverage:v,fleetAttribution:w})}(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]="499dfc08-cf70-55fe-8868-65c3107e3a91")}catch{}})();async function IW(e,t={}){let n=await Kg({pmRoot:x(process.cwd(),e.path),exhaustive:t.exhaustive,...t.status===void 0?{}:{statuses:t.status.flatMap(i=>i.split(",").map(r=>r.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(i=>{let r=i.id;return{...i,canonical_id:r,close_command:`pm close <duplicate-id> --duplicate-of ${r}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import yL from"node:fs/promises";import Tt 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]="32a15ab4-82a2-546f-8519-d4e565e7b578")}catch{}})();var nv=Tt.join("runtime","telemetry","events.jsonl"),iv=Tt.join("runtime","telemetry","state.json"),vL=Tt.join("runtime","telemetry"),wL=20,Qy=["status","flush","stats","clear"],Zy=(e,t)=>{let n=Math.ceil(t*e.length),i=Math.min(e.length-1,Math.max(0,n-1));return e[i]},qc=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,ev=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},bL=e=>({command:qc(e.event.command,"<unknown>"),eventType:qc(e.event.event_type,"unknown"),eventSchemaVersion:ev(e.event.schema_version),clientSchemaVersion:ev(e.client_schema_version)}),kL=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),SL=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},EL=e=>{let t=e?.command_resolution;return qc(t,"")||void 0},rv=(e,t)=>{e[t]=(e[t]??0)+1},TL=(e,t)=>{let n=SL(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let i=EL(t);i!==void 0&&rv(e.resolution_counts,i)},AL=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,tv=(e,t)=>{t!==void 0&&e.add(t)},CL=(e,t)=>{let n=bL(t),i=e.get(n.command)??kL();i.count+=1,i.max_attempts=Math.max(i.max_attempts,AL(t.attempts)),rv(i.event_type_counts,n.eventType),tv(i.event_schema_versions,n.eventSchemaVersion),tv(i.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&TL(i,t.event.payload),e.set(n.command,i)},IL=(e,t)=>{let n=t.ok_count+t.error_count,i=[...t.finish_durations_ms].sort((s,o)=>s-o),r=Object.entries(t.resolution_counts).sort((s,o)=>s[0].localeCompare(o[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,o)=>s[0].localeCompare(o[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,o)=>s-o),client_schema_versions:[...t.client_schema_versions].sort((s,o)=>s-o),...i.length>0?{duration_p50_ms:Zy(i,.5),duration_p95_ms:Zy(i,.95),duration_max_ms:i[i.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...r.length>0?{command_resolution_counts:Object.fromEntries(r)}:{}}},xL=e=>{let t=(e??"status").trim().toLowerCase();if(Qy.includes(t))return t;throw Ki({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Qy,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Kc=()=>{throw new p("--limit must be a positive integer",m.USAGE)},sv=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Kc():e,RL=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Kc():sv(Number.parseInt(t,10))},OL=e=>e===void 0?wL:typeof e=="number"?sv(e):typeof e=="string"?RL(e):Kc(),LL=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},NL=e=>{try{let t=JSON.parse(e);return LL(t)?t:void 0}catch{return}},DL=e=>e===null?[]:e.split(`
|
|
18
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),ov=e=>{let t=DL(e),n=[],i=0;for(let r of t){let s=NL(r);s===void 0?i+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:i,entries:n}},ML=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),PL=e=>{try{let t=JSON.parse(e);return ML(t)?t:{}}catch{return{}}},FL=async e=>{let t=await ee(e);return t===null||t.trim().length===0?{}:PL(t)},Js=e=>e??null,Qs=async e=>{let t=await I(e),n=Tt.join(e,nv),i=Tt.join(e,iv),r=await ee(n),s=ov(r),o=await FL(i);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:i,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(r??"","utf8"),last_attempted_flush_at:Js(o.last_attempted_flush_at),last_successful_flush_at:Js(o.last_successful_flush_at),last_failed_flush_at:Js(o.last_failed_flush_at),last_failed_flush_error:Js(o.last_failed_flush_error)}},$L=e=>{let t=new Map;for(let n of e)CL(t,n);return[...t.entries()].map(([n,i])=>IL(n,i)).sort((n,i)=>i.count-n.count||n.command.localeCompare(i.command))},UL=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Qs(t.globalPmRoot),generated_at:R()}),jL=async(e,t)=>{let n=await Qs(t.globalPmRoot);await fu(t.globalPmRoot);let i=await Qs(t.globalPmRoot),r=Math.max(0,n.queue_entries-i.queue_entries),s=i.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:i.queue_entries,queue_entries_drained:r,queue_progressed:r>0,queue_empty:s,queue_drained:s,status:i,generated_at:R()}},GL=async(e,t)=>{let n=OL(e.limit),i=await ee(t.queuePath),r=ov(i),s=$L(r.entries),o=s.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:r.valid_entries,queue_invalid_rows:r.invalid_rows,queue_rows_total:r.rows_total,truncated:s.length>o.length,stats:o,generated_at:R()}},qL=async(e,t)=>{let n=await I(t.globalPmRoot),i=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",i&&await Xl(t.globalPmRoot,n,"telemetry:clear");let r=Tt.join(t.globalPmRoot,vL),s=await Z(r);return await yL.rm(r,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:i,runtime_dir_removed:s&&!await Z(r),queue_exists_after:await Z(t.queuePath),state_exists_after:await Z(t.statePath),status:await Qs(t.globalPmRoot),generated_at:R()}},KL={status:UL,flush:jL,stats:GL,clear:qL};async function jW(e,t){let n=xL(e.subcommand),i=Ye(process.cwd());return KL[n](e,{globalPmRoot:i,queuePath:Tt.join(i,nv),statePath:Tt.join(i,iv)})}import{spawn as Cv}from"node:child_process";import{cp as Vc,mkdir as io,mkdtemp as Iv,open as Hc,readdir as Yc,rm as Li,symlink as xv}from"node:fs/promises";import{tmpdir as Rv}from"node:os";import H 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]="ffa50b5b-d99f-5ab4-a70d-cbf12911a0f2")}catch{}})();var av=20;function zL(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return av;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?av:t}function zc(e){let t=[...e].filter(i=>i.run_id.trim().length>0&&i.started_at.trim().length>0&&i.finished_at.trim().length>0&&i.recorded_at.trim().length>0).sort((i,r)=>{let s=qi(i.recorded_at,r.recorded_at);if(s!==0)return s;let o=i.run_id.localeCompare(r.run_id);return o!==0?o:i.kind.localeCompare(r.kind)}),n=zL();return t.length>n?t.slice(t.length-n):t}async function Zs(e){await le({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=zc([...n,e.entry]),{changedFields:["test_runs"]}}})}(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]="328c7577-364c-5869-aa92-199e56d2f6a7")}catch{}})();var cv=100;function Wc(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new p(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function WL(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=cv?n:`${n.slice(0,cv-3)}...`}function dv(e){return e.map((t,n)=>`${n+1}. ${WL(t)}`).join("; ")}function BL(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function VL(e,t){let n=e.command?.toLowerCase()??"",i=e.path?.toLowerCase()??"";return n.includes(t)||i.includes(t)}function lv(e,t){let n=BL(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((r,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new p(`Combine at most one linked-test selector per run: ${n.map(r=>`--${r}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,m.USAGE);let i=n[0];if(e.length===0)throw new p(`--${i} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(i==="match"){let r=t.match.trim().toLowerCase();if(r.length===0)throw new p("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let s=[],o=[];for(let a=0;a<e.length;a+=1)VL(e[a],r)&&(o.push(e[a]),s.push(a+1));if(o.length===0)throw new p(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${dv(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:o,selected_indexes:s,selected_count:o.length,skipped_count:e.length-o.length}}if(i==="only-index"){let r=Wc(t.onlyIndex);if(r>e.length)throw new p(`--only-index ${r} is out of range: this item has ${e.length} linked test(s). Available entries: ${dv(e)}`,m.USAGE);return{selector:"only-index",requested:String(r),selected:[e[r-1]],selected_indexes:[r],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2833cfc3-db98-5f7f-82e0-388e320ef740")}catch{}})();var no=20*1024*1024,HL=3e3,YL=1e4,XL=5e3,uv=120,JL=new Set(["locks","extensions","runtime"]),QL=new Set(["history","index","search","extensions","locks","runtime"]),ZL=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],eN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,tN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,nN=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Qc(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let i=Number.parseInt(n,10);return!Number.isFinite(i)||i<=0?t:i}function iN(){return Qc("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",HL)}function rN(){return Qc("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",YL)}function sN(){return Qc("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",XL)}function oN(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function aN(e){let t=0,n=0,i=0;for(let r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"){n+=1;continue}i+=1}return{passed:t,failed:n,skipped:i}}function Zc(e){let t=0,n=0,i=0,r=0;for(let s of e){let o=s.execution_context;!o||o.is_pm_command!==!0||(t+=1,o.is_pm_tracker_read_command===!0&&(n+=1),o.mismatch_detected===!0&&(i+=1),o.auto_pm_context_applied===!0&&(r+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:i,auto_remediated:r}}function cN(e){let t=e??"project";if(!De.includes(t))throw new p(`Invalid scope "${e}"`,m.USAGE);return t}function ro(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Ut.includes(t))return t;throw new p(`Invalid --pm-context value "${e}". Expected one of: ${Ut.join(", ")}`,m.USAGE)}function dN(e){return Gt(e??"source","--workspace-context")}function Ov(e,t,n){return n?t:Gt(e.workspace_context_mode,"linked test")??t}function Lv(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:ro(e.pm_context_mode)}function Nv(e,t){return e==="auto"?t?"tracker":"schema":e}function lN(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function uN(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:i}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&i==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function mN(e,t){let n={};if(!e)return n;for(let i of e){let r=vi(i,t);if(r)for(let[s,o]of Object.entries(r))n[s]=o}return n}function _N(e,t){if(!e)return[];let n=[];for(let i of e){let r=wi(i,t);r&&n.push(...r)}return[...new Set(n)]}function pN(e){let t=Ni(e);return Dt(t).some(n=>Yr(n)!==null)}function Dv(e){let t=Ni(e);return Dt(t).some(n=>{let i=Yr(n);if(!i)return!1;let r=Ma(i);return r?nN.has(r.subcommand):!1})}function eo(e){if(e)return df.has(e.subcommand)?bt(e.args,lf)?.subcommand:e.subcommand}function mv(e,t){if(e==="npx"||e==="bunx")return Mt(t)?.command;if(e==="pnpm")return eo(bt(t,Oa));if(e==="npm")return eo(bt(t,La));if(e==="yarn")return eo(bt(t,af));if(e==="bun")return eo(bt(t,cf))}function to(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function Bc(e){return!e||!li(e.command)&&!Da(e.command)?!1:Jr(e.args)==="test-all"}var Mv=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),fN=new Set(["npx","bunx"]);function Pv(e){let t=e.split(" ").filter(o=>o.length>0),n=Xr(t);if(n.length===0)return!1;let[i,...r]=n,s=Mv.get(i);if(s){let o=r.findIndex(a=>s.test(a));return o>=0?Pv(r.slice(o+1).join(" ")):!1}return li(i)||ui(i)?Jr(r)==="test-all":i==="node"&&r.length>0&&ui(r[0])?Jr(r.slice(1))==="test-all":fN.has(i)?Bc(Mt(r)):i==="pnpm"?Bc(Qr(r)):i==="npm"?Bc(Zr(r)):!1}function Fv(e){let t=Ni(e);return Dt(t).some(n=>Pv(n))}function $v(e){if(Fv(e))throw new p('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',m.USAGE)}function Ni(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function _v(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function ed(e){let t=e.split(" ").filter(o=>o.length>0),n=Xr(t);if(n.length===0)return!1;let[i,...r]=n,s=Mv.get(i);if(s){let o=r.findIndex(a=>s.test(a));return o>=0&&ed(r.slice(o+1).join(" "))}return i==="vitest"||i.endsWith("/vitest")||i.endsWith("/vitest.mjs")?!0:i==="node"?gN(r):hN(i,r)}function gN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function hN(e,t){return e==="npx"||e==="bunx"?to(Mt(t)?.command):e==="pnpm"||e==="npm"?to((e==="pnpm"?Qr(t):Zr(t))?.command)||to(mv(e,t)):(e==="yarn"||e==="bun")&&to(mv(e,t))}function EB(e){let t=Ni(e),n=Dt(t),i=n.some(s=>!_v(s)&&ed(s)),r=n.some(_v);return{accepted:!0,command_kind:i?"direct_runner":r?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:i?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function yN(e){if(Fv(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function vN(e){return e?e.map(wN):[]}function wN(e){let t=e.trim(),n=zg(t)?ms(J(e,"--add"),"--add"):{command:t},i=pe(n.command);if(!i)throw new p("--add requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);return $v(i),{command:i,path:pe(n.path),scope:cN(n.scope),timeout_seconds:bN(pe(n.timeout_seconds),pe(n.timeout)),pm_context_mode:hs(pe(n.pm_context_mode),"--add"),workspace_context_mode:Gt(pe(n.workspace_context_mode),"--add"),env_set:vi(pe(n.env_set),"--add"),env_clear:wi(pe(n.env_clear),"--add"),shared_host_safe:gs(pe(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:qt(pe(n.assert_stdout_contains)),assert_stdout_regex:Tn(pe(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:qt(pe(n.assert_stderr_contains)),assert_stderr_regex:Tn(pe(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:ys(pe(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:vs(pe(n.assert_json_field_equals),"--add"),assert_json_field_gte:ws(pe(n.assert_json_field_gte),"--add"),note:pe(n.note)}}function pe(e){let t=e?.trim();return t&&t.length>0?t:void 0}function bN(e,t){if(e&&t&&e!==t)throw new p("--add timeout and timeout_seconds must match when both are provided",m.USAGE);let n=e??t;if(n===void 0)return;let i=Math.floor(_e(n,"timeout_seconds"));if(i<=0)throw new p("--add timeout_seconds must be a positive integer",m.USAGE);return i}function kN(e){return e?e.flatMap(t=>{let n=Vg(t,"--add-json");for(let i of n){let r=i.command;if(!r)throw new p("--add-json requires a non-empty command string",m.USAGE);$v(r)}return n}):[]}function SN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires command or path value",m.USAGE);let i=/^(command|path)\s*=/i.exec(n);if(i){let r=n.slice(i[0].length).trim();if(!r)throw new p("--remove requires a non-empty command=<value> or path=<value>",m.USAGE);return{kind:i[1].toLowerCase(),value:r}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new p("--remove structured selectors require command=<value> or path=<value>",m.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let r=J(n,"--remove"),s=r.path!==void 0?"path":"command",o=r.path??r.command;if(!o?.trim())throw new p("--remove requires command=<value> and/or path=<value>",m.USAGE);return{kind:s,value:o.trim()}}return{kind:"either",value:n}}):[]}function EN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new p("--remove-index must be a positive integer",m.USAGE);return n}))]:[]}function TN(e){try{e.stdin?.end()}catch{}}function Uv(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=uv?t:`${t.slice(0,uv-3)}...`}function jv(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Xc(e){try{process.stderr.write(`${e}
|
|
19
|
-
`)}catch{}}function
|
|
20
|
-
[pm linked-test output truncated at ${
|
|
21
|
-
`:"",b={stdout:`${E.text}${k}`,stderr:T.text,exitCode:w,signal:S,timedOut:v,maxBufferExceeded:!1,outputTruncated:A,spawnError:g};return
|
|
22
|
-
`);return
|
|
23
|
-
${t}`;for(let i of
|
|
24
|
-
${t}`;return VN.some(i=>i.test(n))}function Sv(e){let t=Ni(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Dt(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&ed(n))}function XN(e){return{root:e,schemaProjectPmPath:H.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:H.join(e,"schema","global"),trackerProjectPmPath:H.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:H.join(e,"tracker","global"),workspaceSnapshotRoot:H.join(e,"workspace","project"),workspaceIsolatedRoot:H.join(e,"workspace","isolated")}}function JN(e,t,n){return e.some(i=>Ov(i,t,n)==="snapshot")}async function QN(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await io(H.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await Vc(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(r){let s=H.relative(t,r);return s?!s.split(H.sep).some(o=>n.has(o)):!0}});let i=H.join(t,"node_modules");await Z(i)&&await xv(i,H.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function ZN(e,t){let n=H.join(e,".agents"),i=H.join(n,"pm");await io(n,{recursive:!0}),await Li(i,{recursive:!0,force:!0}),await xv(t,i,process.platform==="win32"?"junction":"dir")}async function eD(e,t=Yo,n=!0){let i={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},i),await t(void 0,{path:e.schemaGlobalPmPath},i),n&&(await t(void 0,{path:e.trackerProjectPmPath},i),await t(void 0,{path:e.trackerGlobalPmPath},i))}async function tD(e,t,n){t&&(await hv(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await hv(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await yv(t.projectPmRoot,e.trackerProjectPmPath),await yv(t.globalPmRoot,e.trackerGlobalPmPath),await vv(t.projectPmRoot,e.trackerProjectPmPath),await vv(t.globalPmRoot,e.trackerGlobalPmPath)))}function nD(e,t,n){return e.some(i=>{let r=i.command??"",s=r.length>0&&Dv(r),o=n?.autoPmContext===!0&&s?"auto":Lv(i,t,n?.overrideLinkedPmContext===!0);return Nv(o,s)==="tracker"})}async function iD(e,t){return{sourceProjectItemCount:t?await Rn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Rn(t.globalPmRoot):0,schemaProjectItemCount:await Rn(e.schemaProjectPmPath),schemaGlobalItemCount:await Rn(e.schemaGlobalPmPath),trackerProjectItemCount:await Rn(e.trackerProjectPmPath),trackerGlobalItemCount:await Rn(e.trackerGlobalPmPath)}}function rD(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,i=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,r=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,o=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":o;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:i,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:r,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==r||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:o,source_workspace_root:a,trust:e.trust}}async function sD(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?ro(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,i=n?pN(n):!1,r=i&&n?Dv(n):!1,s=e.options?.autoPmContext===!0&&r,o=s?"auto":Lv(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Nv(o,r),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await ZN(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await Ua(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Ua(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:rD({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:i,isPmTrackerReadCommand:r,requestedPmContextMode:o,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function Ev(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Jc(e,t,n,i){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...i?{stdout:i.stdout,stderr:i.stderr}:{},error:n}}function oD(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function aD(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let i=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return oD(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${i}`)}function cD(e){if(!e.linkedTest.command)return Ev(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=yN(e.linkedTest.command);return t?Ev(e.linkedTest,e.executionContext,t):null}function dD(e){let t=cD(e);if(t)return t;let n=aD(e);if(n)return n;let i=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,r=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(i||r){let s=uN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Jc(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${s}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!lN(e.linkedTest)?Jc(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function lD(e){let t=$N(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return gv(n,e.runtimeDirectives),gv(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&FN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Xn]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Xn]="read_only"),n}function uD(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function Tv(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function mD(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:jN(e.execution),failure_category:MN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:NN(e.execution,e.timeoutMs)}}function _D(e){if(e.options?.failOnEmptyTestRun===!0||Sv(e.linkedTest.command??"")){let n=HN(e.execution.stdout,e.execution.stderr);if(n)return Tv({...e,emptyRunSignal:n});if(Sv(e.linkedTest.command??"")&&!YN(e.execution.stdout,e.execution.stderr))return Tv({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let t=zN(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Jc(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):uD(e.linkedTest,e.executionContext,e.execution)}async function pD(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,i=await LN(t,n,lD(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return i.exitCode===0&&!i.timedOut&&!i.maxBufferExceeded?_D({...e,execution:i}):mD({...e,execution:i,timeoutMs:n})}async function td(e,t,n){let i=[],r=await Iv(H.join(Rv(),"pm-linked-test-")),s=XN(r),o=ro(n?.pmContext),a=dN(n?.workspaceContext),c=n?.progress===!0?"always":"auto",d=UN(n?.envSet,n?.envClear,n?.sharedHostSafe),l=n?.sourceRoots,u=pi(),_=nD(e,o,n),f=JN(e,a,n?.overrideLinkedWorkspaceContext===!0),g=await _i(u);try{await eD(s,Yo,_),await io(s.workspaceIsolatedRoot,{recursive:!0}),await tD(s,l,_),f&&await QN(s,u);let h=await iD(s,l);for(let y=0;y<e.length;y+=1){let v=e[y],w=Ov(v,a,n?.overrideLinkedWorkspaceContext===!0),S=await sD({linkedTest:v,layout:s,counts:h,sourceRoots:l,runLevelPmContextMode:o,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:w,currentSourceRef:g,sourceWorkspaceRoot:u}),E=dD({linkedTest:v,executionContext:S.executionContext,runLevelPmContextMode:o,linkedOverridePmContextMode:S.linkedOverridePmContextMode,options:n});if(E){i.push(E);continue}i.push(await pD({linkedTest:v,index:y,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:d,progressMode:c,executionContext:S.executionContext,options:n}))}}finally{await Li(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return i}async function fD(e){let{id:t,pmRoot:n,settings:i,typeToFolder:r}=e,s=await Q(n,t,i.id_prefix,i.item_format,r);if(!s)throw new p(`Item ${t} not found`,m.NOT_FOUND);let o=await be(s,{schema:i.schema});return{itemId:s.id,tests:o.document.metadata.tests??[],testRuns:o.document.metadata.test_runs??[],changed:!1,removed:0}}function gD(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function hD(e,t){let n=[...e];for(let i of t)n.some(r=>gD(r,i))||n.push(i);return n}function yD(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let i=new Set(n),r=e.filter((s,o)=>i.has(o+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:r,removed:e.length-r.length}}function vD(e,t,n,i){return yD(hD(e,t),n,i)}function wD(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function bD(e){if(wD(e)&&e.run!==!0)throw new p("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",m.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new p("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",m.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new p("--match, --only-index, and --only-last require --run",m.USAGE)}async function kD(e){let{id:t,options:n,pmRoot:i,settings:r,typeToFolder:s,adds:o,removes:a,removeIndexes:c}=e;if(o.length===0&&a.length===0&&c.length===0)return fD({id:t,pmRoot:i,settings:r,typeToFolder:s});let d=0,l=await le({pmRoot:i,settings:r,id:t,op:o.length>0?"tests_add":"tests_remove",author:G(n.author,r.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let _=u.metadata.tests??[],f=vD(_,o,a,c);if(d=f.removed,(a.length>0||c.length>0)&&d===0)throw new p("No linked tests matched the requested removal selector",m.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(g=>`${g.kind}=${g.value}`),...c.map(g=>`index=${g}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return u.metadata.tests=f.tests,{changedFields:st(_,f.tests)?[]:["tests"]}}});return{itemId:l.item.id,tests:l.item.tests??[],testRuns:l.item.test_runs??[],changed:l.changedFields.length>0,removed:d}}function SD(e,t){bD(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Wc(e.onlyIndex),onlyLast:e.onlyLast},i=e.run===!0?lv(t,n):void 0,r=e.timeout===void 0?void 0:_e(e.timeout,"timeout");if(r!==void 0&&r<=0)throw new p("Test timeout must be a positive number",m.USAGE);return{defaultTimeoutSeconds:r,pmContextMode:ro(e.pmContext),runSelection:i,testsToRun:i?.selected??t}}async function ED(e){let{options:t,runOptions:n,pmRoot:i}=e;return t.run!==!0?[]:await td(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:i,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:i,globalPmRoot:Ye(process.cwd())}})}function TD(e,t,n){let i=[];if(t&&t.selector!==null&&i.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let r=Zc(n);i.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)}return i}function AD(e){let t=aN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),i=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),r=R(),s=Oi(e.options.measure,r);return{run_id:oN("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:r,recorded_at:r,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:i&&i.length>0?i:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(o=>o.command?.trim()).slice(0,32).map(o=>({command:o.command.trim(),requested_pm_context_mode:o.execution_context?.requested_pm_context_mode,pm_context_mode:o.execution_context?.pm_context_mode,workspace_context_mode:o.execution_context?.workspace_context_mode,trust_reason:o.execution_context?.trust.reason}))}}async function CD(e){let{options:t,pmRoot:n,settings:i,itemId:r,runStartedAt:s,runResults:o,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let d=AD({options:t,runStartedAt:s,runResults:o,failOnSkippedTriggered:a});if(i.testing.record_results_to_items!==!0)return d;try{return await Zs({pmRoot:n,settings:i,itemId:r,author:G(t.author,i.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),d}catch(l){return c.push(`test_result_tracking_failed:${r}:${l instanceof Error?l.message:String(l)}`),d}}function Av(e,t,n){let i;if(e.metricBelow!==void 0){let r=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,r).trim(),o=e.metricBelow.slice(r+1).trim(),a=Number(o);if(r<=0||s.length===0||o.length===0||!Number.isFinite(a))throw new p("--metric-below must use name=value",m.USAGE);i=Hy(t,s,a)}return{measurements:n?.measurements,metric_below:i,metric_diff:e.metricDiff===void 0?void 0:Yy(t,e.metricDiff)}}async function ID(e,t,n){if(e.acknowledgeLinkedTests===!0)return gf(t,n,R())}async function Gv(e,t,n){let i=en(),r=x(process.cwd(),n.path);await P(r);let s=await I(r);if((t.measure?.length??0)>0&&t.run!==!0)throw new p("--measure requires --run",m.USAGE);Oi(t.measure,"validation"),Av(t,[],void 0);let o=$(s,M()),a=await i.resolveList(t.add,"--add"),c=await i.resolveList(t.addJson,"--add-json"),d=await i.resolveList(t.remove,"--remove"),l=[...vN(a),...kN(c)],u=await Sn(l,G(t.author,s.author_default),R())??[],_=SN(d),f=EN(t.removeIndex),g=await kD({id:e,options:t,pmRoot:r,settings:s,typeToFolder:o.type_to_folder,adds:u,removes:_,removeIndexes:f}),h=SD(t,g.tests),y=await ID(t,r,g.tests),v=t.run===!0?R():void 0,w=await ED({options:t,runOptions:h,pmRoot:r,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests}),S=so(w),E=t.run===!0&&t.failOnSkipped===!0&&w.some(L=>L.status==="skipped"),T=TD(t,h.runSelection,w);y&&T.push(`linked_test_trust_acknowledged:${y.acknowledged}`);let A=await CD({options:t,pmRoot:r,settings:s,itemId:g.itemId,runStartedAt:v,runResults:w,failOnSkippedTriggered:E,warnings:T}),k=A?zc([...g.testRuns,A]):g.testRuns,b=Av(t,k,A);return{ok:w.every(L=>L.status!=="failed")&&E!==!0,id:g.itemId,tests:g.tests,run_results:w,failure_categories:S,selection:h.runSelection?{selector:h.runSelection.selector,requested:h.runSelection.requested,selected_indexes:h.runSelection.selected_indexes,selected_count:h.runSelection.selected_count,skipped_count:h.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:E?!0:void 0,warnings:T.length>0?T:void 0,changed:g.changed,count:g.tests.length,...g.removed>0?{removed:g.removed}:{},...b}}(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]="e3e3a1d4-4552-5f3c-9b02-c33ae72ea32b")}catch{}})();var xD=(e,t)=>{if(e===void 0)return;let n=se(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new p(`Invalid --status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n},RD=e=>{if(e===void 0)return;let t=_e(e,"timeout");if(t<=0)throw new p("timeout must be a positive number",m.USAGE);return t},qv=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new p(`${t} must be a non-negative integer`,m.USAGE);return n},OD=e=>e instanceof Error?e.message:String(e),LD=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},ND=e=>e.trim().replaceAll(/\s+/g," "),DD=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),MD=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),PD=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},FD=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},oo=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Kv=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),$D=e=>typeof e=="number"?e:void 0,UD=e=>{let t={assert_stdout_contains:oo(e.assert_stdout_contains),assert_stdout_regex:oo(e.assert_stdout_regex),assert_stderr_contains:oo(e.assert_stderr_contains),assert_stderr_regex:oo(e.assert_stderr_regex),assert_stdout_min_lines:$D(e.assert_stdout_min_lines),assert_json_field_equals:Kv(e.assert_json_field_equals),assert_json_field_gte:Kv(e.assert_json_field_gte)};return JSON.stringify(t)},jD=e=>{let t=nd(e.command);return t!==void 0?`command:${e.scope}:${ND(t)}`:`path:${e.scope}:${nd(e.path)??""}`},zv=e=>{let t=DD(e.env_set),n=MD(e.env_clear),i=PD(e.pm_context_mode),r=FD(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",o=UD(e);return`${jD(e)}:${t}:${n}:${i}:${r}:${s}:${o}`},GD=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,qD=e=>{let t=0,n=0,i=0;for(let r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"){n+=1;continue}i+=1}return{passed:t,failed:n,skipped:i}},KD=(e,t)=>{for(let[n,i]of Object.entries(t))e[n]+=i},ao=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
25
|
-
`)}catch{}},
|
|
26
|
-
`)}async function
|
|
27
|
-
`);return}await Ve(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:
|
|
28
|
-
`)}async function
|
|
29
|
-
//# sourceMappingURL=chunk-
|
|
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)}
|
|
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
|
+
`,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
|
+
`,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(`
|
|
5
|
+
`)){let a=o.trim();if(a.length!==0){i+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,s=Math.max(s,d),d>=Np&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:i,highRetryEntries:r,maxAttempts:s}}function jk(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Gk(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function qk(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||Bn().telemetry_disabled?void 0:{attempted:!0,...await Up(n)}}function Kk(e,t,n){let i=[];if(t.invalidRows>0&&i.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return i;let r=n.last_successful_flush_at,s=n.last_failed_flush_at,o=s&&(!r||s>r),a=!r,c=t.validEntries>=gk;return(o||a||c)&&i.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&i.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),i}function zk(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function Wk(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>fu?[`telemetry_schema_version_behind:${t}`]:[]}function Bk(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,i=t.last_otel_success_at,r=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!r&&(!i||r>=i)?[`telemetry_otel_export_failing:${n}`]:[]}function Vk(){return{...Bn(),pm_no_telemetry:Kr("PM_NO_TELEMETRY"),telemetry_otel_disabled:Kr("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:Kr("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:Uk()}}function Hk(e,t){return e.telemetry.enabled&&t.validEntries>0}function Yk(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Up(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(fk)});return{probe_url:zr(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let i of hk){let r=n.headers.get(i)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:zr(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function Xk(e,t){let n=Ye(process.cwd()),i=Ae.join(n,_k),r=Ae.join(n,pk),s=await ee(i),o=s!==null,a=s?Buffer.byteLength(s,"utf8"):0,c=s?$p(s):jk(),d=await ee(r),{runtimeState:l,stateParseFailed:u}=Gk(d),_=e.telemetry.endpoint.trim(),f=zr(_),g=await qk(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...Kk(e,c,l),...zk(g),...Wk(g),...Bk(e,l));let y=Hk(e,c),v=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:f,global_pm_root:n,queue_path:i,queue_exists:o,queue_entries:c.validEntries,queue_draining:Yk(y,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:a,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Np,queue_max_attempts:c.maxAttempts,runtime_state_path:r,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:v,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:g??{attempted:!1},env_overrides:Vk()}},warnings:h}}async function Jk(e){let t;try{t=await Cp(e)}catch(i){let r=i instanceof Error?i.message:String(i);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:r,pm_root:e}},warnings:[`locks_scan_failed:${r}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function Qk(e){let t="metadata",n=e.items,i=await Yn(e.pmRoot,n,{cacheHitVerification:t}),r=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((v,w)=>v.localeCompare(w)),s=[],o=[];if(r.length>0){n=await Ot(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),i=await Yn(e.pmRoot,n),s=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((w,S)=>w.localeCompare(S));let v=new Set(s);o=r.filter(w=>!v.has(w))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:_,workspaceStateMismatches:f,workspaceStateMissing:g,workspaceStateUnreadable:h}=i,y=[...a.map(v=>`history_drift_missing_stream:${v}`),...c.map(v=>`history_drift_unreadable_stream:${v}`),...d.map(v=>`history_drift_hash_mismatch:${v}`),...l.map(v=>`history_drift_chain_mismatch:${v}`),...u.map(v=>`history_drift_version_skew:${v}`),...f.map(v=>`history_drift_workspace_state_mismatch:${v}`),...g.map(v=>`history_drift_workspace_state_missing:${v}`),...h.map(v=>`history_drift_workspace_state_unreadable:${v}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:r.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:r.length>0,reason:r.length>0?"cached_corruption_candidate":null,candidate_items:r,confirmed_items:s,resolved_false_positive_items:o,authoritative_item_source:r.length>0},drifted_items:_,counts:{drifted:_.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:g.length,workspace_state_unreadable:h.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:g,workspace_state_unreadable:h}},warnings:y}}function Zk(e,t){let n=Zl(e),i=au(n.settings),r=cu(n.settings,t),s=i.active?du(i.active.name,i.active.model):null;return{runtimeDefaults:n,providerResolution:i,vectorStoreResolution:r,runtimeEmbeddingIdentity:s,semanticRuntimeAvailable:!!(i.active&&r.active)}}function eS(){return{refreshed:[],skipped:[],warnings:[]}}async function tS(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?eS():uu(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function nS(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&lu(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function iS(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,i)=>n.localeCompare(i))}function rS(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function jp(e,t){let n=t.providerResolution.active?.name??null,i=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:Ro(n,e.search?.provider??null),vector_store_active:i,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:Ro(i,e.vector_store?.adapter??null)}}function sS(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function oS(e,t,n){return e.enabled&&n.length>0&&t}async function aS(e,t,n,i,r){let s=Zk(t,e),o=await Oo(e),a=s.semanticRuntimeAvailable?Vo(n,o.entries):[],c=await tS({pmRoot:e,snapshot:s,refreshPolicy:i,staleBefore:a}),d=await Oo(e),l=s.semanticRuntimeAvailable?Vo(n,d.entries):[],u=!s.runtimeDefaults.auto_ollama_defaults_applied,_=nS({strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:s.runtimeEmbeddingIdentity}),f=iS({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,embeddingIdentityChanged:_,staleAfter:l}),g=wa(a,r),h=wa(l,r),y=oS(i,s.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:s.semanticRuntimeAvailable,compatibility_mode_auto_defaults:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:s.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:s.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:sS(i),...jp(t,s),embedding_identity_changed:_,embedding_identity_before:o.embedding??null,embedding_identity_runtime:s.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:r?"full":"summary",stale_items_summary_limit:Lp,stale_items_before_total:g.total,stale_items_before:g.values,stale_items_before_truncated:g.truncated,refresh_attempted:y,refresh_skipped_reason:rS(i,s.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:f}}function cS(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function Gp(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new p("--check-only cannot be combined with --refresh-vectors",m.USAGE);if(n&&e.noRefresh===!0)throw new p("--no-refresh cannot be combined with --refresh-vectors",m.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var dS=new Set(["extensions","locks","search"]);function lS(e){let t=new Set(Id.filter(r=>r.length>0)),n=new Set,i=new Set(Object.values(xd));for(let r of e.folders)t.has(r)&&!i.has(r)||(t.delete(r),n.add(r));for(let r of dS)t.delete(r),n.add(r);return{requiredDirs:[...t].sort((r,s)=>r.localeCompare(s)),optionalDirs:[...n].sort((r,s)=>r.localeCompare(s)),optionalDirSet:n}}async function uS(e,t,n){let{requiredDirs:i,optionalDirs:r,optionalDirSet:s}=lS(t),o=[],a=[],c=[];for(let d of[...i,...r]){let l=Ae.join(e,d);c.push(...await Me({path:l,scope:"project"})),!await Sa(l)&&(s.has(d)?a.push(d):o.push(d))}return{requiredDirs:i,optionalDirs:r,missingRequiredDirs:o,missingOptionalDirs:a,missingDirs:n?[...o,...a]:[...o],hookWarnings:c}}function qp(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,i=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||i)&&e.full!==!0,skipDrift:(e.skipDrift===!0||i)&&e.full!==!0,skipVectors:(e.skipVectors===!0||i)&&e.full!==!0}}async function mS(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?ke(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):Ot(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function ha(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function _S(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function pS(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function fS(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var Ea=e=>e.unknown_event_count??0,Ta=e=>e.actionable_unknown_event_count??Ea(e);function gS(e,t,n,i,r,s,o){let a=Ea(i),c=Ta(i),d=a>0,l=c>0,u=r.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...d?{author_attribution:i}:{},...u?{stale_in_progress:r}:{},...s.length>0?{provenance_resolver_outcomes:s}:{},...o.length>0?{provenance_invalid_values:o}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Kp(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function hS(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function yS(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function vS(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function zp(e){let t=new Map;for(let[r,s]of Object.entries(e.remediationSources))for(let o of s)t.has(o)||t.set(o,r);let n=new Map(e.checks.map(r=>[r.name,r]));return e.warnings.map(r=>{let s=t.get(r)??"integrity",o=_a(r)?.code??ka(r),a=n.get(s)?.details,d=(typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{})[o],l=ba(r,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:r,code:o,check:s,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function wS(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function bS(e){for(let t of e.checks){let n=pa(e.remediationSources[t.name]);wS({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function kS(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],i=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),r=new Map;for(let o of e.pendingMergeReceipts){if(o.evidence_source!=="clone_local")continue;let a=r.get(o.item_id)??[];a.push(o),r.set(o.item_id,a)}let s=[];for(let o of n){if(i.has(o))continue;let a=r.get(o);if(!(!a||a.length===0))try{await k_(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),s.push(o)}catch{}}return[...new Set(s)].sort((o,a)=>o.localeCompare(a))}function SS(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(i=>i.startsWith("history_drift_hash_mismatch:")?!n.has(i.slice(i.indexOf(":")+1)):!0),...t.map(i=>`history_drift_merge_receipt:${i}`)].sort((i,r)=>i.localeCompare(r)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}function Wp(e,t,n){let i=e.warning_count??e.warnings.length,r={...e,warning_count:i,warning_limit:Nt,warnings_truncated:i>Nt,warnings:e.warnings.slice(0,Nt),findings:(e.findings??[]).filter(o=>e.warnings.slice(0,Nt).includes(o.warning)||e.failed_because.includes(o.warning))},s=n?$k(r):t.brief===!0?Fk(r):r;return{...s,warning_count:i,warning_limit:Nt,warnings_truncated:i>s.warnings.length,...s.projection?{projection:{...s.projection,warning_count:i,warnings_truncated:i>s.warnings.length}}:{}}}async function Bp(e,t={}){let n=x(process.cwd(),e.path);await P(n);let i=Te(n),{settings:r,warnings:s}=await Jl(n),o=[...new Set(s)],a=$(r,M()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=Gp(t),_=await uS(n,a,c),f=cS(r),g=await Xk(r,{checkTelemetry:t.checkTelemetry===!0}),h=await Lk(n,r,!!e.noExtensions),y=qp(t),v=[],w=await mS({pmRoot:n,settings:r,typeRegistry:a,skipPolicy:y,itemReadWarnings:v}),S=w,E=$r(K(r.schema),w),T=[...f,...Ur(E)],A=y.skipDrift?{warnings:[]}:await dr({pmRoot:n,settings:r,itemIds:w.map(ce=>ce.id),commandLabel:"health"}),k=await wk(n,r.history.compact_policy,await yk(n)),b=await oi(n,20,t.verboseAuthorEvents===!0),L=Ta(b),q=L>0?[`history_unknown_author_events:${L}`]:[],F=Kp(await _u(n,w,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),C=await b_(n),V=C.outcomes,we=C.invalid_values,ue=C.warnings,fe=await Jk(n),Le=y.skipIntegrity&&!l?{...ha("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await Tk(n,a.type_to_folder,r.schema,l,w),Ke=y.skipDrift?ha("history_drift"):await Qk({pmRoot:n,items:S,settings:r,typeRegistry:a,itemReadWarnings:v}),ft=[...new Set(v)],it=await kS({gitWorkspaceRoot:Le.gitWorkspaceRoot,pendingMergeReceipts:Le.pendingMergeReceipts,historyDriftCheck:Ke,global:e});SS(Ke,it);let Ht=y.skipVectors?ha("vectorization"):await aS(n,r,S,u,t.verboseStaleItems===!0),ae=[_S(i,r,o),pS(_,c),fS(T,E),g.check,h.check,gS(w,r,k,b,F.scan,V,we),fe.check,Le.check,Ke.check,Ht.check],Ne=hS({directoryState:_,normalizedSettingsReadWarnings:o,settingWarnings:T,normalizedItemReadWarnings:ft,telemetryCheck:g,extensionCheck:h,historyPolicyWarnings:A.warnings,historySummary:k,authorAttributionWarnings:q,staleInProgressWarnings:F.warnings,provenanceWarnings:ue,locksCheck:fe,integrityCheck:Le,historyDriftCheck:Ke,vectorizationCheck:Ht}),Yt=vS({directoryState:_,normalizedSettingsReadWarnings:o,settingWarnings:T,normalizedItemReadWarnings:ft,telemetryCheck:g,extensionCheck:h,historyPolicyWarnings:A.warnings,historySummary:k,authorAttributionWarnings:q,staleInProgressWarnings:F.warnings,provenanceWarnings:ue,locksCheck:fe,integrityCheck:Le,historyDriftCheck:Ke,vectorizationCheck:Ht});bS({checks:ae,remediationSources:Yt,historyDriftedCount:yS(Ke),overThresholdCount:k.over_threshold.length});let D=Ne.filter(ce=>!ba(ce,l)),ge=zp({warnings:Ne,checks:ae,remediationSources:Yt,requireMergeDrivers:l}),je=new Set(ge.filter(ce=>ce.severity==="gate_failing").map(ce=>ce.check)),Xt=new Set(ge.map(ce=>ce.check));for(let ce of ae)ce.ok=!je.has(ce.name),Xt.has(ce.name)&&(ce.status="warn");let ze={ok:D.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&D.length>0?m.GENERIC_FAILURE:0},checks:ae,warnings:Ne,findings:ge,failed_because:D,generated_at:R()};return Wp(ze,t,y.summaryMode)}var i$={buildHierarchyIntegrityWarnings:Mp,buildExtensionHealthTriageSummary:Pp,buildHealthFindings:zp,buildCapabilityContractMetadata:Xo,buildStaleInProgressHealthSummary:Kp,buildVectorizationProviderDetails:jp,collectUnknownCapabilityGuidance:Yo,isAdvisoryHealthWarning:ba,isDirectory:Sa,isExpectedUnmanagedExtension:ya,listItemDocumentPaths:Dp,normalizeEndpointForDisplay:zr,normalizeExtensionNameForMatch:yn,parseTelemetryQueue:$p,probeTelemetryEndpointHealth:Up,projectHealthResult:Wp,resolveActionableUnknownAuthorEventCount:Ta,resolveHealthSkipPolicy:qp,resolveUnknownAuthorEventCount:Ea,resolveVectorRefreshPolicy:Gp,selectStaleItemDetail:wa,summarizeHealthCheckDetails:Fp,summarizeExtensionList:qr,summarizeRecordList:Qe,summarizeStringList:z,telemetryEnvFlagEnabled:Kr,warningCode:ka};(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]="e2cd8850-491a-505c-8709-3dcdb758de75")}catch{}})();function ES(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function Vp(e){return`${e.item_id} ${e.link_kind}`}function Hp(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=ES(r.classification,i.classification),r.owners.set(Vp(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[Vp(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(s=>{let o=t(s.item_id);return{id:s.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:s.link_kind}}).sort((s,o)=>{let a=s.id.localeCompare(o.id);return a!==0?a:s.field.localeCompare(o.field)})}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ccb0d064-940b-5e14-ae63-2803aced4ee7")}catch{}})();function Yp(e,t,n,i,r=40){let s=r===1/0?1/0:Number.isFinite(r)?Math.max(0,Math.floor(r)):40,o=new Map(t.map(d=>[d.path,d])),a={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=Hp(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let g=se(f.status,i)??f.status;i.terminal_statuses.has(g)?(u.push(f),g===i.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):l.push(f)}a.missing_linked_links_count+=d.items.length,a.active_missing_linked_links_count+=l.length,a.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(a.active_missing_linked_paths_count+=1);let _=o.get(d.path);return{...d,candidates:_?.candidates??[],candidates_truncated:_?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,s),items_truncated:d.items.length>s}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),a.missing_linked_path_rows_count=c.length,a.missing_linked_path_rows=c.slice(0,s),a.missing_linked_path_rows_truncated=c.length>s,a}import vn from"node:fs/promises";import wn 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]="9bcae2f2-3739-5ef8-b080-daaaf7df2681")}catch{}})();async function TS(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let s;try{s=await vn.readdir(wn.join(e,r))}catch{return}for(let o of s)for(let a of It)if(o.toLowerCase().endsWith(a)){i.push({relativePath:`${r}/${o}`,id:o.slice(0,-a.length)});break}})),i.sort((r,s)=>r.relativePath.localeCompare(s.relativePath))}function AS(e,t){let{id:n,relativePath:i,liveItemIds:r,out:s}=e,o=rn(t);if(o){s.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=CS(e,t);a!==null&&(a.op==="delete"&&r.has(n)&&s.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(s.repairReconciliations+=1))}function CS(e,t){let{id:n,relativePath:i,out:r}=e,s=null,o=!1,a=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of a){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");s=d}catch{return r.unparseable.push({id:n,path:i,line:c.number,detail:"history line is not a valid JSON object"}),null}if(s.op==="create"){if(o)return r.unparseable.push({id:n,path:i,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return s}function Aa(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function IS(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await vn.readdir(wn.join(e,"history"))}catch{return n}for(let r of i.sort((s,o)=>s.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await vn.readFile(wn.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Aa("history stream",o)});continue}AS({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},s)}return n}function Xp(e){let t=rn(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function xS(e){let t=[],n=0,i=null;try{i=await ee(Te(e))}catch(s){n+=1,t.push({path:"settings.json",detail:Aa("configuration file",s)})}if(i!==null){n+=1;let s=Xp(i);s!==null&&t.push({path:"settings.json",detail:s})}let r;try{r=await vn.readdir(wn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of r.sort((o,a)=>o.localeCompare(a))){if(!s.endsWith(".json"))continue;n+=1;let o;try{o=await vn.readFile(wn.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:Aa("configuration file",c)});continue}let a=Xp(o);a!==null&&t.push({path:`schema/${s}`,detail:a})}return{scanned:n,unparseable:t}}async function Jp(e,t,n,i={}){let r=await TS(e,n),s=new Set(r.map(u=>u.id)),o=new Map;for(let u of r){let _=o.get(u.id);_===void 0?o.set(u.id,[u.relativePath]):_.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,_])=>({id:u,paths:[..._].sort((f,g)=>f.localeCompare(g))})).sort((u,_)=>u.id.localeCompare(_.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let _=wn.join(e,u.relativePath);return cr(await vn.readFile(_,"utf8"),{format:_.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await IS(e,s),l=await xS(e);return{item_files_on_disk:r.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import OS from"node:fs/promises";import $e from"node:path";import LS from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var RS=/^[a-z][a-z0-9+.-]+:\/\//i;function ci(e){return RS.test(e.trim())}(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]="02743545-3a44-565d-932c-7fe736d17eb8")}catch{}})();var NS=["path","scope","note"],DS=["pattern","glob","path","scope","note"],MS=["path"],PS=["from","to"],FS=new Set(["note","scope"]);function Zp(e){let t=e??"project";if(!De.includes(t))throw new p(`Invalid scope "${e}". Valid scopes: ${De.join(", ")} (default: project).`,m.USAGE);return t}function Ca(e){if(e.startsWith("```")||e.includes(`
|
|
6
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),i=n.indexOf("=");return i>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(r=>r>=0&&r<i))?!1:n.includes("=")||Zt(e)}function $S(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function US(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Ca(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let s=e.slice(t+2,-1).trim();if(s.length>0&&$S(s))return{path:s,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let i=e.slice(0,n).trim(),r=e.slice(n+1).trim();if(!(i.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(r)))return{path:r,scope:"project",note:i}}function jS(e,t){return e?e.flatMap(n=>{let i=n.trim();if(t==="doc"){let s=US(i);if(s!==void 0)return[s]}Un(i,"--add",`${t} path`,Ca(i));let r=Ca(i)?J(n,"--add"):{path:i};if(he(r,"--add",NS),!r.path)throw new p(`--add requires path=<value> or a bare ${t} path`,m.USAGE);return[{path:r.path,scope:Zp(r.scope),note:r.note?.trim()||void 0}]}):[]}function GS(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--add-glob requires a glob pattern value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=J(n,"--add-glob");he(i,"--add-glob",DS);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new p("--add-glob key/value form requires pattern=<glob>",m.USAGE);return{pattern:r,scope:Zp(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function qS(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires a path value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=J(n,"--remove"),r=Object.keys(i).filter(s=>FS.has(s.toLowerCase()));if(r.length>0)throw new p(`--remove identifies a linked artifact by path only and does not accept ${r.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,m.USAGE);if(he(i,"--remove",MS),!i.path)throw new p("--remove key/value form requires path=<value>",m.USAGE);return i.path}return n}):[]}function KS(e){return e?e.map(t=>{let n=J(t,"--migrate");he(n,"--migrate",PS);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new p("--migrate requires from=<value> and to=<value>",m.USAGE);return{from:i,to:r}}):[]}function di(e,t){let n=e;for(let i of t)n.startsWith(i.from)&&(n=`${i.to}${n.slice(i.from.length)}`);return n}function zS(e,t,n=[]){if(e.length===0||t.length===0)return;let i=new Set(e.map(s=>di(s.path,n))),r=[...new Set(t.map(s=>di(s,n)).filter(s=>i.has(s)))].sort((s,o)=>s.localeCompare(o));if(r.length!==0)throw new p(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${r.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,m.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function mt(e){return e.split($e.sep).join("/")}function Ia(e,t,n=process.cwd()){let i=e.trim();if(ci(i))return i;if($e.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return mt(i.replaceAll("\\",$e.sep));let r=$e.relative(t,n);return r.startsWith(`..${$e.sep}`)||r===".."||$e.isAbsolute(r)?mt($e.normalize(i)):mt($e.relative(t,$e.resolve(n,i)))}async function WS(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){let s=$e.isAbsolute(r.pattern),o=await LS(r.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(o.map(c=>Ia(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of a)i.push({path:c,scope:r.scope,note:r.note})}return i}function BS(e,t,n){if(t===void 0)return e;if(!n)throw new p("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",m.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function VS(e){return`${e.path}::${e.scope}`}function xa(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function Ra(e){return[...new Map(e.map(t=>[VS(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function HS(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),i=[],r=[],s=[],o=[];for(let a of n){if(ci(a)){o.push(a.trim());continue}let c=$e.isAbsolute(a)?a:$e.resolve(t,a);try{(await OS.stat(c)).isFile()?i.push(a):s.push(a)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&ji(d)){r.push(a);continue}s.push(a)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:s,remote_references:o}}function YS(e,t,n,i){let r=0;for(let o=0;o<e.length;o+=1){let a=di(e[o].path,i);a!==e[o].path&&(e[o]={...e[o],path:a},r+=1)}return{adds:t.map(o=>{let a=di(o.path,i);return a!==o.path&&(r+=1),{...o,path:a}}),removes:n.map(o=>di(o,i)),count:r}}function XS(e,t,n,i){for(let s of t)e.some(o=>o.path===s.path&&o.scope===s.scope)||e.push(s);if(n.length>0)for(let s=e.length-1;s>=0;s-=1)n.includes(e[s].path)&&e.splice(s,1);let r=Ra(e);return i?r:xa(r)}async function Qp(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await HS(t,e.workspaceRoot):void 0}}async function Wr(e,t,n,i){let{metadataKey:r}=i,s=en(),o=x(process.cwd(),n.path),a=He(o),c=process.cwd();await P(o);let d=await I(o),l=$(d,M()),u=await s.resolveList(t.add,"--add"),_=await s.resolveList(t.addGlob,"--add-glob"),f=await s.resolveList(t.remove,"--remove"),g=await s.resolveList(t.migrate,"--migrate"),h=jS(u,i.bareNoun).map(F=>({...F,path:Ia(F.path,a,c)})),y=GS(_),v=await WS(y,a,c),w=BS([...h,...v],t.note,h.length>0||y.length>0),S=qS(f).map(F=>Ia(F,a,c)),E=KS(g);if(zS(w,S,E),!(w.length>0||S.length>0||E.length>0)){let F=await Q(o,e,d.id_prefix,d.item_format,l.type_to_folder);if(!F)throw new p(`Item ${e} not found`,m.NOT_FOUND);let V=(await be(F,{schema:d.schema})).document.metadata[r]??[];return Qp({id:F.id,artifacts:V,changed:!1,options:t,workspaceRoot:a})}let A=G(t.author,d.author_default),k=await le({pmRoot:o,settings:d,id:e,op:i.op,author:A,message:t.message,force:t.force,skipNoop:!0,mutate(F){let C=F.metadata,V=C[r]??[],we=[...V],ue=YS(we,w,S,E),fe=XS(we,ue.adds,ue.removes,i.supportsAppendStable&&t.appendStable===!0);fe.length>0?C[r]=fe:delete C[r];let Le=!st(V,fe);return{changedFields:Le?[r]:[],warnings:Le&&ue.count>0?[`path_migrations_applied:${ue.count}`]:[]}}}),b=k.item[r]??[],L=k.warnings.find(F=>F.startsWith("path_migrations_applied:")),q=L?Number(L.slice(24)):0;return Qp({id:k.item.id,artifacts:b,changed:k.changedFields.includes(r),migrationsApplied:q,options:t,workspaceRoot:a})}function Br(e,t){let n={};for(let[i,r]of Object.entries(e))n[i==="artifacts"?t:i]=r;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aef928ec-4a5b-5614-bb5c-cbf63f891845")}catch{}})();async function ef(e,t,n){let i=await Wr(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Br(i,"docs")}import{execFile as JS}from"node:child_process";import tf 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]="1d4534aa-5a56-5a76-8971-aa3ba6c52e59")}catch{}})();function nf(e,t){return new Promise((n,i)=>{JS("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(r,s)=>{r?i(r):n(s)})})}function rf(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function j$(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(rf(n),!n)throw new RangeError("Source line range must use start:end.");return n}function QS(e){let t=new Map;for(let n of e.split(`
|
|
7
|
+
`)){let i=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];i&&t.set(i,(t.get(i)??0)+1)}return t}function ZS(e){let t=e.split("\0"),n=new Map;for(let i=0;i+1<t.length;i+=2){let r=t[i]?.trim();if(!r)continue;let s=[...new Set(t[i+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,a)=>o.localeCompare(a));n.set(r,s)}return n}async function eE(e){let t=tf.relative(e.workspaceRoot,tf.resolve(e.workspaceRoot,e.sourcePath)),n=await nf(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),i=await nf(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:QS(n),commitItems:ZS(i),available:!0}}function tE(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,i;for(let r of e.graph.incidentEdges(t)){let s=r.source===t,o=s?r.target:r.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let a=e.graph.registry().require(r.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,s?r.kind:a.inverse??r.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(i=n,e.found.push(c)):e.queue.push(c)}return i}function nE(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),i=[],r;for(;t.length>0;){let s=t.shift(),o=s.kinds.length;r!==void 0&&o>=r||o>=e.maxDepth||(r=tE({current:s,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:i})??r)}return i.sort((s,o)=>s.nodes.join("\0").localeCompare(o.nodes.join("\0"))),i}function iE(e,t,n){let i=l_(t);if(!i.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let r=nE({itemId:e,maxDepth:n,graph:i.graph,details:new Map(i.details.map(a=>[a.id,a]))}),s=r[0];if(!s)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(r.map(a=>a.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:s.nodes,kinds:s.kinds,alternative_decision_ids:o.slice(1)}}async function rE(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await eE({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function sE(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function oE(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function sf(e){rf(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await rE(e),i=oE(n),r=new Map;for(let s of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(s.item.id)),a=o.reduce((l,[,u])=>l+u,0),c=iE(s.item.id,e.corpus,t),d=sE({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});r.set(s.item.id,{score:a*100+s.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(s.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...s.files.map(l=>({kind:"linked_file",reference:l.path})),...o.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:s.item.value?.trim()||null,why_now:s.item.why_now?.trim()||null,outcome:s.item.outcome?.trim()||null,objective:s.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:r,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:i.length,unmapped_commit_count:n.commitLines.size-i.length,decision_depth:t}}}import of from"node:fs/promises";import Ue 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]="573da024-c791-5ff2-b3ee-3529804bab43")}catch{}})();var aE=32768;function Oa(e){return mt(Ue.normalize(e))}async function Vr(e){try{return await of.realpath(e)}catch{return Ue.resolve(e)}}function bn(e,t){let n=Ue.isAbsolute(e.path)?Ue.resolve(e.path):Ue.resolve(t,e.path);return`${Oa(n)}::${e.scope}`}function Hr(e,t,n){if(typeof e=="string"){let i=e.trim();i.length>0&&n.push({field:t,value:i});return}if(Array.isArray(e)){e.forEach((i,r)=>Hr(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))Hr(r,t?`${t}.${i}`:i,n)}function cE(e){let t=[];return Hr(e.metadata,"metadata",t),Hr(e.body,"body",t),t}function dE(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function lE(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,i=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let r of e){let s=new Set,o=r.value.slice(0,aE);for(let[a,c]of[[n,r.value],[i,o]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=dE(d[0]);!l||s.has(l)||(s.add(l),t.push({field:r.field,value:l}))}}}return t}async function uE(e,t,n=t){let i=Ue.isAbsolute(e)?Ue.resolve(e):Ue.resolve(n,e),r;try{r=await of.stat(i)}catch{return}if(!r.isFile())return;let[s,o]=await Promise.all([Vr(t),Vr(i)]);if(vo(s,o)){let a=Ue.relative(s,o);return!a||a.startsWith("..")||Ue.isAbsolute(a)?void 0:{path:Oa(a),scope:"project"}}return{path:Oa(i),scope:"global"}}async function mE(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>bn(c,t))),r=new Map,s=lE(cE(e)),o=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{o.set(c,await uE(c,t,n))}));let a=s.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=bn(d,t),u=r.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,r.set(l,u)}return[...r.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:i.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function af(e,t,n){let i=await Wr(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Br(i,"files")}async function _E(e,t){let n=await Vr(t),i=await Promise.all(e.map(async s=>{let o=s.trim();if(!o)throw new p("Files lookup paths must not be empty.",m.USAGE);if(!Ue.isAbsolute(o))return mt(o);let a=await Vr(o);return vo(n,a)?mt(Ue.relative(n,a)):mt(a)})),r=[...new Set(i)].sort((s,o)=>s.localeCompare(o));if(r.length===0)throw new p("Files lookup requires at least one path.",m.USAGE);return r}function pE(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new p(`Files lookup ${i} must be a non-negative integer.`,m.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function cf(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function df(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let i=t.item.updated_at.localeCompare(e.item.updated_at);return i===0?e.item.id.localeCompare(t.item.id):i}function fE(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(mt(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,i)=>{let r=n.path.localeCompare(i.path);return r===0?n.scope.localeCompare(i.scope):r})})).filter(t=>t.files.length>0).sort(df)}async function gE(e){if(e.explain)return sf({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function hE(e){if([e.strictRead,e.noTruncate,e.explain,ol()].includes(!0))return null;let t=await gr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?tu({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function yE(e){let t=[],n=await dn(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),i=fE({metadata:n,paths:e.paths,scope:e.scope}),r=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&r.length>0)throw new p(`Files lookup could not read every item: ${r.join("; ")}`,m.GENERIC_FAILURE);let s=await gE({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:i,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(s?[...i].sort((c,d)=>{let l=s.explanations.get(d.item.id).score-s.explanations.get(c.item.id).score;return l!==0?l:df(c,d)}):i).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<i.length,truncated:e.offset+a.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:cf(c.item),files:c.files,...s?{traceability:s.explanations.get(c.item.id)}:{}})),...s?{traceability_receipt:s.receipt}:{}}}async function rU(e,t){let n=x(process.cwd(),t.path),i=He(n);await P(n);let r=await _E(e.paths,i);if(e.lineRange&&r.length!==1)throw new p("Files lookup line attribution requires exactly one source path.",m.USAGE);let s=await I(n),o=$(s,M()),{offset:a,limit:c}=pE(e),d=await hE({pmRoot:n,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:r,total:d.total,count:d.matches.length,offset:a,limit:c,has_more:a+d.matches.length<d.total,truncated:a+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:cf(l.item),files:l.files}))}:yE({pmRoot:n,settings:s,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:i,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function sU(e,t,n){let i=x(process.cwd(),n.path),r=He(i);await P(i);let s=await I(i),o=$(s,M()),a=await Q(i,e,s.id_prefix,s.item_format,o.type_to_folder);if(!a)throw new p(`Item ${e} not found`,m.NOT_FOUND);let c=await be(a,{schema:s.schema}),d=await mE(c.document,r,process.cwd()),l=d.filter(b=>b.status==="addable"),u=d.filter(b=>b.status==="already_linked"),_=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!_||l.length===0){let b=c.document.metadata.files??[];return{id:a.id,files:b,changed:!1,apply:_,count:b.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let g=G(t.author,s.author_default),h=l.map(b=>({path:b.path,scope:b.scope,note:f})),y=[],v=new Set,w=await le({pmRoot:i,settings:s,id:e,op:"files_discover",author:g,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let L=[...b.metadata.files??[]],q=new Set(L.map(V=>bn(V,r)));y=[],v.clear();for(let[V,we]of h.entries()){let ue=bn(we,r);q.has(ue)||(L.push(we),q.add(ue),y.push(we),v.add(V))}let F=Ra(L),C=t.appendStable?F:xa(F);return C.length>0?b.metadata.files=C:delete b.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==h.length?[`files_discover_skipped_existing:${h.length-y.length}`]:[]}}}),S=w.item.files??[],E=new Set(y.map(b=>bn(b,r))),T=S.filter(b=>E.has(bn(b,r))),A=l.filter((b,L)=>!v.has(L)),k=[...u,...A];return{id:w.item.id,files:S,changed:T.length>0,apply:!0,count:S.length,candidate_count:d.length,addable_count:l.length,added_count:T.length,skipped_existing_count:k.length,candidates:d,added:T,skipped_existing:k}}import{readFileSync as vE}from"node:fs";import Yr 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]="e69d7d9b-9ae8-5337-9ea3-a8e40a62d3af")}catch{}})();var wE=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),La=new Set(["--pm-path","--path","--author"]),bE={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},kE=new Set(["-p","--package"]),SE=new Set(["-c","--call"]),Na=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Da=new Set(["-C","--prefix","--userconfig","--cache"]),lf=new Set(["--cwd"]),uf=new Set(["--cwd"]),EE=new Set(["exec","x"]),mf=new Set(["run","run-script"]),_f=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Dt(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function Xr(e,t=process.cwd()){let n=Jr(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[i,...r]=n;if(li(i)||ui(i,t))return r;if(i==="node"&&r[0]&&ui(r[0],t))return r.slice(1);let s=i==="npx"||i==="bunx"?Mt(r):i==="pnpm"?Zr(r):i==="npm"?es(r):null;return s&&(li(s.command)||Pa(s.command))?s.args:null}var Ma=(e,t="pm")=>{let n=t.trim().toLowerCase(),i=n.length;for(;i>0&&n[i-1]==="-";)i-=1;let r=n.slice(0,i);if(r.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of Dt(s)){let c=Xr(a),d=c?Fa(c):null,l=d&&wE.has(d.subcommand)?AE(d.remaining,bE[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&o.add(l)}return[...o].sort((a,c)=>a.localeCompare(c))};function Jr(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Qr(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(La.has(n)){t+=2;continue}t+=1;continue}return n}}function li(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function TE(e){let t=e.trim();if(!t.startsWith("@")){let r=t.indexOf("@");return r===-1?t:t.slice(0,r)}let n=t.indexOf("/");if(n===-1)return t;let i=t.indexOf("@",n+1);return i===-1?t:t.slice(0,i)}function Pa(e){let t=TE(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function ui(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let i=Yr.resolve(t,e);try{return JSON.parse(vE(Yr.join(Yr.dirname(Yr.dirname(i)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Mt(e){let t=0;for(;t<e.length;){let i=e[t];if(i==="--"){t+=1;break}if(!i.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(i);if(r){let s=r[1];return s?{command:s,args:e.slice(t+1)}:null}if(SE.has(i)){t+=1;break}t+=kE.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function bt(e,t){let n=0;for(;n<e.length;){let i=e[n];if(i==="--"){n+=1;continue}if(i.startsWith("-")){if(i.includes("=")){n+=1;continue}if(t.has(i)){n+=2;continue}n+=1;continue}return{subcommand:i,args:e.slice(n+1)}}return null}function Zr(e){let t=bt(e,Na);return t?.subcommand!=="dlx"?null:Mt(t.args)}function es(e){let t=bt(e,Da);return!t||!EE.has(t.subcommand)?null:Mt(t.args)}function Fa(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(La.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function AE(e,t=new Set){for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")return e[n+1];if(!i.startsWith("-"))return i;!i.includes("=")&&(La.has(i)||t.has(i))&&(n+=1)}}import{execFile as CE}from"node:child_process";import{readFile as IE}from"node:fs/promises";import ff from"node:path";import{promisify as xE}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]="eeb9bc22-b9e1-5449-9ad0-fbb1a14fb09d")}catch{}})();var RE=xE(CE),$a=1,OE="linked-test-trust.json";function Ua(e){return ff.join(zd(e),OE)}function pf(){return{version:$a,acknowledged:{}}}async function ja(e){try{let t=JSON.parse(await IE(Ua(e),"utf8"));return t.version!==$a||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?pf():{version:$a,acknowledged:t.acknowledged}}catch{return pf()}}async function _i(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await RE("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),i=n.trim();return i.length===0?void 0:i}catch{return}}function pi(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function LE(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Nd(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function mi(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function NE(e,t,n,i){return e?.map(r=>r.command&&!r.provenance?{...r,provenance:{author:t,created_at:n,source_kind:"local_mutation",...i?{source_ref:i}:{}}}:r)}async function kn(e,t,n){if(!e||e.length===0)return e;let i=pi();return NE(e,t,n,await _i(i))}function gf(e){return tl(ie({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function Ga(e,t,n){let i=await ja(e);return hf(t,n,i)}function hf(e,t,n){let i=gf(e),r=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:i,trusted:!0,reason:"legacy"};let s=Object.hasOwn(n.acknowledged,i);return e.provenance_invalid===!0||!LE(e.provenance)?s?{fingerprint:i,trusted:!0,reason:"acknowledged",...mi(void 0,t)}:{fingerprint:i,trusted:!1,reason:"invalid_provenance",...mi(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r===void 0?{fingerprint:i,trusted:!0,reason:"local_mutation",...mi(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r!==void 0&&r===t?{fingerprint:i,trusted:!0,reason:"local_source_ref",source_ref:r,current_source_ref:t}:s?{fingerprint:i,trusted:!0,reason:"acknowledged",...mi(r,t)}:{fingerprint:i,trusted:!1,reason:"foreign_source_ref",...mi(r,t)}}async function yf(e,t,n){let i=await ja(e);return t.map(r=>hf(r,n,i))}async function vf(e,t,n){let i=await ja(e),r=t.filter(s=>typeof s.command=="string"&&s.command.length>0).map(gf);for(let s of r)i.acknowledged[s]={acknowledged_at:n};return await gt(ff.dirname(Ua(e))),await Ve(Ua(e),`${JSON.stringify(i,null,2)}
|
|
8
|
+
`),{acknowledged:r.length,fingerprints:r}}import ec from"node:fs/promises";import{realpathSync as GE}from"node:fs";import{execFile as qE}from"node:child_process";import Ce from"node:path";import{promisify as KE}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]="55d5ac7a-9aa4-569e-9bb6-f504a0ac7421")}catch{}})();var DE=["metadata","resolution"],qa=["metadata","resolution","estimates","lifecycle"],ME="completed";function Ka(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function wf(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function bf(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=wf(n.close_reason)??ME;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${Ka(i)}`,gate:"resolution"})}return t}function kf(e){let t=[];for(let n of e){let i=wf(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${Ka(i)}`,gate:"metadata"})}return t}function Sf(e,t){return e.map(n=>{let i=Xl(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function Ef(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function Tf(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${i} ${n.item_id} --remove ${Ka(n.path)}`})}return t}function Af(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new p(`--fix-scope values must not be empty. Supported values: ${qa.join(", ")}.`,m.USAGE);return new Set(DE)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(qa.includes(r)){n.add(r);continue}throw new p(`Unknown --fix-scope value "${i}". Supported values: ${qa.join(", ")}.`,m.USAGE)}return n}function Cf(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function fi(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="40703093-d602-5e6b-92b6-6b5efe3613fe")}catch{}})();var PE=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function FE(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let i=PE.exec(n);if(!i)return null;let r=i[1],s=r.toUpperCase(),o=r.slice(0,r.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(_=>_.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(r.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${s}`)||d.includes(`ISSUE CODE \`${s}\``)||d.includes(`\`${s}\``)||d.includes(`[${s}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(o.toUpperCase())||l?s:null}function If(e){return typeof e=="string"&&e.trim().length>0}function xf(e,t={}){let n=new Map;for(let r of e){if(typeof r.title!="string"||If(r.duplicate_of))continue;let s=FE(r.title,{...t,evidenceText:r.body});if(s===null)continue;let o=n.get(s);o||(o=[],n.set(s,o)),o.some(a=>a.id===r.id)||o.push({id:r.id,title:r.title,parent:If(r.parent)?r.parent.trim():null})}let i=[];for(let[r,s]of n){if(s.length<2)continue;let o=new Set(s.map(d=>d.id.toLowerCase())),a=s.filter(d=>d.parent===null||!o.has(d.parent.toLowerCase()));if(a.length<2)continue;let c=[...a].sort((d,l)=>d.id.localeCompare(l.id));i.push({code:r,count:c.length,ids:c.map(d=>d.id),titles:c.map(d=>d.title)})}return i.sort((r,s)=>r.code.localeCompare(s.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b51a9fba-7bbe-573b-a708-5ffea6fa040f")}catch{}})();function Rf(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,s)=>r.localeCompare(s))){let r=t.get(i),s={};for(let o of[...r.keys()].sort((a,c)=>a.localeCompare(c)))s[o]=r.get(o);n[i]=s}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ede22770-cb10-5054-85a7-89bb2758c25f")}catch{}})();var Of=3;function Lf(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Nf(e,t,n=Of){let i=Number.isFinite(n)&&n>=1?Math.floor(n):Of,r=new Map;for(let s of t){let o=Lf(s);if(o.length===0)continue;let a=r.get(o);a?a.push(s):r.set(o,[s])}return e.map(s=>{if(s.includes(",")||s.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:s,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(r.get(Lf(s))??[]).filter(a=>a!==s).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:o.slice(0,i),candidates_truncated:o.length>i}})}function Df(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ae38c0a-7f43-5457-b9a5-d23491a371ea")}catch{}})();async function ts(e){return e.includeBody?Ot(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):dn(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42402d5d-8074-591f-98b4-75f479509cb4")}catch{}})();var $E=5;async function ns(e,t,n){let i=await Yn(e,t),s=[["validate_history_drift_missing_streams",i.missingStreams.length],["validate_history_drift_unreadable_streams",i.unreadableStreams.length],["validate_history_drift_hash_mismatches",i.hashMismatches.length],["validate_history_drift_chain_mismatches",i.chainMismatches.length],["validate_history_drift_version_skews",i.versionSkews.length],["validate_history_drift_workspace_state_mismatches",i.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",i.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",i.workspaceStateUnreadable.length]].filter(([,d])=>d>0).map(([d,l])=>`${d}:${l}`),o=n?Number.POSITIVE_INFINITY:$E,a=i.driftedItems.slice(0,o),c=i.identityDiscontinuities??[];return{check:{name:"history_drift",status:c.length>0?"error":s.length===0?"ok":"warn",ok:c.length===0&&s.length===0,details:{identity_discontinuities:c.slice(0,o),identity_discontinuities_count:c.length,identity_discontinuities_truncated:c.length>o,checked_items:t.length,drifted_items_count:i.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<i.driftedItems.length,counts:{missing_streams:i.missingStreams.length,unreadable_streams:i.unreadableStreams.length,hash_mismatches:i.hashMismatches.length,chain_mismatches:i.chainMismatches.length,version_skews:i.versionSkews.length,workspace_state_mismatches:i.workspaceStateMismatches.length,workspace_state_missing:i.workspaceStateMissing.length,workspace_state_unreadable:i.workspaceStateUnreadable.length},workspace_state_mismatches:i.workspaceStateMismatches,workspace_state_missing:i.workspaceStateMissing,workspace_state_unreadable:i.workspaceStateUnreadable,version_skews:i.versionSkews.slice(0,o)}},warnings: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]="c357729b-f316-51e7-9768-fc7bb4600e06")}catch{}})();function is(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],s=new Set([n]),o=a=>{for(let c of(t.get(a)??[]).filter(d=>i.has(d))){if(c===n&&r.length>1)return r.push(n),!0;if(!s.has(c)){if(s.add(c),r.push(c),o(c))return!0;r.pop(),s.delete(c)}}return!1};return o(n)?[...r]:[...e,n]}function UE(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function jE(e,t,n,i){for(let r of e.dependencies??[]){if(typeof r!="object"||r===null||typeof r.id!="string")continue;let s=i.resolve(r.kind);if(!s?.hierarchy)continue;let o=n.get(r.id.toLowerCase());o&&(s.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function za(e,t=Se()){let n=new Map(e.map(r=>[r.id.toLowerCase(),r.id])),i=new Map(e.map(r=>[r.id,[]]));for(let r of[...e].sort((s,o)=>s.id.localeCompare(o.id))){let s=i.get(r.id),o=UE(r.parent,n);o&&s.push(o),jE(r,i,n,t)}for(let[r,s]of i)i.set(r,[...new Set(s)].sort());return i}function Wa(e,t,n=Se()){let i=kr(e,o=>t?sr(o,t):o==="closed"||o==="canceled",n),r=za(e,n),s=i.cycles.map(o=>o.item_ids);return{cycle_count:s.length,active_cycle_count:i.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:i.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(s.flat())].sort(),cycle_sample_paths:s.map(o=>is(o,r).join("->")),cardinality_violation_count:i.cardinality_violations.length,active_cardinality_violation_count:i.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:i.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:i.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:i.divergences.length,active_parent_divergence_count:i.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:i.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:i.divergences.map(o=>`${o.child_id}:scalar=${o.scalar_parent_id}:dependencies=${o.dependency_parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1d8059aa-0711-522b-a12e-f5469286542f")}catch{}})();function kt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Ba(e){return kt(e).replace(/\/+$/,"")}function Ge(e){let t=ne(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return 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]="16aa1db1-b6f2-504b-aa4e-0e384ad1d7a5")}catch{}})();var zE=["src","tests","docs"],WE=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],BE=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),VE=["resolution","expected_result","actual_result"],HE=["default","tracked-all","tracked-all-strict"],Mf=["core","strict","custom"],os=["off","warn","error"],Ya=["author","acceptance_criteria","estimated_minutes","close_reason"],$f=[...Ya,"reviewer","risk","confidence","sprint","release"],Xa=Array.from(new Set($f)),YE={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},XE={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},JE={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},QE={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},ZE={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},eT=32*1024*1024,tT=1e4,Ja=40,et=5,nT=4096,iT=255,rT=KE(qE);function Uf(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||i===!1&&n.endsWith("_truncated")||(t[n]=typeof i=="object"&&i!==null?Uf(i):i);return t}function sT(e){return{...e,checks:e.checks.map(t=>({...t,details:Uf(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function cs(e,t){return se(e,t)??e}function gi(e,t){return t.terminal_statuses.has(cs(e,t))}function St(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function rs(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function oT(e){let t=St(Rd),n={blocked_reason:St(Gi.blocked_reason),resolution:St(Gi.resolution),actual_result:St(Gi.actual_result)},i=St(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:St(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:St(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:St(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:rs(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:rs(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:rs(r.resolution,n.resolution)?"default":"settings",actual_result:rs(r.actual_result,n.actual_result)?"default":"settings"}}}function jf(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Mf.includes(t))return t;throw new p(`Unknown --metadata-profile value "${e}". Supported values: ${Mf.join(", ")}.`,m.USAGE)}function Gf(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(os.includes(t))return t;throw new p(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${os.join(", ")}.`,m.USAGE)}function qf(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(os.includes(t))return t;throw new p(`Unknown --parent-cycle-severity value "${e}". Supported values: ${os.join(", ")}.`,m.USAGE)}function aT(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>YE[n]).filter(n=>n!==void 0).sort((n,i)=>n.localeCompare(i))}function cT(e,t,n){let i=aT(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Ya],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...$f],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:i.length>0?{profile:e,profile_source:t,required_fields:i,configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Ya],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var dT=new Set(["acceptance_criteria","estimated_minutes"]);function Kf(e,t,n,i){return!i&&dT.has(t)&&gi(e.status,n)?!1:t==="author"?!ne(e.author):t==="acceptance_criteria"?!ne(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?cs(e.status,n)===n.close_status&&!ne(e.close_reason):t==="reviewer"?!ne(e.reviewer):t==="risk"?!ne(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!ne(e.confidence):t==="sprint"?!ne(e.sprint):!ne(e.release)}function zf(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new p(`Unknown --scan-mode value "${e}". Supported values: ${HE.join(", ")}.`,m.USAGE)}function Wf(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Ce.resolve(t);let n=Ce.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Ce.dirname(Ce.dirname(n));let r=Ce.resolve(process.cwd()),s=Pf(n),o=Pf(r),a=Ce.relative(s,o);return a.length===0||!a.startsWith("..")&&!Ce.isAbsolute(a)?n:r}function Pf(e){try{return GE.native(e)}catch{return Ce.resolve(e)}}function lT(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function tc(e,t,n){let i=t.length>0?Ce.join(e,t):e,r;try{r=await ec.readdir(i,{withFileTypes:!0})}catch(s){if(W(s))return;throw s}for(let s of r){if(s.name.startsWith("."))continue;let o=t.length>0?Ce.join(t,s.name):s.name;if(s.isDirectory()){if(BE.has(s.name))continue;await tc(e,o,n);continue}s.isFile()&&n.push(kt(o))}}async function Qa(e){let t=[];for(let n of zE)await tc(e,n,t);for(let n of WE){let i=Ce.join(e,n);try{(await ec.stat(i)).isFile()&&t.push(kt(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function Bf(e){try{let{stdout:t}=await rT("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:eT,windowsHide:!0,timeout:tT}),n=t.split("\0").map(i=>kt(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function uT(e,t){let n=new Set,i=Ba(Cd);i.length>0&&n.add(i);let r=Ba(Ce.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((s,o)=>s.localeCompare(o))}function Ff(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function mT(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await Bf(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await Qa(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await Qa(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function te(e,t=et){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Pt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=te(e,Ja);return{values:n.values,truncated:n.truncated,total:e.length}}var _T={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},pT={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function fT(e){let t=e.missing_fields.map(n=>`${_T[n]} "${pT[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Vf(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(o=>typeof o=="string"):xp(t);if(r.length===0)return;let s=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...s?{fix_hints_truncated:!0}:{}}}function Hf(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var gT="validate_metadata_duplicate_issue_codes";function Yf(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:et,i=e.slice(0,n);return{rows:i.map(s=>({code:s.code,count:s.count,ids:s.ids,titles:s.titles,remediation_hint:`Items ${s.ids.join(", ")} share issue code "${s.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${gT}:${e.length}`]}}function hT(e,t,n){let i=Object.fromEntries(Xa.map(r=>[r,[]]));for(let r of e)for(let s of Xa)Kf(r,s,t,n)&&i[s].push(r.id);return i}function yT(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let s=t[r];s.length>0&&i.push(`${XE[r]}:${s.length}`)}return i.push(...n),i}function Xf(e,t){let n={};for(let i of e.required_fields){let r=t[i],s=r?r.length:0,o=JE[i];n[o]=s}return n}function Jf(e,t,n){let i=[];for(let r of e.required_fields){let s=t[r];if(s)for(let o of s){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";i.push({item_type:c,field:r})}}return i}function vT(e,t,n,i){for(let r of t.required_fields){let s=n[r];if(!s||s.length===0)continue;let o=QE[r],a=ZE[r];if(!o||!a)continue;let c=te(s,i?s.length:et);e[o]=c.values,e[a]=c.truncated}}function Qf(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:ne(n.get(r)?.resolution)})):[]}function Zf(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:ne(n.get(r)?.type)})):[]}function wT(e,t,n,i,r){let s=new Map(e.map(v=>[v.id,v])),o=t.profile==="strict",a=hT(e,n,o),c=xf(e,{configuredPrefixes:r}),d=Yf(c,i),l=yT(t,a,d.warnings),u=Xf(t,a),_=Jf(t,a,s),f=Rf(_),g={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...Xa],counts:u,missing_by_type:f,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(g.configured_custom_required_fields=[...t.configured_custom_fields]),vT(g,t,a,i);let h=Qf(t,a,s),y=Zf(t,a,s);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:g},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:y}}function bT(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(_=>i.has(cs(_.status,t))),s=[],o=[];for(let _ of r){let f=VE.filter(g=>!ne(_[g]));f.length!==0&&(s.push({id:_.id,missing_fields:f}),o.push({id:_.id,missing_fields:f,close_reason:ne(_.close_reason)}))}let a=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:et,d=te(s.map(_=>`${_.id}:${_.missing_fields.join(",")}`),c),l=s.map(_=>fT(_)),u=te(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:r.length,missing_resolution_items:s.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function eg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tg(e,t="pm",n=Zd()){let i=new Set(e.map(s=>s.id)),r=[...e].sort((s,o)=>s.id.localeCompare(o.id));return new Map(r.map(s=>{let o=new Set,a=Ge(s.blocked_by);a&&i.has(a)&&o.add(a),(s.dependencies??[]).filter(d=>{let l=Ge(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ge(d.id)).filter(d=>d!==void 0&&i.has(d)).forEach(d=>o.add(d));let c=Ge(s.definition_of_ready);return ig(c??"",t).filter(d=>i.has(d)).forEach(d=>o.add(d)),[s.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function ng(e,t,n){let i=d_(e,n?l=>gi(l,n):void 0),r=i.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),s=i.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:et,a=te(r,o),c=te(s,o),d=te(i.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:r.length===0?"ok":"warn",ok:r.length===0,details:{checked_items:e.length,dangling_reference_count:r.length+s.length,active_dangling_reference_count:r.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:i.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:i.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function ig(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${eg(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,s)=>r.localeCompare(s))}function rg(e){let t=0,n=new Map,i=new Map,r=[],s=new Set,o=[],a=l=>{n.set(l,t),i.set(l,t),t+=1,r.push(l),s.add(l);for(let _ of e.get(l)??[])n.has(_)?s.has(_)&&i.set(l,Math.min(i.get(l),n.get(_))):(a(_),i.set(l,Math.min(i.get(l),i.get(_))));if(i.get(l)!==n.get(l))return;let u=[];for(;r.length>0;){let _=r.pop();if(s.delete(_),u.push(_),_===l)break}u.sort((_,f)=>_.localeCompare(f)),o.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return o.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function sg(e,t="pm"){let n=tg(e,t),i=rg(n),r=[...new Set(i.flat())].sort((o,a)=>o.localeCompare(a)),s=i.map(o=>is(o,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:s}}function og(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function as(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function ag(e,t){let n=as(e).split("/").filter(Boolean),i=as(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function kT(e,t){let n=as(t),i=as(e),r=t.endsWith("/")?t:`${t}/`,s=e.startsWith(r),o=n.length>0&&n===i,a=ag(e,t);return!s&&!o&&a===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function ST(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function ET(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(s=>(i==="docs"?s.docs??[]:s.files??[]).map(o=>({item:s,link:o}))).forEach(({item:s,link:o})=>{if(o.scope!=="project")return;let a=kt(o.path);if(a.length===0||a===e)return;let c=kT(e,a);c!==null&&ST(r,s,c.score)&&(r={item:s,score:c.score,confidence:c.confidence})}),r?{id:r.item.id,type:r.item.type,title:r.item.title,status:r.item.status,confidence:r.confidence}:null}function cg(e,t){return e.map(n=>{let i=og(n),r=i==="docs_unowned"?"docs":"files",s=ET(n,i,t),o=s?.id??"<id>";return{path:n,classification:i,owner_candidate:s,remediation_hint:`pm ${r} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function dg(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function TT(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=Ge(e[n]);return r?i.some(s=>r.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function AT(e,t,n,i,r){let s=Ge(t.parent),o=s?n.get(i.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!gi(o.status,r)}}function CT(e,t,n,i){let r=Ge(e.blocked_by),s=Ge(e.blocked_reason),o=s?.toLowerCase(),a=cs(e.status,n),c=[];return t.has(a)?(!r&&!s&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&i.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function IT(e,t,n,i){let r=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!gi(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=TT(c,i);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=Ge(c.parent),u=l?r.get(s.get(l.toLowerCase())??l):void 0;if(u&&gi(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(AT(c,u,r,s,n))),t){let _=CT(c,o,n,i);_.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(_)].sort((f,g)=>f.localeCompare(g))})}}return a}function xT(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function ss(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Va(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function RT(e,t,n,i,r){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=ss("validate_lifecycle_dependency_cycles",n,r.dependencyCycles),a=ss("validate_hierarchy_parent_cycle",i,r.activeHierarchyCycles),c=ss("validate_hierarchy_cardinality_violation",i,r.activeHierarchyCardinality),d=ss("validate_hierarchy_parent_divergence",i,r.activeHierarchyDivergence),l=Va("validate_legacy_hierarchy_parent_cycle",i,r.legacyHierarchyCycles),u=Va("validate_legacy_hierarchy_cardinality_violation",i,r.legacyHierarchyCardinality),_=Va("validate_legacy_hierarchy_parent_divergence",i,r.legacyHierarchyDivergence);return[...s,...o?[o]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],..._?[_]:[]]}function lg(e){let t=kt(e);return t.length>nT||t.split(/[\\/]/).some(n=>n.length>iT)}async function OT(e,t){let n=Ce.isAbsolute(t)?t:Ce.resolve(e,t);if(lg(n))return!1;try{let i=await ec.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return lT(i,["ENOENT","ENOTDIR"])}}async function LT(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(s=>({item:r,artifact:s,link_kind:"files"})),...(r.docs??[]).map(s=>({item:r,artifact:s,link_kind:"docs"}))]);for(let{item:r,artifact:s,link_kind:o}of i){if(s.scope!=="project")continue;if(ci(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let a=kt(s.path);a.length!==0&&(n.linkedProjectPaths.add(a),await OT(t,s.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:r.id,path:a,link_kind:o})))}return n}function NT(e,t,n,i,r,s){let o=i==="tracked-all-strict",a=o&&!r,c=r||o,d=c?[]:uT(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>Ff(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Ff(f,d)),_={};if(l.length>0){let f=Pt(l,s);_.pm_internals={count:l.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:_}}function ug(e,t,n,i,r,s,o,a="pm"){let c=IT(e,t,r,s);xT(c);let d=sg(c.activeItems,a),l=Wa(e,r),u=$r(r,e,o?Number.POSITIVE_INFINITY:et),_=[...RT(c,t,n,i,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...Ur(u)],f=o?Number.POSITIVE_INFINITY:et,g=te(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),f),h=te(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),f),y=te(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),f),v=te(d.cycle_item_ids,f),w=te(d.cycle_sample_paths,f),S=te(l.cycle_item_ids,f),E=te(l.cycle_sample_paths,f),T=te(l.cardinality_violation_rows,f),A=te(l.parent_divergence_rows,f),k=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&i==="error";return{check:{name:"lifecycle",status:k?"error":_.length===0?"ok":"warn",ok:!k&&_.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:g.values,active_closure_like_metadata_rows_truncated:g.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:v.values,dependency_cycle_item_ids_truncated:v.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:i,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:S.values,parent_cycle_item_ids_truncated:S.truncated,parent_cycle_sample_paths:E.values,parent_cycle_sample_paths_truncated:E.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:T.values,hierarchy_cardinality_violation_rows_truncated:T.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:A.values,hierarchy_parent_divergence_rows_truncated:A.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:_,terminalParentFixRows:c.terminalParentFixRows}}async function mg(e,t,n,i,r,s,o=K(Ct.schema)){let a=await LT(e,t),c=new Map(e.map(C=>[C.id,C])),d=[...new Set(a.missingLinkedPaths)].sort((C,V)=>C.localeCompare(V)),l=await mT(t,i),u=NT(l,n,t,i,r,s),_=u.candidateFiles.filter(C=>!a.linkedProjectPaths.has(C)),f=cg(_,e),g=Nf(d,u.candidateFiles),h=new Map(g.map(C=>[C.path,C.classification])),y=g.filter(C=>C.classification==="moved").length,v=a.staleLinkRows.map(C=>({...C,classification:h.get(C.path)??"deleted"})).sort((C,V)=>C.item_id.localeCompare(V.item_id)||C.path.localeCompare(V.path)||C.link_kind.localeCompare(V.link_kind)),w=[];u.strictModeForcesPmInternals&&w.push("validate_files_tracked_all_strict_forces_pm_internals"),_.length>0&&w.push(`validate_files_orphaned_paths:${_.length}`);let S=[...a.remoteLinkedPaths].sort((C,V)=>C.localeCompare(V)),E=Pt(S,s),T=Pt(d,s),A=Pt(_,s),k=Pt(f.map(C=>`${C.path}:${C.classification}:owner_candidate=${C.owner_candidate?.id??"unowned"}`),s),b=s?f:Pt(dg(f),!1).values,L=Pt(Df(g),s),F=Yp(v,g,C=>c.get(C),o,s?1/0:Ja);return F.active_missing_linked_paths_count>0&&w.push(`validate_files_missing_linked_paths:${F.active_missing_linked_paths_count}`),{check:{name:"files",status:w.length===0?"ok":"warn",ok:w.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:s?"full":"summary",file_list_summary_limit:Ja,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:r,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:S.length,remote_linked_paths_total:E.total,remote_linked_paths:E.values,remote_linked_paths_truncated:E.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:T.total,missing_linked_paths:T.values,missing_linked_paths_truncated:T.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:g.filter(C=>C.classification==="deleted").length,missing_linked_paths_malformed_count:g.filter(C=>C.classification==="malformed").length,missing_linked_path_classifications:L.values,missing_linked_path_classifications_truncated:L.truncated,...F,orphaned_paths_count:_.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.truncated,orphaned_path_classifications:k.values,orphaned_path_classifications_truncated:k.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:b}},warnings:w,staleLinkPruneRows:v}}function _g(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function DT(e,t,n){return`${e}:${t}:${_g(n)}`}function MT(e,t){let n=[];return e.forEach(({item:i,linkedTest:r},s)=>{let o=t[s];if(o.trusted)return;let a=_g(r.command??"");n.push(`${i.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${a}`)}),n}async function pg(e,t,n,i){let r=new Set(e.map(T=>T.id.toLowerCase())),s=0,o=0,a=new Set,c=[],d=e.flatMap(T=>(T.tests??[]).map(A=>({item:T,linkedTest:A}))),l=await _i(pi()),u=await yf(i,d.map(({linkedTest:T})=>T),l),_=MT(d,u);for(let{item:T,linkedTest:A}of d){if(typeof A.command!="string"||A.command.trim().length===0)continue;s+=1;let k=Ma(A.command,t);if(k.length!==0){o+=k.length;for(let b of k)a.add(b),r.has(b.toLowerCase())||c.push(DT(T.id,b,A.command))}}let f=[...new Set(c)].sort((T,A)=>T.localeCompare(A)),g=[...new Set(f.map(T=>T.split(":")[1]??""))].filter(T=>T.length>0).sort((T,A)=>T.localeCompare(A)),h=[];f.length>0&&h.push(`validate_command_references_stale_pm_ids:${f.length}`),_.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${_.length}`);let y=n?Number.POSITIVE_INFINITY:et,v=te(f,y),w=te(g,y),S=te([...a].sort((T,A)=>T.localeCompare(A)),y),E=te(_,y);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:s,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:S.values,unique_referenced_pm_ids_truncated:S.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:_.length,untrusted_linked_tests:E.values,untrusted_linked_tests_truncated:E.truncated,stale_pm_id_references_count:f.length,stale_pm_ids_count:g.length,stale_pm_ids:w.values,stale_pm_ids_truncated:w.truncated,stale_pm_id_reference_rows:v.values,stale_pm_id_reference_rows_truncated:v.truncated}},warnings:h}}function PT(e,t){let n=ar(e.map(c=>({ref:c.id,version:or(c)}))),i=[];n.outdated.length>0&&i.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&i.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:et,s=te(n.outdated,r),o=te(n.ahead,r),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:gl,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:i}}var Za="pm validate auto-fix";async function fg(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:Za};if(e.kind==="set_resolution"?i.resolution=e.value:e.kind==="set_close_reason"?i.closeReason=e.value:e.kind==="set_estimate"?i.estimatedMinutes=e.value:e.kind==="reparent"?i.parent=e.parent_id:i.unset=["parent"],!n.runUpdate)throw new p("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",m.USAGE);await n.runUpdate(e.item_id,i,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Ha(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function gg(e,t,n){let i=[],r=[],s=new Map;for(let o of e.filter(a=>Ha(a)===null))try{await fg(o,t,n),i.push(o)}catch(a){r.push({fix:o,error:a})}for(let o of e.filter(a=>Ha(a)!==null)){let a=Ha(o),c=s.get(a);c?c.push(o):s.set(a,[o])}for(let o of s.values()){let a=o[0];if(!a)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await af(a.item_id,{remove:c,message:Za},t):await ef(a.item_id,{remove:c,message:Za},t),i.push(...o)}catch(d){r.push(...o.map(l=>({fix:l,error:d})))}}return{applied:i,failed:r}}var Aj={applyValidateFix:fg,applyValidateFixes:gg,attachValidateFixHints:Vf,buildCommandReferencesCheck:pg,buildDependencyReferencesCheck:ng,buildCloseReasonBackfillRows:Qf,buildFilesCheck:mg,buildLifecycleCheck:ug,buildLifecycleDependencyGraph:tg,buildLifecycleParentGraph:za,buildEstimateBackfillRows:Zf,buildMetadataCounts:Xf,buildMissingFieldOccurrences:Jf,buildOrphanedPathRows:cg,classifyOrphanedPath:og,collectDefaultProjectFileCandidates:Qa,collectTrackedGitFileCandidates:Bf,detectLifecycleDependencyCycles:sg,detectLifecycleParentCycles:Wa,escapeRegExp:eg,extractItemIds:ig,findLifecycleDependencyCycleComponents:rg,isMetadataFieldMissing:Kf,linkedArtifactPathExceedsFilesystemLimits:lg,listFilesRecursive:tc,resolveDependencyCycleSeverity:Gf,resolveParentCycleSeverity:qf,resolveFileScanMode:zf,resolveLifecycleDependencyCycleSamplePath:is,resolveRequestedChecks:Hf,resolveValidateMetadataProfile:jf,resolveWorkspaceRoot:Wf,sharedDirectoryPrefixLength:ag,summarizeOrphanedPathRows:dg,summarizeDuplicateIssueCodes:Yf,toMeaningfulString:Ge};function FT(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function $T(e,t,n,i){let r=await Jp(e,new Set(t.map(y=>y.id)),n,{schema:i.schema,extensionFieldNames:ht(M())}),s=[];r.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let o=s.length,a=await Gr(e);a.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Tr(e,Er(i));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await wt(e),l=d===null?null:await ln(d);l!==null&&l.status!=="ok"&&s.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await un(d??e,{includeLossless:!0,pmRoot:e}),_=u.receipts,{pendingDecisions:f,lossless:g}=mn(_);f.length>0&&s.push(`validate_merge_decisions_unreviewed:${f.length}`),FT(s,u.invalid_evidence_count);let h=o>0?"error":s.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...r,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:f.length,pending_merge_decision_items:[...new Set(f.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),lossless_merge_receipt_count:g.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(g.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:s}}function Ze(e,t,n){n&&Vf(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function UT(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,i=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let r=await h_(e.pmRoot,e.items,i?1/0:et,e.sourceIncomplete);Ze(t,r,n)}if(e.requestedChecks.has("metadata")){let r=wT(e.items,e.metadataPolicy,e.statusRegistry,i,[e.settings.id_prefix]);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows,Ze(t,r,n)}if(e.requestedChecks.has("resolution")){let r=bT(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,Ze(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=ug(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,Ze(t,r,n),Ze(t,ng(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await mg(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=r.staleLinkPruneRows,Ze(t,r,n)}return e.requestedChecks.has("command_references")&&Ze(t,await pg(e.items,e.settings.id_prefix,i,e.pmRoot),n),e.requestedChecks.has("history_drift")&&Ze(t,await ns(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&Ze(t,PT(e.items,i),n),e.requestedChecks.has("storage_integrity")&&Ze(t,await $T(e.pmRoot,e.items,$(e.settings,M()).type_to_folder,e.settings),n),t}function jT(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...kf(t.closeReasonBackfillRows)),i.push(...bf(t.resolutionBackfillRows)),i.push(...Sf(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...Ef(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...Tf(t.staleLinkPruneRows)),i}async function GT(e,t,n,i,r,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=jT(e,t,n),{applicable:a,gated:c}=Cf(o,i),d=e.dryRun===!0,l=[],u=[];if(!d){let _=await gg(a,r,s);l.push(..._.applied.map(fi)),u.push(..._.failed.map(({fix:f,error:g})=>({...fi(f),error:g instanceof Error?g.message:String(g)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...i].sort((_,f)=>_.localeCompare(f)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(fi),applied_fixes:l,gated_fixes:c.map(_=>({...fi(_),gate_hint:`Withheld: re-run with --fix-scope ${_.gate} to apply.`})),failed_fixes:u}}async function hg(e,t,n={}){Sl(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new p("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",m.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new p("--fix-scope requires --auto-fix.",m.USAGE);let r=Af(e.fixScope),s=x(process.cwd(),t.path);await P(s);let o=await I(s),a=K(o.schema),c=$(o,M()),d=Hf(e),l=[],u=await ts({includeBody:["history_drift","metadata","completeness"].some(q=>d.has(q)),pmRoot:s,settings:o,typeToFolder:c.type_to_folder,warnings:l}),_=l.length>0;if(d.has("history_drift")){let q=await oi(s);q.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${q.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",g=jf(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),h=cT(g,f,o.validation.metadata_required_fields),y=oT(o),v=Gf(e.dependencyCycleSeverity),w=qf(e.parentCycleSeverity),S=zf(e.scanMode),E=Wf(s),T=await UT({requestedChecks:d,options:e,global:t,pmRoot:s,workspaceRoot:E,settings:o,items:u,statusRegistry:a,metadataPolicy:h,lifecyclePatternPolicy:y,dependencyCycleSeverity:v,parentCycleSeverity:w,fileScanMode:S,initialWarnings:[...new Set(l)],sourceIncomplete:_}),A=i?await GT(e,T,o,r,t,n):void 0,k=[...new Set(T.warnings)].sort((q,F)=>q.localeCompare(F)),L={ok:!T.checks.some(q=>q.status==="error"),has_warnings:k.length>0,checks:T.checks,warnings:k,...A!==void 0?{fixes:A}:{},generated_at:R(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?L:{...sT(L),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as qT}from"node:child_process";import{promisify as KT}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]="894154aa-88b8-5a3b-a03c-e3ef8a85f1c0")}catch{}})();var zT=KT(qT),WT=16,BT=3e4;function VT(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(s=>typeof s=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function HT(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let i=t.parameters??{},r=n.parameters??{};for(let s of Object.entries(r).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(i,s))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${s}`);for(let[s,o]of Object.entries(i)){let a=r[s];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${s}`);if(o===null||typeof o!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${s} must be ${a.type}`)}return{...i}}async function YT(e,t,n,i){let r=HT(e,t),s=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:r,trigger:i,pm_root:n,...nl(n)}));s.catch(()=>{});let o;try{let a=await Promise.race([s,new Promise((c,d)=>{o=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??BT),o.unref?.()})]);return VT(e,t.key,a)}finally{clearTimeout(o)}}function vg(e,t,n,i){let r=e;for(let s of t.split(".")){if(typeof r!="object"||r===null||Array.isArray(r))throw new Je(`assurance field ${t} is not present`,{source_kind:n,field:t,...i?{check:i}:{}});r=r[s]}if(typeof r=="number"&&Number.isFinite(r)||Array.isArray(r)&&r.every(s=>typeof s=="string"))return r;throw new Je(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...i?{check:i}:{}})}function yg(e,t,n,i){let r=e.checks.find(o=>o.name===t);if(!r)throw new Je(`assurance check ${t} is not present`,{source_kind:i,field:n,check:t});return{value:n==="status"||n==="ok"?r.ok?0:1:vg(r.details,n,i,t),population_size:1,cost:e.checks.length}}async function XT(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await zT("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function JT(e,t){let n=new Array(t.length),i=0,r=Array.from({length:Math.min(WT,t.length)},async()=>{for(;i<t.length;){let s=i;i+=1;let o=t[s],a=await on(Qt(e,o.id),o.id);n[s]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(r),n.flat()}async function hi(e,t={}){let n=await I(e),i=$(n),r=K(n.schema),o=(t.strict_read===!0?(await R_(void 0,{status:"all",full:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await dn(e,n.item_format,i.type_to_folder,void 0,n.schema)).map(f=>({...f,id:f.id,status:f.status,type:f.type})),a={path:e},c=M(),d=Object.fromEntries((c?.assurance_providers??[]).map(f=>[f.definition.id,{cost_class:f.runtime_definition.cost_class,network:f.runtime_definition.network}])),l=new Map,u,_;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await XT(e,t.tree_id),items:o,history:t.include_history===!1?[]:await JT(e,o),terminal_statuses:[...r.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async f=>{if(f.kind==="graph"){let y=ie({operation:f.operation,parameters:f.parameters??{}}),v=l.get(y);v===void 0&&(v=__(f.operation,void 0,void 0,{...f.parameters,full:!0},a),l.set(y,v));let w=await v;return{value:vg(w,f.field,f.kind),population_size:o.length,cost:o.length}}if(f.kind==="validate"){u??=hg({counts:!0},a);let y=await u;return yg(y,f.check,f.field,f.kind)}if(f.kind==="health"){_??=Bp(a,{checkOnly:!0,full:!0});let y=await _;return yg(y,f.check,f.field,f.kind)}let g=t.providers?.[f.provider];if(g)return g(f);let h=dl(c,f.provider);if(!h)throw new TypeError(`assurance provider ${f.provider} is not registered`);return YT(h.runtime_definition,f,e,t.trigger??"sdk")}}}import{createHash as QT}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="538168d9-116c-5e72-81a4-a23e021c48f5")}catch{}})();function wg(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:i,limit:r}=wr({...t,change:{}});return{policy:n,...i===void 0?{}:{cursor:i},...r===void 0?{}:{limit:r},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function ZT(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let i=n;if(i.fingerprint!==t||typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return i.offset}function eA(e,t,n,i,r,s){let o=Object.fromEntries(zo.map(f=>[f,0])),a=0,c=0,d=0,l=0,u=[],_=QT("sha256").update(r);for(let f of i){let g=e.membership.get(f),h=n.has(f),y=g.family_ids.length>0;y&&h&&(a+=1),y||(c+=1),h||(d+=1);let v=t.get(f)?.escape_class;v!==void 0&&zo.includes(v)&&(o[v]+=1,l+=1),_.update(ie([f,h,t.get(f)??null,g.id,g.family_ids])),(!s||!y||!h)&&u.push(f)}return{classCounts:o,coveredCount:a,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:_.digest("hex")}}function bg(e,t,n={}){s_(e);let i=n.limit??25;if(!Number.isSafeInteger(i)||i<1||i>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let r=new Set,s=new Map;for(let E of t){if(r.has(E.id))throw new TypeError(`Duplicate recurrence item ${E.id}`);r.add(E.id);let T=vr(E);T!==void 0&&s.set(E.id,T)}let o=n_(e.families,s),a=[...o.membership.keys()].sort(),c=ie({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:_,classifiedCount:f,selected:g,fingerprint:h}=eA(o,s,r,a,c,n.uncoveredOnly===!0),y=ZT(n.cursor,h);if(y>g.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let v=g.slice(y,y+i).map(E=>{let T=o.membership.get(E),A=r.has(E);return{item_id:E,lineage_id:T.id,lineage_item_count:T.item_ids.length,family_ids:T.family_ids,present:A,...A?T.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),w=y+v.length,S=a.length===0?null:d.production_defect/a.length;return{ok:u===0&&_===0,fingerprint:h,items:v,total:g.length,has_more:w<g.length,...w<g.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:w})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:a.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:_,classified_item_count:f,unclassified_item_count:a.length-f,class_counts:d,escape_rate:f===a.length?S:null,escape_rate_lower_bound:S},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:i},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as tA}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77425e45-ae19-569b-b196-e024f9e2729f")}catch{}})();var nc,kg=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],ic=["measurement","assertion","gate"];function nA(e){if(kg.includes(e))return e;throw Ki({command_path:"assurance",token:e,allowed:kg,display_name:"assurance action"})}function Sn(e,t,n){throw new p(t,m.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function iA(e){if(!e)return Sn("kind",`Assurance declaration kind is required. Expected: ${ic.join(", ")}`,"pm assurance list measurement");if(ic.includes(e))return e;throw new p(`Assurance declaration kind is required. Expected: ${ic.join(", ")}`,m.USAGE)}function Sg(e){if(!e)return Sn("preset",`Assurance preset is required. Expected: ${ii.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(ii.includes(e))return e;throw new p(`Assurance preset is required. Expected: ${ii.join(", ")}`,m.USAGE)}function rc(e){return e.owner?.trim()?e.owner.trim():Sn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function rA(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(i){throw new p("assurance definition must be valid JSON",m.USAGE,{reason:i instanceof Error?i.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new p("assurance put requires a JSON object definition",m.USAGE);return n}async function sA(e){let[t,n,i]=await Promise.all([ni(e,"measurement"),ni(e,"assertion"),ni(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:i.items}}function Eg(e,t){return t===!0?{id:e.id}:e}async function oA(e,t){let n=t.authorization_decision;if(!n)return[];let i=await hi(e,{include_history:!1,resolve_tree:!1}),r=i.items.find(o=>o.id===n),s=new Set(i.terminal_statuses);if(!r||r.type.toLowerCase()!=="decision"||!s.has(r.status))throw new p(`Assurance authorization ${n} must name a terminal Decision item`,m.USAGE);return[r.id]}async function aA(e,t){let n=la(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>pn))throw new p(`assurance verdict limit must be an integer from 1 through ${pn}`,m.USAGE);let i=await J_(t,{gate_id:e.id??e.gate,limit:n});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function cA(e,t,n){if(e==="presets"){if(t.preset??t.id)return Nr(Sg(t.preset??t.id),rc(t));let r=ii.map(s=>{let o=Nr(s,"pm-owner");return{id:s,title:o.title,description:o.description}});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return _n(()=>Z_(n,Sg(t.preset??t.id),rc(t),{author:t.author,message:t.message}));if(e==="derive"){let r=await ep(await hi(n,{resolve_tree:!1,trigger:"derive"}),rc(t)),s=t.apply?await _n(()=>tp(n,r,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:r,count:r.length,...s?{applied:s}:{}}}if(!t.id)return Sn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new p("assurance promote requires --enforcement warn|block",m.USAGE);let i=await ra(n,"assertion",t.id);return _n(()=>np(n,i,t.enforcement,{author:t.author,message:t.message}))}async function dA(e,t,n){if(!e.id)return Sn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let i=e.id;if(!e.trigger)throw new p("assurance run requires a trigger",m.USAGE);if(!ct.includes(e.trigger))throw new p(`Unknown assurance trigger ${e.trigger}. Expected: ${ct.join(", ")}`,m.USAGE);let r=e.trigger,[s,o]=await Promise.all([sA(t),hi(t,{...n.workspace,tree_id:e.tree,trigger:r})]),a=await M_(()=>V_(i,s,o,{trigger:r,dry_run:e.dry_run===!0}));return a.dry_run||await X_(t,a,{author:e.author,message:e.message}),a}function Tg(e){throw e instanceof p?e:new p(e instanceof Error?e.message:"assurance risk request is invalid",m.USAGE)}function lA(e){if(e.limit!==void 0)throw new p(`assurance ${e.action} does not accept --limit; set limit inside the definition`,m.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new p(`assurance ${e.action} definition must be valid JSON`,m.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?wg(t):wr(t)}catch(n){return Tg(n)}}function uA(e,t){let n=new Set;for(let[i,r]of t)e.item_fingerprints.get(i)!==r&&n.add(i);for(let i of e.item_fingerprints.keys())t.has(i)||n.add(i);return n}function mA(e,t,n){let i=ie(t.policy),r=nc?.pm_root===e?nc:void 0,s=new Map(n.map(d=>[d.id,tA("sha256").update(ie([e_(d),vr(d)])).digest("hex")])),o=r?.policy_serialized===i?r:void 0,a=o?uA(o,s):new Set,c=i_(t.policy,o?n.filter(d=>a.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...a]}:{});return nc={pm_root:e,policy_serialized:i,item_fingerprints:s,index:c},c}async function _A(e,t){let n=lA(e),i=await hi(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?r_(mA(t,n,i.items),n.change,{cursor:n.cursor,limit:n.limit}):bg(n.policy,i.items,n)}catch(r){return Tg(r)}}async function pA(e,t={},n={}){let i=nA(e.action),r=x(process.cwd(),t.path);if(i==="presets"||i==="apply"||i==="derive"||i==="promote")return cA(i,e,r);if(i==="verdicts")return aA(e,r);if(i==="run")return dA(e,r,n);if(["risk","lineages"].includes(i))return _A(e,r);let s=iA(e.kind);if(i==="list")return ni(r,s);if(!e.id)return Sn("id",`assurance ${i} requires an id`,`pm assurance ${i} ${s} <id>`);let o=e.id;if(i==="show")return ra(r,s,o);if(i==="remove"){let l=await _n(()=>Y_(r,s,o,{author:e.author,message:e.message}));return Eg(l,e.idOnly)}let a=rA(s,e.definition);if(a.id!==o)throw new p(`Assurance definition id ${a.id} does not match requested id ${o}`,m.USAGE);let c={author:e.author,message:e.message,...s==="assertion"?{authorized_decision_ids:await oA(r,a)}:{}},d=await _n(()=>Or(r,s,a,c));return Eg(d,e.idOnly)}function a1(e,t,n){let i={...e,...t};return pA({action:O(i,"subcommand")??O(i,"assuranceAction")??O(i,"operation")??"",kind:O(i,"kind"),id:O(i,"id"),definition:i.definition,trigger:O(i,"trigger"),tree:O(i,"treeId")??O(i,"tree"),gate:O(i,"gate"),limit:la(i.limit,"assurance verdict limit"),dry_run:i.dryRun===!0||i.dry_run===!0,fullChangedFields:i.fullChangedFields===!0,idOnly:i.idOnly===!0,author:O(i,"author"),message:O(i,"message"),preset:O(i,"preset"),owner:O(i,"owner"),apply:i.apply===!0,enforcement:O(i,"enforcement")},n)}import{readFile as fA}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a5fc27e-3f5a-59e0-998e-be5da72913dd")}catch{}})();function S1(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Pe(e,t)}function Ag(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new p(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function gA(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Ft(e,t){let n=e[t];return Array.isArray(n)?n:[]}function E1(e,t={}){let n=e.trim();if(!n)return"";let i=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&i&&!n.startsWith("```"))return n.slice(i[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let s=J(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function hA(e){return typeof e=="object"&&e!==null&&"code"in e}function Cg(e,t){if(!Rt(e))throw new p(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function yA(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new p(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let i=en(),r=Rt(e);if(e.add!==void 0)return{value:await i.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return Cg(e,"--stdin"),{value:await i.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new p("--file path cannot be empty",m.USAGE);if(s==="-")return Cg(e,"--file -"),{value:await i.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await fA(s,"utf8"),emptyFlag:"--file"}}catch(o){if(hA(o)&&ji(o))throw new p(`--file path not found: ${s}. Use --file - to read stdin.`,m.USAGE);let a=o instanceof Error?o.message:String(o);throw new p(`Failed to read --file path "${s}": ${a}. Use --file - to read stdin.`,m.USAGE)}}async function T1(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new p("Specify only one of --edit or --delete",m.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new p("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new p("--delete must be a positive integer",m.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new p("--edit must be a positive integer",m.USAGE);let n=await yA(e,t);if(e.edit!==void 0){if(!n)throw new p("--edit requires replacement text from --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function yi(e,t){throw e instanceof p&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new p(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function xg(e){return e==="comments"?"--stdin":"--add -"}function vA(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let i=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(i))return;let r=xg(t.collectionKey),s=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new p(`--add value "${i}" looks like an option, not annotation text. Use ${r} to read stdin, or use text=${i} for literal dash-leading text.`,m.USAGE,{code:"annotation_flag_like_value",required:`Use ${r} for stdin input, pass plain text, or use text=${i} when the text really starts with "-".`,examples:[`${s} ${r}`,`${s} --add text=${i}`]})}function wA(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new p(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,m.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new p(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,m.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${xg(e.collectionKey)}`]})}function bA(e,t,n,i,r,s){let o=Ft(e.metadata,t),a=r?o.findIndex(c=>c.author===n&&c.text===i):-1;return a>=0?{changedFields:[],entryIndex:a+1}:(o.push(s({created_at:R(),author:n,text:i})),e.metadata[t]=o,{changedFields:[t],entryIndex:o.length})}async function A1(e,t,n,i){wA(i,t);let r=x(process.cwd(),n.path);await P(r);let s=await I(r),o=$(s,M()),a=zn(t.limit);if(i.input.mode==="list"){let g=await Q(r,e,s.id_prefix,s.item_format,o.type_to_folder);if(!g)throw new p(`Item ${e} not found`,m.NOT_FOUND);let h=await be(g,{schema:s.schema}),y=Ft(h.document.metadata,i.collectionKey);return ds(g.id,i.collectionKey,y,a,t.includeMeta===!0)}let c=G(t.author,s.author_default);if(i.input.mode==="delete"){let g=i.deleteOp??i.op,h;try{h=await le({pmRoot:r,settings:s,id:e,op:g,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,mutate(v){let w=Ft(v.metadata,i.collectionKey),S=Ig(i.input.index,w.length,i.collectionKey);return Ag(w[S],"deleted"),w.splice(S,1),v.metadata[i.collectionKey]=w,{changedFields:[i.collectionKey]}}})}catch(v){yi(v,i.conflictGuidance)}let y=Ft(h.item,i.collectionKey);return ds(h.item.id,i.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:i.input.index},t.fullHistory===!0)}let d=i.input.rawValue??i.input.value??"";vA(d,i);let l=i.parseText(i.input.value??"");if(!l.trim())throw new p(`${i.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(i.input.mode==="edit"){let g=i.editOp??i.op,h;try{h=await le({pmRoot:r,settings:s,id:e,op:g,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,mutate(v){let w=Ft(v.metadata,i.collectionKey),S=Ig(i.input.index,w.length,i.collectionKey),E=w[S];return Ag(E,"edited"),w[S]={...E,text:l,edited_at:R()},v.metadata[i.collectionKey]=w,{changedFields:[i.collectionKey]}}})}catch(v){yi(v,i.conflictGuidance)}let y=Ft(h.item,i.collectionKey);return ds(h.item.id,i.collectionKey,y,a,t.includeMeta===!0,{action:"edit",entryIndex:i.input.index,entry:y[i.input.index-1]},t.fullHistory===!0)}let u,_=0;try{u=await le({pmRoot:r,settings:s,id:e,op:i.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(g){let h=bA(g,i.collectionKey,c,l,t.ifAbsent===!0,i.createEntry);return _=h.entryIndex,{changedFields:h.changedFields}}})}catch(g){yi(g,i.conflictGuidance)}let f=Ft(u.item,i.collectionKey);return ds(u.item.id,i.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:_,entry:f[_-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Ig(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let i=n.replace(/s$/,""),r=`${i.charAt(0).toUpperCase()}${i.slice(1)}`,s=t===1?`1 ${i}`:`${t} ${n}`;throw new p(`${r} index ${e??"(missing)"} out of range (item has ${s})`,m.USAGE)}return e-1}function kA(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function ds(e,t,n,i,r,s,o=!1){let a=s===void 0||o?gA(n,s!==void 0&&o?void 0:i):s.entry===void 0?[]:[s.entry],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...s?.changedCount===void 0?{}:{changed:s.changedCount===1},...[r,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...i!==void 0?{limit:i}:{}}:{},...kA(t,s,c)}}(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]="f366dd76-73b4-55c4-8c63-2913d0a0c380")}catch{}})();async function Rg(e,t,n){return[...await Promise.resolve().then(()=>on(Qt(e,t),t)).catch(()=>[])].reverse().find(s=>s.patch.some(o=>o.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${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]="f2901314-4044-5a91-ad72-6b4bebde16c2")}catch{}})();var Og="no_available_next_item";function SA(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function sc(e,t,n,i={}){let r=x(process.cwd(),n.path);await P(r);let s=await I(r),o=K(s.schema),a=G(i.author,s.author_default),c=Co(a),d=null,l=!1,u=[],_=await le({pmRoot:r,settings:s,id:e,op:"claim",author:a,message:i.message,force:t,skipNoop:!0,async mutate(f){let h=f.metadata.assignee??"",y=f.metadata.claim_principal?.trim()||h;if(d=h.trim().length>0?h:null,sr(f.metadata.status,o)&&!t)throw new p(`Cannot claim terminal item ${f.metadata.id} without --force`,m.CONFLICT);if(d!==null&&y!==c){if(i.ifAvailable===!0)return l=!0,u.push(`claim_skipped_held_by:${d}`),{changedFields:[]};if(!t){let E=await Rg(r,f.metadata.id,h);throw new p(`Item ${f.metadata.id} is already ${E}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}u.push(`claim_takeover:${d}->${a}`)}let w={assignee:a,claim_principal:c},S=["assignee","claim_principal"].filter(E=>f.metadata[E]!==w[E]);return Object.assign(f.metadata,w),{changedFields:S,warnings:u}}});return l||await O_({pmRoot:r,settings:s,principal:c,itemId:_.item.id}),{item:_.item,changed_fields:_.changedFields,claimed_by:l&&d!==null?d:a,previous_assignee:d,forced:t,...l?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function F1(e,t,n={},i={}){let r=EA(n.maxAttempts),s=await I(x(process.cwd(),t.path)),o={...n,author:G(n.author,s.author_default)},a=await N_({...i,callerAuthor:o.author,limit:String(r)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return TA(c.slice(0,r),e,t,o)}function EA(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new p("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function TA(e,t,n,i={},r=sc){let s=0;for(let a of e){s+=1;try{let c=await r(a.id,t,n,i),d={...c,recommendation:a,attempts:s,available:!0};if(!c.skipped)return d}catch(c){if(!SA(c))throw c}}if(i.ifAvailable===!0)return{available:!1,item:null,claimed_by:G(i.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[Og]};let o=s===0;throw new p(o?"No actionable items matched the selection filters":"No actionable item remained available to claim",o?m.NOT_FOUND:m.CONFLICT,{code:Og,why:o?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[o?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function oc(e,t,n,i={}){let r=x(process.cwd(),n.path);await P(r);let s=await I(r),o=G(i.author,s.author_default),a=Co(o),c=i.ownershipReleaseBypass===!0,d=null,l;try{l=await le({pmRoot:r,settings:s,id:e,op:"release",author:o,message:i.message,force:t,bypassAssigneeConflict:c,mutate(f){return d=f.metadata.assignee??null,!d&&!f.metadata.claim_principal?{changedFields:[]}:(delete f.metadata.assignee,delete f.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(f){yi(f,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await L_({pmRoot:r,principal:a,itemId:l.item.id});let u=K(s.schema),_=Ao(l.item.status,u)===Ao(u.in_progress_status,u);return{item:l.item,released_by:o,changed_fields:l.changedFields,previous_assignee:d,forced:t,..._?{warnings:["released_unclaimed_in_progress"],suggestions:[`${l.item.id} remains ${l.item.status} and unclaimed. If work is paused, run pm release ${l.item.id} --pause to move it to ${u.open_status}.`]}:{}}}(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]="e63a8049-309b-57f2-ba48-cd0a550c11ab")}catch{}})();var G1=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function AA(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let i=n.value?.trim();if(i)return{closeReason:i,source:n.source}}return{source:"none"}}function Ng(e,t){return ac(e,t,{operation:"close"})}function ac(e,t,n){let i=AA(e);if(!t||i.closeReason!==void 0)return i;let r=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new p("Close reason text is required because governance.require_close_reason is enabled",m.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:r,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function Dg(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",i=e.blocked_by!==void 0,r=e.dependencies??[],s=r.filter(d=>d.kind==="blocked_by"),o=e.blocked_reason!==void 0,a=[];if(i&&(delete e.blocked_by,a.push("blocked_by")),o&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let d=r.filter(l=>l.kind!=="blocked_by");d.length>0?e.dependencies=d:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...s.map(d=>d.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[t.orderingEdges==="preserve"?`closed_preserved_predecessors:${e.id}:${c.join(",")}`:`closed_removed_predecessors:${e.id}:${c.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]="49e375b7-49a8-5b6f-89c8-be70d334b78f")}catch{}})();var CA=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function IA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new p(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,m.USAGE)}function Mg(e){let t=[];for(let n of CA){let i=e[n.key];(typeof i!="string"||i.trim().length===0)&&t.push(n)}return t}function Pg(e,t,n={}){let i=Mg(e);if(i.length===0)return;let r={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},s=i.map(a=>`--${a.key.replaceAll("_","-")}`),o=["--pm-path",t,"update",e.id,...i.flatMap((a,c)=>[s[c],r[a.key]?.trim()||"<value>"])];return{missing:s,suggested_retry:at(o),suggested_retry_args:o}}async function xA(e,t,n){let i=new Set,r=t;for(;typeof r=="string"&&r.trim().length>0;){let s=r.trim();if(s===n)return!0;if(i.has(s))return!1;i.add(s),r=(await e(s))?.duplicate_of}return!1}function RA(e){return typeof e!="string"||e.trim().length===0}async function OA(e,t,n,i){let r=n?.trim();if(!r)return;if(r===i)throw new p("An item cannot be closed as a duplicate of itself.",m.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=$(t,M()),o=new Map,a=async d=>{if(o.has(d))return o.get(d)??null;let l=await Q(e,d,t.id_prefix,t.item_format,s.type_to_folder);if(!l)return o.set(d,null),null;let{document:u}=await be(l,{schema:t.schema});return o.set(d,u.metadata),u.metadata},c=await a(r);if(!c)throw new p(`Duplicate target "${r}" was not found. Create or locate the canonical item first.`,m.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${i} "Duplicate of ${r}" --duplicate-of ${r}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await xA(a,c.duplicate_of,i))throw new p(`Circular duplicate reference detected. Target "${r}" points back to "${i}".`,m.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new p(`Duplicate target "${r}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,m.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${i} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function LA(e,t,n){return e.filter(i=>i.parent===t&&!de(i.status,n)).map(i=>i.id).sort((i,r)=>i.localeCompare(r))}function NA(e,t,n){let i=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),r=S_(e),s=t.trim().toLowerCase(),o=n.blocked_statuses;return e.filter(a=>o.has(a.status)).map(a=>({item:a,blockerIds:r.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let d=i.get(c);return d!==void 0&&de(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function DA(e,t,n,i,r,s){let o=NA(n,i,s),a=[];for(let c of o)try{let d=await le({pmRoot:e,settings:t,id:c.id,op:"update",author:r,message:`Auto-unblocked after blocker ${i} closed`,mutate(l){let u=l.metadata.dependencies??[],_=u.filter(g=>{let h=g.id.trim().toLowerCase();return g.kind!=="blocked_by"||!c.blocker_ids.includes(h)});l.metadata.status=s.open_status,delete l.metadata.blocked_by,delete l.metadata.blocked_reason,l.metadata.unblock_note=`Auto-unblocked after blocker ${i} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,_.length>0?l.metadata.dependencies=_:delete l.metadata.dependencies;let f=["status","blocked_by","blocked_reason","unblock_note"];return _.length!==u.length&&f.push("dependencies"),{changedFields:f}}});a.push(`auto_unblocked:${d.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(d){let l=d instanceof Error?d.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${l}`)}return a}function MA(e,t){let n=[],i=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:r,key:s}of i){if(typeof r!="string")continue;let o=r.trim();o.length!==0&&(e[s]=o,n.push(s))}return n}function PA(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],i=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:r,value:s}of i)RA(e[r])&&(e[r]=s,n.push(r));return n}function FA(e,t,n,i){let r=[];if(t!=="off"){let s=Mg(e);if(s.length>0){let o=s.map(a=>a.label);if(t==="strict"){let a=s.map(d=>`--${d.key.replaceAll("_","-")}`),c=["--pm-path",i,"update",e.id,...a.flatMap(d=>[d,"<value>"])];throw new p(`Cannot close item ${e.id}: missing ${o.join(", ")}. Populate fields or use --validate-close warn.`,m.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:at(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}r.push(`close_validation_missing_fields:${e.id}:${o.join(",")}`)}if(n.length>0){if(t==="strict")throw new p(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,m.USAGE);r.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return r}return n.length>0&&r.push(`closed_with_active_children:${e.id}:${n.join(",")}`),r}function $A(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function UA(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function jA(e,t){if(de(e.status,t.statusRegistry)&&!t.force)throw new p(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,m.CONFLICT,{recovery:Pg(e,t.pmRoot,t.options)});let n=MA(e,t.options),i=PA(e,t.duplicateOf),r=FA(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let o=["status","closed_at",...s?["completed_at"]:[],...$A(e,t.closeReason),...n];if(pu(e)&&(e.plan_mode="completed",o.push("plan_mode")),t.duplicateOf!==void 0){o.push("duplicate_of");for(let c of i)o.includes(c)||o.push(c)}o.push(...UA(e));let a=Dg(e,t.lifecyclePolicy);return o.push(...a.changedFields),r.push(...a.warnings),{changedFields:o,...r.length>0?{warnings:r}:{}}}async function GA(e,t,n,i){let r=x(process.cwd(),i.path);await P(r);let s=await I(r),o=K(s.schema),a=G(n.author,s.author_default),c=$(s,M()).type_to_folder,d=await Q(r,e,s.id_prefix,s.item_format,c);if(!d)throw await Wn(r,e,s.id_prefix,c);let l=await OA(r,s,n.duplicateOf,d.id),u={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},_=Ng({explicit:t,duplicateOf:l,resolution:n.resolution,message:n.message},u.requireCloseReason).closeReason,f=IA(n.validateClose)??s.governance.close_validation_default,g=await ke(r,s.item_format,c,void 0,s.schema),h=LA(g,d.id,o),y=R(),v=n.completedAt===void 0?y:me(n.completedAt,new Date(y),"completed-at"),w=await le({pmRoot:r,settings:s,id:d.id,op:"close",author:a,message:n.message,force:n.force,mutate(E){return jA(E.metadata,{pmRoot:r,statusRegistry:o,force:n.force,options:n,duplicateOf:l,validateCloseMode:f,activeChildIds:h,closeReason:_,closedAt:y,completedAt:v,lifecyclePolicy:u})}}),S=f==="warn"?Pg(w.item,r):void 0;return{item:w.item,changed_fields:w.changedFields,...S?{recovery:S}:{},warnings:[...w.warnings,...await DA(r,s,g,d.id,a,o)]}}function ls(e,t,n,i){return GA(e,t,n,i)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="874a21db-ed3b-5b4f-a913-bf87103172e7")}catch{}})();function Fg(e){return[...e].sort().join("\0")}function qA(e,t,n){let i=e.successors.get(t);i?i.push(n):e.successors.set(t,[n]);let r=e.predecessors.get(n);r?r.push(t):e.predecessors.set(n,[t])}function $g(e,t,n,i,r){let s=t.resolve(r);if(s?.ordering!==!0)return;let o=c_(i),a=o===void 0?void 0:e.canonicalIds.get(o.toLowerCase());if(a===void 0)return;let c=(s.precedence??"source_before_target")==="source_before_target";qA(e,c?n:a,c?a:n)}function KA(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},i=e.filter(r=>typeof r?.id=="string"&&r.id.trim().length>0);for(let r of i){let s=r.id.trim();n.canonicalIds.set(s.toLowerCase(),s)}for(let r of i){let s=r.id.trim();$g(n,t,s,r.blocked_by,"blocked_by");for(let o of r.dependencies??[])typeof o!="object"||o===null||$g(n,t,s,o.id,typeof o.kind=="string"?o.kind:"related")}for(let r of[n.successors,n.predecessors])for(let s of r.values())s.sort();return n}function zA(e,t){let n=new Set([t]),i=[t];for(;i.length>0;){let r=i.pop();for(let s of[e.successors,e.predecessors])for(let o of s.get(r)??[])n.has(o)||(n.add(o),i.push(o))}return n}function WA(e,t){let n=new Map;for(let i of t){let r=(e.successors.get(i)??[]).filter(s=>t.has(s));r.length>0&&n.set(i,r)}return n}function Ug(e,t,n){let i=KA(e,t),r=i.canonicalIds.get(n.trim().toLowerCase());if(r===void 0)return{cycles:[],successors:new Map,canonical:n};let s=WA(i,zA(i,r));return{cycles:u_(s).filter(o=>o.includes(r)),successors:s,canonical:r}}function BA(e,t,n){let i=new Set(t),r=i.has(n)?n:t[0];if(e.get(r)?.includes(r))return[r,r];for(let s of e.get(r)??[]){if(!i.has(s))continue;let o=VA(e,i,r,s);if(o)return o}return[...t,t[0]]}function VA(e,t,n,i){let r=[[i]],s=new Set([n,i]);for(;r.length>0;){let o=r.shift(),a=o.at(-1);for(let c of e.get(a)??[]){if(c===n)return[n,...o,n];!t.has(c)||s.has(c)||(s.add(c),r.push([...o,c]))}}}function us(e,t,n){let i=Se(),r=Ug(e,i,n),s=Ug(t,i,n),o=new Set(r.cycles.map(Fg)),a=new Set(Bo(e,void 0,i).map(d=>`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`));return[...Bo(t,void 0,i).filter(d=>d.holder_id.toLowerCase()===n.trim().toLowerCase()&&!a.has(`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`)).map(d=>`ordering_storage_contradiction_created:${m_(d)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...s.cycles.filter(d=>!o.has(Fg(d))).map(d=>`ordering_cycle_created:${BA(s.successors,d,s.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}(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]="4e54ed7b-3bab-51a2-912b-1284eaf8187a")}catch{}})();var ms=1e6;function cc(e,t=ms,n=.8,i=!1){let r=new Set,s=(l,u)=>{if(r.add(`${l}:${u}`),r.size>t)throw new p(`Duplicate sweep exceeded ${t} candidate pairs; narrow it with statuses or since.`,m.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the duplicate query or increase its similarity threshold. No partial result was returned."})};if(i||n===0){for(let l=0;l<e.length;l+=1)for(let u=0;u<l;u+=1)s(u,l);return r}let o=new Map;for(let{prepared:l}of e)for(let u of l.tokens)o.set(u,(o.get(u)??0)+1);let a=new Map,c=new Map,d=new Map;for(let[l,{prepared:u}]of e.entries()){let _=[...u.tokens].sort((h,y)=>o.get(h)-o.get(y)||h.localeCompare(y)),f=_.length-Math.ceil(n*_.length-1e-12)+1,g=[{index:a,keys:[u.normalized],lengthFilter:!1},{index:c,keys:n<=.99?u.issueCodes:[],lengthFilter:!1},{index:d,keys:_.length===0?[""]:_.slice(0,f),lengthFilter:!0}];for(let h of g)HA(e,l,h,n,s)}return r}function HA(e,t,n,i,r){let s=e[t].prepared.tokens.length;for(let o of n.keys){let a=n.index.get(o)??[];for(let c of a){let d=e[c].prepared.tokens.length;n.lengthFilter&&Math.min(d,s)/Math.max(d,s)+1e-12<i||r(c,t)}a.push(t),n.index.set(o,a)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d07624c-8663-5aba-8018-1b2c47997bef")}catch{}})();var YA=3,jg=20,XA=.8,JA=100,Gg=1e3;function qg(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`,`likely_duplicate_recovery:${e.recovery.action}:${e.recovery.item_id}`]}async function QA(e,t){let n=e.items[0],i=x(t.cwd??process.cwd(),t.pmRoot),r=K((await I(i)).schema);return de(n.status,r)?{action:"reopen",item_id:n.id,command:`pm item reopen ${n.id} "<recurrence reason>"`,args:["item","reopen",n.id,"<recurrence reason>"]}:{action:"reuse",item_id:n.id,command:`pm get ${n.id} --full`,args:["get",n.id,"--full"]}}function dc(e){let t=e.limit??YA,n=e.threshold??XA;if(!Number.isSafeInteger(t)||t<0||t>jg)throw new p(`Similarity limit must be an integer from 0 to ${jg}.`,m.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new p("Similarity threshold must be a number from 0 to 1.",m.USAGE);return{limit:t,threshold:n}}function Kg(e){let t=e.limit??JA;if(!Number.isSafeInteger(t)||t<0||t>Gg)throw new p(`Duplicate cluster limit must be an integer from 0 to ${Gg}.`,m.USAGE);let n=e.since===void 0?void 0:new Date(e.since);if(n&&Number.isNaN(n.getTime()))throw new p("Duplicate cluster --since must be a valid ISO timestamp.",m.USAGE);return{limit:t,since:n}}async function ZA(e,t){let n=x(e.cwd??process.cwd(),e.pmRoot),i=await I(n),r=$(i),s=e.statuses?.map(u=>u.trim().toLowerCase()).filter(Boolean);if(e.statuses!==void 0&&s?.length===0)throw new p("Duplicate cluster statuses must include at least one lifecycle status or all.",m.USAGE);let o=K(i.schema),a=s?.map(u=>{if(u==="all")return u;let _=se(u,o);if(!_)throw new p(`Unknown duplicate-cluster status "${u}". Allowed: all, ${o.definitions.map(f=>f.id).join(", ")}.`,m.USAGE);return _}),c=a?.includes("all")===!0;if(c&&a?.some(u=>u!=="all"))throw new p('The "all" status cannot be combined with other statuses.',m.USAGE);let d=c?void 0:a,l=d?new Set(d):void 0;return{items:(await ke(n,i.item_format,r.type_to_folder,void 0,i.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())),statuses:d}}var yG={buildDuplicateClusters:Wg,collectDuplicateCandidatePairs:cc,createDuplicateUnionFind:zg};function zg(e){let t=Array.from({length:e},(i,r)=>r);return{parent:t,findRoot:i=>{let r=i;for(;t[r]!==r;)r=t[r];for(;t[i]!==i;){let s=t[i];t[i]=r,i=s}return r}}}function eC(e,t,n,i){let r=[];for(let s of t){let[o,a]=s.split(":").map(u=>Number.parseInt(u,10)),c=Mo(e[o].prepared,e[a].prepared);if(c.score<n)continue;let d=i.findRoot(o),l=i.findRoot(a);d!==l&&(i.parent[l]=d),r.push({left_id:e[o].item.id,right_id:e[a].item.id,...c})}return r}function Wg(e,t,n,i){let r=new Map;for(let a of e.keys()){let c=n.findRoot(a),d=r.get(c)??[];d.push(a),r.set(c,d)}let s=new Map(e.map(({item:a},c)=>[a.id,n.findRoot(c)])),o=new Map;for(let a of t){let c=s.get(a.left_id),d=o.get(c)??[];d.push(a),o.set(c,d)}return[...r.values()].filter(a=>a.length>1).map(a=>{let c=(o.get(n.findRoot(a[0]))??[]).sort((d,l)=>l.score-d.score||d.left_id.localeCompare(l.left_id)||d.right_id.localeCompare(l.right_id));return{id:e[a[0]].item.id,items:a.map(d=>{let l=e[d].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((a,c)=>c.max_score-a.max_score||a.id.localeCompare(c.id)).slice(0,i)}function tC(e,t,n,i,r){return t.filter(s=>!n.has(s.id)).map(s=>({id:s.id,title:s.title,status:s.status,type:s.type,...Do(e,s.title)})).filter(s=>s.score>=i).sort((s,o)=>o.score-s.score||s.id.localeCompare(o.id)).slice(0,r)}async function nC(e,t={}){let n=e.title.trim();if(n.length===0)throw new p("Similarity candidate title must not be empty.",m.USAGE);let{limit:i,threshold:r}=dc(t),s=x(t.cwd??process.cwd(),t.pmRoot),o=await I(s),a=$(o),c=await gr(s,Object.values(a.type_to_folder)),d=Lo(n),l=c&&d.length>0?await nu({pmRoot:s,expectedSourceCursor:c.source_cursor,query:d.map(f=>`"${f.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(i*10,50)}):null,u=l===null?await ke(s,o.item_format,a.type_to_folder,void 0,o.schema):l.items,_=tC(n,u,new Set(e.excludeIds??[]),r,i);return{items:_,count:_.length,threshold:r,source:l?"persistent_index":"metadata_fallback"}}function iC(e,t={}){let{threshold:n}=dc({...t,limit:void 0}),{limit:i}=Kg(t),r=new Set;for(let l of e){if(!l.id.trim()||r.has(l.id))throw new p("Duplicate analysis requires unique non-empty item ids.",m.USAGE);r.add(l.id)}let s=[...e].sort((l,u)=>l.id.localeCompare(u.id)).map(l=>({item:l,prepared:No(l.title)})),o=cc(s,ms,n,t.exhaustive===!0),a=zg(s.length),c=eC(s,o,n,a),d=Wg(s,c,a,i);return{clusters:d,count:d.length,threshold:n,cost:{item_count:s.length,algorithm:t.exhaustive===!0||n===0?"exhaustive":"prefix_exact",possible_pairs:s.length*(s.length-1)/2,pair_limit:ms,recall_guarantee:"exact",candidate_pairs:o.size,scored_pairs:o.size}}}async function Bg(e={}){dc({...e,limit:void 0});let{since:t}=Kg(e),{items:n,statuses:i}=await ZA(e,t);return{...iC(n,e),source:"metadata_scan",filters:{statuses:i??null,since:e.since??null}}}async function lc(e,t){if(t.mode==="off")return;let n=await nC(e,t);if(n.count===0)return;let i=await QA(n,t),r=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!r){let s=n.items.map(a=>`${a.id} (${a.status}): ${a.title}`).join("; "),o=i.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new p(`Likely duplicate item(s) found: ${s}. ${o} or pass --allow-duplicate with explicit intent.`,m.CONFLICT,{code:"likely_duplicate",required:`${o}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:i.command,suggested_retry_args:i.args}})}return{mode:t.mode,bypassed:r,result:n,recovery:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="70971b2a-c025-50a8-918f-871fc8adfd2a")}catch{}})();var _t=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],rC=new Set(_t);function Vg(e){return Qi(e,_t)}function _s(e,t){let n={},i=[];for(let[r,s]of Object.entries(e)){let o=r.toLowerCase();if(!rC.has(o)){i.push(r);continue}if(Object.hasOwn(n,o))throw new p(`${t} provides key "${r}" more than once after case normalization`,m.USAGE);n[o]=s}if(i.length>0)throw new p(`${t} does not recognize key${i.length>1?"s":""} ${i.map(r=>`"${r}"`).join(", ")}. Allowed keys: ${_t.join(", ")}.`,m.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new p(`${t} command and cmd must match when both are provided`,m.USAGE);let{cmd:r,...s}=n;return{...s,command:s.command??r}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="800bdce7-d4d2-5702-9ceb-d83ac4a95fb0")}catch{}})();var jt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Xn,g_,"FORCE_COLOR"]),gs=/^[A-Za-z_][A-Za-z0-9_]*$/,Ut=["schema","tracker","auto"],Hg=["source","isolated","snapshot"];function vi(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new p(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new p(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,m.USAGE);let o=r.slice(0,s).trim(),a=r.slice(s+1);if(!gs.test(o))throw new p(`${t} env_set key "${o}" is invalid`,m.USAGE);if(jt.has(o.toUpperCase()))throw new p(`${t} env_set key "${o}" is reserved for sandbox safety`,m.USAGE);i[o]=a}return Object.keys(i).length>0?i:void 0}function wi(e,t){if(!e)return;let n=Po(e,{separators:/[;,\n]/});if(n.length===0)throw new p(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let i of n){if(!gs.test(i))throw new p(`${t} env_clear key "${i}" is invalid`,m.USAGE);if(jt.has(i.toUpperCase()))throw new p(`${t} env_clear key "${i}" is reserved for sandbox safety`,m.USAGE)}return n}function hs(e,t,n){if(!e)return;let i=e.trim().toLowerCase();if(i==="true"||i==="1"||i==="yes")return!0;if(i==="false"||i==="0"||i==="no")return!1;throw new p(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function ys(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Ut.includes(n))return n;throw new p(`${t} pm_context_mode must be one of: ${Ut.join(", ")}`,m.USAGE)}function Gt(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Hg.includes(n))return n;throw new p(`${t} workspace_context_mode must be one of: ${Hg.join(", ")}`,m.USAGE)}function qt(e){if(!e)return;let t=Po(e,{separators:/[;\n]/});return t.length>0?t:void 0}function En(e,t,n){let i=qt(e);if(!(!i||i.length===0)){for(let r of i)try{new RegExp(r,"m")}catch(s){throw new p(`${t} ${n} includes invalid regex "${r}": ${s instanceof Error?s.message:String(s)}`,m.USAGE)}return i}}function vs(e,t){if(!e)return;let n=_e(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new p(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function ws(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new p(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new p(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let o=r.slice(0,s).trim(),a=r.slice(s+1).trim();if(o.length===0||a.length===0)throw new p(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);i[o]=a}return Object.keys(i).length>0?i:void 0}function bs(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new p(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new p(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let o=r.slice(0,s).trim(),a=r.slice(s+1).trim();if(o.length===0||a.length===0)throw new p(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new p(`${t} assert_json_field_gte value for "${o}" must be numeric`,m.USAGE);i[o]=c}return Object.keys(i).length>0?i:void 0}var sC=new Set(_t);function ks(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function oC(e,t){let n={},i=[];for(let[r,s]of Object.entries(e)){let o=r.toLowerCase();if(!sC.has(o)){i.push(r);continue}if(Object.hasOwn(n,o))throw t(`provides key "${r}" more than once after case normalization`);n[o]=s}if(i.length>0)throw t(`does not recognize key${i.length>1?"s":""} ${i.map(r=>`"${r}"`).join(", ")}. Allowed keys: ${_t.join(", ")}.`);return n}function $t(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i!==void 0){if(typeof i!="string")throw n(`field "${t}" must be a JSON string`);return i}}function ps(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i===void 0)return;let r=typeof i=="string"?[i]:i;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=r.filter(o=>o.length>0);return s.length>0?s:void 0}function Yg(e,t,n){let i=ps(e,t,n);if(i){for(let r of i)try{new RegExp(r,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${r}": ${s instanceof Error?s.message:String(s)}`)}return i}}function fs(e,t,n){let i=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(i))throw n(`field "${t}" must be a finite number (or numeric string)`);return i}function aC(e,t){let n=e.timeout_seconds,i=e.timeout;if(n===void 0&&i===void 0)return;let r=n===void 0?void 0:fs(n,"timeout_seconds",t),s=i===void 0?void 0:fs(i,"timeout",t);if(r!==void 0&&s!==void 0&&r!==s)throw t("timeout and timeout_seconds must match when both are provided");let o=r??s;if(!Number.isInteger(o)||o<=0)throw t("timeout_seconds must be a positive integer");return o}function cC(e,t){let n=$t(e,"scope",t);if(n===void 0)return"project";if(!De.includes(n))throw t(`field "scope" must be one of: ${De.join(", ")}`);return n}function dC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!ks(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${r}" must be a string`);if(!gs.test(r))throw t(`field "env_set" key "${r}" is invalid`);if(jt.has(r.toUpperCase()))throw t(`field "env_set" key "${r}" is reserved for sandbox safety`);i[r]=s}return Object.keys(i).length>0?i:void 0}function lC(e,t){let n=ps(e,"env_clear",t);if(n){for(let i of n){if(!gs.test(i))throw t(`field "env_clear" key "${i}" is invalid`);if(jt.has(i.toUpperCase()))throw t(`field "env_clear" key "${i}" is reserved for sandbox safety`)}return n}}function uC(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i!==void 0){if(typeof i!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return i}}function mC(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let i=fs(n,"assert_stdout_min_lines",t);if(!Number.isInteger(i)||i<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return i}function _C(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!ks(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(r.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${r}" must be a string, number, or boolean`);i[r]=String(s)}return Object.keys(i).length>0?i:void 0}function pC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!ks(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(r.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');i[r]=fs(s,`assert_json_field_gte.${r}`,t)}return Object.keys(i).length>0?i:void 0}function fC(e,t,n){let i=_=>new p(`${n} ${t} ${_}`,m.USAGE);if(!ks(e))throw i(`must be a JSON object with linked-test fields. Allowed keys: ${_t.join(", ")}.`);let r=oC(e,i),s=$t(r,"command",i),o=$t(r,"cmd",i);if(s!==void 0&&o!==void 0&&s!==o)throw i("command and cmd must match when both are provided");let a=s??o;if(a===void 0||a.trim().length===0)throw i('requires a non-empty "command" string');let c=$t(r,"path",i),d=$t(r,"pm_context_mode",i);if(d!==void 0&&!Ut.includes(d))throw i(`field "pm_context_mode" must be one of: ${Ut.join(", ")}`);let l=Gt($t(r,"workspace_context_mode",i),`${n} ${t}`),u=$t(r,"note",i);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:cC(r,i),timeout_seconds:aC(r,i),pm_context_mode:d,workspace_context_mode:l,env_set:dC(r,i),env_clear:lC(r,i),shared_host_safe:uC(r,"shared_host_safe",i),assert_stdout_contains:ps(r,"assert_stdout_contains",i),assert_stdout_regex:Yg(r,"assert_stdout_regex",i),assert_stderr_contains:ps(r,"assert_stderr_contains",i),assert_stderr_regex:Yg(r,"assert_stderr_regex",i),assert_stdout_min_lines:mC(r,i),assert_json_field_equals:_C(r,i),assert_json_field_gte:pC(r,i),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function Xg(e,t){let n=e.trim();if(n.length===0)throw new p(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let i;try{i=JSON.parse(n)}catch(s){throw new p(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,m.USAGE)}let r=Array.isArray(i)?i:[i];if(r.length===0)throw new p(`${t} array must include at least one linked-test entry object`,m.USAGE);return r.map((s,o)=>fC(s,r.length>1?`entry ${o+1}`:"entry",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]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var gC={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function hC(e){return gC[e]}function uc(e){return hC(e)!==void 0}(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]="4db3d1b3-68f3-5f74-b6f0-9847b3b00fc0")}catch{}})();var yC="hierarchy-integrity";async function Ss(e){let t=e.required?await sn(e.pmRoot,yC,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await 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]="c45ead8e-c9ed-5b59-84e5-b8e077e84010")}catch{}})();function Es(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ts(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function As(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Md.includes(t))return t;let n=_e(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new p("Confidence must be an integer 0..100 or one of low|med|medium|high",m.USAGE);return n}function Cs(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new p("Regression must be one of true|false|1|0",m.USAGE)}(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]="add1928e-08d1-5ead-9a4e-0f1a9b6580fc")}catch{}})();var vC=new Set(["none","null"]);function Is(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function qe(e){return e===void 0?!1:vC.has(e.trim().toLowerCase())}function xs(e,t,n){if(!qe(e))return;let i=n?` ${n}`:"";throw new p(`${t} no longer accepts "none" or "null".${i}`.trim(),m.USAGE)}function Ie(e,t,n){if(!e||e.length===0||!e.some(s=>qe(s)))return;let r=n?` ${n}`:"";throw new p(`${t} no longer accepts "none" or "null".${r}`.trim(),m.USAGE)}function Rs(e,t){for(let n of t){let i=e[n.optionKey];if(!Array.isArray(i)||i.length===0)continue;if(!i.every(a=>typeof a=="string"))throw new p(`${n.valueFlag} entries must be strings.`,m.USAGE);let r=i;if(!r.some(a=>qe(a)))continue;if(r.filter(a=>!qe(a)).length>0)throw new p(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,m.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(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]="ca230957-d5a6-5f20-94b5-e1eeca8ca714")}catch{}})();var wC=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Jg(e,t,n,i){if(wC.has(t.trim().toLowerCase())||n!==i.open_status)return;let r=tn("in_progress",i);if(!(r===void 0||r===i.open_status))return{command:`pm claim ${e} --start`,to_status:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0562fd00-217b-5e1f-8004-df4574f8b796")}catch{}})();var mc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],_c=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],Qg=[...mc,..._c],Os=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function Ls(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let i of e.raw){let r=i.trim().toLowerCase();if(!r)throw new p("--unset values must not be empty",m.USAGE);if(qe(r))throw new p('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',m.USAGE);let s=e.resolveDefinition(r);if(!s)throw new p(`Unsupported --unset field "${i}". Supported fields: ${e.supportedFields}`,m.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function Ns(e,t,n){let i=e.trim().toLowerCase();if(!n)return;let r=n.command_to_fields?.get(t)??[];for(let s of r){if(s.allow_unset===!1)continue;let o=new Set;if(typeof s.key=="string"&&s.key.length>0&&o.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&o.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(o.add(s.cli_flag.replaceAll("-","_").toLowerCase()),o.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let a of s.cli_aliases)typeof a!="string"||a.length===0||(o.add(a.replaceAll("-","_").toLowerCase()),o.add(a.toLowerCase()));if(o.has(i))return{optionKey:s.key,metadataKey:s.metadata_key}}}(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]="49f970c3-e408-52d5-bb4d-8cea0c7f8ef4")}catch{}})();function eh(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new p(`${t} must be one of true|false|1|0|yes|no`,m.USAGE)}function pc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function xe(e,t,n,i=n){if(!t.includes(e))throw new p(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,m.USAGE,{field:i,required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var th=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function bC(e,t){return t==="defined"?e!==void 0:!!e}function Zg(e,t,n){if(!bC(e,n))return;let i=_e(e,`event ${t}`);if(!Number.isInteger(i)||i<1)throw new p(`--event ${t} must be an integer >= 1`,m.USAGE);return i}function kC(e,t,n){let i=e?me(e,n,"event.recur_until"):void 0;if(i&&i<t)throw new p("--event recur_until must be at or after start",m.USAGE);return i}function SC(e){return Array.from(new Set(pc(e).map(t=>xe(t.toLowerCase(),Gd,"event weekday")))).sort((t,n)=>bo(t)-bo(n))}function EC(e){return Array.from(new Set(pc(e).map(t=>{let n=_e(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new p("--event recur_by_month_day values must be integers 1..31",m.USAGE);return n}))).sort((t,n)=>t-n)}function TC(e,t){return Array.from(new Set(pc(e).map(n=>me(n,t,"event.recur_exdates")))).sort((n,i)=>n.localeCompare(i))}function nh(e,t,n,i){let r=e.recur_freq?.trim(),s=e.recur_interval?.trim(),o=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![r,s,o,a,c,d,l].some(S=>S!==void 0))return;if(!r)throw new p("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",m.USAGE);let _=xe(r.toLowerCase(),jd,"event recurrence frequency"),f=Zg(s,"recur_interval",i),g=Zg(o,"recur_count",i),h=kC(a,t,n),y=SC(c),v=EC(d),w=TC(l,n);return{freq:_,interval:f,count:g,until:h,by_weekday:y.length>0?y:void 0,by_month_day:v.length>0?v:void 0,exdates:w.length>0?w:void 0}}(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]="e2e87672-508a-5aef-b728-42e40544cf3c")}catch{}})();function bi(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new p(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,m.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function ki(e,t,n=Se()){for(let i of t??[])try{el(e,i.id,i.kind,n)}catch(r){throw new p(Od(r),m.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${i.id} (${i.kind}) violates the active relationship-kind policy`})}}async function ih(e,t){return(await be(e,{schema:t})).document.metadata.created_at}async function AC(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await Q(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:ih(n,t.schema)}function CC(e){let t=e.registry.require(e.dependency.kind);return new p(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,m.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function IC(e){let t=e.dependencies.filter(r=>e.registry.resolve(r.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(r.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:r,located:s})=>s===null?[]:[[r,s]])),i=new Map(await Promise.all([...new Set(t.map(({id:r})=>r))].map(async r=>[r,await ih(n.get(r),e.context.schema)])));for(let r of e.holders){let s=await AC(r,e.context);if(s!==void 0)for(let o of t){let a=i.get(o.id),c=Date.parse(s),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw CC({holder:r,dependency:o,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function Ds(e){let t=e.registry??Se(),n=(e.dependencies??[]).filter(o=>!t_(o.source_kind)),i=[...new Set(n.map(o=>o.id))],r=await Promise.all(i.map(async o=>({target:o,located:await Q(e.pmRoot,o,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=r.filter(({located:o})=>o===null).map(({target:o})=>o).sort((o,a)=>o<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new p(`Dependency target${s.length===1?"":"s"} not found: ${s.join(", ")}`,m.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:s,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${s.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await IC({dependencies:n,missingTargets:s,resolutions:r,holders:e.holders??[],registry:t,context:e}),s.map(o=>`dependency_target_unresolved:${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]="ae7fdf9b-e2d5-511e-90db-cf0bc121628d")}catch{}})();var rh="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",xC="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",RC=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,OC=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,oh=1e3,fc=60*oh,LC=60*fc;function sh(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new p(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,m.USAGE);return n.toISOString()}function NC(e,t){let n=new Date(e),i=t.trim(),r=RC.exec(i);if(r){let a=r[1]==="-"?-1:1,c=Number.parseInt(r[2],10)*a;return sh(n.getTime()+c*fc,i)}let s=OC.exec(i);if(s){let[,a,c,d,l]=s;if(c||d||l){let _=a==="-"?-1:1,f=Number.parseInt(c??"0",10),g=Number.parseInt(d??"0",10),h=Number.parseInt(l??"0",10),y=f*LC+g*fc+h*oh;return sh(n.getTime()+_*y,i)}}let o=i.startsWith("+")||i.startsWith("-")?i:`+${i}`;return me(o,n,"event.duration")}function ah(e,t,n,i){if(t&&n)throw new p(xC,m.USAGE);if(n){let s=NC(e,n);if(s<e)throw new p(rh,m.USAGE);return s===e?void 0:s}if(!t)return;let r=me(t,i,"event.end");if(r<e)throw new p(rh,m.USAGE);if(r!==e)return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dfce9924-8453-5ded-a5df-47477caa9fe7")}catch{}})();var DC=["at","date","text","title"],MC=["start","date","end","duration","title","description","location","timezone","all_day",...th],PC=["key","value"];function ch(e,t){return t==="trimmed"?e?.trim():e}function FC(e,t){return t==="defined"?e!==void 0:!!e}function Ms(e,t,n){return e.map(i=>{let r=J(i,"--reminder");he(r,"--reminder",DC);let s=ch(r.at??r.date,n.valueMode),o=ch(r.text??r.title,n.valueMode);if(!s||!o)throw new p("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",m.USAGE);let a=o.trim();if(!a)throw new p("--reminder text must not be empty",m.USAGE);return{at:me(s,t,"reminder.at"),text:a}})}function Ps(e,t,n){return e.map(i=>{let r=J(i,"--event");he(r,"--event",MC);let s=(r.start??r.date)?.trim();if(!s)throw new p("--event requires start=<iso|relative> or date=<iso|relative>",m.USAGE);let o=me(s,t,"event.start"),a=r.end?.trim(),c=r.duration?.trim(),d=ah(o,a,c,t),l=r.title,u=r.description,_=r.location,f=r.timezone,g=l?.trim(),h=u?.trim(),y=_?.trim(),v=f?.trim(),w=[["title",l,g],["description",u,h],["location",_,y],["timezone",f,v]];for(let[A,k,b]of w)if(k!==void 0&&!b)throw new p(`--event ${A} must not be empty`,m.USAGE);let S=r.all_day?.trim(),E=nh(r,o,t,n.recurrenceEmptyNumericGuard),T=FC(S,n.allDayEmptyGuard)?eh(S,"--event all_day"):void 0;return{start_at:o,end_at:d,title:g,description:h,location:y,all_day:T,timezone:v,recurrence:E}})}function Fs(e){let t={};for(let n of e){let i=n.trim();if(i.length===0)throw new p("--type-option values must not be empty",m.USAGE);let r,s;if(i.includes(",")||i.includes(`
|
|
9
|
+
`)||i.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(i)){let a=J(i,"--type-option");he(a,"--type-option",PC),r=a.key?.trim(),s=a.value?.trim()}else{let a=i.indexOf("="),c=i.indexOf(":"),d=a;if(a<=0&&c>0&&(d=c),d<=0||d===i.length-1)throw new p("--type-option requires key=value or key=<name>,value=<value> entries",m.USAGE);r=i.slice(0,d).trim(),s=i.slice(d+1).trim()}if(!r||!s)throw new p("--type-option requires key and value",m.USAGE);t[r]=s}return Object.fromEntries(Object.entries(t).sort((n,i)=>n[0].localeCompare(i[0])))}(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]="ad3f992c-db2e-5276-a8ae-5d5d4ec8ae68")}catch{}})();var $C=["strict","progressive"],UC=["lightweight"],mh=new Set(["Reminder","Meeting","Event"]),jC=new Set(["author","created_at","text"]),hc=[...Qg,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...Os],GC=(()=>{let e=new Map;for(let t of hc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),$s=new Map(hc.map(e=>[e.optionKey,e.canonical])),qC=hc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function KC(e,t){let n=se(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new p(`Invalid status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n}function zC(e,t){let n=e.default_status;if(n!==void 0){let i=se(n,t);if(i)return i}return t.open_status}function gc(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`Invalid created_at timestamp "${e}"`,m.USAGE);return new Date(n).toISOString()}var WC=Is();function _h(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=r=>{let s=t.unset?[...t.unset]:[];s.includes(r)||s.push(r),t.unset=s};qe(t.template)&&(t.template=void 0);let i=new Set([...$s.keys(),"rank"]);for(let r of i){let s=t[r];if(typeof s!="string"||!qe(s))continue;let o=r==="rank"?"order":$s.get(r)??r;n(o),t[r]=void 0}return Pe(e,Rs(t,WC))}function ye(e){if(e!==void 0)return e}function BC(e,t){return Ls({raw:e,supportedFields:qC,resolveDefinition:n=>GC.get(n)??Ns(n,"create",t)})}var dh=["id","kind","type","author","created_at","source_kind"],Us=["path","scope","note"];function VC(e,t,n,i){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let o=s.trim(),a=js(o,dh);bi(o,a);let c=a?J(s,"--dep"):{id:o,kind:"related"};a&&he(c,"--dep",dh);let d=ye(c.id),l=HC(ye(c.kind??c.type));if(!d||!l)throw new p("--dep requires id and kind, or a bare item id to create a related dependency",m.USAGE);if(d.trim().toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,m.USAGE);let u=Vn(ye(c.source_kind)),_=ye(c.author);return{id:Hn(d,n,u),kind:xe(l,Mn,"dependency kind","kind"),created_at:gc(c.created_at,t),author:_??i,source_kind:u??"cli:create:dep",author_source:_?"asserted":"detected"}}),explicitEmpty:!1})}function HC(e){return typeof e=="string"?xt(e)??e.trim():e}function js(e,t){return Qi(e,t)?!0:Zt(e)}function zt(e,t,n,i){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Ie(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(o=>{let a=o.trim(),c=()=>{if(a.length===0)throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:n,author:i,text:a}},d;try{d=J(o,e)}catch(_){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw _}if(Object.keys(d).filter(_=>!jC.has(_)).length>0)return{created_at:gc(d.created_at,n),author:ye(d.author)??i,text:a};let u=d.text??"";if(u==="")throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:gc(d.created_at,n),author:ye(d.author)??i,text:u}}),explicitEmpty:!1})}function yc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let i=n.trim(),r=js(i,Us);Un(i,"--file","file path",r);let s=r?J(n,"--file"):{path:i};if(r&&he(s,"--file",Us),!s.path)throw new p("--file requires path=<value> or a bare file path",m.USAGE);return{path:s.path,scope:xe(s.scope??"project",De,"file scope"),note:ye(s.note)}}),explicitEmpty:!1})}function vc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let i=n.trim(),r=js(i,_t);Un(i,"--test","test command",r);let s=r?_s(J(n,"--test"),"--test"):{command:i},o=ye(s.command),a=ye(s.path);if(!o)throw new p("--test requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);let c=ye(s.timeout_seconds),d=ye(s.timeout);if(c&&d&&c!==d)throw new p("--test timeout and timeout_seconds must match when both are provided",m.USAGE);let l=c??d;return{command:o,path:a,scope:xe(s.scope??"project",De,"test scope"),timeout_seconds:l?_e(l,"timeout_seconds"):void 0,pm_context_mode:ys(s.pm_context_mode,"--test"),workspace_context_mode:Gt(s.workspace_context_mode,"--test"),env_set:vi(s.env_set,"--test"),env_clear:wi(s.env_clear,"--test"),shared_host_safe:hs(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:qt(s.assert_stdout_contains),assert_stdout_regex:En(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:qt(s.assert_stderr_contains),assert_stderr_regex:En(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:vs(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:ws(s.assert_json_field_equals,"--test"),assert_json_field_gte:bs(s.assert_json_field_gte,"--test"),note:ye(s.note)}}),explicitEmpty:!1})}function wc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let i=n.trim(),r=js(i,Us),s=r?J(n,"--doc"):{path:i};if(r&&he(s,"--doc",Us),!s.path)throw new p("--doc requires path=<value> or a bare doc path",m.USAGE);return{path:s.path,scope:xe(s.scope??"project",De,"doc scope"),note:ye(s.note)}}),explicitEmpty:!1})}function YC(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Ms(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function XC(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--event","Use --clear-events to clear linked events."),{values:Ps(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function JC(e,t,n,i=[]){let r=[...Ad.filter(s=>e[s]!==void 0),...i.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(r))}function QC(e,t){let n=e??"";if(t.length===0)return n;let i=`explicit_unset=${t.join(",")}`;return n?`${n} | ${i}`:i}function lh(e,t,n){let i=Pn("create",e);if(!i)throw new p(`Unsupported ${n} entry "${e}" for type "${t}"`,m.CONFLICT);return i}function ZC(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function ph(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function eI(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let i of e.required_create_fields)n.add(lh(i,e.name,"required_create_fields"));for(let i of e.required_create_repeatables)n.add(lh(i,e.name,"required_create_repeatables"));return n}function tI(e,t,n,i){for(let r of e)if(!(!ph(t,r)&&!n.has(r)))throw new p(`Option ${Ee("create",r)} is disabled for type "${i}" by command_option_policies`,m.USAGE)}function nI(e,t,n){if(t!=="strict")return;let i=e.filter(s=>n.has(s)&&!uc(s));if(i.length===0)return;let r=[...new Set(i.map(s=>Ee("create",s)))].sort((s,o)=>s.localeCompare(o));throw new p(`Strict create mode requires concrete values for ${r.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,m.USAGE)}function iI(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Fs(e),explicitEmpty:!1})}async function rI(e){return await nr(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function sI(e){return Rt(e)?await rI(e):e}function oI(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new p(`Invalid --create-mode value "${e}". Allowed: ${$C.join(", ")}`,m.USAGE)}function aI(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new p("--schedule-preset must not be empty",m.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new p(`Invalid --schedule-preset value "${e}". Allowed: ${UC.join(", ")}`,m.USAGE)}function cI(e,t,n){let i=oI(e,n);if(t===void 0)return i;if(typeof e=="string"&&e.trim().length>0&&i==="strict")throw new p("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",m.USAGE);return"progressive"}function dI(e,t,n,i){let r=e.name,s=ZC(t),o=eI(e,n),a=Jt(e,"create",o);if(a.errors.length>0)throw new p(a.errors.join("; "),m.CONFLICT);tI(a.disabled,s,i,r),nI(a.required,n,i);let c=l=>l==="status"&&e.default_status!==void 0||i.has(l)&&uc(l)?!0:ph(s,l),d=a.required.filter(l=>!c(l));return[...new Set(d.map(l=>Ee("create",l)))].sort((l,u)=>l.localeCompare(u))}var fh=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function lI(e,t){let n=[];for(let i of e){let r=i.match(fh);r&&r[2]===t&&n.push(r[1])}return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}function uI(e,t){return e.filter(n=>{let i=n.match(fh);return!i||i[2]!==t})}function mI(e,t,n,i){let r=uI(e,t);if(r.length===0)return;let s=gh(n,[],[],i.open_status);throw new p(r.join("; "),m.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function _I(e,t){let i=e.options.find(r=>r.key===t)?.values[0];return typeof i=="string"&&i.trim().length>0?i:"<value>"}function pI(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function gh(e,t,n,i){let r=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],o=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of o)a.has(c)||(r.push(...pI(c,e.name,i)),a.add(c));for(let c of n){let d=_I(e,c);r.push("--type-option",`${c}=${d}`)}return r.join(" ")}function bc(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new p("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",m.USAGE):new p('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',m.USAGE):new p(`Missing required option ${t}`,m.USAGE);return n}function fI(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=Array.isArray(r)?[...r]:r;for(let[i,r]of Object.entries(t))r!==void 0&&(n[i]=Array.isArray(r)?[...r]:r);return n}function gI(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function hI(){let e=M();return e?e.commands.some(t=>t.action==="templates-show"||gI(t.command)==="templates show"):!1}function yI(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new p(`Templates package returned invalid payload for template "${t}". Expected an options object.`,m.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new p(`Templates package returned invalid options for template "${t}".`,m.GENERIC_FAILURE);let i={};for(let[r,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){i[r]=s;continue}if(Array.isArray(s)&&s.every(o=>typeof o=="string")){i[r]=[...s];continue}throw new p(`Templates package returned unsupported option value for "${r}" in template "${t}".`,m.GENERIC_FAILURE)}return i}async function vI(e,t,n){if(!hI())throw new p("--template requires the templates package. Install it first (for example: pm install templates --project).",m.USAGE);let i=await cl({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!i.handled){let r=i.warnings.length>0?` (${i.warnings.join(", ")})`:"";throw new p(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${r}`,m.USAGE)}return yI(i.result,e)}function H(e,t,n){return e.has(t)||n===void 0?void 0:ye(n)}function Kt(e,t,n,i){return e.has(t)||n===void 0?void 0:i(n)}var wI=new Set(["milestone","meeting","reminder","event"]);function hh(e,t,n,i){let r=t!==void 0,s=n!==void 0&&n.length>0,o=i!==void 0&&i.length>0;return wI.has(e.toLowerCase())&&!r&&!s&&!o}function bI(e,t,n,i,r){let s=[];return e.toLowerCase()==="event"&&(r===void 0||r.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),hh(e,n,i,r)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function kI(e,t,n,i){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let r=await bl(i);return r===void 0?{parent:e,parentSource:void 0}:{parent:r,parentSource:"focus"}}async function SI(e,t,n,i,r,s){let o=br(lr(r),t.id_prefix);if(yr(o))return{parent:o,warnings:[]};if(mr(i,o,t.id_prefix),await Q(e,o,t.id_prefix,t.item_format,n.type_to_folder))return{parent:o,warnings:[]};let c=yt(o,t.id_prefix);return{parent:o,warnings:ur(c,s).warnings}}async function EI(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await SI(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function TI(e){if(e.explicitId===void 0)return zl(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new p("--id must be a string",m.USAGE);let t=e.explicitId.trim();if(t.length===0||Wl(t))throw new p("--id must not be empty or use a placeholder token",m.USAGE);let n=yt(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new p("--id must contain only letters, numbers, and dashes after normalization",m.USAGE);return n}function uh(e,t,n,i,r){let s=H(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let o=pr(i,s,r);return{value:o.value,warnings:o.warnings}}async function AI(e){let{pmRoot:t,settings:n,typeRegistry:i,statusRegistry:r,blockedBy:s,status:o,statusExplicit:a,nowValue:c,author:d}=e,l=e.dependencyValues;if(s===void 0)return{dependencyValues:l,status:o};let u=yt(s,n.id_prefix),_=await Q(t,u,n.id_prefix,n.item_format,i.type_to_folder);if(!_)return{dependencyValues:l,status:o};if((l??[]).some(h=>h.id===_.id&&h.kind==="blocked_by")||(l=[...l??[],{id:_.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:l,status:o};let g=r.blocked_statuses.has("blocked")?"blocked":[...r.blocked_statuses].sort((h,y)=>h.localeCompare(y))[0]??r.open_status;return{dependencyValues:l,status:g}}function CI(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let r=t.governance.create_default_type?.trim();if(r&&r.length>0&&rt(r,n)){e.type=r;return}rt("Task",n)&&(e.type="Task")}function II(e,t){return e.options.filter(n=>Pn("create",n.key)===void 0).flatMap(n=>{let i=t[n.key];if(i===void 0)return[];if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")return[n];throw new p(`Template custom type option "${n.key}" must be a string, number, or boolean value`,m.USAGE)})}async function xI(e,t,n,i,r){let s=e,o=[];if(s.template!==void 0){let g=s.template.trim();if(g.length===0)throw new p("--template must not be empty. Omit --template to disable template usage.",m.USAGE);let h=await vI(g,t,n);s=_h(fI(h,s))}if(s.type===void 0&&CI(s,i,r),s.type===void 0)throw new p("Missing required option --type <value>",m.USAGE);let a=rt(s.type,r);if(!a){let g=Bl(s.type),h=g?rt(g,r):void 0;if(h)o.push(`type_coercion:${s.type.trim()}:${h}`),s.type=h,a=h;else throw new p(fr(s.type,r.types,rr(n,i.schema)),m.USAGE)}let c=Bi(a,r);if(!c)throw new p(`Invalid type value "${s.type}"`,m.USAGE);let d=c.name,l=II(c,s),u=l.map(g=>`${g.key}=${String(s[g.key])}`);if(u.length>0){s.typeOption=[...u,...s.typeOption??[]];for(let g of l)delete s[g.key]}let _=aI(s.schedulePreset);if(_!==void 0&&!mh.has(d))throw new p(`--schedule-preset ${_} is only supported for Reminder, Meeting, or Event types`,m.USAGE);let f=cI(s.createMode,_,i.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:d,schedulePreset:_,createMode:f,warnings:o}}function RI(e,t){let n=new Set(t.metadataKeys),i=new Set(t.optionKeys),r=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of r)if(s.enabled){if(s.values&&s.values.length>0)throw new p(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,m.USAGE);n.add(s.metadataKey),i.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:i}}function OI(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[i,r]of Object.entries(n)){if(!r||!t.optionKeys.has(i))continue;let s=$s.get(i)??i;throw new p(`Cannot combine --unset ${s} with ${Ee("create",i)}`,m.USAGE)}}function LI(e){let t=(n,i)=>{let r=$s.get(i),s=r?`Use --unset ${r} to clear this field.`:void 0;xs(n,Ee("create",i),s)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function NI(e,t,n){for(let i of Object.keys(e))if(n.metadataKeys.has(i))throw new p(`Cannot combine --unset ${i.replaceAll("_","-")} with --field ${i}=...`,m.USAGE);for(let i of Object.keys(t.values??{}))if(n.metadataKeys.has(i))throw new p(`Cannot combine --unset ${i.replaceAll("_","-")} with its value flag`,m.USAGE)}var DI={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function MI(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:i,missingRequiredTypeOptionKeys:r,openStatus:s,type:o,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(g=>{let h=g.type==="boolean"?"<true|false>":g.type==="array"?"<json-array>":g.type==="object"?"<json-object>":g.type==="number"?"<number>":g.type==="string_array"||g.repeatable?"<value>":"<string>";return{example:`--${g.cli_flag} ${h}`,description:`--${g.cli_flag} maps to ${g.metadata_key} (${g.type}${g.repeatable?", repeatable":""})`}}),l=[gh(n,i,r,s),...d.map(g=>g.example)].join(" "),u=[`Run "pm create --help --type ${o}" for type-aware required option guidance.`,...t.filter(g=>g==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+o+").")];a==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),mh.has(o)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(g=>g.description).join("; ")}.`);let _=[...new Set(t.flatMap(g=>{let h=g.split(" ",1)[0],y=DI[h];return y?[y]:[]}))];_.length>0&&u.push(`If the truthful value is an empty collection, use ${_.join(", ")} instead of inventing metadata.`);let f=t.length===1?`Missing required option ${t[0]} for type "${o}"`:`Missing required options ${t.join(", ")} for type "${o}"`;throw new p(f,m.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${o}" in one invocation.`,examples:[..._.map(g=>`pm create --type ${o} ${g} ...`),l],nextSteps:u,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[..._,...t,"--create-mode progressive"]}:void 0})}function PI(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Zi(t.tags):[];return tr(n,t.addTags)}function FI(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new p("--order and --rank must match when both are provided",m.USAGE);let n=t.order??t.rank,i=Kt(e,"order",n,r=>_e(r,"order"));if(i!==void 0&&!Number.isInteger(i))throw new p("Order must be an integer",m.USAGE);return i}function $I(e,t,n,i,r,s){if(i.completedAt!==void 0&&e!==t.close_status)throw new p("--completed-at requires a terminal create status.",m.USAGE);let o=e!==t.close_status?void 0:i.completedAt===void 0?s:me(i.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:o,warnings:[]};let a=n.governance.require_close_reason?{explicit:i.closeReason??i.message,resolution:r}:{explicit:i.closeReason};return{closeReason:ac(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:o,warnings:[]}}async function UI(e){let{pmRoot:t,type:n,id:i,settings:r,typeRegistry:s,author:o,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:_,similarityCandidate:f,allowDuplicate:g}=e,h=qd(t,n,i,r.item_format,s.type_to_folder),y=Qt(t,i),v=Se(),w=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(A=>v.resolve(A.kind)?.hierarchy),S=await Ss({pmRoot:t,author:o,ttlSeconds:r.locks.ttl_seconds,waitMs:r.locks.wait_ms,required:w}),E=w,T=[];try{let A=await sn(t,i,r.locks.ttl_seconds,o,!1,r.governance.force_required_for_stale_lock,r.locks.wait_ms);try{let k=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await ke(t,r.item_format,s.type_to_folder,void 0,r.schema):void 0;if(await Q(t,i,r.id_prefix,r.item_format,s.type_to_folder))throw new p(`Item "${i}" already exists`,m.CONFLICT);if(k){let C=K(r.schema);Sr(k,[...k,c.metadata],i,V=>de(V,C),v)}let L=await eu({pmRoot:t,settings:r,operation:"create",author:o,before:null,after:c});await sl({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:su({pmRoot:t,settings:r,typeToFolder:s.type_to_folder})});let q=await iu(t,o,{required:r.governance.duplicate_detection_mode==="strict"&&g!==!0}),F=[];try{r.governance.duplicate_detection_mode==="strict"&&g!==!0&&await lc(f,{pmRoot:t,mode:"strict",threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:!1}),await Ve(h,yl(c,{format:r.item_format,schema:r.schema,extensionFieldNames:a}));try{let C=Gl({nowIso:_,author:o,op:"create",before:d,after:c,message:l,context:L.decisions.length===0?void 0:{workflow_policies:L.decisions}});await ql(y,C)}catch(C){throw await Ed(h),C}E&&(await S(),E=!1),F=await ru({pmRoot:t,preferredFormat:r.item_format,typeToFolder:s.type_to_folder,schema:r.schema,itemPath:h,document:c})}finally{await q()}T=[...L.warnings,...k?us(k,[...k,c.metadata],i):[],...F,...await ot({path:h,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await ot({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],il({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:rl(c.metadata,u),changed_fields:u})}finally{await A()}}finally{E&&await S()}return T}async function kc(e,t){let n=_h(await sI(e)),i=x(process.cwd(),t.path);await P(i);let r=await I(i),s=K(r.schema),o=nn(r.schema),a=$(r,M()),c=await xI(n,t,i,r,a);n=c.resolvedOptions;let{typeDefinition:d,type:l,createMode:u}=c,_=BC(n.unset,o),{explicitUnsets:f,clearOptionKeys:g}=RI(n,_);OI(n,_),LI(n);let h=dI(d,n,u,g),y=R(),v=G(ye(n.author),r.author_default),w=VC(n.dep,y,r.id_prefix,v),S=zt("--comment",n.comment,y,v),E=zt("--note",n.note,y,v),T=zt("--learning",n.learning,y,v),A=yc(n.file),k=vc(n.test);k.values=await kn(k.values,v,y);let b=wc(n.doc),L=YC(n.reminder,y),q=XC(n.event,y),F=iI(n.typeOption),C=Fn(l,F.values,a),V=M(),we=ht(V),ue=Xi(n.field,V),fe=pl(n,o,l),Le=new Set(fe.missing_required_flags),Ke=o.definitions.filter(X=>Le.has(`--${X.cli_flag}`));NI(ue,fe,_);let ft=lI(C.errors,l),it=ft.map(X=>`--type-option ${X}=<value>`),Ht=[...new Set([...h,...it,...fe.missing_required_flags])].sort((X,ho)=>X.localeCompare(ho));MI({combinedMissingFlags:Ht,typeDefinition:d,missingRequiredCreateFlags:h,missingRequiredTypeOptionKeys:ft,openStatus:s.open_status,type:l,createMode:u,missingRequiredRuntimeFields:Ke}),mI(C.errors,l,d,s);let ae=await TI({pmRoot:i,settings:r,typeRegistry:a,explicitId:n.id}),Ne=n.status!==void 0?KC(n.status,s):zC(d,s),Yt=n.priority!==void 0?_r(n.priority):2,D=_.metadataKeys,ge=PI(D,n),je=Kt(D,"deadline",n.deadline,X=>me(X,new Date(y),"deadline")),Xt=Kt(D,"estimated_minutes",n.estimatedMinutes,X=>ir(X,"estimated-minutes")),ze=H(D,"acceptance_criteria",n.acceptanceCriteria),ce=H(D,"definition_of_ready",n.definitionOfReady),We=FI(D,n),uo=H(D,"goal",n.goal),Pi=H(D,"objective",n.objective),pw=H(D,"value",n.value),fw=H(D,"impact",n.impact),gw=H(D,"outcome",n.outcome),hw=H(D,"why_now",n.whyNow),yw=H(D,"assignee",n.assignee),vw=D.has("author")?void 0:ye(n.author)??v,ww=H(D,"parent",n.parent),md=await kI(ww,n,D,i),mo=md.parent,bw=md.parentSource,kw=H(D,"reviewer",n.reviewer),Sw=Kt(D,"risk",n.risk,X=>xe(Es(X),zi,"risk")),Ew=Kt(D,"confidence",n.confidence,X=>As(X)),Tw=n.allowMissingParent===!0&&r.validation.parent_reference==="strict_error"?"warn":r.validation.parent_reference,_d=r.validation.sprint_release_format,At=[...c.warnings,...bI(l,ae,je,L.values,q.values)],pd=await EI({itemId:ae,parent:mo,pmRoot:i,settings:r,typeRegistry:a,policy:Tw});mo=pd.parent,At.push(...pd.warnings);let fd=uh(D,"sprint",n.sprint,"sprint",_d),Aw=fd.value;At.push(...fd.warnings);let gd=uh(D,"release",n.release,"release",_d),Cw=gd.value;At.push(...gd.warnings);let hd=H(D,"blocked_by",n.blockedBy),yd=await AI({pmRoot:i,settings:r,typeRegistry:a,statusRegistry:s,blockedBy:hd,dependencyValues:w.values,status:Ne,statusExplicit:n.status!==void 0,nowValue:y,author:v}),_o=yd.dependencyValues;ki(ae,_o),At.push(...await Ds({pmRoot:i,dependencies:_o,idPrefix:r.id_prefix,itemFormat:r.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:ae,createdAt:y}],schema:r.schema})),Ne=yd.status;let Iw=H(D,"blocked_reason",n.blockedReason),xw=H(D,"unblock_note",n.unblockNote),Rw=H(D,"reporter",n.reporter),Ow=Kt(D,"severity",n.severity,X=>xe(Ts(X),Wi,"severity")),Lw=H(D,"environment",n.environment),Nw=H(D,"repro_steps",n.reproSteps),vd=H(D,"resolution",n.resolution),Dw=H(D,"expected_result",n.expectedResult),Mw=H(D,"actual_result",n.actualResult),Pw=H(D,"affected_version",n.affectedVersion),Fw=H(D,"fixed_version",n.fixedVersion),$w=H(D,"component",n.component),Uw=Kt(D,"regression",n.regression,X=>Cs(X)),jw=H(D,"customer_impact",n.customerImpact),po=bc(n.title,"--title"),fo=n.description??"",Fi=n.body??"",wd=await lc({title:po,description:fo,body:Fi},{pmRoot:i,mode:r.governance.duplicate_detection_mode,threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});At.push(...qg(wd));let go=$I(Ne,s,r,n,vd,y),Gw=go.closeReason,qw=Ne===s.close_status?y:void 0,Kw=go.completedAt;At.push(...go.warnings);let $i=hl({id:ae,title:po,description:fo,type:l,type_options:C.normalized,status:Ne,closed_at:qw,completed_at:Kw,close_reason:Gw,priority:Yt,tags:ge,created_at:y,updated_at:y,deadline:je,assignee:yw,author:vw,estimated_minutes:Xt,acceptance_criteria:ze,definition_of_ready:ce,order:We,goal:uo,objective:Pi,value:pw,impact:fw,outcome:gw,why_now:hw,parent:mo,reviewer:kw,risk:Sw,confidence:Ew,sprint:Aw,release:Cw,blocked_by:hd,blocked_reason:Iw,unblock_note:xw,reporter:Rw,severity:Ow,environment:Lw,repro_steps:Nw,resolution:vd,expected_result:Dw,actual_result:Mw,affected_version:Pw,fixed_version:Fw,component:$w,regression:Uw,customer_impact:jw,dependencies:_o,comments:S.values,notes:E.values,learnings:T.values,files:A.values,tests:k.values,docs:b.values,reminders:L.values,events:q.values,...ue,...fe.values});try{Ji($i,V)}catch(X){throw new p(X instanceof Error?X.message:"Invalid extension item field values",m.USAGE)}let zw=vl({metadata:$i,body:Fi},{schema:r.schema,extensionFieldNames:we}),Ww={metadata:{},body:""},bd=[...f].sort((X,ho)=>X.localeCompare(ho)),Bw=QC(n.message,bd),kd=JC($i,Fi,bd,[...Object.keys(ue),...Object.keys(fe.values??{})]),Vw=await UI({pmRoot:i,type:l,id:ae,settings:r,typeRegistry:a,author:v,extensionFieldNames:we,afterDocument:zw,beforeDocument:Ww,historyMessage:Bw,changedFields:kd,nowValue:y,similarityCandidate:{title:po,description:fo,body:Fi},allowDuplicate:n.allowDuplicate}),Sd=structuredClone($i);u==="strict"&&f.has("dependencies")&&(Sd.dependencies=[]);let Hw=Jg(ae,l,Ne,s);return hh(l,je,L.values,q.values)&&jl(`[pm] warning: ${l} '${ae}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${ae} --deadline <ISO>' or 'pm update ${ae} --event "start=<ISO>,end=<ISO>"'.`),{item:Sd,changed_fields:kd,warnings:[...At,...Vw],...Object.fromEntries([["parent_source",bw],["next_transition",Hw],["similarity_advisory",wd]].filter(X=>X[1]!==void 0))}}(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]="80ec599f-7198-5b07-bca2-253f85c137b7")}catch{}})();var Ac=[...mc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},..._c,...Os],jI=(()=>{let e=new Map;for(let t of Ac)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Gs=new Map(Ac.map(e=>[e.optionKey,e.canonical])),GI=Ac.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),qI=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),KI=Is({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Th(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=r=>{let s=t.unset?[...t.unset]:[];s.includes(r)||s.push(r),t.unset=s},i=new Set([...Gs.keys(),"rank"]);for(let r of i){let s=t[r];if(typeof s!="string"||!qe(s))continue;let o=r==="rank"?"order":Gs.get(r)??r;n(o),t[r]=void 0}return Pe(e,Rs(t,KI))}function Ah(e,t,n=[]){return Ls({raw:e,supportedFields:GI,resolveDefinition:i=>{let r=n.find(o=>{let a=o.toLowerCase();return a===i||a.replaceAll("_","-")===i||a.replaceAll("-","_")===i});return jI.get(i)??Ns(i,"update",t)??(r?{optionKey:"field",metadataKey:r}:void 0)}})}var yh=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function vh(e){let t=e.disallowedFlags.flatMap(i=>{let r=yh.get(i);return r?[r(e.id)]:[]}),n=e.disallowedFlags.flatMap(i=>{let r=yh.get(i);return r?[`Replace ${i} with: ${r(e.id)}`]:[]});return new p(e.message,m.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function zI(e,t,n){let i=t.ownershipMetadataBypass===!0,r=t.ownershipDependencyBypass===!0;if(!i&&!r)return;if(i&&r)throw new p("Choose only one package-provided ownership bypass mode.",m.USAGE);let s=(c,d,l)=>{c&&l.push(d)};if(r){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new p("The dependency ownership bypass requires at least one --dep value",m.USAGE);if(c.length>0)throw vh({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let o=[];s(t.status!==void 0,"--status",o),s(t.closeReason!==void 0,"--close-reason",o),s(t.assignee!==void 0,"--assignee",o),s(t.parent!==void 0,"--parent",o),s(t.blockedBy!==void 0,"--blocked-by",o),s(t.blockedReason!==void 0,"--blocked-reason",o),s(t.unblockNote!==void 0,"--unblock-note",o),s(t.dep!==void 0,"--dep",o),s(t.depRemove!==void 0,"--dep-remove",o),s(t.replaceDeps===!0,"--replace-deps",o),s(t.replaceTests===!0,"--replace-tests",o),s(t.replaceFiles===!0,"--replace-files",o),s(t.replaceDocs===!0,"--replace-docs",o),s(t.note!==void 0,"--note",o),s(t.learning!==void 0,"--learning",o),s(t.test!==void 0,"--test",o),s(t.reminder!==void 0,"--reminder",o),s(t.event!==void 0,"--event",o),s(t.clearDeps===!0,"--clear-deps",o),s(t.clearComments===!0,"--clear-comments",o),s(t.clearNotes===!0,"--clear-notes",o),s(t.clearLearnings===!0,"--clear-learnings",o),s(t.clearFiles===!0,"--clear-files",o),s(t.clearTests===!0,"--clear-tests",o),s(t.clearDocs===!0,"--clear-docs",o),s(t.clearReminders===!0,"--clear-reminders",o),s(t.clearEvents===!0,"--clear-events",o);let a=[...n].filter(c=>qI.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(o.push(...a),o.length>0)throw vh({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${o.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:o})}function WI(e,t){let n=se(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new p(`Invalid --status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n}function BI(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Hl({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=se(e.fromStatus,e.statusRegistry)??e.fromStatus,i=se(e.toStatus,e.statusRegistry)??e.toStatus,r=`Disallowed transition for type "${e.typeName}": ${n} -> ${i}. Allowed transitions: ${Yl(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new p(r,m.USAGE);return`workflow_transition_not_allowed: ${r}`}function VI(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:Ch(e)}function Ch(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new p(`Invalid dependency created_at timestamp "${e}"`,m.USAGE);return new Date(t).toISOString()}function Tn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var HI=["id","kind","type","author","created_at","source_kind"],YI=["id","kind","type","author","created_at","source_kind"];function Ih(e){return e.startsWith("```")||e.includes(`
|
|
10
|
+
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Zt(e)}function xh(e){return typeof e=="string"?xt(e)??e.trim():e}function XI(e,t,n,i){return e?(Ie(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let o=s.trim(),a=Ih(o);bi(o,a);let c=a?J(s,"--dep"):{id:o,kind:"related"};a&&he(c,"--dep",HI);let d=c.id?.trim(),l=xh((c.kind??c.type)?.trim());if(!d||!l)throw new p("--dep requires id and kind, or a bare item id to add a related dependency",m.USAGE);if(d.toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,m.USAGE);let u=Vn(Tn(c.source_kind)),_=Tn(c.author);return{id:Hn(d,t,u),kind:xe(l,Mn,"dependency kind","kind"),created_at:VI(c.created_at,n),author:_??i,source_kind:u??"cli:update:dep",author_source:_?"asserted":"detected"}})}):{additions:[]}}function JI(e,t){return e?(Ie(e,"--dep-remove"),e.map(n=>{let i=n.trim();if(!i)throw new p("--dep-remove requires id or key/value selectors",m.USAGE);let r=Ih(i);if(bi(i,r,"--dep-remove"),r){let s=J(i,"--dep-remove");he(s,"--dep-remove",YI);let o=s.id?.trim();if(!o)throw new p("--dep-remove key/value form requires id=<value>",m.USAGE);if(o.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${o}"`,m.USAGE);let a=xh(Tn(s.kind??s.type)),c=Vn(Tn(s.source_kind)),d=Tn(s.author),l=Tn(s.created_at);return{id:Hn(o,t,c),kind:a?xe(a,Mn,"dependency kind","kind"):void 0,source_kind:c,author:d,created_at:l?Ch(l):void 0}}if(i.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${i}"`,m.USAGE);return{id:yt(i,t)}})):[]}function qs(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function QI(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",i=e.created_at?.trim()??"",r=Date.parse(i),s=Number.isFinite(r)?new Date(r).toISOString():i;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function ZI(e,t,n,i){let r=[...e??[]],s=!1;if(t===void 0){let o=r.filter(a=>a.kind!=="blocked_by");return o.length!==r.length&&(r=o,s=!0),s?{dependencies:r.length>0?r:void 0,changed:!0}:{dependencies:e,changed:!1}}return r.some(o=>o.kind==="blocked_by"&&o.id===t)||(r.push({id:t,kind:"blocked_by",created_at:n,author:i,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:r.length>0?r:void 0,changed:!0}:{dependencies:e,changed:!1}}async function e0(e,t,n,i,r,s){if(e===void 0||t)return{};let o=e.trim();if(o.length===0)return{};let a=await Q(n,yt(o,i),i,r,s);return a?{id:a.id}:{unresolved:o}}function t0(e,t,n,i,r){let s=ZI(e.dependencies,t,n,i);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,r.includes("dependencies")||r.push("dependencies"))}function n0(e){return`${e.path}::${e.scope}`}function i0(e){return`${e.path}::${e.scope}`}function r0(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function Rh(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function wh(e,t){let n=Pn("update",e);if(!n)throw new p(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,m.CONFLICT);return n}function s0(e,t,n){let i=new Set,r=(s,o)=>{o&&i.add(s)};if(r("title",e.title!==void 0),r("description",e.description!==void 0),r("body",e.body!==void 0),r("status",e.status!==void 0),r("closeReason",e.closeReason!==void 0),r("priority",e.priority!==void 0),r("type",e.type!==void 0),r("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),r("deadline",e.deadline!==void 0),r("estimatedMinutes",e.estimatedMinutes!==void 0),r("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),r("definitionOfReady",e.definitionOfReady!==void 0),r("order",e.order!==void 0||e.rank!==void 0),r("goal",e.goal!==void 0),r("objective",e.objective!==void 0),r("value",e.value!==void 0),r("impact",e.impact!==void 0),r("outcome",e.outcome!==void 0),r("whyNow",e.whyNow!==void 0),r("author",e.author!==void 0),r("message",e.message!==void 0),r("assignee",e.assignee!==void 0),r("parent",e.parent!==void 0),r("reviewer",e.reviewer!==void 0),r("risk",e.risk!==void 0),r("confidence",e.confidence!==void 0),r("sprint",e.sprint!==void 0),r("release",e.release!==void 0),r("blockedBy",e.blockedBy!==void 0),r("blockedReason",e.blockedReason!==void 0),r("unblockNote",e.unblockNote!==void 0),r("reporter",e.reporter!==void 0),r("severity",e.severity!==void 0),r("environment",e.environment!==void 0),r("reproSteps",e.reproSteps!==void 0),r("resolution",e.resolution!==void 0),r("expectedResult",e.expectedResult!==void 0),r("actualResult",e.actualResult!==void 0),r("affectedVersion",e.affectedVersion!==void 0),r("fixedVersion",e.fixedVersion!==void 0),r("component",e.component!==void 0),r("regression",e.regression!==void 0),r("customerImpact",e.customerImpact!==void 0),r("dep",e.dep!==void 0),r("depRemove",e.depRemove!==void 0),r("dep",e.replaceDeps===!0),r("comment",e.comment!==void 0),r("note",e.note!==void 0),r("learning",e.learning!==void 0),r("file",e.file!==void 0),r("test",e.test!==void 0),r("test",e.replaceTests===!0),r("file",e.replaceFiles===!0),r("doc",e.replaceDocs===!0),r("doc",e.doc!==void 0),r("reminder",e.reminder!==void 0),r("event",e.event!==void 0),r("typeOption",e.typeOption!==void 0),r("field",e.field!==void 0),r("force",e.force===!0),r("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),r("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),r("dep",e.clearDeps===!0),r("comment",e.clearComments===!0),r("note",e.clearNotes===!0),r("learning",e.clearLearnings===!0),r("file",e.clearFiles===!0),r("test",e.clearTests===!0),r("doc",e.clearDocs===!0),r("reminder",e.clearReminders===!0),r("event",e.clearEvents===!0),r("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=Ah(e.unset,t,n);for(let o of s.optionKeys)r(o,!0)}return i}function o0(e,t,n,i,r){let s=Bi(e,n);if(!s)throw new p(`Invalid type value "${e}"`,m.USAGE);let o=Jt(s,"update",[]);if(o.errors.length>0)throw new p(o.errors.join("; "),m.CONFLICT);let a=s0(t,i,r);for(let c of o.disabled)if(a.has(wh(c,e)))throw new p(`Option ${Ee("update",c)} is disabled for type "${e}" by command_option_policies`,m.USAGE);for(let c of o.required)if(!a.has(wh(c,e)))throw new p(`Missing required option ${Ee("update",c)} for type "${e}"`,m.USAGE)}var a0=new Set(["order","rank"]),c0=ko.filter(e=>!a0.has(e)),Oh=["tags","closeReason",...c0],d0=["title","description","body","status","closeReason","completedAt","priority","type",...ko,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],l0=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>me(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>ir(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],u0=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>xe(Es(e),zi,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>As(e)}],m0=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>xe(Ts(e),Wi,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>Cs(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Tc(e,t,n){for(let i of e){let r=t[i.optionKey],s=n.clearItemMetadataKeys.has(i.metadataKey);if(!(r===void 0&&!s)){if(s){delete n.metadataRecord[i.metadataKey],n.changedFields.push(i.metadataKey);continue}if(typeof r!="string")throw new p(`${Ee("update",String(i.optionKey))} must be a string value`,m.USAGE);n.metadataRecord[i.metadataKey]=i.transform?i.transform(r,n):r.trim(),n.changedFields.push(i.metadataKey)}}}async function _0(e){return Th(await nr(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function p0(e){return Rt(e)?await _0(e):Th(e)}function f0(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function Sc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new p(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,m.USAGE);if(e.enabled&&e.clearEnabled)throw new p(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,m.USAGE)}function g0(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new p("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",m.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new p("--replace-deps requires at least one --dep entry",m.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new p("--replace-deps cannot be combined with --dep-remove",m.USAGE);Sc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Sc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Sc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function h0(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new p(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,m.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function y0(e){let t={};for(let n of Oh)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function v0(e,t){let n=y0(e);for(let[i,r]of Object.entries(n)){if(!r||!t.optionKeys.has(i))continue;let s=Gs.get(i)??i;throw new p(`Cannot combine --unset ${s} with ${Ee("update",i)}`,m.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --add-ac",m.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --remove-ac",m.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new p("Cannot combine --unset tags with --remove-tags",m.USAGE)}}function w0(e){let t=(n,i)=>{let r=Gs.get(i),s=r?`Use --unset ${r} to clear this field.`:void 0;xs(n,Ee("update",i),s)};for(let n of Oh)t(e[n],String(n));t(e.order??e.rank,"order"),Ie(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Ie(e.event,"--event","Use --clear-events to clear linked events.")}function b0(e,t){let n={};for(let i of d0)n[String(i)]=e[i]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.runtimeFields=Object.keys(t).length>0,n}async function k0(e){let t=await Q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Wn(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await be(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function S0(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return ke(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function E0(e){e.before&&Sr(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>de(t,e.statusRegistry),Se())}function T0(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new p("--order and --rank must match when both are provided",m.USAGE)}async function A0(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=br(lr(e.options.parent),e.settings.id_prefix);if(yr(t))return{resolvedParentValue:t,warnings:[]};if(mr(e.id,t,e.settings.id_prefix),await Q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let i=yt(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:ur(i,e.parentReferencePolicy).warnings}}function C0(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function I0(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await Q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Wn(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await be(t,{schema:e.settings.schema}),i=e.options.type!==void 0?rt(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",r=BI({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:i,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return r?[r]:[]}async function x0(e){if(!e.fieldFlags.status||se(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),i=[],r=[];if(n.length>0){let a=Pe(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),c=await Ks(e.id,a,e.global);r=c.changed_fields,i.push(...c.warnings)}let s=await ls(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),o=[...e.workflowTransitionWarnings,...i,...s.warnings,"auto_routed_from_update_to_close"];return{item:s.item,changed_fields:[...r,...s.changed_fields],warnings:o}}function R0(e,t,n,i){return t.title!==void 0&&(e.metadata.title=bc(t.title,"--title"),i.push("title")),t.description!==void 0&&(e.metadata.description=t.description,i.push("description")),t.body!==void 0&&(e.body=t.body,i.push("body")),se(e.metadata.status,n)??e.metadata.status}var O0=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function L0(e,t){for(let n of O0)e[n]!==void 0&&(delete e[n],t.push(n))}function N0(e,t,n,i,r){let s=WI(n,t.statusRegistry);if(e.metadata.status=s,r.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,r.push("closed_at","completed_at");return}!de(s,t.statusRegistry)&&de(i,t.statusRegistry)&&L0(e.metadata,r)}function D0(e,t,n,i){if(t.options.status!==void 0&&N0(e,t,t.options.status,n,i),t.options.completedAt!==void 0){if(!de(e.metadata.status,t.statusRegistry))throw new p("--completed-at can only be set on a terminal item",m.USAGE);e.metadata.completed_at=me(t.options.completedAt,new Date(t.nowIso),"completed-at"),i.push("completed_at")}}function M0(e,t,n,i){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let r=t.options.closeReason?.trim()??"";if(r.length===0)throw new p("--close-reason must not be empty",m.USAGE);e.metadata.close_reason=r}i.push("close_reason");return}t.options.status!==void 0&&de(n,t.statusRegistry)&&!de(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,i.push("close_reason"))}function P0(e,t,n,i){D0(e,t,n,i),M0(e,t,n,i)}function F0(e,t,n){let i=rt(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=_r(t.options.priority),n.push("priority")),t.options.type!==void 0){let r=rt(t.options.type,t.typeRegistry);if(!r)throw new p(fr(t.options.type,t.typeRegistry.types,rr(t.pmRoot,t.settings.schema)),m.USAGE);e.metadata.type=r,i=r,n.push("type")}return o0(i,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),$0(e,t,i,n),i}function $0(e,t,n,i){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let s=Fs(t.options.typeOption??[]),o=Fn(n,s,t.typeRegistry);if(o.errors.length>0)throw new p(o.errors.join("; "),m.USAGE);e.metadata.type_options=o.normalized}i.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let r=Fn(n,e.metadata.type_options,t.typeRegistry);if(r.errors.length>0)throw new p(`Current type options are incompatible with type "${n}". ${r.errors.join("; ")}. Use --clear-type-options to clear them.`,m.USAGE);e.metadata.type_options=r.normalized}function U0(e,t){let n=new Set(t.map(r=>qs(r))),i=new Set;return e.filter(r=>{if(!n.has(qs(r)))return!0;let s=QI(r);return i.has(s)?!1:(i.add(s),!0)})}function j0(e,t,n){let i=t.filter(r=>!e.some(s=>Rh(s,r)));if(i.length!==0)throw new p(`Dependency removal did not match ${i.length===1?"a stored edge":"stored edges"}.`,m.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:i,available_dependencies:e.map(r=>({id:r.id,kind:r.kind,source_kind:r.source_kind,author:r.author,created_at:r.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function G0(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let i=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){i=U0(i,t.dependencyUpdates.additions);let r=new Set(i.map(s=>qs(s)));for(let s of t.dependencyUpdates.additions){let o=qs(s);r.has(o)||(i.push(s),r.add(o))}}t.dependencyRemovals.length>0&&(j0(i,t.dependencyRemovals,e.metadata.id),i=i.filter(r=>!t.dependencyRemovals.some(s=>Rh(r,s)))),i.length===0?delete e.metadata.dependencies:e.metadata.dependencies=i,n.push("dependencies")}function q0(e,t,n){Ec(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Ec(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Ec(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Ec(e,t,n,i,r,s){n===void 0&&!r.has(t)||(r.has(t)||!i||i.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...i],s.push(t))}function K0(e,t,n){bh(e,"files",t.options.file,t.fileUpdates.values,n0,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),z0(e,t,n),bh(e,"docs",t.options.doc,t.docUpdates.values,i0,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function bh(e,t,n,i,r,s,o,a){if(!(n===void 0&&!o.has(t))){if(s)e.metadata[t]=i;else if(o.has(t)||!i||i.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>r(l)));for(let l of i){let u=r(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}a.push(t)}}function z0(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=kh(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=kh([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function kh(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let i of e){let r=r0(i);n.has(r)||(t.push(i),n.add(r))}return t}function W0(e,t,n){let i=t.options.addTags,r=t.options.removeTags,s=Array.isArray(i)&&i.length>0||Array.isArray(r)&&r.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let o=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Zi(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=ul(tr(o,i),r),n.changedFields.push("tags")}Tc(l0,t.options,n),V0(e,t,n.changedFields)}function B0(e,t,n){let i=t.options.addAc,r=t.options.removeAc;if(!(Array.isArray(i)&&i.length>0)&&!(Array.isArray(r)&&r.length>0))return;let s=ll(er(e.metadata.acceptance_criteria),i,r);if(s.unmatchedRemovals.length>0)throw new p(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let o=s.criteria.join("; ");e.metadata.acceptance_criteria!==o&&(o===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=o,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function V0(e,t,n){let i=t.options.order??t.options.rank;if(!(i===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let r=_e(i??"","order");if(!Number.isInteger(r))throw new p("Order must be an integer",m.USAGE);e.metadata.order=r}n.push("order")}}function H0(e,t,n,i){Y0(e,t,n.changedFields),X0(e,t,n.changedFields),Tc(u0,t.options,n),Sh(e,t,"sprint",i,n.changedFields),Sh(e,t,"release",i,n.changedFields),J0(e,t,n.changedFields),Tc(m0,t.options,n)}function Y0(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let i=t.options.assignee?.trim()??"";if(i==="")throw new p("--assignee must not be empty. Use --unset assignee to clear it.",m.USAGE);e.metadata.assignee=i}n.push("assignee")}}function X0(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function Sh(e,t,n,i,r){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=pr(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,i.push(...s.warnings)}r.push(n)}}function J0(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&t0(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function Q0(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Ms(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=Ps(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function Z0(e,t,n){Eh(e,t.runtimeFieldRegistry.definitions.map(r=>r.metadata_key),t.clearItemMetadataKeys,n),Eh(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[r,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(r)){let o=r.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(d=>d.metadata_key===r)?.cli_flag??o;throw new p(`Cannot combine --unset ${o} with --${c}`,m.USAGE)}st(e[r],s)||(e[r]=s,n.push(r))}let i=Xi(t.options.field,t.extensionRegistrations);for(let r of Object.keys(i))if(t.clearItemMetadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,m.USAGE);for(let[r,s]of Object.entries(i))st(e[r],s)||(e[r]=s,n.push(r))}function Eh(e,t,n,i){for(let r of t)!n.has(r)||e[r]===void 0||(delete e[r],i.push(r))}function ex(e,t){let n=structuredClone(e.metadata),i=e.body,r=[],s=[],o=R0(e,t.options,t.statusRegistry,r),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:r,nowValue:t.nowValue};P0(e,t,o,r),F0(e,t,r),G0(e,t,r),q0(e,t,r),K0(e,t,r),W0(e,t,c),B0(e,t,c),H0(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&ki(e.metadata.id,e.metadata.dependencies),se(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,r.includes("assignee")||r.push("assignee")),Q0(e,t,r),Z0(a,t,r);try{Ji(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(u){throw new p(u instanceof Error?u.message:"Invalid extension item field values",m.USAGE)}let d=e.metadata,l=[...new Set(r)].filter(u=>u==="body"?e.body!==i:!st(n[u],d[u]));return t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${er(n.acceptance_criteria).length}:${er(d.acceptance_criteria).length}`),{changedFields:l,warnings:s}}async function Lh(e,t,n,i={}){t=await p0(t);let r=x(process.cwd(),n.path);await P(r);let s=await I(r),o=K(s.schema),a=nn(s.schema),c=M(),d=ht(c),l=$(s,c),u=s.governance.workflow_enforcement??"off",_=u==="off"?[]:Vl(s.schema),f=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],g=Ah(t.unset,a,d),h=new Set(g.optionKeys),y=new Set(g.metadataKeys);g0(t),h0({definitions:f0(t),options:t,clearOptionKeys:h,clearItemMetadataKeys:y}),zI(e,t,y),v0(t,g),w0(t);let v=G(t.author,s.author_default),w=new Date,S=w.toISOString(),E=XI(t.dep,s.id_prefix,S,v);ki(e,E.additions);let T=await Ds({pmRoot:r,dependencies:E.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:l.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),A=JI(t.depRemove,s.id_prefix),k=zt("--comment",t.comment,S,v),b=t.ownershipMetadataBypass===!0&&k.values?{...k,values:k.values.map(ge=>({...ge,author:v}))}:k,L=zt("--note",t.note,S,v),q=zt("--learning",t.learning,S,v),F=yc(t.file),C=vc(t.test);C.values=await kn(C.values,v,S);let V=wc(t.doc),we=[],ue=await A0({id:e,options:t,unsetTargets:g,pmRoot:r,settings:s,typeRegistry:l,parentReferencePolicy:f}),fe=await e0(t.blockedBy,y.has("blocked_by"),r,s.id_prefix,s.item_format,l.type_to_folder),Le=fe.id,Ke=[...ue.warnings,...C0(fe)],ft=fl(t,a,t.runtimeFieldCommands),it=b0(t,ft);if(!Object.values(it).some(Boolean))return k0({pmRoot:r,id:e,settings:s,typeRegistry:l});we.push(...await I0({options:t,fieldFlags:it,workflowEnforcement:u,typeWorkflows:_,statusRegistry:o,typeRegistry:l,pmRoot:r,id:e,settings:s}));let ae=await x0({options:t,fieldFlags:it,statusRegistry:o,workflowTransitionWarnings:we,global:n,id:e});if(ae)return ae;T0(t);let Ne=Se(),Yt=it.parent&&!y.has("parent")||E.additions.some(ge=>Ne.resolve(ge.kind)?.hierarchy),D=await Ss({pmRoot:r,author:v,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Yt});try{let ge=await S0({fieldFlags:it,clearedMetadataKeys:y,pmRoot:r,settings:s,typeToFolder:l.type_to_folder}),je,Xt,ze=await ou({pmRoot:r,settings:s,typeToFolder:l.type_to_folder,id:e,op:tx(t,i),author:v,message:t.message,resolveHistoryContext:()=>Xt,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:d,skipNoop:!0,mutate(We){je=nx({document:We,recurrenceReason:i.recurrenceReason,requestedStatus:t.status,statusRegistry:o}),Xt=je?{recurrence:je}:void 0,ge=ge?.map(Pi=>Pi.id===We.metadata.id?structuredClone(We.metadata):Pi);let uo=ex(We,{options:t,settings:s,typeRegistry:l,statusRegistry:o,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:d,clearItemMetadataKeys:y,dependencyUpdates:E,dependencyRemovals:A,commentUpdates:b,noteUpdates:L,learningUpdates:q,fileUpdates:F,testUpdates:C,docUpdates:V,resolvedParentValue:ue.resolvedParentValue,resolvedBlockedByDependencyId:Le,runtimeFieldUpdates:ft,nowValue:w,nowIso:S,author:v,pmRoot:r});return E0({before:ge,document:We,statusRegistry:o}),uo}});await D();let ce=ge?us(ge,ge.map(We=>We.id===ze.item.id?ze.item:We),ze.item.id):[];return{item:ze.item,changed_fields:ze.changedFields,warnings:[...we,...Ke,...T,...ce,...ze.warnings],...je===void 0?{}:{lifecycle_transition:je}}}finally{await D()}}function tx(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function nx(e){if(e.recurrenceReason===void 0)return;let t=se(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!de(t,e.statusRegistry))throw new p(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,m.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,i=se(n,e.statusRegistry)??n,r=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(o=>{let a=r[o];return typeof a=="string"?[[o,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:i,previous_terminal:s}}async function Ks(e,t,n){return Lh(e,t,n)}async function eK(e,t,n,i){let r=await Lh(e,t,n,{recurrenceReason:i});if(r.lifecycle_transition===void 0)throw new p(`Item ${e} did not produce the required recurrence receipt.`,m.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...r,lifecycle_transition:r.lifecycle_transition}}(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]="961c1918-75f9-5e5d-bbae-b333ca29534f")}catch{}})();function Nh(e){return tn("in_progress",e)??e.open_status}(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]="7f0e8f0f-bef3-5d61-b851-7582a03430b6")}catch{}})();async function Cc(e,t,n){try{return await n()}catch(i){let r=i instanceof p?i.context:{},s=new p(i instanceof Error?i.message:String(i),i instanceof p?i.exitCode:m.GENERIC_FAILURE,{...r,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${r.why?` ${r.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...r.nextSteps??[]]});throw s.cause=i,s}}async function pK(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new p("--start requires an explicit item id and cannot be combined with --next or --if-available",m.USAGE);let i=await I(x(process.cwd(),n.path)),r=Nh(K(i.schema)),s=await sc(e,t.force===!0,n,t),o=await Cc(e,"claim",()=>Ks(e,da(t,{status:r},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:e,action:"start_task",claim:s,update:o}}async function fK(e,t,n){let i=await I(x(process.cwd(),n.path)),r=K(i.schema).open_status,s=await Ks(e,da(t,{status:r},["assignee","pause"]),n),o=await Cc(e,"update",()=>oc(e,t.force===!0,n,t));return{id:e,action:"pause_task",update:s,release:o}}async function gK(e,t,n,i){let r=await ls(e,t,n,i),s=await Cc(e,"close",()=>oc(e,n.force===!0,i,n));return{id:e,action:"close_task",close:r,release: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]="86ee3f5f-ce07-59dc-a2ee-f4e0373a0345")}catch{}})();var Ic=[{exit_code:m.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:m.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:m.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:m.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:m.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:m.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:m.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:m.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],Dh=[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED],ix=new Set(["close-many","update-many"]),Ph=Xe.map(e=>({command:e,exit_codes:ix.has(e)?[...Dh,m.NO_EFFECT,m.PARTIAL_EFFECT]:[...Dh]})),Mh=new Map(Ph.map(e=>[e.command,e])),rx=[m.SUCCESS,m.NO_EFFECT,m.PARTIAL_EFFECT];function wK(e){return rx.includes(e)}function bK(e){return Ic.some(t=>t.exit_code===e)}function Fh(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return Mh.get(t)??Mh.get(t.split(" ")[0])}function kK(e,t=Xe,n=Ph){let i=new Map(n.map(d=>[d.command,d])),r=t.filter(d=>!i.has(d)),s=e.filter(d=>{let l=i.get(d.command)??i.get(d.command.split(" ")[0]);return l===void 0||!l.exit_codes.includes(d.exit_code)}),o=new Set(e.map(d=>d.exit_code)),c=[...new Set(n.flatMap(d=>d.exit_codes))].filter(d=>!o.has(d)).sort((d,l)=>d-l);return{ok:r.length===0&&s.length===0&&c.length===0,missing_commands:r,undeclared_observations:s,unreachable_exit_codes:c}}function SK(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:m.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:m.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS}}import xc from"node:fs/promises";import $h 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]="9189cea6-950f-5594-9321-b7590171297c")}catch{}})();var sx=1440*60*1e3,ox=new Set(["committed","compensated"]);function ax(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function cx(e,t,n,i,r){let s=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(s))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=i-s;return ox.has(t)?o>r?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function dx(e,t,n,i){let r=i.hooks?.onRead?await i.hooks.onRead(e):[],s=ax(await xc.readFile(e,"utf8")),o=cx(t,s.status,s.updatedAt,i.nowMs,i.retentionMs);return o.entry.reason==="unparseable"&&r.push(`transaction_journal_unparseable:${n}`),o.remove&&!i.dryRun&&(await xc.rm(e,{force:!0}),i.hooks?.onWrite&&r.push(...await i.hooks.onWrite(e))),{decision:o,warnings:r}}async function Uh(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),s=Math.max(0,t.retentionDays)*sx,o=$h.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await xc.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(W(d))return a;throw d}for(let d of c){let l=$h.join(o,d),u=`transactions/sdk/${d}`,_=await dx(l,u,d,{dryRun:n,hooks:i,nowMs:r,retentionMs:s});a.warnings.push(..._.warnings),a.scanned+=1;let{decision:f}=_;if(!f.remove){a.retained.push(u),a.entries.push(f.entry);continue}a.removed.push(u),a.entries.push(f.entry)}return a}import An from"node:fs/promises";import Ws from"node:path";import zs from"node:fs/promises";import Rc 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]="fe72275e-b195-5a7e-b963-a9f159f9c67c")}catch{}})();var lx=864e5;function ux(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function mx(e,t){let n;try{n=await zs.readdir(e,{withFileTypes:!0})}catch(r){if(W(r))return[];throw r}let i=[];for(let r of n)if(r.isDirectory()){let s=Rc.join(e,r.name),o;try{o=await zs.readdir(s)}catch(a){W(a)||t.push(`checkpoint_subdir_unreadable:${r.name}`);continue}for(let a of o)a.endsWith(".json")&&i.push(`${r.name}/${a}`)}else r.name.endsWith(".json")&&i.push(r.name);return i.sort()}async function jh(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),s=Math.max(0,t.retentionDays)*lx,o=Rc.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await mx(o,a.warnings);for(let d of c){let l=Rc.join(o,d),u=`checkpoints/${d}`;a.scanned+=1,i?.onRead&&a.warnings.push(...await i.onRead(l));let _;try{_=await zs.readFile(l,"utf8")}catch(v){if(W(v)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=ux(_),g=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(g)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=r-g,y={file:u,created_at:f,age_seconds:Math.floor(h/1e3),stale:h>s,reason:h>s?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await zs.unlink(l)}catch(v){if(!W(v)){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}i?.onWrite&&a.warnings.push(...await i.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e2e3b62-5eb1-5773-96bf-866b26a59345")}catch{}})();var Si=["index","embeddings","runtime","locks","checkpoints","transactions"],_x=1440*60*1e3,px=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function fx(e,t,n){let i=t.relativePath,r=Ws.join(e,i),s=await Me({path:r,scope:"project"});try{let o=await An.stat(r);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...s,`not_a_file:${i}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...s,`not_a_directory:${i}`]};if(n)return{removed:!0,warnings:s};t.kind==="file"?await An.unlink(r):await An.rm(r,{recursive:!0,force:!0});let a=await ot({path:r,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...s,...a]}}catch(o){if(W(o))return{removed:!1,warnings:s};throw o}}async function gx(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],i=[],r=[],s=[],o=Date.now()-_x;for(let a of n){let c=Ws.join(e,a.relativePath);if(!await Z(c))continue;let d=(await An.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=Ws.posix.join(a.relativePath,l),_=Ws.join(c,l);s.push(...await Me({path:_,scope:"project"}));let f=await An.stat(_).catch(g=>{if(!W(g))throw g});if(f){if(f.mtimeMs>o){r.push(u);continue}i.push(u),!t&&(await An.rm(_,{recursive:!0,force:!0}),s.push(...await ot({path:_,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:i,retained:r,warnings:s}}function hx(e){if(!e||e.length===0)return[...Si];let t=e.flatMap(i=>i.split(",")).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);if(t.length===0)throw new p(`--scope requires at least one value (${Si.join(",")})`,m.USAGE);let n=new Set;for(let i of t){if(!Si.includes(i))throw new p(`Invalid --scope value "${i}". Expected one or more of: ${Si.join(", ")}`,m.USAGE);n.add(i)}return Si.filter(i=>n.has(i))}function yx(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),i=e.removed.some(r=>r==="index/manifest.json"||r==="search/embeddings.jsonl"||r==="search/vectorization-status.json"||r==="search/lancedb"||r==="search/pending-refresh.json"||r==="search/pending-refresh.gate.lock");return n&&i&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(r=>r.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(r=>r.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function BK(e,t={}){let n=x(process.cwd(),e.path);await P(n);let i=await I(n),r=t.dryRun===!0,s=hx(t.scope),o=px.filter(g=>s.includes(g.scope)),a=[],c=[],d=[];for(let g of o){let h=await fx(n,g,r);h.removed?a.push(g.relativePath):c.push(g.relativePath),d.push(...h.warnings)}if(s.includes("runtime")){let g=await gx(n,r);a.push(...g.removed),c.push(...g.retained),d.push(...g.warnings)}let l;if(s.includes("locks")){let g=await Ip(n,{dryRun:r,hooks:{onRead:h=>Me({path:h,scope:"project"}),onWrite:h=>ot({path:h,scope:"project",op:"gc:lock_remove"})}});a.push(...g.removed),c.push(...g.retained),d.push(...g.warnings),l={scanned:g.scanned,removed:g.removed.length,retained:g.retained.length}}let u;if(s.includes("transactions")){let g=i.checkpoints.retention_days,h=await Uh(n,{dryRun:r,retentionDays:g,hooks:{onRead:y=>Me({path:y,scope:"project"}),onWrite:y=>ot({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:g}}let _;if(s.includes("checkpoints")){let g=i.checkpoints.retention_days,h=await jh(n,{dryRun:r,retentionDays:g,hooks:{onRead:y=>Me({path:y,scope:"project"}),onWrite:y=>ot({path:y,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),_={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:g}}d.push(...await al({mode:r?"gc:dry-run":"gc",total_items:o.length}));let f=yx({dryRun:r,scopes:s,removed:a});return{ok:d.length===0,dry_run:r,scope:s,removed:a,retained:c,warnings:d,...l?{locks:l}:{},..._?{checkpoints:_}:{},...u?{transactions:u}:{},guidance:f,generated_at:R()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a196ae-61e1-528d-99a2-83eb9e11158b")}catch{}})();var vx="1h",wx="now",bx="+1d";function Et(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Gh(e,t,n){let i={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return Pe(n,i)}async function qh(e,t,n,i){let r=Gh(e,t,n),s=[];return Et(s,"start",n.start??wx),n.end!==void 0?Et(s,"end",n.end):Et(s,"duration",n.duration??vx),Et(s,"location",n.location),Et(s,"timezone",n.timezone),n.allDay===!0&&Et(s,"all_day","true"),r.event=[s.join(",")],kc(r,i)}function XK(e,t,n){return qh("Meeting",e,t,n)}function JK(e,t,n){return qh("Event",e,t,n)}function QK(e,t,n){let i=Gh("Reminder",e,t),r=[];return Et(r,"at",t.at??bx),Et(r,"text",t.text??e),i.reminder=[r.join(",")],kc(i,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]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();import Ti from"node:crypto";import{cp as Kh,lstat as kx,mkdir as Wt,readFile as Cn,readdir as Lc,rename as Bh,rm as Dc,writeFile as Bs}from"node:fs/promises";import U from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="91604cb2-8afd-585e-9c18-26e223df25bc")}catch{}})();var Vh="https://schema.unbrained.dev/pm/workspace-snapshot/v1",pz=["create","list","inspect","restore","delete"],Hh=U.join("runtime","workspace-snapshots"),Sx=new Set(["checkpoints","locks","runtime","search","transactions"]),Ex=/^[a-z0-9][a-z0-9._-]*$/,Ei="sdk-workspace-transaction",Oc={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Yh={renameEntry:Bh,removeEntry:async e=>{await Dc(e,{recursive:!0,force:!0})}},Nc=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,i){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(i*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await Cn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==Ei||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await Ve(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
|
|
11
|
+
`)}};async function Xh(e,t=""){let n=await Lc(U.join(e,t),{withFileTypes:!0}),i=[];for(let r of n.sort((s,o)=>s.name.localeCompare(o.name))){if(t.length===0&&Sx.has(r.name))continue;let s=U.posix.join(t.replaceAll(U.sep,"/"),r.name);if(r.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${s}`);if(r.isDirectory())i.push(...await Xh(e,s));else if(r.isFile())i.push(s);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${s}`)}return i}async function Jh(e){let t=await Xh(e),n=Ti.createHash("sha256"),i=[],r=0;for(let o of t){let a=await Cn(U.join(e,o));i.push(a),r+=a.byteLength,n.update(o),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let s=n.digest("hex");return{manifest:{schema:Vh,fingerprint:s,files:t,bytes:r},contents:i}}function zh(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
|
|
12
|
+
`).filter(t=>t.trim().length>0).length}async function Tx(e,t){let n=new Map;for(let i=0;i<t.length;i+=32){let r=t.slice(i,i+32),s=await Promise.all(r.map(async o=>[o,await Cn(U.join(e,o))]));for(let[o,a]of s)n.set(o,a)}return n}function Mc(e){if(!Ex.test(e))throw new p("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",m.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Qh(e,t){return $n(`workspace_snapshot_${e}`,t,{codes:{capacity:Oc.capacity.code,permission:Oc.permission.code,resource:Oc.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function Bt(e){return U.join(e,Hh)}function Zh(e){return new p(`Unknown workspace snapshot: ${e}`,m.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function ey(e,t){try{return JSON.parse(await Cn(e,"utf8"))}catch(n){throw W(n)?Zh(t):n}}async function Wh(e,t,n){try{await Dc(e,{recursive:n})}catch(i){throw W(i)?Zh(t):i}}async function Ax(e,t,n=Yh){try{return await n.renameEntry(e,t),!1}catch(i){if(!(i instanceof Error&&"code"in i&&(i.code==="EEXIST"||i.code==="ENOTEMPTY")))throw i;return await n.removeEntry(e),!0}}async function Cx(e,t,n,i,r){await i.renameEntry(t,n);try{await i.renameEntry(e,t),await r?.()}catch(s){throw await i.renameEntry(n,t),await i.removeEntry(e),s}await i.removeEntry(n)}async function Ix(e,t){return Mc(t),/^[a-f0-9]{64}$/.test(t)?t:(await ey(U.join(Bt(e),"refs",`${t}.json`),t)).fingerprint}async function xx(e,t={}){if(t.name!==void 0&&(Mc(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new p("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",m.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:i}=await Jh(e),r=Bt(e),s=U.join(r,"objects",n.fingerprint),o=!1;try{o=(await kx(s)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&W(a)))throw a}if(!o){let a=U.join(r,"objects",`.create-${process.pid}-${Ti.randomUUID()}`);await Qh("create_object",async()=>{await Wt(U.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let l=U.join(a,"files",d);await Wt(U.dirname(l),{recursive:!0}),await Bs(l,i[c])}await Bs(U.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
|
|
13
|
+
`,"utf8"),await Wt(U.dirname(s),{recursive:!0})}),o=await Ax(a,s)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=U.join(r,"refs");await Wt(c,{recursive:!0});let d=U.join(c,`.ref-${process.pid}-${Ti.randomUUID()}`);await Bs(d,`${JSON.stringify(a,null,2)}
|
|
14
|
+
`,"utf8"),await Bh(d,U.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:o}}async function Pc(e,t){let n=await Ix(e,t),i=await ey(U.join(Bt(e),"objects",n,"manifest.json"),t);if(i.schema!==Vh||i.fingerprint!==n)throw new p(`Snapshot manifest identity mismatch: ${t}`,m.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return i}async function Rx(e){let t=Bt(e),n=await Lc(U.join(t,"objects")).catch(r=>{if(r instanceof Error&&"code"in r&&W(r))return[];throw r}),i=await Lc(U.join(t,"refs")).catch(r=>{if(r instanceof Error&&"code"in r&&W(r))return[];throw r});return{objects:await Promise.all(n.filter(r=>/^[a-f0-9]{64}$/.test(r)).sort().map(r=>Pc(e,r))),references:await Promise.all(i.filter(r=>r.endsWith(".json")).sort().map(async r=>JSON.parse(await Cn(U.join(t,"refs",r),"utf8"))))}}async function Ox(e,t){let n=await Pc(e,t),{manifest:i,contents:r}=await Jh(e),s=new Map(i.files.map((u,_)=>[u,r[_]])),o=await Tx(U.join(Bt(e),"objects",n.fingerprint,"files"),n.files),a=new Set(i.files),c=new Set(n.files),d=new Set([...a,...c]);for(let u of d){let _=s.get(u),f=o.get(u);_!==void 0&&f!==void 0&&_.equals(f)&&d.delete(u)}let l=i.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let _=zh(s.get(u)),f=zh(o.get(u));return{path:u,current_entries:_,target_entries:f,removed_entries:Math.max(0,_-f)}}).filter(u=>u.removed_entries>0).sort((u,_)=>u.path.localeCompare(_.path));return{target_fingerprint:n.fingerprint,current_fingerprint:i.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!a.has(u)).length,removed_item_count:[...a].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:l.length,removed_history_entry_count:l.reduce((u,_)=>u+_.removed_entries,0),affected_history_streams:l,changes_authoritative_state:i.fingerprint!==n.fingerprint}}async function Lx(e,t,n={}){if(n.force!==!0)throw new p("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",m.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let i=n.author?.trim()||"pm-sdk",r=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,o=await sn(e,Ei,r,i,!1,!1,s),a=new Nc(Vi(e,Ei),i,r);a.start(),await a.refreshNow();let c,d=!1,l=!1;try{let u=await Ox(e,t),_=await Pc(e,t),f=await xx(e),g=_.fingerprint,h=Bt(e),y=U.join(h,"objects",g,"files"),v=U.dirname(e),w=U.basename(e);c=U.join(v,`.${w}.restore-${Ti.randomUUID()}`);let S=U.join(v,`.${w}.backup-${Ti.randomUUID()}`);await Qh("restore_stage",async()=>{await Wt(c,{recursive:!0}),await Kh(y,c,{recursive:!0,force:!1}),await Wt(U.join(c,"runtime"),{recursive:!0}),await Kh(h,U.join(c,Hh),{recursive:!0,force:!1})});let E=await an({pmRoot:c,op:"workspace_snapshot_restore",author:i,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${f.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:f.manifest.fingerprint,changed_file_count:u.changed_file_count,removed_file_count:u.removed_file_count,removed_item_count:u.removed_item_count,affected_history_stream_count:u.affected_history_stream_count,removed_history_entry_count:u.removed_history_entry_count},lockTtlSeconds:r,lockWaitMs:s}),T=U.relative(c,E.historyPath).replaceAll("\\","/");await a.stop(),l=!0;let A=Vi(c,Ei);return await Wt(U.dirname(A),{recursive:!0}),await Bs(A,await Cn(Vi(e,Ei)),{flag:"wx"}),d=!0,await Cx(c,e,S,Yh,async()=>{a.start(),l=!1,await a.refreshNow()}),await a.stop(),l=!0,{manifest:_,plan:u,recovery_fingerprint:f.manifest.fingerprint,audit_history_path:T,audit_operation:"workspace_snapshot_restore"}}catch(u){throw c!==void 0&&!d&&await Promise.allSettled([Dc(c,{recursive:!0,force:!0})]),u}finally{try{l||await a.stop()}catch{}finally{await o()}}}async function fz(e,t){return(await Lx(e,t,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function gz(e,t){Mc(t);let n=Bt(e);if(!/^[a-f0-9]{64}$/.test(t))return await Wh(U.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:i}=await Rx(e);if(i.some(r=>r.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Wh(U.join(n,"objects",t),t,!0),{deleted:"object",target: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]="48abeea1-703c-57e9-9d99-787cb2829efb")}catch{}})();function ty(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function ny(e,t,n=process.platform){let i=["--pm-path",t];return e==="merge_evidence_invalid"?at([...i,"merge","report"],n):e==="history_evidence_invalid"?at([...i,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?at([...i,"merge","reconcile"],n):e==="history_repair_required"?at([...i,"history-repair","--all"],n):e==="merge_fence_unprepared"?at([...i,"merge","install"],n):null}function iy(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(i=>typeof i=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(i=>typeof i=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function xz(e){let t=x(process.cwd(),e.path);await P(t);let n=await I(t),i=$(n,M()),r=[],s=await ts({includeBody:!0,pmRoot:t,settings:n,typeToFolder:i.type_to_folder,warnings:r}),o=await wt(t),[a,c,d,l]=await Promise.all([Tr(t,Er(n)),o===null?Promise.resolve(null):ln(o),un(o??t,{includeLossless:!0,pmRoot:t}),ns(t,s,!1)]),{pendingDecisions:u,lossless:_}=mn(d.receipts),f=[...new Set(u.map(v=>v.item_id))].sort((v,w)=>v.localeCompare(w)),g=l.check.details,h=iy(g),y=ty({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:_.length,historyEvidenceValid:h.evidence_valid,driftedItemCount:h.drifted_item_count,fence:a,drivers:c});return{ok:y==="ready",state:y,merge_fence:{committed:a,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:f.slice(0,25),pending_item_ids_truncated:f.length>25,lossless_count:_.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:h,next_action:{command:ny(y,t),reason:y},warnings:[...new Set(r)].sort((v,w)=>v.localeCompare(w)),generated_at:R()}}function Rz(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
|
|
15
|
+
`)}var Oz={commandForWorkspacePositionState:ny,normalizeWorkspaceHistoryDrift:iy,selectWorkspacePositionState:ty};(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]="c6f4f9d1-e167-5a06-a1a1-a32d3b3f4d9f")}catch{}})();var Nx=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file, or from stdin when set to -.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),Dx=new Set(["--add","--body","--comment","--dep","--dep-remove","--description","--doc","--event","--field","--file","--learning","--note","--remove","--reminder","--test","--type-option"]),Mx=new Set(["append","comments","create","docs","files","learnings","notes","test","update","update-many"]),Px=new Set(["close-many:--ids","comments:--file","create:--body-file","history-compact:--ids","learnings:--file","notes:--file","update:--body-file","update-many:--ids"]),Fx=new Set(["close-many:--ids","history-compact:--ids","update-many:--ids"]),$x=["--allow-","--check-","--dry-run","--explain","--fail-","--fix-","--full","--has-","--include-","--json","--no-","--prune-","--quiet","--refresh-","--require-","--runtime-only","--schema-only","--skip-","--stream","--strict-","--summary","--today","--verbose"],Ux=new Set(["--activate","--active-only","--adopt","--adopt-all","--all","--all-actionable","--all-affected-ids","--all-day","--all-streams","--acknowledge-linked-tests","--append-stable","--auto-fix","--auto-pm-context","--availability-only","--background","--brief","--by-assignee","--by-priority","--by-tag","--catalog","--claim","--clear","--clear-comments","--clear-criteria","--clear-deps","--clear-docs","--clear-events","--clear-files","--clear-learnings","--clear-notes","--clear-reminders","--clear-tests","--clear-type-options","--cli-only","--closed","--compact","--completion","--count","--counts","--deactivate","--declarative","--defaults","--describe","--diff","--doctor","--empty-body","--explore","--field-utilization","--filter-empty-body","--flags-only","--follow","--force","--global","--highlight","--hybrid","--id-only","--if-available","--ignore-global","--include_unparented","--infer","--init","--install","--isolated","--lean","--list","--local","--manage","--markdown","--metadata-coverage","--next","--normalize-provenance","--only","--only-last","--output-row-contract","--override-linked-pm-context","--override-linked-workspace-context","--packages-only","--past","--phrase-exact","--profile","--progress","--project","--promote-to-item-dep","--provenance","--provenance-summary","--raw","--ready-only","--ready_only","--rebuild","--recent","--reload","--repair","--replace-deps","--replace-docs","--replace-files","--replace-tests","--required","--required-on-create","--run","--runtime-probe","--save-baseline","--scaffold","--semantic","--shared-host-safe","--storage","--title-exact","--token-accounting","--trace","--tree","--unbounded","--uninstall","--validate-paths","--verify","--watch","--with-packages"]),jx=new Set(["--only-index"]),Gx=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),qx=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),Kx=new Set(["--regression"]);function zx(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:Px.has(`${e}:${t}`)?["argv","file","stdin"]:t.endsWith("-file")?["argv","file"]:Dx.has(t)&&Mx.has(e)?["argv","stdin"]:["argv"]}function Wx(e,t){let n=Gx.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,i=t.value_type==="boolean"||t.flag==="--stdin"||t.flag==="--stdin-json"||t.flag.startsWith("--filter-")&&(t.flag.endsWith("-missing")||t.flag.startsWith("--filter-has-")||t.flag.startsWith("--filter-no-"))||$x.some(r=>t.flag.startsWith(r));return n||jx.has(t.flag)||!Ux.has(t.flag)&&!i}function Bx(e,t){let n=Ui(e),i=Wx(n,t),r=zx(n,t.flag),s=t.description??Nx[t.flag]??`${i?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:s,takes_value:i,value_required:i&&!Kx.has(t.flag)&&!qx.has(`${n}:${t.flag}`),...i?{value_name:t.value_name??"value"}:{},value_type:i?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:r,...r.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{},...Fx.has(`${n}:${t.flag}`)?{file_token_prefix:"@"}:{}}}function ry(e,t){return t.map(n=>Bx(e,n))}function Dz(e,t,n){let i=e.trim().toLowerCase(),r=[],s=new Map,o=0;for(let c of n)if(c.command.trim().toLowerCase()===i){if(o+=1,s.has(c.flag)){r.push({code:"duplicate_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} was observed more than once.`});continue}s.set(c.flag,c)}let a=new Set(t.map(({flag:c})=>c));for(let c of t){let d=s.get(c.flag);if(!d){r.push({code:"missing_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} has no executable option observation.`});continue}for(let[l,u]of[["takes_value","takes_value_mismatch"],["value_required","value_required_mismatch"],["repeatable","repeatable_mismatch"]])c[l]!==d[l]&&r.push({code:u,command:i,flag:c.flag,detail:`${i} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of s.values())a.has(c.flag)||r.push({code:"undeclared_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} is executable but absent from invocation contracts.`});return r.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:r.length===0,declared_count:t.length,observed_count:o,findings:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="235bac43-67ba-5fad-9ec2-e392aeb7feda")}catch{}})();var Vx=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate"]),Hx=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),Yx=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),Xx=new Set(["extension","install","package","packages","upgrade"]);function Jx(e){let t=B(e.trim().toLowerCase());if(t==="ops")return"quality";for(let[n,i]of Object.entries(Yx))if(i.has(t))return n;return Xx.has(t)?"extensions":"internal"}var In=Object.freeze([...Xe.flatMap(e=>e==="item"?["item","item-reopen"]:[e,...Be.filter(t=>t.alias===e).map(t=>t.canonical)]).map(e=>({command:e,tier:Vx.has(B(e))?"core":Hx.has(B(e))?"standard":"full",family:Jx(e)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]),Qx=In,sy=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),$z=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function Uz(e){let t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=sy.max_lines&&n<=sy.max_utf8_bytes}}var oy={core:0,standard:1,full:2,internal:3},ay=new Map(Qx.map(({command:e,tier:t})=>[e,t]));function Fc(e,t="standard"){return ay.get(e.trim().toLowerCase())??ay.get(B(e.trim().toLowerCase()))??t}function jz(e){return cy(e,In)}function cy(e,t){let n=oy[e];return t.filter(i=>i.tier!=="internal"&&oy[i.tier]<=n).map(i=>i.command)}function Gz(e){return dy(e,In)}function dy(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}var Zx=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],eR=new Set([...Dn.filter(e=>e.hidden).map(e=>e.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function qz(e=In){return Zx.map(t=>({family:t,commands:dy(t,e).filter(n=>e.find(i=>i.command===n)?.tier!=="internal"&&!eR.has(n))})).filter(({commands:t})=>t.length>0)}var tR=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function Kz(e,t){return nR(e,t,In)}function nR(e,t,n){if(t==="full")return[...e];let i=new Set(cy(t,n));return e.filter(r=>{let s=tR[r];return s!==void 0&&i.has(s)})}var zz=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),Wz=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function Bz(){return iR(In)}function iR(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:n,tier:i,family:r})=>`| \`${n}\` | ${i} | ${r} |`),""].join(`
|
|
16
|
+
`)}(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]="a2e77c4f-3899-518a-885f-ce5dd2090ac6")}catch{}})();var rR=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],sR=new Map(rR.map(e=>[e.exit_code,e.class]));function Vs(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function oR(e){if(!e)return[];let t=new Set,n=new Set;return e.map(i=>{let r=i.state.trim(),s=i.probe_id.trim(),o=Vs(i.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(r)||!/^[a-z][a-z0-9-]*$/.test(s)||o.length===0||t.has(r)||n.has(s))throw new TypeError("Invalid pm refusal state contract");return t.add(r),n.add(s),{state:r,probe_id:s,entrypoints:o,expected_exit_class:i.expected_exit_class}}).sort((i,r)=>i.state.localeCompare(r.state))}function aR(e,t,n,i,r){return![[1,2,3,4,5].includes(e.exit_code),e.meaning.trim().length>0,e.recovery.trim().length>0,t.length>0,n.length>0,/^[a-z][a-z0-9_]*$/.test(i),r.every(s=>/^[a-z][a-z0-9_]*$/.test(s)),sR.get(e.exit_code)===e.class].includes(!1)}function cR(e,t){let n=e,i=new Set;for(;n.canonical_code!==n.code;){if(i.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);i.add(n.code);let r=t.get(n.canonical_code);if(!r)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=r}return n}function dR(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let i=cR(n,t);if(i.exit_code!==n.exit_code||i.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let r=e.filter(s=>s.code!==i.code&&s.canonical_code===i.code).map(s=>s.code).sort();if(n.code===i.code?JSON.stringify(n.aliases)!==JSON.stringify(r):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function uy(e){let t=new Set,n=e.map(i=>{let r=i.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(r))throw new TypeError(`Invalid pm error code: ${JSON.stringify(i.code)}`);if(t.has(r))throw new TypeError(`Duplicate pm error code: ${r}`);t.add(r);let s=Vs(i.sources),o=Vs(i.emitting_commands),a=(i.canonical_code??r).trim(),c=Vs(i.aliases??[]),d=oR(i.owned_states);if(!aR(i,s,o,a,c))throw new TypeError(`Invalid pm error code contract: ${r}`);if(d.some(l=>l.expected_exit_class!==i.class))throw new TypeError(`Invalid pm refusal state exit class: ${r}`);return Object.freeze({...i,code:r,meaning:i.meaning.trim(),recovery:i.recovery.trim(),sources:s,emitting_commands:o,canonical_code:a,aliases:c,owned_states:d})});return dR(n),Object.freeze(n.sort((i,r)=>i.code.localeCompare(r.code)))}function Hz(e,t){let n=ly(e,t);return ly(n.canonical_code??n.code,t)}function ly(e,t){let n=e.trim(),i=t.find(r=>r.code===n);if(!i)throw new TypeError(`Unknown pm error code "${n}"`);return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ea8d1914-d35c-5fb6-a047-6f9e1aa9d22e")}catch{}})();var my=[{code:"acceptance_criteria_mutation_conflict",meaning:"Acceptance criteria mutation conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"],canonical_code:"acceptance_criteria_mutation_conflict",aliases:[]},{code:"acceptance_criteria_remove_unmatched",meaning:"Acceptance criteria remove unmatched condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"],canonical_code:"acceptance_criteria_remove_unmatched",aliases:[]},{code:"acceptance_criteria_semicolon_forbidden",meaning:"Acceptance criteria semicolon forbidden condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"],canonical_code:"acceptance_criteria_semicolon_forbidden",aliases:[]},{code:"accepted_rejected_value",meaning:"Accepted rejected value condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"accepted_rejected_value",aliases:[]},{code:"alias_collision",meaning:"Alias collision condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"alias_collision",aliases:[]},{code:"alias_target_missing",meaning:"Alias target missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"alias_target_missing",aliases:[]},{code:"already_claimed_by",meaning:"Already claimed by condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"],canonical_code:"already_claimed_by",aliases:[]},{code:"ambiguous_option_combination",meaning:"Ambiguous option combination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"ambiguous_option_combination",aliases:[]},{code:"annotation_alias_conflict",meaning:"Annotation alias conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_alias_conflict",aliases:[]},{code:"annotation_flag_like_value",meaning:"Annotation flag like value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_flag_like_value",aliases:[]},{code:"annotation_if_absent_without_append",meaning:"Annotation if absent without append condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_if_absent_without_append",aliases:[]},{code:"annotation_message_without_text",meaning:"Annotation message without text condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_message_without_text",aliases:[]},{code:"annotation_transposed_subcommand",meaning:"Annotation transposed subcommand condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_transposed_subcommand",aliases:[]},{code:"append_empty_body",meaning:"Append empty body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"],canonical_code:"append_empty_body",aliases:[]},{code:"assurance_registry_invalid",meaning:"Assurance registry invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/assurance.ts"],emitting_commands:["*"],canonical_code:"assurance_registry_invalid",aliases:[]},{code:"bare_comma_entry_ambiguous",meaning:"Bare comma entry ambiguous condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"],canonical_code:"bare_comma_entry_ambiguous",aliases:[]},{code:"body_file_conflicts_with_body",meaning:"Body file conflicts with body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_conflicts_with_body",aliases:[]},{code:"body_file_missing_path",meaning:"Body file missing path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_missing_path",aliases:[]},{code:"body_file_unreadable",meaning:"Body file unreadable condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_unreadable",aliases:[]},{code:"budget_exceeded",meaning:"Budget exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"budget_exceeded",aliases:[]},{code:"bulk_ids_input_empty",meaning:"Bulk ids input empty condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts","sdk/history-compact.ts","sdk/history-mcp.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_empty",aliases:[],owned_states:[{state:"bulk_ids_stdin_contains_no_nonempty_ids",probe_id:"bulk-ids-stdin-empty",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_missing_path",meaning:"Bulk ids input missing path condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_missing_path",aliases:[],owned_states:[{state:"bulk_ids_file_token_omits_its_path",probe_id:"bulk-ids-file-path-missing",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_unreadable",meaning:"Bulk ids input unreadable condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_unreadable",aliases:[],owned_states:[{state:"bulk_ids_file_path_cannot_be_read",probe_id:"bulk-ids-file-unreadable",entrypoints:["update-many"],expected_exit_class:"not_found"}]},{code:"bundle_integrity_torn_install",meaning:"Bundle integrity torn install condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/bundle-integrity.ts"],emitting_commands:["*"],canonical_code:"bundle_integrity_torn_install",aliases:[]},{code:"capability_undeclared",meaning:"Capability undeclared condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"capability_undeclared",aliases:[]},{code:"capability_unused",meaning:"Capability unused condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"capability_unused",aliases:[]},{code:"child_projection_item_bound_exceeded",meaning:"Child projection item bound exceeded condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-children.ts"],emitting_commands:["*"],canonical_code:"child_projection_item_bound_exceeded",aliases:[]},{code:"close_reason_required",meaning:"Close reason required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"],canonical_code:"close_reason_required",aliases:[]},{code:"close_through_update",meaning:"Close through update condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"close_through_update",aliases:[]},{code:"close_validation_missing_fields",meaning:"Close validation missing fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"close_validation_missing_fields",aliases:[]},{code:"collected_zero_items",meaning:"Collected zero items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"collected_zero_items",aliases:[]},{code:"collection_transposed_subcommand",meaning:"Collection transposed subcommand condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"collection_transposed_subcommand",aliases:[]},{code:"command_failed",meaning:"Command failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"command_failed",aliases:[]},{code:"command_namespace",meaning:"Command namespace condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"],canonical_code:"command_namespace",aliases:[]},{code:"command_override_conflict",meaning:"Command override conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"command_override_conflict",aliases:[]},{code:"config_duplicate",meaning:"Config duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_duplicate",aliases:[]},{code:"config_key_unknown",meaning:"Config key unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_key_unknown",aliases:[]},{code:"config_value_invalid",meaning:"Config value invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_value_invalid",aliases:[]},{code:"conflicting_lifecycle_owner",meaning:"Conflicting lifecycle owner condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-operations.ts"],emitting_commands:["*"],canonical_code:"conflicting_lifecycle_owner",aliases:[]},{code:"context_signal_store_invalid",meaning:"Context signal store invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_invalid",aliases:[]},{code:"context_signal_store_stale",meaning:"Context signal store stale condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_stale",aliases:[]},{code:"context_signal_store_write_failed",meaning:"Context signal store write failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_write_failed",aliases:[]},{code:"context_takes_no_item_argument",meaning:"Context takes no item argument condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"context_takes_no_item_argument",aliases:[]},{code:"core_item_field_requires_dedicated_flag",meaning:"Core item field requires dedicated flag condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"core_item_field_requires_dedicated_flag",aliases:[]},{code:"create_positional_type_without_title",meaning:"Create positional type without title condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts"],emitting_commands:["*"],canonical_code:"create_positional_type_without_title",aliases:[]},{code:"dependency_edge_not_allowed",meaning:"Dependency edge not allowed condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_edge_not_allowed",aliases:[]},{code:"dependency_flag_value_invalid",meaning:"Dependency flag value invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_flag_value_invalid",aliases:[]},{code:"dependency_remove_no_match",meaning:"Dependency remove no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"dependency_remove_no_match",aliases:[]},{code:"dependency_target_not_found",meaning:"Dependency target not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_target_not_found",aliases:[]},{code:"dependency_temporal_order_invalid",meaning:"Dependency temporal order invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_temporal_order_invalid",aliases:[]},{code:"duplicate_canonical_flag",meaning:"Duplicate canonical flag condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_canonical_flag",aliases:[]},{code:"duplicate_command",meaning:"Duplicate command condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"duplicate_command",aliases:[]},{code:"duplicate_destination",meaning:"Duplicate destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_destination",aliases:[]},{code:"duplicate_edge",meaning:"Duplicate edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"],canonical_code:"duplicate_edge",aliases:[]},{code:"duplicate_observation",meaning:"Duplicate observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_observation",aliases:[]},{code:"duplicate_probe",meaning:"Duplicate probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"duplicate_probe",aliases:[]},{code:"duplicate_sweep_cost_limit",meaning:"Duplicate sweep cost limit condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/duplicate-candidates.ts"],emitting_commands:["duplicate-candidates"],canonical_code:"duplicate_sweep_cost_limit",aliases:[]},{code:"duplicate_target_circular",meaning:"Duplicate target circular condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_circular",aliases:[]},{code:"duplicate_target_is_duplicate",meaning:"Duplicate target is duplicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_is_duplicate",aliases:[]},{code:"duplicate_target_missing",meaning:"Duplicate target missing condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_missing",aliases:[]},{code:"duplicate_target_self",meaning:"Duplicate target self condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_self",aliases:[]},{code:"empty_corpus",meaning:"Empty corpus condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"empty_corpus",aliases:[]},{code:"empty_surface",meaning:"Empty surface condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"empty_surface",aliases:[]},{code:"error_code_mismatch",meaning:"Error code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"error_code_mismatch",aliases:[]},{code:"event_cursor_query_mismatch",meaning:"Event cursor query mismatch condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"event_cursor_query_mismatch",aliases:[]},{code:"event_index_unavailable",meaning:"Event index unavailable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"event_index_unavailable",aliases:[]},{code:"exit_code_mismatch",meaning:"Exit code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"exit_code_mismatch",aliases:[]},{code:"extension_command_activation_failed",meaning:"Extension command activation failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/commander-usage.ts"],emitting_commands:["*"],canonical_code:"extension_command_activation_failed",aliases:[]},{code:"extension_dependency_name_unsafe",meaning:"Extension dependency name unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_name_unsafe",aliases:[]},{code:"extension_dependency_spec_invalid",meaning:"Extension dependency spec invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_spec_invalid",aliases:[]},{code:"extension_dependency_version_unsafe",meaning:"Extension dependency version unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_version_unsafe",aliases:[]},{code:"extension_install_soft_failed",meaning:"Extension install soft failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"],canonical_code:"extension_install_soft_failed",aliases:[]},{code:"extension_install_source_contains_destination",meaning:"Extension install source contains destination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_install_source_contains_destination",aliases:[]},{code:"extension_item_field_reserved",meaning:"Extension item field reserved condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_reserved",aliases:[]},{code:"extension_item_field_type_conflict",meaning:"Extension item field type conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_type_conflict",aliases:[]},{code:"extension_item_field_unknown",meaning:"Extension item field unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_unknown",aliases:[]},{code:"extension_mutation_guard_failed",meaning:"Extension mutation guard failed condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_failed",aliases:[]},{code:"extension_mutation_guard_invalid_decision",meaning:"Extension mutation guard invalid decision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_invalid_decision",aliases:[]},{code:"extension_mutation_guard_invalid_denial",meaning:"Extension mutation guard invalid denial condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_invalid_denial",aliases:[]},{code:"extension_mutation_guard_timed_out",meaning:"Extension mutation guard timed out condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_timed_out",aliases:[]},{code:"extension_update_health_partial_coverage",meaning:"Extension update health partial coverage condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"extension_update_health_partial_coverage",aliases:[]},{code:"field_duplicate",meaning:"Field duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_duplicate",aliases:[]},{code:"field_invalid",meaning:"Field invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_invalid",aliases:[]},{code:"field_mcp_input_collision",meaning:"Field mcp input collision condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_mcp_input_collision",aliases:[]},{code:"github_source_entry_unbuilt",meaning:"Github source entry unbuilt condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/shared.ts"],emitting_commands:["*"],canonical_code:"github_source_entry_unbuilt",aliases:[]},{code:"hierarchy_cardinality_created",meaning:"Hierarchy cardinality created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_cardinality_created",aliases:[]},{code:"hierarchy_cycle_created",meaning:"Hierarchy cycle created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_cycle_created",aliases:[]},{code:"hierarchy_parent_divergence_created",meaning:"Hierarchy parent divergence created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_parent_divergence_created",aliases:[]},{code:"history_author_acknowledge_plan_conflict",meaning:"History author acknowledge plan conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_plan_conflict",aliases:[]},{code:"history_author_acknowledge_plan_fingerprint_required",meaning:"History author acknowledge plan fingerprint required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_plan_fingerprint_required",aliases:[]},{code:"history_author_acknowledge_preview_limit_invalid",meaning:"History author acknowledge preview limit invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_preview_limit_invalid",aliases:[]},{code:"history_author_acknowledge_required_values_missing",meaning:"History author acknowledge required values missing condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_required_values_missing",aliases:[]},{code:"history_author_acknowledge_selector_conflict",meaning:"History author acknowledge selector conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_selector_conflict",aliases:[]},{code:"history_author_acknowledge_selector_required",meaning:"History author acknowledge selector required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_selector_required",aliases:[]},{code:"history_author_acknowledge_target_not_actionable",meaning:"History author acknowledge target not actionable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_target_not_actionable",aliases:[]},{code:"history_author_acknowledge_target_unreadable",meaning:"History author acknowledge target unreadable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_target_unreadable",aliases:[]},{code:"history_baseline_unavailable",meaning:"History baseline unavailable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_baseline_unavailable",aliases:[]},{code:"history_drift_chain_mismatch",meaning:"History drift chain mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_chain_mismatch",aliases:["validate_history_drift_chain_mismatches"]},{code:"history_drift_hash_mismatch",meaning:"History drift hash mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_hash_mismatch",aliases:["validate_history_drift_hash_mismatches"]},{code:"history_drift_merge_receipt",meaning:"History drift merge receipt condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_merge_receipt",aliases:[]},{code:"history_drift_missing_stream",meaning:"History drift missing stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_missing_stream",aliases:["validate_history_drift_missing_streams"]},{code:"history_drift_unreadable_stream",meaning:"History drift unreadable stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_unreadable_stream",aliases:["validate_history_drift_unreadable_streams"]},{code:"history_drift_version_skew",meaning:"History drift version skew condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_version_skew",aliases:["validate_history_drift_version_skews"]},{code:"history_json_invalid",meaning:"History json invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"],canonical_code:"history_json_invalid",aliases:[]},{code:"history_merge_conflict_markers_detected",meaning:"History merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"],canonical_code:"merge_conflict_markers_detected",aliases:[]},{code:"history_replay_invalid",meaning:"History replay invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts","core/history/tombstone.ts"],emitting_commands:["*"],canonical_code:"history_replay_invalid",aliases:[]},{code:"history_salvage_refused",meaning:"History salvage refused condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history/salvage.ts"],emitting_commands:["*"],canonical_code:"history_salvage_refused",aliases:[]},{code:"history_stream_over_compact_threshold",meaning:"History stream over compact threshold condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_stream_over_compact_threshold",aliases:[]},{code:"history_target_out_of_range",meaning:"History target out of range condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_target_out_of_range",aliases:[]},{code:"history_timestamp_invalid",meaning:"History timestamp invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/event-index.ts","core/history/history.ts"],emitting_commands:["*"],canonical_code:"history_timestamp_invalid",aliases:[]},{code:"history_unknown_author_events",meaning:"History unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_unknown_author_events",aliases:["validate_history_unknown_author_events"]},{code:"history_version_mapping_unavailable",meaning:"History version mapping unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/version-address.ts"],emitting_commands:["*"],canonical_code:"history_version_mapping_unavailable",aliases:[]},{code:"history_version_pruned",meaning:"History version pruned condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_version_pruned",aliases:[]},{code:"host_environment_capacity_fault",meaning:"Host environment capacity fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_capacity_fault",aliases:[]},{code:"host_environment_operation_invalid",meaning:"Host environment operation invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_operation_invalid",aliases:[]},{code:"host_environment_permission_fault",meaning:"Host environment permission fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_permission_fault",aliases:[]},{code:"host_environment_resource_fault",meaning:"Host environment resource fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_resource_fault",aliases:[]},{code:"improvement_metric_contract_conflict",meaning:"Improvement metric contract conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"improvement_metric_contract_conflict",aliases:[]},{code:"improvement_observation_conflict",meaning:"Improvement observation conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"improvement_observation_conflict",aliases:[]},{code:"incomplete_allowed_values",meaning:"Incomplete allowed values condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"incomplete_allowed_values",aliases:[]},{code:"inconsistent_concept_kind",meaning:"Inconsistent concept kind condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"inconsistent_concept_kind",aliases:[]},{code:"init_existing_settings_requires_force",meaning:"Init existing settings requires force condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_existing_settings_requires_force",aliases:[]},{code:"init_gitignore_unwritable",meaning:"Init gitignore unwritable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace.ts"],emitting_commands:["*"],canonical_code:"init_gitignore_unwritable",aliases:[]},{code:"init_id_prefix_conflict",meaning:"Init id prefix conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_id_prefix_conflict",aliases:[]},{code:"init_id_prefix_path_like",meaning:"Init id prefix path like condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_id_prefix_path_like",aliases:[]},{code:"integrity_history_conflict_marker",meaning:"Integrity history conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_conflict_marker",aliases:["validate_storage_history_conflict_markers"]},{code:"integrity_history_invalid_json",meaning:"Integrity history invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_invalid_json",aliases:[]},{code:"integrity_history_unreadable",meaning:"Integrity history unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_unreadable",aliases:[]},{code:"integrity_item_ahead_format_version",meaning:"Integrity item ahead format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_ahead_format_version",aliases:["validate_format_version_ahead_items"]},{code:"integrity_item_conflict_marker",meaning:"Integrity item conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_conflict_marker",aliases:[]},{code:"integrity_item_outdated_format_version",meaning:"Integrity item outdated format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_outdated_format_version",aliases:["validate_format_version_outdated_items"]},{code:"integrity_item_parse_failed",meaning:"Integrity item parse failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_parse_failed",aliases:[]},{code:"integrity_item_unreadable",meaning:"Integrity item unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_unreadable",aliases:[]},{code:"invalid_argument_value",meaning:"Invalid argument value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/governance/assurance-mutation-error.ts","sdk/lifecycle/create.ts"],emitting_commands:["*","create"],canonical_code:"invalid_argument_value",aliases:[]},{code:"invalid_command_usage",meaning:"Invalid command usage condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"invalid_command_usage",aliases:[]},{code:"invalid_event_cursor",meaning:"Invalid event cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_cursor",aliases:[]},{code:"invalid_event_cursor_mode",meaning:"Invalid event cursor mode condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-list-query.ts","sdk/mutation-events.ts","sdk/runtime-extended-actions.ts"],emitting_commands:["*"],canonical_code:"invalid_event_cursor_mode",aliases:[]},{code:"invalid_event_follow_interval",meaning:"Invalid event follow interval condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_follow_interval",aliases:[]},{code:"invalid_event_limit",meaning:"Invalid event limit condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_limit",aliases:[]},{code:"invalid_event_since",meaning:"Invalid event since condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_since",aliases:[]},{code:"invalid_history_analytics_limit",meaning:"Invalid history analytics limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_limit",aliases:[]},{code:"invalid_history_analytics_minimum_sample",meaning:"Invalid history analytics minimum sample condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_minimum_sample",aliases:[]},{code:"invalid_history_analytics_since",meaning:"Invalid history analytics since condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_since",aliases:[]},{code:"invalid_improvement_ledger",meaning:"Invalid improvement ledger condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger-validation.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_ledger",aliases:[]},{code:"invalid_improvement_metric",meaning:"Invalid improvement metric condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_metric",aliases:[]},{code:"invalid_improvement_observation",meaning:"Invalid improvement observation condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation",aliases:[]},{code:"invalid_improvement_observation_limit",meaning:"Invalid improvement observation limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation_limit",aliases:[]},{code:"invalid_improvement_observation_timestamp",meaning:"Invalid improvement observation timestamp condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation_timestamp",aliases:[]},{code:"invalid_provenance_predicate",meaning:"Invalid provenance predicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"],canonical_code:"invalid_provenance_predicate",aliases:[]},{code:"invalid_query_cursor",meaning:"Invalid query cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/pagination.ts"],emitting_commands:["*"],canonical_code:"invalid_query_cursor",aliases:[]},{code:"invalid_read_output_session",meaning:"Invalid read output session condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output-session.ts"],emitting_commands:["*"],canonical_code:"invalid_read_output_session",aliases:[]},{code:"invalid_reproducible_process_environment",meaning:"Invalid reproducible process environment condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/reproducibility/process.ts"],emitting_commands:["*"],canonical_code:"invalid_reproducible_process_environment",aliases:[]},{code:"invalid_workspace_snapshot_target",meaning:"Invalid workspace snapshot target condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"invalid_workspace_snapshot_target",aliases:[]},{code:"item_already_active",meaning:"Item already active condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"item_already_active",aliases:[]},{code:"item_deleted",meaning:"Item deleted condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/tombstone.ts"],emitting_commands:["*"],canonical_code:"item_deleted",aliases:[]},{code:"item_document_encoding_invalid",meaning:"Item document encoding invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"],canonical_code:"item_document_encoding_invalid",aliases:[]},{code:"item_document_invalid",meaning:"Item document invalid condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_document_invalid",aliases:[]},{code:"item_document_roundtrip_failed",meaning:"Item document roundtrip failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_document_roundtrip_failed",aliases:[]},{code:"item_id_collision",meaning:"Item id collision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"],canonical_code:"item_id_collision",aliases:[]},{code:"item_identity_ambiguous",meaning:"Item identity ambiguous condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"],canonical_code:"item_identity_ambiguous",aliases:[]},{code:"item_identity_conflict",meaning:"Item identity conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/three-way.ts"],emitting_commands:["*"],canonical_code:"item_identity_conflict",aliases:[]},{code:"item_identity_reserved",meaning:"Item identity reserved condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/history.ts"],emitting_commands:["*"],canonical_code:"item_identity_reserved",aliases:[]},{code:"item_not_found",meaning:"Item not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"item_not_found",aliases:[]},{code:"likely_duplicate",meaning:"Likely duplicate condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/similarity.ts"],emitting_commands:["*"],canonical_code:"likely_duplicate",aliases:[]},{code:"linked_artifact_mutation_conflict",meaning:"Linked artifact mutation conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/linked-artifacts.ts"],emitting_commands:["*"],canonical_code:"linked_artifact_mutation_conflict",aliases:[]},{code:"linked_test_remove_no_match",meaning:"Linked test remove no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"linked_test_remove_no_match",aliases:[]},{code:"linked_test_value_not_quoted",meaning:"Linked test value not quoted condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"linked_test_value_not_quoted",aliases:[]},{code:"list_source_incomplete",meaning:"List source incomplete condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/list.ts"],emitting_commands:["list"],canonical_code:"list_source_incomplete",aliases:[]},{code:"local_package_archive_unsafe",meaning:"Local package archive unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"local_package_archive_unsafe",aliases:[]},{code:"local_source_not_found_bare_name",meaning:"Local source not found bare name condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"local_source_not_found_bare_name",aliases:[]},{code:"lock_conflict",meaning:"Lock conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"lock_conflict",aliases:[]},{code:"locks_stale_count",meaning:"Locks stale count condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"locks_stale_count",aliases:[]},{code:"locks_unreadable",meaning:"Locks unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"locks_unreadable",aliases:[]},{code:"malformed_plan_step_evidence",meaning:"Malformed plan step evidence condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"malformed_plan_step_evidence",aliases:[]},{code:"manifest_capabilities_absent",meaning:"Manifest capabilities absent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"manifest_capabilities_absent",aliases:[]},{code:"manifest_unknown_key",meaning:"Manifest unknown key condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/manifest-schema.ts"],emitting_commands:["*"],canonical_code:"manifest_unknown_key",aliases:[],owned_states:[{state:"author_workspace_manifest_declares_an_unknown_top_level_key",probe_id:"author-manifest-unknown-key",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"mcp_annotation_file_unavailable",meaning:"Mcp annotation file unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/runtime-input.ts"],emitting_commands:["*"],canonical_code:"mcp_annotation_file_unavailable",aliases:[]},{code:"mcp_stdin_unavailable",meaning:"Mcp stdin unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"mcp_stdin_unavailable",aliases:[]},{code:"mcp_task_not_found_or_not_authorized",meaning:"Mcp task not found or not authorized condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mcp/tasks.ts"],emitting_commands:["*"],canonical_code:"mcp_task_not_found_or_not_authorized",aliases:[]},{code:"merge_conflict_markers_detected",meaning:"Merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"merge_conflict_markers_detected",aliases:["history_merge_conflict_markers_detected"]},{code:"merge_decisions_unreviewed",meaning:"Merge decisions unreviewed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_decisions_unreviewed",aliases:[]},{code:"merge_git_config_unwritable",meaning:"Merge git config unwritable condition.",stability:"stable",exit_code:5,class:"dependency_failed",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_git_config_unwritable",aliases:[]},{code:"merge_receipt_evidence_invalid",meaning:"Merge receipt evidence invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts","sdk/merge/reconcile.ts"],emitting_commands:["*"],canonical_code:"merge_receipt_evidence_invalid",aliases:[]},{code:"merge_receipt_history_reference_missing",meaning:"Merge receipt history reference missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_receipt_history_reference_missing",aliases:[]},{code:"merge_receipts_pending",meaning:"Merge receipts pending condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_receipts_pending",aliases:[]},{code:"merge_reconcile_receipt_evidence_untrusted",meaning:"Merge reconcile receipt evidence untrusted condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-repair.ts"],emitting_commands:["*"],canonical_code:"merge_reconcile_receipt_evidence_untrusted",aliases:[]},{code:"merge_root_not_found",meaning:"Merge root not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_root_not_found",aliases:[]}];(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]="fec88380-eb4c-5be0-93fa-87a444fd7825")}catch{}})();var _y=[{code:"missing_allowed_values",meaning:"Missing allowed values condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_allowed_values",aliases:[]},{code:"missing_budget",meaning:"Missing budget condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_budget",aliases:[]},{code:"missing_cli_flag",meaning:"Missing cli flag condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/tool-option-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_cli_flag",aliases:[]},{code:"missing_destination",meaning:"Missing destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_destination",aliases:[]},{code:"missing_directory",meaning:"Missing directory condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"missing_directory",aliases:[]},{code:"missing_init_recovery",meaning:"Missing init recovery condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_init_recovery",aliases:[]},{code:"missing_lifecycle_target",meaning:"Missing lifecycle target condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension.ts"],emitting_commands:["*"],canonical_code:"missing_lifecycle_target",aliases:[]},{code:"missing_observation",meaning:"Missing observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_observation",aliases:[]},{code:"missing_observed_signature",meaning:"Missing observed signature condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_observed_signature",aliases:[]},{code:"missing_parameter_alias",meaning:"Missing parameter alias condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/tool-option-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_parameter_alias",aliases:[]},{code:"missing_positive_execution_receipt",meaning:"Missing positive execution receipt condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"missing_positive_execution_receipt",aliases:[]},{code:"missing_probe",meaning:"Missing probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_probe",aliases:[]},{code:"missing_required_argument",meaning:"Missing required argument condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","cli/schema/registration.ts","core/telemetry/observability.ts","sdk/governance/assurance-action.ts","sdk/history-redact.ts","sdk/invocation-author.ts"],emitting_commands:["*"],canonical_code:"missing_required_argument",aliases:[]},{code:"missing_required_option",meaning:"Missing required option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"],canonical_code:"missing_required_option",aliases:[]},{code:"missing_suggested_retry",meaning:"Missing suggested retry condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_suggested_retry",aliases:[]},{code:"missing_suggested_retry_args",meaning:"Missing suggested retry args condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_suggested_retry_args",aliases:[]},{code:"module_import_failed",meaning:"Module import failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"module_import_failed",aliases:[]},{code:"multi_target_github_install_ambiguous",meaning:"Multi target github install ambiguous condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"],canonical_code:"multi_target_github_install_ambiguous",aliases:[]},{code:"mutation_author_required",meaning:"Mutation author required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"],canonical_code:"mutation_author_required",aliases:[]},{code:"mutation_secret_guard_blocked",meaning:"Mutation secret guard blocked condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"],canonical_code:"mutation_secret_guard_blocked",aliases:[]},{code:"no_matching_tests",meaning:"No matching tests condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_matching_tests",aliases:[]},{code:"no_projects_matched_filters",meaning:"No projects matched filters condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_projects_matched_filters",aliases:[]},{code:"no_test_files_found",meaning:"No test files found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_test_files_found",aliases:[]},{code:"no_tests_found",meaning:"No tests found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_tests_found",aliases:[]},{code:"no_update_fields",meaning:"No update fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"no_update_fields",aliases:[]},{code:"no_version_bounds_declared",meaning:"No version bounds declared condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/manifest-schema.ts"],emitting_commands:["*"],canonical_code:"no_version_bounds_declared",aliases:[],owned_states:[{state:"author_workspace_manifest_omits_canonical_pm_version_bounds",probe_id:"author-manifest-version-bounds-missing",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"non_refusal_exit",meaning:"Non refusal exit condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"non_refusal_exit",aliases:[]},{code:"npm_pack_json_shape_unsupported",meaning:"Npm pack json shape unsupported condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_pack_json_shape_unsupported",aliases:[]},{code:"npm_package_archive_missing",meaning:"Npm package archive missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_archive_missing",aliases:[]},{code:"npm_package_archive_unsafe",meaning:"Npm package archive unsafe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_archive_unsafe",aliases:[]},{code:"npm_package_not_found",meaning:"Npm package not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_not_found",aliases:[]},{code:"ownership_conflict",meaning:"Ownership conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"ownership_conflict",aliases:[]},{code:"ownership_dependency_bypass_restricted_options",meaning:"Ownership dependency bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"ownership_dependency_bypass_restricted_options",aliases:[]},{code:"ownership_metadata_bypass_restricted_options",meaning:"Ownership metadata bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"ownership_metadata_bypass_restricted_options",aliases:[]},{code:"package_spec_empty",meaning:"Package spec empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"package_spec_empty",aliases:[]},{code:"package_upgrade_modes_mutually_exclusive",meaning:"Package upgrade modes mutually exclusive condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/upgrade.ts"],emitting_commands:["*"],canonical_code:"package_upgrade_modes_mutually_exclusive",aliases:[]},{code:"positional_shape_budget_exceeded",meaning:"Positional shape budget exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"positional_shape_budget_exceeded",aliases:[]},{code:"positional_signature_mismatch",meaning:"Positional signature mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"positional_signature_mismatch",aliases:[]},{code:"profile_name_empty",meaning:"Profile name empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_name_empty",aliases:[]},{code:"profile_name_not_normalized",meaning:"Profile name not normalized condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_name_not_normalized",aliases:[]},{code:"profile_summary_empty",meaning:"Profile summary empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_summary_empty",aliases:[]},{code:"profile_title_empty",meaning:"Profile title empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_title_empty",aliases:[]},{code:"project_runtime_history_epoch_incompatible",meaning:"Project runtime history epoch incompatible condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_history_epoch_incompatible",aliases:[]},{code:"project_runtime_stale_mutation",meaning:"Project runtime stale mutation condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_stale_mutation",aliases:[]},{code:"project_runtime_stale_read",meaning:"Project runtime stale read condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_stale_read",aliases:[]},{code:"projection_options_mutually_exclusive",meaning:"Projection options mutually exclusive condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"],canonical_code:"projection_options_mutually_exclusive",aliases:[]},{code:"provenance_value_domain_invalid",meaning:"Provenance value domain invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"provenance_value_domain_invalid",aliases:[]},{code:"read_output_cursor_command_mismatch",meaning:"Read output cursor command mismatch condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_command_mismatch",aliases:[]},{code:"read_output_cursor_invalid",meaning:"Read output cursor invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_invalid",aliases:[]},{code:"read_output_cursor_stale",meaning:"Read output cursor stale condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_stale",aliases:[]},{code:"recovery_kind_mismatch",meaning:"Recovery kind mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"recovery_kind_mismatch",aliases:[]},{code:"redundant_edge",meaning:"Redundant edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"],canonical_code:"redundant_edge",aliases:[]},{code:"refusal_allowed_values_mismatch",meaning:"Refusal allowed values mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_allowed_values_mismatch",aliases:[]},{code:"refusal_error_code_mismatch",meaning:"Refusal error code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_error_code_mismatch",aliases:[]},{code:"refusal_exit_code_mismatch",meaning:"Refusal exit code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_exit_code_mismatch",aliases:[]},{code:"refusal_mutated_state",meaning:"Refusal mutated state condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_mutated_state",aliases:[]},{code:"refusal_probe_missing",meaning:"Refusal probe missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_probe_missing",aliases:[]},{code:"refusal_recovery_failed",meaning:"Refusal recovery failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_recovery_failed",aliases:[]},{code:"reindex_already_running",meaning:"Reindex already running condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/reindex.ts"],emitting_commands:["*"],canonical_code:"reindex_already_running",aliases:[]},{code:"removed_canonical_spelling",meaning:"Removed canonical spelling condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"removed_canonical_spelling",aliases:[]},{code:"removed_compatibility_spelling",meaning:"Removed compatibility spelling condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"removed_compatibility_spelling",aliases:[]},{code:"reopen_reason_required",meaning:"Reopen reason required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"],canonical_code:"reopen_reason_required",aliases:[]},{code:"reopen_receipt_missing",meaning:"Reopen receipt missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"reopen_receipt_missing",aliases:[]},{code:"reopen_target_status_invalid",meaning:"Reopen target status invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"],canonical_code:"reopen_target_status_invalid",aliases:[]},{code:"reported_zero_passes",meaning:"Reported zero passes condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"reported_zero_passes",aliases:[]},{code:"reported_zero_tests",meaning:"Reported zero tests condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"reported_zero_tests",aliases:[]},{code:"reserved_item_field",meaning:"Reserved item field condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"reserved_item_field",aliases:[]},{code:"retry_failed",meaning:"Retry failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"retry_failed",aliases:[]},{code:"schema_migration_input_required",meaning:"Schema migration input required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/migration-gates.ts"],emitting_commands:["*"],canonical_code:"schema_migration_input_required",aliases:[]},{code:"semantic_spelling_collision",meaning:"Semantic spelling collision condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"semantic_spelling_collision",aliases:[]},{code:"settings_read_fs_error",meaning:"Settings read fs error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_fs_error",aliases:[]},{code:"settings_read_invalid_json",meaning:"Settings read invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_invalid_json",aliases:[]},{code:"settings_read_invalid_schema",meaning:"Settings read invalid schema condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_invalid_schema",aliases:[]},{code:"settings_read_merge_failed",meaning:"Settings read merge failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_merge_failed",aliases:[]},{code:"stale_budget",meaning:"Stale budget condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_budget",aliases:[]},{code:"stale_destination",meaning:"Stale destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_destination",aliases:[]},{code:"stale_observed_signature",meaning:"Stale observed signature condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_observed_signature",aliases:[]},{code:"status_duplicate",meaning:"Status duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"status_duplicate",aliases:[]},{code:"status_invalid",meaning:"Status invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"status_invalid",aliases:[]},{code:"status_lifecycle_role_required",meaning:"Status lifecycle role required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"status_lifecycle_role_required",aliases:[]},{code:"stdin_json_invalid",meaning:"Stdin json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"stdin_json_invalid",aliases:[]},{code:"stdin_json_unknown_key",meaning:"Stdin json unknown key condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"stdin_json_unknown_key",aliases:[]},{code:"structured_event_immutable",meaning:"Structured event immutable condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"structured_event_immutable",aliases:[]},{code:"structured_event_input_conflict",meaning:"Structured event input conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_input_conflict",aliases:[]},{code:"structured_event_json_empty",meaning:"Structured event json empty condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_json_empty",aliases:[]},{code:"structured_event_json_invalid",meaning:"Structured event json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_json_invalid",aliases:[]},{code:"structured_event_since_invalid",meaning:"Structured event since invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_since_invalid",aliases:[]},{code:"suggested_retry_args_mismatch",meaning:"Suggested retry args mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"suggested_retry_args_mismatch",aliases:[]},{code:"telemetry_endpoint_probe_failed",meaning:"Telemetry endpoint probe failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_endpoint_probe_failed",aliases:[]},{code:"telemetry_endpoint_probe_http_status",meaning:"Telemetry endpoint probe http status condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_endpoint_probe_http_status",aliases:[]},{code:"telemetry_otel_export_failing",meaning:"Telemetry otel export failing condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_otel_export_failing",aliases:[]},{code:"telemetry_queue_high_retries",meaning:"Telemetry queue high retries condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_high_retries",aliases:[]},{code:"telemetry_queue_invalid_rows",meaning:"Telemetry queue invalid rows condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_invalid_rows",aliases:[]},{code:"telemetry_queue_pending",meaning:"Telemetry queue pending condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_pending",aliases:[]},{code:"telemetry_schema_version_behind",meaning:"Telemetry schema version behind condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_schema_version_behind",aliases:[]},{code:"telemetry_state_invalid_json",meaning:"Telemetry state invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_state_invalid_json",aliases:[]},{code:"template_type_unknown",meaning:"Template type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"template_type_unknown",aliases:[]},{code:"terminal_plan_mutation",meaning:"Terminal plan mutation condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"terminal_plan_mutation",aliases:[]},{code:"terminal_state_conflict",meaning:"Terminal state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"terminal_state_conflict",aliases:[]},{code:"tracked_runtime_cache_files",meaning:"Tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"tracked_runtime_cache_files",aliases:["validate_storage_tracked_runtime_cache_files"]},{code:"tracker_not_initialized",meaning:"Tracker not initialized condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/store/tracker-preflight.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"tracker_not_initialized",aliases:[],owned_states:[{state:"selected_tracker_root_exists_without_settings",probe_id:"tracker-root-settings-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_missing",meaning:"Tracker root missing condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_missing",aliases:[],owned_states:[{state:"selected_tracker_root_does_not_exist",probe_id:"tracker-root-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_not_directory",meaning:"Tracker root not directory condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_not_directory",aliases:[],owned_states:[{state:"selected_tracker_root_is_a_regular_file",probe_id:"tracker-root-not-directory",entrypoints:["list"],expected_exit_class:"usage"}]},{code:"tracker_root_unreadable",meaning:"Tracker root unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_unreadable",aliases:[],owned_states:[{state:"selected_tracker_root_is_not_readable",probe_id:"tracker-root-unreadable",entrypoints:["list"],expected_exit_class:"generic_failure"}]},{code:"type_duplicate",meaning:"Type duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"type_duplicate",aliases:[]},{code:"type_invalid",meaning:"Type invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"type_invalid",aliases:[]},{code:"undeclared_observation",meaning:"Undeclared observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"undeclared_observation",aliases:[]},{code:"unexpected_refusal_probe",meaning:"Unexpected refusal probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"unexpected_refusal_probe",aliases:[]},{code:"unknown_command",meaning:"Unknown command condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_command",aliases:[]},{code:"unknown_context_intent",meaning:"Unknown context intent condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-intent-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_context_intent",aliases:[]},{code:"unknown_error",meaning:"Unknown error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"unknown_error",aliases:[]},{code:"unknown_field",meaning:"Unknown field condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_field",aliases:[]},{code:"unknown_field_projection",meaning:"Unknown field projection condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"],canonical_code:"unknown_field_projection",aliases:[]},{code:"unknown_item_type",meaning:"Unknown item type condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_item_type",aliases:[]},{code:"unknown_lifecycle_action",meaning:"Unknown lifecycle action condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/subcommand-recovery.ts"],emitting_commands:["*"],canonical_code:"unknown_subcommand",aliases:[]},{code:"unknown_noun",meaning:"Unknown noun condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_noun",aliases:[]},{code:"unknown_option",meaning:"Unknown option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"unknown_option",aliases:[],owned_states:[{state:"declared_option_is_rejected_on_the_selected_command_path",probe_id:"cross-command-unknown-option",entrypoints:["deps"],expected_exit_class:"usage"}]},{code:"unknown_plan_template",meaning:"Unknown plan template condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"unknown_plan_template",aliases:[]},{code:"unknown_provenance_dimension",meaning:"Unknown provenance dimension condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"],canonical_code:"unknown_provenance_dimension",aliases:[]},{code:"unknown_status",meaning:"Unknown status condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_status",aliases:[]},{code:"unknown_subcommand",meaning:"Unknown subcommand condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","sdk/agent/subcommand-recovery.ts"],emitting_commands:["*"],canonical_code:"unknown_subcommand",aliases:["unknown_lifecycle_action"],owned_states:[{state:"config_action_token_is_not_declared",probe_id:"config-unknown-action",entrypoints:["config"],expected_exit_class:"usage"},{state:"graph_command_token_is_not_declared",probe_id:"graph-unknown-subcommand",entrypoints:["graph"],expected_exit_class:"usage"},{state:"nested_command_token_is_not_declared_by_its_family",probe_id:"schema-unknown-subcommand",entrypoints:["schema"],expected_exit_class:"usage"},{state:"package_lifecycle_token_is_not_declared",probe_id:"package-unknown-action",entrypoints:["package"],expected_exit_class:"usage"}]},{code:"unsafe_init_recovery",meaning:"Unsafe init recovery condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"unsafe_init_recovery",aliases:[]},{code:"unsupported_update_option",meaning:"Unsupported update option condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"unsupported_update_option",aliases:[]},{code:"validate_command_references_stale_pm_ids",meaning:"Validate command references stale pm ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_command_references_stale_pm_ids",aliases:[]},{code:"validate_files_missing_linked_paths",meaning:"Validate files missing linked paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_missing_linked_paths",aliases:[]},{code:"validate_files_orphaned_paths",meaning:"Validate files orphaned paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_orphaned_paths",aliases:[]},{code:"validate_files_tracked_all_strict_forces_pm_internals",meaning:"Validate files tracked all strict forces pm internals condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_tracked_all_strict_forces_pm_internals",aliases:[]},{code:"validate_format_version_ahead_items",meaning:"Validate format version ahead items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_ahead_format_version",aliases:[]},{code:"validate_format_version_outdated_items",meaning:"Validate format version outdated items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_outdated_format_version",aliases:[]},{code:"validate_hierarchy_parent_cycle",meaning:"Validate hierarchy parent cycle condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_hierarchy_parent_cycle",aliases:[]},{code:"validate_hierarchy_parent_cycle_error",meaning:"Validate hierarchy parent cycle error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_hierarchy_parent_cycle_error",aliases:[]},{code:"validate_history_drift_chain_mismatches",meaning:"Validate history drift chain mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_chain_mismatch",aliases:[]},{code:"validate_history_drift_hash_mismatches",meaning:"Validate history drift hash mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_hash_mismatch",aliases:[]},{code:"validate_history_drift_missing_streams",meaning:"Validate history drift missing streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_missing_stream",aliases:[]},{code:"validate_history_drift_unreadable_streams",meaning:"Validate history drift unreadable streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_unreadable_stream",aliases:[]},{code:"validate_history_drift_version_skews",meaning:"Validate history drift version skews condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_version_skew",aliases:[]},{code:"validate_history_unknown_author_events",meaning:"Validate history unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_unknown_author_events",aliases:[]},{code:"validate_lifecycle_active_closure_like_metadata",meaning:"Validate lifecycle active closure like metadata condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_active_closure_like_metadata",aliases:[]},{code:"validate_lifecycle_active_terminal_parent",meaning:"Validate lifecycle active terminal parent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_active_terminal_parent",aliases:[]},{code:"validate_lifecycle_dependency_cycles",meaning:"Validate lifecycle dependency cycles condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_dependency_cycles",aliases:[]},{code:"validate_lifecycle_dependency_cycles_error",meaning:"Validate lifecycle dependency cycles error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_dependency_cycles_error",aliases:[]},{code:"validate_lifecycle_stale_blockers",meaning:"Validate lifecycle stale blockers condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_stale_blockers",aliases:[]},{code:"validate_merge_decisions_unreviewed",meaning:"Validate merge decisions unreviewed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_decisions_unreviewed",aliases:[]},{code:"validate_merge_fence_drift",meaning:"Validate merge fence drift condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_fence_drift",aliases:[]},{code:"validate_metadata_custom_profile_missing_required_fields",meaning:"Validate metadata custom profile missing required fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_custom_profile_missing_required_fields",aliases:[]},{code:"validate_metadata_duplicate_issue_codes",meaning:"Validate metadata duplicate issue codes condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_duplicate_issue_codes",aliases:[]},{code:"validate_metadata_missing_acceptance_criteria",meaning:"Validate metadata missing acceptance criteria condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_acceptance_criteria",aliases:[]},{code:"validate_metadata_missing_close_reason",meaning:"Validate metadata missing close reason condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_close_reason",aliases:[]},{code:"validate_metadata_missing_confidence",meaning:"Validate metadata missing confidence condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_confidence",aliases:[]},{code:"validate_metadata_missing_estimate",meaning:"Validate metadata missing estimate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_estimate",aliases:[]},{code:"validate_metadata_missing_release",meaning:"Validate metadata missing release condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_release",aliases:[]},{code:"validate_metadata_missing_reviewer",meaning:"Validate metadata missing reviewer condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_reviewer",aliases:[]},{code:"validate_metadata_missing_risk",meaning:"Validate metadata missing risk condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_risk",aliases:[]},{code:"validate_metadata_missing_sprint",meaning:"Validate metadata missing sprint condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_sprint",aliases:[]},{code:"validate_resolution_missing_fields",meaning:"Validate resolution missing fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_resolution_missing_fields",aliases:[]},{code:"validate_storage_duplicate_item_ids",meaning:"Validate storage duplicate item ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_duplicate_item_ids",aliases:[]},{code:"validate_storage_history_conflict_markers",meaning:"Validate storage history conflict markers condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_conflict_marker",aliases:[]},{code:"validate_storage_resurrected_items",meaning:"Validate storage resurrected items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_resurrected_items",aliases:[]},{code:"validate_storage_tracked_runtime_cache_files",meaning:"Validate storage tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"tracked_runtime_cache_files",aliases:[]},{code:"validate_storage_unparseable_config",meaning:"Validate storage unparseable config condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unparseable_config",aliases:[]},{code:"validate_storage_unparseable_history",meaning:"Validate storage unparseable history condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unparseable_history",aliases:[]},{code:"validate_storage_unreadable_items",meaning:"Validate storage unreadable items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unreadable_items",aliases:[]},{code:"vectorization_embedding_identity_changed",meaning:"Vectorization embedding identity changed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"vectorization_embedding_identity_changed",aliases:[]},{code:"vectorization_stale_items_remaining",meaning:"Vectorization stale items remaining condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"vectorization_stale_items_remaining",aliases:[]},{code:"visible_surface_ceiling_exceeded",meaning:"Visible surface ceiling exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"visible_surface_ceiling_exceeded",aliases:[]},{code:"workflow_duplicate_type",meaning:"Workflow duplicate type condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_duplicate_type",aliases:[]},{code:"workflow_policy_approval_history_invalid",meaning:"Workflow policy approval history invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_approval_history_invalid",aliases:[]},{code:"workflow_policy_audit_failed",meaning:"Workflow policy audit failed condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_audit_failed",aliases:[]},{code:"workflow_policy_input_unreadable",meaning:"Workflow policy input unreadable condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_input_unreadable",aliases:[]},{code:"workflow_policy_invalid",meaning:"Workflow policy invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_invalid",aliases:[]},{code:"workflow_policy_refused",meaning:"Workflow policy refused condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_refused",aliases:[]},{code:"workflow_policy_registry_invalid",meaning:"Workflow policy registry invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_registry_invalid",aliases:[]},{code:"workflow_status_unknown",meaning:"Workflow status unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_status_unknown",aliases:[]},{code:"workflow_transition_malformed",meaning:"Workflow transition malformed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_transition_malformed",aliases:[]},{code:"workflow_type_empty",meaning:"Workflow type empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_type_empty",aliases:[]},{code:"workflow_type_unknown",meaning:"Workflow type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_type_unknown",aliases:[]},{code:"workspace_history_chain_invalid",meaning:"Workspace history chain invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"],canonical_code:"workspace_history_chain_invalid",aliases:[]},{code:"workspace_history_state_conflict",meaning:"Workspace history state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"],canonical_code:"workspace_history_state_conflict",aliases:[]},{code:"workspace_root_pm_path",meaning:"Workspace root pm path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"workspace_root_pm_path",aliases:[]},{code:"workspace_snapshot_force_required",meaning:"Workspace snapshot force required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_force_required",aliases:[]},{code:"workspace_snapshot_manifest_mismatch",meaning:"Workspace snapshot manifest mismatch condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_manifest_mismatch",aliases:[]},{code:"workspace_snapshot_name_reserved_fingerprint",meaning:"Workspace snapshot name reserved fingerprint condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_name_reserved_fingerprint",aliases:[]},{code:"workspace_snapshot_not_found",meaning:"Workspace snapshot not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_not_found",aliases:[]},{code:"workspace_snapshot_permission_denied",meaning:"Workspace snapshot permission denied condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_permission_denied",aliases:[]},{code:"workspace_snapshot_resource_exhausted",meaning:"Workspace snapshot resource exhausted condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_resource_exhausted",aliases:[]},{code:"workspace_snapshot_storage_exhausted",meaning:"Workspace snapshot storage exhausted condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_storage_exhausted",aliases:[]},{code:"wrong_item_type",meaning:"Wrong item type condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"wrong_item_type",aliases:[]}];(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]="70a7dc18-ab34-5e17-83eb-f5fac0b7fdd9")}catch{}})();var py=uy([...my,..._y]);(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]="49e76519-d1f8-58ef-818f-927c563aa006")}catch{}})();var lR=["mutation_receipt","entity","collection","diagnostic","stream"],uR=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),mR=new Set(["close-many","update-many"]),_R=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),pR=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function Ai(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!lR.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function fy(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return mR.has(n)?Ai({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):uR.has(n)?Ai({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):_R.has(n)?Ai({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):pR.has(n)?Ai({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):Ai({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var fR=Xe.map(e=>fy(e)),gR=new Map(fR.map(e=>[e.command,e]));function gy(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=Ui(t).split(" "),i=gR.get(n);return i?{...i,command:t}:fy(t)}function hR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yR(e){return hR(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function r2(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!yR(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}(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]="1979adcd-4a7f-5dc7-b5dd-6bfc15eed1af")}catch{}})();var vR=Wo("list").properties.outputSession,wR={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...vR},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},hy={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},yy={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},oe={type:"string",description:"pm item id, for example pm-abc1."},bR=`Operation name (one of): ${Io.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,kR={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},SR={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function j(e,t=[]){return{...yy,properties:{...yy.properties,...e},required:t}}var ER=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:j({action:{type:"string",enum:[...Io],description:bR},id:oe,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...wR},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:j({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:j({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:j({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:j({query:{type:"string"},options:{type:"object"},...SR},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:j({options:{type:"object"},...kR})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:j({id:oe,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:j({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:j({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:j({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:oe,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:j({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:j({id:oe,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:j({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:j({id:oe,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:j({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:j({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:j({id:oe,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:j({subcommand:{type:"string",enum:[...Ol]},id:oe,target:oe,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:j({id:oe,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:j({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:j({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:j({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:j({...hy,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...El],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...wo]},description:`Lifecycle roles for add-status: ${wo.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:hy}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:j({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:j({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:j({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],TR={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},AR=ER.map(e=>{let t=TR[e.name];if(!t)return e;let n=e.inputSchema.properties,i=e.inputSchema.required.map(String);return{...e,inputSchema:Wo(t,{properties:n,required:i})}});function vy(){return AR.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(i=>String(i)).sort((i,r)=>i.localeCompare(r)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(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]="67c51368-f551-5951-b934-6781e38c69ad")}catch{}})();var wy=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),CR=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Ry=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Ys=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),Ci=new Set(["search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),Oy=new Map([["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),Ly=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),Ny=new Map([...Ly.entries()].flatMap(([e,t])=>pt(t).map(n=>[n,e]))),Dy=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],jc=new Map(Dy.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),IR=10,xR=20,by=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),My=[["init",Ju],["install",Zu],["uninstall",em],["explore",tm],["manage",am],["describe",nm],["reload",cm],["doctor",dm],["catalog",lm],["adopt",um],["adopt-all",im],["activate",rm],["deactivate",sm],["migrate",om]],RR=[...My.map(([e,t])=>e==="init"?[e,Qu]:[e,t]),["upgrade",Go]],OR=[...My.map(([e,t])=>[`extension ${e}`,t]),...RR.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Hu],["config",Yu],["extension",Xu],["package",jo],["packages",jo],["install",mm],["create",Dm],["item mutate",Mm],["item complete",Pm],["item reopen",Fm],["copy",$m],["focus",Um],["update",jm],["update-many",Gm],["upgrade",Go],["calendar",qo],["cal",qo],["context",Ko],["ctx",Ko],["get",zm],["search",Xm],["eval",Hm],["events",Km],["workspace",vt],["workspace position",[]],["workspace snapshot",vt],["workspace snapshot create",vt],["workspace snapshot list",vt],["workspace snapshot inspect",vt],["workspace snapshot restore",vt],["workspace snapshot delete",vt],["next",Ym],["aggregate",Lu],["deps",Bm],["graph",Vm],["guide",Wm],["reindex",_m],["history",$u],["history-compact",Ku],["history-attest",zu],["history-redact",ju],["history-repair",Gu],["history-author-acknowledge",qu],["merge",Uu],["schema",Wu],["profile",Bu],["plan",Vu],["restore",ym],["delete",vm],["close",pm],["close-many",fm],["append",gm],["claim",hm],["release",wm],["start-task",bm],["pause-task",km],["close-task",Sm],["comments",Nu],["notes",Du],["learnings",Mu],["files",Pu],["docs",Fu],["test",Em],["test-runs-worker",[]],["test-all",Tm],["telemetry",Am],["test-runs",Cm],["gc",Im],["stats",xm],["ops",[]],["duplicates",Rm],["validate",Lm],["health",Om],["assurance",Nm],...Zm,["contracts",Jm],["completion",Qm],["activity",qm],...[...Ry].map(e=>[e,Ou])],Ii=new Map(OR);for(let{alias:e,canonical:t}of Be){let n=Ii.get(e);n!==void 0&&Ii.set(t,n)}function LR(e){let t=Ny.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function ky(e){let t=Be.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Xe.includes(e)?ve(e):e.startsWith("extension-")?ve(`extension ${e.slice(10)}`):e.startsWith("package-")?ve(`package ${e.slice(8)}`):e.startsWith("item-")?ve(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ve(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ve(`templates ${e.slice(10)}`):Ys.has(e)?Ly.get(e)??ve(e):null}function NR(e,t){let n=B(t);return n!==t||Be.some(i=>i.alias===t)?e.action===n:e.command_path===null?!1:pt(e.command_path).some(i=>i===t?!0:i.startsWith(`${t} `)||t.startsWith(`${i} `))}function pt(e){return e.split("|").map(t=>ve(t)).filter(t=>t.length>0)}function DR(e,t){let n=new Set(t),i=new Set;for(let r of e)if(r.command_path)for(let s of pt(r.command_path)){let o=s.split(" ").filter(a=>a.length>0);if(o.length!==0)for(let a=o.length;a>0;a-=1){let c=o.slice(0,a).join(" ");if(n.has(c)){i.add(c);break}}}return[...i].sort((r,s)=>r.localeCompare(s))}function Hs(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function xi(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function MR(e,t){if(!t)return{...e};let i=xi(e).filter(r=>{let s=r.properties;if(typeof s!="object"||s===null)return!1;let o=s.action;return typeof o!="object"||o===null?!1:o.const===t});return{...e,oneOf:i}}function $c(e,t){let i=xi(e).filter(r=>{let s=r.properties;if(typeof s!="object"||s===null)return!1;let o=s.action;if(typeof o!="object"||o===null)return!1;let a=o.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:i}}function ve(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Py(e){return e.replace(/\s+/g,"-")}function tt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Sy(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let i of e){let r=tt(i);!r||n.has(r)||(n.add(r),t.push(r))}return t}function Uc(e,t,n){n&&(e[t]=!0)}function Ey(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function PR(e){let t=Ey(e.long,"long"),n=Ey(e.short,"short"),i=t??n;if(!i)return null;let r={flag:i};n&&t&&(r.short=n),Uc(r,"required",e.required===!0),Uc(r,"repeatable",e.repeatable===!0),Uc(r,"list",e.list===!0);let s=tt(e.description);s&&(r.description=s);let o=tt(e.value_name);o&&(r.value_name=o);let a=[tt(e.value_type),tt(e.type),o?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(r.value_type=a),r}function Fy(e){let t=new Map;for(let i of e){let r=ve(i.target_command);if(r.length===0)continue;let s=t.get(r)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},o=`${i.layer}:${i.name}`;s.sourceDedupe.has(o)||(s.sourceDedupe.add(o),s.sources.push({layer:i.layer,name:i.name}));for(let a of i.flags){let c=PR(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;s.dedupe.has(d)||(s.dedupe.add(d),s.flags.push(c))}t.set(r,s)}let n=new Map;for(let[i,r]of t.entries())n.set(i,{flags:r.flags,sources:r.sources.sort((s,o)=>{let a=s.layer.localeCompare(o.layer);return a!==0?a:(s.name??"").localeCompare(o.name??"")})});return n}function FR(e){let t=Fy(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let o=ve(s.command);if(o.length===0)continue;let a=tt(s.action)??Py(o),c=Array.isArray(s.arguments)?s.arguments.map(d=>{let l=tt(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:tt(d.description)}:null}).filter(d=>d!==null):[];n.set(o,{...s.tier===void 0?{}:{tier:s.tier},command:o,action:a,source:{layer:s.layer,name:s.name},description:tt(s.description),intent:tt(s.intent),arguments:c,flags:t.get(o)?.flags??[],examples:Sy(s.examples),failure_hints:Sy(s.failure_hints)})}let i=new Set;for(let s of e.handlers)i.add(ve(s));for(let s of n.keys())i.add(s);for(let s of t.keys())i.add(s);let r=[];for(let s of[...i].sort((o,a)=>o.localeCompare(a))){let o=n.get(s);r.push($R(s,o,t.get(s)?.flags??[]))}return r}function $R(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Py(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function UR(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let i=t.replace(/-([a-z0-9])/g,(r,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return i.length>0?i:null}function jR(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function GR(e,t){let n=e.value_type??"boolean",i=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",r=e.repeatable===!0||e.list===!0;return{type:r?"array":i,...r?{items:{type:i}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function qR(e){let t=e.command.split("|").map(r=>r.trim()).filter(r=>r.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},i=["action"];for(let r of e.arguments)n[r.name]=jR(r,e.action),r.required&&i.push(r.name);for(let r of e.flags){let s=UR(r);!s||n[s]!==void 0||(n[s]=GR(r,e.action),r.required===!0&&i.push(s))}return{type:"object",properties:n,required:i,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function KR(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function zR(e){let t=new Map;for(let n of e){let i=t.get(n.action);if(!i){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}i.command=[...new Set([i.command,n.command])].sort((s,o)=>s.localeCompare(o)).join("|"),i.arguments=i.arguments.length>=n.arguments.length?i.arguments:n.arguments;let r=new Set(i.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let o=`${s.flag}|${s.short??""}`;if(!r.has(o))r.add(o),i.flags.push(s);else{let a=i.flags.find(c=>`${c.flag}|${c.short??""}`===o);a&&KR(a,s)}}i.examples=[...new Set([...i.examples,...n.examples])],i.failure_hints=[...new Set([...i.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,i)=>n.action.localeCompare(i.action))}async function WR(e,t=I){let n={mode:Ct.extensions.policy.mode,trust_mode:Ct.extensions.policy.trust_mode,default_sandbox_profile:Ct.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let i=x(process.cwd(),e.path);if(!await Z(Te(i)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let r=await t(i),s=await Hi({pmRoot:i,settings:r,cwd:process.cwd(),noExtensions:!1}),o=await Yi({...s,loaded:s.loaded});return{handlers:new Set(o.commands.handlers.map(c=>ve(c.command))),disabledReason:null,commandDefinitions:o.registrations.commands,flagRegistrations:o.registrations.flags,registrations:o.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function BR(e,t={}){let n=new Map;for(let i of Ll){let r=Ys.has(i);if(r&&!t.includePackageOwnedActions)continue;let s=ky(i);n.set(i,{action:i,provider:r?"extension":"core",requires_extension:r,command_path:s})}if(t.includePackageOwnedActions)for(let i of Ys)n.has(i)||n.set(i,{action:i,provider:"extension",requires_extension:!0,command_path:ky(i)});for(let i of e)n.has(i.action)||n.set(i.action,{action:i.action,provider:"extension",requires_extension:!0,command_path:Be.find(r=>r.alias===i.command)?.canonical??ve(i.command)});return[...n.values()].sort((i,r)=>(i.action??"").localeCompare(r.action??""))}function VR(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null};let n=e.command_path?pt(e.command_path):[],i=n.some(o=>t.handlers.has(o)||t.handlers.has(B(o))),r=n.map(o=>Oy.get(B(o))).find(o=>typeof o=="string"),s=t.disabledReason===null&&i;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(r?`optional_package_not_installed:${r}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:i,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function $y(e){return Ii.get(e)??Ru}function HR(e){return Ci.has(B(e))?!1:Ii.has(e)}function YR(e){return Ry.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Ty(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function XR(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function JR(e){let t=new Map;for(let i of e.definitions){let r=Ty(i.cli_flag);if(!r)continue;let s=i.cli_aliases.map(a=>XR(a)).find(a=>a!==null),o=i.cli_aliases.map(a=>Ty(a)).filter(a=>a!==null&&a!==r);for(let a of i.commands){let c=t.get(a)??{flags:[],seen:new Set},d=s?{flag:r,short:s}:{flag:r},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of o){let _=`${u}|`;c.seen.has(_)||(c.seen.add(_),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[i,r]of t.entries())n.set(i,Uo(r.flags));return n}function Ay(e,t){let n=[],i=new Set;for(let r of[...e,...t]){let s=`${r.flag}|${r.short??""}`;i.has(s)||(i.add(s),n.push(r))}return Uo(n)}function QR(e,t,n,i,r){let s=new Map(t);for(let{alias:o,canonical:a}of Be){let c=t.get(a)??t.get(o);c&&(s.set(o,c),s.set(a,c))}return e.map(o=>{let a=HR(o),c=a?$y(o):[],d=n.get(YR(o))??[],l=s.get(o),u=Ay(c,d),_=Ay(u,l?.flags??[]),f=c.length>0&&(l?.flags.length??0)>0?"mixed":a?"core":"extension";return{command:o,flags:_,...i?{canonical_command:jy(o),visibility:Uy(o,r),positionals:Cu(o)?.slots??[],flag_invocations:ry(o,_)}:{},provider:f,extension_sources:l?.sources}}).sort((o,a)=>o.command.localeCompare(a.command))}function ZR(e,t=Dn){let n=new Set(e),i=new Map;for(let r of Dy){let s=r.aliases.filter(o=>n.has(o));i.set(r.canonical,{canonical:r.canonical,aliases:s,contracts:[]})}for(let r of t){if(!n.has(r.canonical)||r.registration==="commander"&&!n.has(r.alias))continue;let s=i.get(r.canonical)??{canonical:r.canonical,aliases:[],contracts:[]};s.aliases.includes(r.alias)||s.aliases.push(r.alias),s.contracts.push(r),i.set(r.canonical,s)}return[...i.values()].map(({contracts:r,...s})=>r.length===0?s:{...s,contracts:r}).sort((r,s)=>r.canonical.localeCompare(s.canonical))}function eO(){return{create_string_options:Eu,create_repeatable_options:Tu,update_string_options:hr,update_repeatable_options:Au,list_string_options:vu,search_string_options:wu,calendar_string_options:bu,context_string_options:ku,activity_string_options:Su}}function Cy(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let i=Jt(e,"create",n),r=[...new Set(i.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(r.map(a=>Ee("create",a)))].sort((a,c)=>a.localeCompare(c)),o=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:r,required_flags:s,required_type_options:o,policy_errors:[...new Set(i.errors)].sort((a,c)=>a.localeCompare(c))}}function tO(e){let t={},n={};for(let i of[...e.types].sort((r,s)=>r.localeCompare(s))){let r=e.by_type[i];t[i]=Cy(r,"strict"),n[i]=Cy(r,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function nO(e,t){let n=xi(e);if(n.length===0)return e;let i=!1,r=n.map(s=>{let o=s.properties;if(typeof o!="object"||o===null)return s;let a=o.action;return typeof a!="object"||a===null||a.const!=="create"?s:(i=!0,{...s,"x-create-required-options":t})});return i?{...e,oneOf:r}:e}function iO(e){let t=Hs(e.action)!==void 0||Hs(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,i=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,r=e.schemaOnly===!0,s=e.flagsOnly===!0,o=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=Hs(e.action),l=Hs(e.command),u=!i&&!c&&!r&&!s&&!o&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:i,schemaOnly:r,flagsOnly:s,availabilityOnly:o,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function rO(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new p("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function sO(e,t=I){try{return await t(e)}catch{return structuredClone(Ct)}}async function oO(e,t,n){let i=await sO(t),r=await WR(e),s=$(i,r.registrations??M()),o=nn(i.schema),a=FR(r);return{settings:i,runtimeProbe:r,typeRegistry:s,statusRegistry:K(i.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:JR(o),createRequiredOptionContracts:tO(s),extensionContracts:a,mergedExtensionContracts:zR(a.filter(c=>Xs(n,c.command,a))),extensionFlagMap:Fy(r.flagRegistrations)}}function Iy(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Ys.has(e.selectedAction)||e.selectedCommand!==void 0&&Ci.has(B(e.selectedCommand)))}function aO(e,t){let n=BR(t,{includePackageOwnedActions:Iy(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let i=new Set(Nl);return n.filter(r=>!i.has(r.action)&&(e.fullOutput||(t.find(s=>s.action===r.action)?.tier??Fc(r.action))!=="internal"))}return Iy(e)&&e.selectedCommand!==void 0&&Ci.has(B(e.selectedCommand))&&!n.some(i=>i.command_path===e.selectedCommand)&&n.push({action:LR(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function cO(e,t){let n=new Set(t.map(i=>i.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new p(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function dO(e,t){return[...new Set([...Xe.filter(n=>!Ci.has(B(n))),...[...Ii.keys()].filter(n=>!Ci.has(B(n))),...e.flatMap(n=>n.command_path?pt(n.command_path):[]),...t.flatMap(n=>n.command.split("|").flatMap(i=>{let r=Be.find(s=>s.alias===i||s.canonical===i);return r===void 0?[i]:[r.alias,r.canonical]}))])].map(n=>ve(n)).filter(n=>n.length>0).sort((n,i)=>n.localeCompare(i))}function lO(e,t){let n=t.slice(0,IR),i=t.length-n.length,r=i>0?`${n.join(", ")}, and ${i} more`:n.join(", "),s=t.slice(0,xR),o=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new p(`Command "${e}" is a command namespace. Choose a concrete child command: ${r}.`,m.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:o,nextSteps:[`Retry with a child command, for example: ${o[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function uO(e,t){return new p(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,m.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function mO(e){return new p(`Unknown command: "${e}".`,m.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function _O(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let i=t.filter(s=>s.startsWith(`${e.selectedCommand} `));if(i.length>0)throw lO(e.selectedCommand,i);let r=Oy.get(B(e.selectedCommand));throw r?uO(e.selectedCommand,r):mO(e.selectedCommand)}function pO(e,t){let n=aO(e,t.mergedExtensionContracts);cO(e,n);let i=dO(n,t.mergedExtensionContracts);_O(e,i);let r=e.selectedCommand?Ny.get(B(e.selectedCommand)):void 0,s=e.selectedCommand?n.filter(d=>r?d.action===r:NR(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.some(d=>d.action===e.selectedAction))throw new p(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let o=e.selectedAction?s.filter(d=>d.action===e.selectedAction):s,a=[...new Map(o.map(d=>VR(d,t.runtimeProbe)).map(d=>[r?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:i,commandScopedDescriptors:s,scopedActionDescriptors:o,selectedPackageOwnedAction:r,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function fO(e){return new Set(xi(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let i=n.action;if(typeof i!="object"||i===null)return null;let r=i.const;return typeof r=="string"?r:null}).filter(t=>t!==null))}function gO(e){let t=o_,n=xi(t),i=fO(t),r=e.filter(s=>!i.has(s.action)).map(s=>qR(s));return r.length>0?{...t,oneOf:[...n,...r]}:t}function xy(e,t,n){let i=new Set(t.actionDescriptors.map(s=>s.action)),r=e.selectedAction?MR(n,e.selectedAction):e.selectedCommand?$c(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):$c(n,i);return e.runtimeOnly&&!e.selectedAction?$c(r,new Set(t.actions)):r}function hO(e,t,n){let i=gO(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?nO(xy(e,n,i),t.createRequiredOptionContracts):xy(e,n,i);return{mergedSchema:i,filteredSchema:s}}function yO(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?DR(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Uy(e,t){return t.find(n=>B(n.command)===B(e))?.tier??Fc(e)}function Xs(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||Uy(t,n)!=="internal"}function vO(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let i=new Set(Dn.filter(r=>r.hidden&&(r.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(r=>r.alias));if(e.summary&&!e.fullOutput)for(let r of jc.keys())i.add(r);return t.filter(r=>!i.has(r)&&Xs(e,r,n))}function jy(e){let t=Be.find(i=>i.alias===e||i.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":jc.get(n)??n}var wO=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),bO=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function kO(e,t){let n=by.get(B(e))??(e.includes(" ")?void 0:by.get(jy(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let i=t.find(d=>pt(d.command).some(l=>B(l)===B(e)));if(i?.intent!==null&&i?.intent!==void 0)return{intent:i.intent,intent_source:"command"};if(i?.description!==null&&i?.description!==void 0)return{intent:i.description,intent_source:"description"};let r=e.split(" "),s=r.at(-1),o=r.slice(0,-1).join(" "),a=wO.get(s),c=bO.get(e)??o;return{intent:a===void 0||o.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function SO(e,t=[],n={}){let i=n.includeFormatBudgets??!0,r=n.includeIntentProvenance??!0;return[...new Set(e.map(ve))].filter(s=>s.length>0).sort((s,o)=>s.localeCompare(o)).map(s=>{let o=xo(s,{generateFallback:!0}),a=s.split(" ")[0],c=jc.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...$y(s).map(_=>_.flag),...t.filter(_=>pt(_.command).some(f=>B(f)===B(s))).flatMap(_=>_.flags.map(f=>f.flag))]),l=(wy.get(B(s))??wy.get(c)??CR).filter(_=>d.has(_)),u=kO(s,t);return{command:s,intent:u.intent,...r||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:o.default_max_estimated_tokens,...i?{default_max_estimated_tokens_by_format:{...o.default_max_estimated_tokens_by_format}}:{}}})}function EO(e){return e.map(t=>({budget:xo(t,{generateFallback:!0}),envelope:gy(t)}))}function TO(e){let t=new Map;for(let n of e){let i=Fh(n),r=i===void 0?[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED]:i.exit_codes,s=r.join(","),o=t.get(s)??{commands:[],exit_codes:r};o.commands.push(n),t.set(s,o)}return[...t.values()]}function AO(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(i=>pt(i.command).some(r=>B(r)===B(e.selectedCommand)));if(e.selectedAction){let i=new Set(n);return t.extensionContracts.filter(r=>pt(r.command).some(s=>i.has(s)))}return t.extensionContracts.filter(i=>Xs(e,i.command,t.extensionContracts))}function CO(e,t,n,i){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:i,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function IO(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=wl);let i=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(r=>r.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([r])=>i===void 0||r===i).map(([r,s])=>[r,[...new Set(s.map(o=>`--${o.cli_flag}`))].sort((o,a)=>o.localeCompare(a))]))},!(i!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Tl],services:[...Al],policy_modes:[...Cl],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Rl],trust_modes:[...Il],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...xl],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Pd],create_modes:[...Fd],close_validation_modes:[...$d],workflow_enforcement_modes:[...Ud]},e.relationship_kind_contracts=[...Qd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(r=>r.definitions)].sort((r,s)=>r.kind.localeCompare(s.kind)).map(r=>({canonical:r.kind,aliases:[...r.aliases??[]],...r.inverse===void 0?{}:{inverse:r.inverse},ordering:r.ordering,hierarchy:r.hierarchy})))}function xO(e,t,n,i){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=i;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=i}}function RO(e,t,n,i,r){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=QR(i,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let s=new Set(i);e.list_projections=Object.entries(x_).filter(([o])=>s.has(o)).map(([o,a])=>({command:o,default:a,brief_fields:[...I_],compact_fields:[...C_]}))}e.command_aliases=t.fullOutput?r:r.map(({canonical:s,aliases:o})=>({canonical:s,aliases:o})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function OO(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=eO();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function LO(e,t,n,i){e.command_summaries=SO(t,n,{includeFormatBudgets:i.includeFormatBudgets,includeIntentProvenance:i.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Dl],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...i.includeProjectionModeMatrix?{commands:[...new Set(t.map(ve))].filter(r=>Fl(r)!==void 0).sort((r,s)=>r.localeCompare(s)).map(r=>({command:r,modes:[...$l(r).keys()]}))}:{}},e.grammar_contracts={nouns:Lt.nouns,shared_verbs:Lt.shared_verbs,scope_before_verb:Lt.scope_before_verb,visible_top_level_ceiling:Lt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Lt.ceiling_raise_requires_pm_item,positional_shape_budget:Lt.positional_shape_budget,positional_shape_count:new Set($o.map(({slots:r})=>xu(r))).size,positional_action_count:Fo.length,positional_action_parents:[...new Set(Fo.map(({parent:r})=>r))].sort((r,s)=>r.localeCompare(s)),...i.includePositionalSignatures?{positional_signatures:$o}:{}}}async function I2(e,t){let n=iO(e);rO(n);let i=x(process.cwd(),t.path),r=await oO(t,i,n),s=pO(n,r),o=hO(n,r,s),a=yO(n,s),c=vO(n,a,r.extensionContracts),d=CO(n,o,s,c),l=AO(n,r,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&LO(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return d;let _=ZR(s.commandCatalog.filter(f=>Xs(n,f,r.extensionContracts)));return n.flagsOnly&&!n.fullOutput||IO(d,r,n),xO(d,n,o,l),RO(d,n,r,c,_),OO(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...Zn],gate_triggers:[...ct]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=Iu.map(f=>({...f,reason:f.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=vy(),d.context_intents=Ul(),d.read_output_dimensions=Pl,d.error_codes=py,d.command_output_contracts=EO(c),d.diagnostic_output_contracts=Ml,d.command_exit_contracts={vocabulary:Ic,command_sets:TO(c)}),d}import{createHash as DO}from"node:crypto";import{execFile as MO}from"node:child_process";import Ky from"node:path";import{promisify as PO}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]="39d2b5aa-c6f3-57ac-adb4-e775bc838828")}catch{}})();var Gy=1;function NO(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Gc(e){if(e===null)return{format_version:Gy,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new p("Improvement ledger contains invalid JSON.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Gy||!Array.isArray(t.observations))throw new p("Improvement ledger has an unsupported shape or format version.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let i of n)if(!NO(i))throw new p("Improvement ledger contains an invalid observation.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return 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]="c800f76b-2867-51f5-80d6-fb7b1c61f9e4")}catch{}})();var FO=PO(MO),$O=50,qy=1e3,UO=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function zy(e){let t=e.trim().toLowerCase();if(!UO.test(t))throw new p(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,m.USAGE,{code:"invalid_improvement_metric"});return t}function jO(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new p("Improvement direction must be higher, lower, or target.",m.USAGE,{code:"invalid_improvement_observation"});return t}function Ri(e,t){let n=e?.trim();if(n){if(n.length>256)throw new p(`${t} must not exceed 256 characters.`,m.USAGE,{code:"invalid_improvement_observation"});return n}}function GO(e){let t=e??$O;if(!Number.isSafeInteger(t)||t<0||t>qy)throw new p(`Improvement observation limit must be an integer from 0 to ${qy}.`,m.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Wy(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`${t} must be an ISO timestamp.`,m.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function qO(e,t,n){if(!Number.isFinite(n.value))throw new p("Improvement observation value must be finite.",m.USAGE,{code:"invalid_improvement_observation"});let i=zy(n.metric),r=jO(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||r==="target"&&n.threshold===void 0)throw new p("Target-directed observations require a finite threshold.",m.USAGE,{code:"invalid_improvement_observation"});let s=await zO(e,n.revision),o=Ri(n.source,"source"),a=Ri(n.itemId,"itemId"),c=Ri(n.unit,"unit"),d=Ri(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,i,o??"manual",a??"workspace"].join(":")),l={metric:i,value:n.value,direction:r,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Wy(n.observedAt??R(),"observedAt"),...s,author:G(n.author,t.author_default),...a===void 0?{}:{item_id:a},...o===void 0?{}:{source:o},...d===void 0?{}:{idempotency_key:d}};return{id:DO("sha256").update(ie(l)).digest("hex").slice(0,24),...l}}function KO(e,t){let n=t.idempotency_key?e.observations.find(r=>r.idempotency_key===t.idempotency_key):e.observations.find(r=>r.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new p(`Improvement observation retry key already records a different value for ${t.metric}.`,m.CONFLICT,{code:"improvement_observation_conflict"});return n}let i=e.observations.find(r=>r.metric===t.metric);if(i&&(i.direction!==t.direction||i.unit!==t.unit||t.direction==="target"&&i.threshold!==t.threshold))throw new p(`Metric ${t.metric} is already declared with direction ${i.direction} and unit ${i.unit??"<none>"}.`,m.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function zO(e,t){let n=Ri(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await FO("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:He(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function WO(e){let t=e[0],n=e[e.length-1],i=n.value-t.value,r=n.direction==="higher"?i>0:n.direction==="lower"?i<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:i,improved:r,sample_count:e.length}}async function By(e,t={}){let n=x(process.cwd(),t.path);await P(n);let i=await I(n),r=await qO(n,i,e),s=Ky.join(n,"improvement-ledger.json"),o=await cn({pmRoot:n,filePath:s,op:"improvement_observe",author:r.author,lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,message:e.message??`Record ${r.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Gc(a),d=KO(c,r);return d?{raw:a,result:d}:(c.observations.push(r),c.observations.sort((l,u)=>l.observed_at.localeCompare(u.observed_at)||l.metric.localeCompare(u.metric)||l.id.localeCompare(u.id)),{raw:`${ie(c)}
|
|
17
|
+
`,result:r})}});return{changed:o.changed,observation:o.result,ledger_path:"improvement-ledger.json"}}async function Vy(e={}){let t=x(e.cwd??process.cwd(),e.pmRoot);await P(t);let n=e.metric===void 0?void 0:zy(e.metric),i=e.since===void 0?void 0:Wy(e.since,"since"),r=GO(e.limit),o=Gc(await ee(Ky.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(i===void 0||c.observed_at>=i)),a=new Map;for(let c of o){let d=a.get(c.metric)??[];d.push(c),a.set(c.metric,d)}return{observations:[...o].reverse().slice(0,r),total:o.length,truncated:o.length>r,trends:[...a].map(([,c])=>WO(c)).sort((c,d)=>c.metric.localeCompare(d.metric)),source:"audited_workspace_singleton"}}(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]="2e7a7f40-523d-590f-8aea-90b65535506e")}catch{}})();function BO(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function VO(e,t,n){let i=t,r=new Set([e.id]);for(;i!==void 0&&!r.has(i.id);)r.add(i.id),i=i.parent_id?n.get(i.parent_id):void 0;return i===void 0}function HO(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((i,r)=>i.entries[0].ts.localeCompare(r.entries[0].ts)||i.id.localeCompare(r.id)),t.push(...n.map(i=>i.children))}}function Hy(e=Gn,t=jn){return t.map(n=>{let i=e.filter(r=>((n==="model"?r.model_environment_keys:r.provenance_environment_keys?.[n])?.length??0)>0||r.provenance_resolvers?.[n]!==void 0).map(r=>r.harness).sort();return{dimension:n,harnesses:i,covered:i.length>0}})}function X2(e,t=1){let n=new Map;for(let i of e){if(!i.agent_harness)continue;let r=n.get(i.agent_harness)??{harness:i.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};r.entries+=1,i.agent_model||i.agent_provenance?.model&&i.agent_provenance.model.value.length>0?r.observed+=1:i.agent_provenance?.model===null?r.unavailable+=1:r.legacy_missing+=1,n.set(i.agent_harness,r)}return[...n.values()].map(i=>{let r=i.observed+i.unavailable;return{...i,coverage:r===0?null:i.observed/r,inert:r>=t&&i.observed===0}}).sort((i,r)=>i.harness.localeCompare(r.harness))}function Yy(e,t=jn,n=1){let i=new Map;for(let r of e)if(r.agent_harness)for(let s of t){let o=`${r.agent_harness}\0${s}`,a=i.get(o)??{harness:r.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=r.agent_provenance?.[s];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,i.set(o,a)}return[...i.values()].map(r=>{let s=r.observed+r.unavailable;return{...r,coverage:s===0?null:r.observed/s,inert:s>=n&&r.observed===0}}).sort((r,s)=>r.harness.localeCompare(s.harness)||r.dimension.localeCompare(s.dimension))}function J2(e,t={}){let n=t.minimumCoverage??.8,i=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(i),i>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let r=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let l=`${c.agent_harness}\0${d}`,u=r.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let _=c.agent_provenance?.[d];_?.value&&(u.observed+=1,u.by_source[_.source]=(u.by_source[_.source]??0)+1),r.set(l,u)}let s=[...r.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[l])=>d.localeCompare(l)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),o=s.filter(c=>c.entries>=i),a=o.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:o.length>0&&a.length===0,minimum_coverage:n,minimum_entries:i,rows:s,failures:a}}function Q2(e){let t=[...e].sort((s,o)=>s.ts.localeCompare(o.ts)||s.author.localeCompare(o.author)||s.op.localeCompare(o.op)||s.before_hash.localeCompare(o.before_hash)||s.after_hash.localeCompare(o.after_hash)),n=new Map,i=new Map;for(let s of t){let o=s.agent_episode,a=BO(s),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(s);continue}let l={id:a.id,...o?.label===void 0?{}:{label:o.label},...o?.parent_id===void 0?{}:{parent_id:o.parent_id},source:a.source,entries:[s],children:[]};n.set(c,l),o!==void 0&&i.set(a.id,l)}let r=[];for(let s of n.values()){let o=s.parent_id?i.get(s.parent_id):void 0;o&&VO(s,o,i)?o.children.push(s):r.push(s)}return HO(r),r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0eeefcd-2202-55c6-94e9-0372fcfe0c87")}catch{}})();var YO=1e4,Xy=1e5,XO=1e3,JO=30,QO=["append","comment","docs","file","learning","note","test_run"];function ZO(e){let t=e??YO;if(!Number.isSafeInteger(t)||t<1||t>Xy)throw new p(`History analytics event limit must be an integer from 1 to ${Xy}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return t}function Jy(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new p("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function eL(e){let t=e?.trim();if(!t)return new Date(Date.now()-JO*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let r=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(r)||r<1)throw new p("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-r*s).toISOString()}let i=Date.parse(t);if(!Number.isFinite(i))throw new p("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(i).toISOString()}async function Js(e,t){let n=ZO(t.eventLimit),i=eL(t.since),r=[],s=i,o=!1;for(;r.length<n;){let a=await D_({pmRoot:e,since:s,limit:Math.min(XO,n-r.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(r.push(...c),o=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:r,receipt:{since:i,events:r.length,truncated:o,...o?{next_cursor:s}:{},source:"history_event_index"}}}function tL(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function nL(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function iL(e){return QO.some(t=>e.startsWith(t))}function Qy(e,t){let n=e.get(t);if(n)return n;let i={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,i),i}function rL(e,t,n){let i=new Map,r=new Map,s=new Map;for(let o of t){let a=tL(o.entry,e),c=nL(o.entry),d=r.get(o.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&r.set(o.item_id,l),!a)continue;let u=Qy(i,a);u.events+=1,iL(o.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,s.set(o.item_id,a)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:i,lastCloseValue:s}}function sL(e,t,n){for(let i of n){if(i.type!=="Issue")continue;let r=new Set((i.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of r){let o=t.get(s);o&&(Qy(e,o).defectEscapes+=1)}}}function oL(e,t,n,i){let r=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:r==="available"?t.closes/i:null,rework_rate:r==="available"?t.reopens/t.closes:null,defect_escape_rate:r==="available"?t.defectEscapes/t.closes:null,sample_status:r}}function aL(e,t,n,i,r,s){let{buckets:o,lastCloseValue:a}=rL(e,t,i);return sL(o,a,n),{dimension:e,status:o.size===0?"unavailable":"available",rows:[...o].map(([c,d])=>oL(c,d,r,s)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function cL(e,t){let n=e[0]?.entry.ts??t,i=e[e.length-1]?.entry.ts??n,r=Date.parse(n),s=Date.parse(i);return!Number.isFinite(r)||!Number.isFinite(s)?1:Math.max(1,(s-r)/864e5)}function dL(e,t,n){let i=Hy(t),r=Yy(e,jn,n),s=r.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),o=i.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:i,observations:r,inert:s,undeclared:o,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...o.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function sW(e,t=Gn,n={}){return qc(await Js(e,n),t,n)}function qc(e,t=Gn,n={}){let i=Jy(n.minimumSample);return{...dL(e.events.map(r=>r.entry),t,i),window:e.receipt}}async function oW(e,t,n,i={}){return Kc(await Js(e,i),t,n,i)}function Kc(e,t,n,i={}){let r=Jy(i.minimumSample),s=cL(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(o=>aL(o,e.events,t,n,r,s)),minimum_sample:r,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(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]="c81415a5-81fa-57ed-936f-236841e5f066")}catch{}})();var lL=32;function uL(e){let t=[];for(let n of e??[]){let i=[];for(let r of n.split(",")){let s=r.slice(0,r.indexOf("=")).trim();i.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(i.join(",")),i=[]),i.push(r)}t.push(i.join(","))}return t}function Oi(e,t){let n=uL(e).map(r=>{let[s,...o]=r.split(","),a=s.indexOf("="),c=s.slice(0,a).trim(),d=s.slice(a+1).trim(),l=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(l))throw new p(`Invalid --measure "${r}"; expected name=value[,unit=...][,threshold=...]`,m.USAGE);let u,_;for(let f of o){let g=f.indexOf("="),h=f.slice(0,g).trim(),y=f.slice(g+1).trim();if(h==="unit"&&y.length>0)u=y;else if(h==="threshold"&&y.length>0&&Number.isFinite(Number(y)))_=Number(y);else throw new p(`Invalid --measure attribute "${f}"`,m.USAGE)}return{name:c,value:l,unit:u,threshold:_,recorded_at:t}});return[...new Map(n.map(r=>[r.name,r])).values()].sort((r,s)=>r.name.localeCompare(s.name)).slice(0,lL)}function Zy(e,t,n){return e.flatMap(i=>(i.measurements??[]).filter(r=>r.name===t&&r.value<n).map(r=>({...r,run_id:i.run_id})))}function ev(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,o)=>o.recorded_at.localeCompare(s.recorded_at)),i=n[0],r=n[1];return{name:t,latest:i?.value??null,previous:r?.value??null,delta:i!==void 0&&r!==void 0?i.value-r.value:null,unit:i?.unit}}import _L from"node:fs/promises";import nv 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]="60090339-2f94-5f22-be47-518498838b92")}catch{}})();function Qs(e,t,n,i,r,s="min"){let o=r==="min"?e-t:t-e,a=s==="min"?n.localeCompare(i??n):(i??n).localeCompare(n);return o<0||o===0&&i!==null&&a<0}function mL(e,t){let n=Buffer.byteLength(t,"utf8"),i=0,r=null,s=null,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;i+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,_=Date.parse(u);Number.isNaN(_)||(Qs(_,o,u,r,"min")&&(o=_,r=u),Qs(_,a,u,s,"max","max")&&(a=_,s=u))}return{id:e,bytes:n,lines:i,oldest_ts:r,newest_ts:s}}function tv(e,t){let n=t?.topN??5,i=Math.max(0,Math.floor(n)),r=e.map(({id:f,raw:g})=>mL(f,g)),s=0,o=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let f of r){if(s+=f.lines,o+=f.bytes,f.oldest_ts!==null){let g=Date.parse(f.oldest_ts);Qs(g,d,f.id,a?.id??null,"min")&&(d=g,a={id:f.id,ts:f.oldest_ts})}if(f.newest_ts!==null){let g=Date.parse(f.newest_ts);Qs(g,l,f.id,c?.id??null,"max")&&(l=g,c={id:f.id,ts:f.newest_ts})}}let u=i===0?[]:[...r].sort((f,g)=>g.bytes-f.bytes||f.id.localeCompare(g.id)).slice(0,i),_=i===0?[]:[...r].sort((f,g)=>g.lines-f.lines||f.id.localeCompare(g.id)).slice(0,i);return{total_streams:e.length,total_lines:s,total_bytes:o,largest_by_bytes:u,deepest_by_lines:_,oldest_entry:a,newest_entry:c}}(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]="a567e72a-faff-580d-b9ae-e2ebfa492b89")}catch{}})();function pL(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function fL(e,t,n,i,r){let s=Qn(e,"type",i),o=new Set(s.rows.map(_=>_.key)),a=t.filter(_=>!o.has(_)),d=(r?[...s.rows,...a.map(_=>({label:_,key:_,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(_=>({type:_.key??_.label,total:_.total,open:_.buckets.open,in_progress:_.buckets.in_progress,blocked:_.buckets.blocked,draft:_.buckets.draft,closed:_.buckets.closed,canceled:_.buckets.canceled,other:_.buckets.other})),l=pL([...n]);for(let _ of e)l[_.status]+=1;let u=Object.fromEntries(Object.entries(l).filter(([,_])=>r||_>0));return{byType:d,byStatus:u,omitted:r?0:a.length+Object.values(l).filter(_=>_===0).length}}function gL(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function hL(e){let t=nv.join(e,"history");if(!await Z(t))return[];await Me({path:t,scope:"project"});let n=(await _L.readdir(t)).filter(r=>r.endsWith(".jsonl")).sort((r,s)=>r.localeCompare(s)),i=[];for(let r of n){let s=nv.join(t,r),o=await ee(s);o!==null&&(await Me({path:s,scope:"project"}),i.push({id:r.slice(0,-6),raw:o}))}return i}async function yL(e,t){let n=[],i=R();for(let r of Oi(t.observe,i))n.push(await By({metric:r.name,value:r.value,direction:t.direction,unit:r.unit,threshold:r.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:i,author:t.author,message:t.message},e));return n}function vL(e,t,n){let i={};return t.byAssignee&&(i.assignee=Qn(e,"assignee",n)),t.byTag&&(i.tag=Qn(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(i.priority=Qn(e,"priority",n)),i}async function wL(e,t,n,i,r){let s={since:r.since,eventLimit:r.eventLimit,minimumSample:r.minimumSample},o=r.provenanceCoverage||r.fleetAttribution?await Js(e,s):void 0;return{provenanceCoverage:r.provenanceCoverage&&o?qc(o,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:r.fleetAttribution&&o?Kc(o,t,i,s):void 0}}function bL(e,t,n,i,r){let s=Object.keys(r.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:i,...r.metadataCoverage?{metadata_coverage:r.metadataCoverage}:{},...s?{breakdowns:r.breakdowns}:{},...r.storage?{storage:r.storage}:{},...r.fieldUtilization?{field_utilization:r.fieldUtilization}:{},...r.improvementLedger?{improvement_ledger:r.improvementLedger}:{},...r.recordedObservations.length>0?{recorded_observations:r.recordedObservations}:{},...r.provenanceCoverage?{provenance_coverage:r.provenanceCoverage}:{},...r.fleetAttribution?{fleet_attribution:r.fleetAttribution}:{},generated_at:R()}}async function xW(e,t={}){let n=x(process.cwd(),e.path);await P(n);let i=await I(n),r=await yL(e,t),s=$(i,M()),o=K(i.schema),a=t.fieldUtilization?await Ot(n,i.item_format,s.type_to_folder,void 0,i.schema):await ke(n,i.item_format,s.type_to_folder,void 0,i.schema);await dr({pmRoot:n,settings:i,itemIds:a.map(S=>S.id),commandLabel:"stats"});let c=E_(o),d=fL(a,s.types,o.definitions.map(S=>S.id),c,t.includeEmpty===!0),l=await hL(n),u=0;for(let S of l)u+=gL(S.raw);let _=t.storage?tv(l):void 0,f=t.metadataCoverage?T_(a,c):void 0,g=vL(a,t,c),h=t.fieldUtilization?A_(a):void 0,y=t.measurements===!0||r.length>0?await Vy({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:v,fleetAttribution:w}=await wL(n,a,i,o.terminal_statuses,t);return bL({items:a.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:f,breakdowns:g,storage:_,fieldUtilization:h,improvementLedger:y,recordedObservations:r,provenanceCoverage:v,fleetAttribution:w})}(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]="499dfc08-cf70-55fe-8868-65c3107e3a91")}catch{}})();async function NW(e,t={}){let n=await Bg({pmRoot:x(process.cwd(),e.path),exhaustive:t.exhaustive,...t.status===void 0?{}:{statuses:t.status.flatMap(i=>i.split(",").map(r=>r.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(i=>{let r=i.id;return{...i,canonical_id:r,close_command:`pm close <duplicate-id> --duplicate-of ${r}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import kL from"node:fs/promises";import Tt 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]="0c2960a8-84b8-57d1-bf5f-cea9cde0f544")}catch{}})();var av=Tt.join("runtime","telemetry","events.jsonl"),cv=Tt.join("runtime","telemetry","state.json"),SL=Tt.join("runtime","telemetry"),EL=20,iv=["status","flush","stats","clear"],rv=(e,t)=>{let n=Math.ceil(t*e.length),i=Math.min(e.length-1,Math.max(0,n-1));return e[i]},zc=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,sv=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},TL=e=>({command:zc(e.event.command,"<unknown>"),eventType:zc(e.event.event_type,"unknown"),eventSchemaVersion:sv(e.event.schema_version),clientSchemaVersion:sv(e.client_schema_version)}),AL=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),CL=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},IL=e=>{let t=e?.command_resolution;return zc(t,"")||void 0},dv=(e,t)=>{e[t]=(e[t]??0)+1},xL=(e,t)=>{let n=CL(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let i=IL(t);i!==void 0&&dv(e.resolution_counts,i)},RL=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,ov=(e,t)=>{t!==void 0&&e.add(t)},OL=(e,t)=>{let n=TL(t),i=e.get(n.command)??AL();i.count+=1,i.max_attempts=Math.max(i.max_attempts,RL(t.attempts)),dv(i.event_type_counts,n.eventType),ov(i.event_schema_versions,n.eventSchemaVersion),ov(i.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&xL(i,t.event.payload),e.set(n.command,i)},LL=(e,t)=>{let n=t.ok_count+t.error_count,i=[...t.finish_durations_ms].sort((s,o)=>s-o),r=Object.entries(t.resolution_counts).sort((s,o)=>s[0].localeCompare(o[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,o)=>s[0].localeCompare(o[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,o)=>s-o),client_schema_versions:[...t.client_schema_versions].sort((s,o)=>s-o),...i.length>0?{duration_p50_ms:rv(i,.5),duration_p95_ms:rv(i,.95),duration_max_ms:i[i.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...r.length>0?{command_resolution_counts:Object.fromEntries(r)}:{}}},NL=e=>{let t=(e??"status").trim().toLowerCase();if(iv.includes(t))return t;throw Ki({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:iv,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Wc=()=>{throw new p("--limit must be a positive integer",m.USAGE)},lv=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Wc():e,DL=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Wc():lv(Number.parseInt(t,10))},ML=e=>e===void 0?EL:typeof e=="number"?lv(e):typeof e=="string"?DL(e):Wc(),PL=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},FL=e=>{try{let t=JSON.parse(e);return PL(t)?t:void 0}catch{return}},$L=e=>e===null?[]:e.split(`
|
|
18
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),uv=e=>{let t=$L(e),n=[],i=0;for(let r of t){let s=FL(r);s===void 0?i+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:i,entries:n}},UL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),jL=e=>{try{let t=JSON.parse(e);return UL(t)?t:{}}catch{return{}}},GL=async e=>{let t=await ee(e);return t===null||t.trim().length===0?{}:jL(t)},Zs=e=>e??null,eo=async e=>{let t=await I(e),n=Tt.join(e,av),i=Tt.join(e,cv),r=await ee(n),s=uv(r),o=await GL(i),a=Bn();return{enabled:t.telemetry.enabled&&!a.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:a,endpoint:t.telemetry.endpoint,queue_path:n,state_path:i,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(r??"","utf8"),last_attempted_flush_at:Zs(o.last_attempted_flush_at),last_successful_flush_at:Zs(o.last_successful_flush_at),last_failed_flush_at:Zs(o.last_failed_flush_at),last_failed_flush_error:Zs(o.last_failed_flush_error)}},qL=e=>{let t=new Map;for(let n of e)OL(t,n);return[...t.entries()].map(([n,i])=>LL(n,i)).sort((n,i)=>i.count-n.count||n.command.localeCompare(i.command))},KL=async(e,t)=>({action:"telemetry",subcommand:"status",status:await eo(t.globalPmRoot),generated_at:R()}),zL=async(e,t)=>{let n=await eo(t.globalPmRoot);await yu(t.globalPmRoot);let i=await eo(t.globalPmRoot),r=Math.max(0,n.queue_entries-i.queue_entries),s=i.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:i.queue_entries,queue_entries_drained:r,queue_progressed:r>0,queue_empty:s,queue_drained:s,status:i,generated_at:R()}},WL=async(e,t)=>{let n=ML(e.limit),i=await ee(t.queuePath),r=uv(i),s=qL(r.entries),o=s.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:r.valid_entries,queue_invalid_rows:r.invalid_rows,queue_rows_total:r.rows_total,truncated:s.length>o.length,stats:o,generated_at:R()}},BL=async(e,t)=>hu(async()=>{let n=await I(t.globalPmRoot),i=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",i&&await Ql(t.globalPmRoot,n,"telemetry:clear");let r=Tt.join(t.globalPmRoot,SL),s=await Z(r);return await kL.rm(r,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:i,runtime_dir_removed:s&&!await Z(r),queue_exists_after:await Z(t.queuePath),state_exists_after:await Z(t.statePath),status:await eo(t.globalPmRoot),generated_at:R()}},t.globalPmRoot),VL={status:KL,flush:zL,stats:WL,clear:BL};async function BW(e,t){let n=NL(e.subcommand),i=Ye(process.cwd());return VL[n](e,{globalPmRoot:i,queuePath:Tt.join(i,av),statePath:Tt.join(i,cv)})}import{spawn as Lv}from"node:child_process";import{cp as Yc,mkdir as so,mkdtemp as Nv,open as Xc,readdir as Jc,rm as Li,symlink as Dv}from"node:fs/promises";import{tmpdir as Mv}from"node:os";import Y 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]="ffa50b5b-d99f-5ab4-a70d-cbf12911a0f2")}catch{}})();var mv=20;function HL(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return mv;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?mv:t}function Bc(e){let t=[...e].filter(i=>i.run_id.trim().length>0&&i.started_at.trim().length>0&&i.finished_at.trim().length>0&&i.recorded_at.trim().length>0).sort((i,r)=>{let s=qi(i.recorded_at,r.recorded_at);if(s!==0)return s;let o=i.run_id.localeCompare(r.run_id);return o!==0?o:i.kind.localeCompare(r.kind)}),n=HL();return t.length>n?t.slice(t.length-n):t}async function to(e){await le({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=Bc([...n,e.entry]),{changedFields:["test_runs"]}}})}(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]="328c7577-364c-5869-aa92-199e56d2f6a7")}catch{}})();var _v=100;function Vc(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new p(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function YL(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=_v?n:`${n.slice(0,_v-3)}...`}function pv(e){return e.map((t,n)=>`${n+1}. ${YL(t)}`).join("; ")}function XL(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function JL(e,t){let n=e.command?.toLowerCase()??"",i=e.path?.toLowerCase()??"";return n.includes(t)||i.includes(t)}function fv(e,t){let n=XL(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((r,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new p(`Combine at most one linked-test selector per run: ${n.map(r=>`--${r}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,m.USAGE);let i=n[0];if(e.length===0)throw new p(`--${i} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(i==="match"){let r=t.match.trim().toLowerCase();if(r.length===0)throw new p("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let s=[],o=[];for(let a=0;a<e.length;a+=1)JL(e[a],r)&&(o.push(e[a]),s.push(a+1));if(o.length===0)throw new p(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${pv(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:o,selected_indexes:s,selected_count:o.length,skipped_count:e.length-o.length}}if(i==="only-index"){let r=Vc(t.onlyIndex);if(r>e.length)throw new p(`--only-index ${r} is out of range: this item has ${e.length} linked test(s). Available entries: ${pv(e)}`,m.USAGE);return{selector:"only-index",requested:String(r),selected:[e[r-1]],selected_indexes:[r],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2833cfc3-db98-5f7f-82e0-388e320ef740")}catch{}})();var ro=20*1024*1024,QL=3e3,ZL=1e4,eN=5e3,gv=120,tN=new Set(["locks","extensions","runtime"]),nN=new Set(["history","index","search","extensions","locks","runtime"]),iN=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],rN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,sN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,oN=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function ed(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let i=Number.parseInt(n,10);return!Number.isFinite(i)||i<=0?t:i}function aN(){return ed("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",QL)}function cN(){return ed("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",ZL)}function dN(){return ed("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",eN)}function lN(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function uN(e){let t=0,n=0,i=0;for(let r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"){n+=1;continue}i+=1}return{passed:t,failed:n,skipped:i}}function td(e){let t=0,n=0,i=0,r=0;for(let s of e){let o=s.execution_context;!o||o.is_pm_command!==!0||(t+=1,o.is_pm_tracker_read_command===!0&&(n+=1),o.mismatch_detected===!0&&(i+=1),o.auto_pm_context_applied===!0&&(r+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:i,auto_remediated:r}}function mN(e){let t=e??"project";if(!De.includes(t))throw new p(`Invalid scope "${e}"`,m.USAGE);return t}function oo(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Ut.includes(t))return t;throw new p(`Invalid --pm-context value "${e}". Expected one of: ${Ut.join(", ")}`,m.USAGE)}function _N(e){return Gt(e??"source","--workspace-context")}function Pv(e,t,n){return n?t:Gt(e.workspace_context_mode,"linked test")??t}function Fv(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:oo(e.pm_context_mode)}function $v(e,t){return e==="auto"?t?"tracker":"schema":e}function pN(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function fN(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:i}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&i==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function gN(e,t){let n={};if(!e)return n;for(let i of e){let r=vi(i,t);if(r)for(let[s,o]of Object.entries(r))n[s]=o}return n}function hN(e,t){if(!e)return[];let n=[];for(let i of e){let r=wi(i,t);r&&n.push(...r)}return[...new Set(n)]}function yN(e){let t=Ni(e);return Dt(t).some(n=>Xr(n)!==null)}function Uv(e){let t=Ni(e);return Dt(t).some(n=>{let i=Xr(n);if(!i)return!1;let r=Fa(i);return r?oN.has(r.subcommand):!1})}function no(e){if(e)return mf.has(e.subcommand)?bt(e.args,_f)?.subcommand:e.subcommand}function hv(e,t){if(e==="npx"||e==="bunx")return Mt(t)?.command;if(e==="pnpm")return no(bt(t,Na));if(e==="npm")return no(bt(t,Da));if(e==="yarn")return no(bt(t,lf));if(e==="bun")return no(bt(t,uf))}function io(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function Hc(e){return!e||!li(e.command)&&!Pa(e.command)?!1:Qr(e.args)==="test-all"}var jv=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),vN=new Set(["npx","bunx"]);function Gv(e){let t=e.split(" ").filter(o=>o.length>0),n=Jr(t);if(n.length===0)return!1;let[i,...r]=n,s=jv.get(i);if(s){let o=r.findIndex(a=>s.test(a));return o>=0?Gv(r.slice(o+1).join(" ")):!1}return li(i)||ui(i)?Qr(r)==="test-all":i==="node"&&r.length>0&&ui(r[0])?Qr(r.slice(1))==="test-all":vN.has(i)?Hc(Mt(r)):i==="pnpm"?Hc(Zr(r)):i==="npm"?Hc(es(r)):!1}function qv(e){let t=Ni(e);return Dt(t).some(n=>Gv(n))}function Kv(e){if(qv(e))throw new p('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',m.USAGE)}function Ni(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function yv(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function nd(e){let t=e.split(" ").filter(o=>o.length>0),n=Jr(t);if(n.length===0)return!1;let[i,...r]=n,s=jv.get(i);if(s){let o=r.findIndex(a=>s.test(a));return o>=0&&nd(r.slice(o+1).join(" "))}return i==="vitest"||i.endsWith("/vitest")||i.endsWith("/vitest.mjs")?!0:i==="node"?wN(r):bN(i,r)}function wN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function bN(e,t){return e==="npx"||e==="bunx"?io(Mt(t)?.command):e==="pnpm"||e==="npm"?io((e==="pnpm"?Zr(t):es(t))?.command)||io(hv(e,t)):(e==="yarn"||e==="bun")&&io(hv(e,t))}function RB(e){let t=Ni(e),n=Dt(t),i=n.some(s=>!yv(s)&&nd(s)),r=n.some(yv);return{accepted:!0,command_kind:i?"direct_runner":r?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:i?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function kN(e){if(qv(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function SN(e){return e?e.map(EN):[]}function EN(e){let t=e.trim(),n=Vg(t)?_s(J(e,"--add"),"--add"):{command:t},i=pe(n.command);if(!i)throw new p("--add requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);return Kv(i),{command:i,path:pe(n.path),scope:mN(n.scope),timeout_seconds:TN(pe(n.timeout_seconds),pe(n.timeout)),pm_context_mode:ys(pe(n.pm_context_mode),"--add"),workspace_context_mode:Gt(pe(n.workspace_context_mode),"--add"),env_set:vi(pe(n.env_set),"--add"),env_clear:wi(pe(n.env_clear),"--add"),shared_host_safe:hs(pe(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:qt(pe(n.assert_stdout_contains)),assert_stdout_regex:En(pe(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:qt(pe(n.assert_stderr_contains)),assert_stderr_regex:En(pe(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:vs(pe(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:ws(pe(n.assert_json_field_equals),"--add"),assert_json_field_gte:bs(pe(n.assert_json_field_gte),"--add"),note:pe(n.note)}}function pe(e){let t=e?.trim();return t&&t.length>0?t:void 0}function TN(e,t){if(e&&t&&e!==t)throw new p("--add timeout and timeout_seconds must match when both are provided",m.USAGE);let n=e??t;if(n===void 0)return;let i=Math.floor(_e(n,"timeout_seconds"));if(i<=0)throw new p("--add timeout_seconds must be a positive integer",m.USAGE);return i}function AN(e){return e?e.flatMap(t=>{let n=Xg(t,"--add-json");for(let i of n){let r=i.command;if(!r)throw new p("--add-json requires a non-empty command string",m.USAGE);Kv(r)}return n}):[]}function CN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires command or path value",m.USAGE);let i=/^(command|path)\s*=/i.exec(n);if(i){let r=n.slice(i[0].length).trim();if(!r)throw new p("--remove requires a non-empty command=<value> or path=<value>",m.USAGE);return{kind:i[1].toLowerCase(),value:r}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new p("--remove structured selectors require command=<value> or path=<value>",m.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let r=J(n,"--remove"),s=r.path!==void 0?"path":"command",o=r.path??r.command;if(!o?.trim())throw new p("--remove requires command=<value> and/or path=<value>",m.USAGE);return{kind:s,value:o.trim()}}return{kind:"either",value:n}}):[]}function IN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new p("--remove-index must be a positive integer",m.USAGE);return n}))]:[]}function xN(e){try{e.stdin?.end()}catch{}}function zv(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=gv?t:`${t.slice(0,gv-3)}...`}function Wv(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Qc(e){try{process.stderr.write(`${e}
|
|
19
|
+
`)}catch{}}function RN(e,t){if(!Wv(t))return null;let n=zv(e.command),i=Date.now();Qc(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let r=setInterval(()=>{let s=Date.now()-i;Qc(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},cN());return r.unref?.(),r}function ON(e,t,n,i){if(!Wv(i))return;let r=zv(e.command),s=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let d=t.exitCode===null?"null":String(t.exitCode),l=c.length>0?` ${c.join(" ")}`:"";Qc(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${d} elapsed_ms=${s}${l} command="${r}"`)}async function vv(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Lv("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function LN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function NN(e,t){let n=!1;return async()=>{if(n)return;n=!0;let i=e.pid;if(!i||i<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await vv(i);return}try{process.kill(-i,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{vv(i)},aN()),t.forceKillTimer.unref?.()}}function DN(e){return new Promise(t=>{let n=!1,i=null,r=(s,o=!1)=>{n||(n=!0,i&&(clearTimeout(i),i=null),o&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,o)=>{n||(i=setTimeout(()=>{r({code:s,signal:o},!0)},dN()),i.unref?.())}),e.on("close",(s,o)=>{r({code:s,signal:o})})})}function MN(e,t,n,i,r){return Lv(e,{cwd:r,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,i]})}async function wv(e){let t=await Xc(e,"r");try{let n=(await t.stat()).size,i=Math.min(n,ro),r=Buffer.alloc(i);return i>0&&await t.read(r,0,i,0),{text:r.toString("utf8"),truncated:n>ro}}finally{await t.close()}}async function PN(e,t,n,i,r,s=process.cwd()){let o=Date.now(),a=await Nv(Y.join(Mv(),"pm-linked-test-output-"));try{let c=Y.join(a,"stdout.log"),d=Y.join(a,"stderr.log"),[l,u]=await Promise.all([Xc(c,"w"),Xc(d,"w")]),_;try{_=MN(e,n,l.fd,u.fd,s)}catch(L){throw await Promise.all([l.close(),u.close()]),L}let f=DN(_),g;_.on("error",L=>{g=L.message}),await Promise.all([l.close(),u.close()]),xN(_);let h={heartbeat:RN(i,r),forceKillTimer:null,timedOutTimer:null},y=NN(_,h),v=!1;h.timedOutTimer=setTimeout(()=>{v=!0,y()},t),h.timedOutTimer.unref?.();let{code:w,signal:S}=await f;LN(h);let[E,T]=await Promise.all([wv(c),wv(d)]),A=E.truncated||T.truncated,k=A?`
|
|
20
|
+
[pm linked-test output truncated at ${ro} bytes per stream; the child process continued to completion]
|
|
21
|
+
`:"",b={stdout:`${E.text}${k}`,stderr:T.text,exitCode:w,signal:S,timedOut:v,maxBufferExceeded:!1,outputTruncated:A,spawnError:g};return ON(i,b,o,r),b}finally{await Li(a,{recursive:!0,force:!0})}}function FN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${ro} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let i=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,r=e.spawnError?.trim()||i||"Linked test command failed.";return n.length===0?r:`${r} ${n.join(" ")}`}function $N(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
22
|
+
`);return iN.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>rN.test(n)&&sN.test(n))}function UN(e){return $N(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function jN(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function ao(e){let t=jN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function bv(e,t){for(let[n,i]of Object.entries(t.env_set))jt.has(n.toUpperCase())||(e[n]=i);for(let n of t.env_clear)jt.has(n.toUpperCase())||delete e[n]}function GN(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function qN(e,t){let n={...e.env_set,...t.env_set},i=[...new Set([...e.env_clear,...t.env_clear??[]])],r=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:i,shared_host_safe:r}}function KN(e,t,n){return{env_set:gN(e,"--env-set"),env_clear:hN(t,"--env-clear"),shared_host_safe:n===!0}}async function Rn(e,t,n=!1,i=so){if(await Z(e))try{await $n("seed_linked_test",async()=>{if(await i(Y.dirname(t),{recursive:!0}),n){await Yc(e,t,{recursive:!0,force:!0});return}await Yc(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&W(r))return;throw r}}async function kv(e,t,n){await Rn(Te(n.projectPmRoot),Te(e)),await Rn(Y.join(n.projectPmRoot,"extensions"),Y.join(e,"extensions"),!0),await Rn(Te(n.globalPmRoot),Te(t)),await Rn(Y.join(n.globalPmRoot,"extensions"),Y.join(t,"extensions"),!0)}async function Sv(e,t){if(!await Z(e))return;let n=await Jc(e,{withFileTypes:!0});for(let i of n){if(tN.has(i.name))continue;let r=Y.join(e,i.name),s=Y.join(t,i.name);if(i.isDirectory()){await Rn(r,s,!0);continue}i.isFile()&&await Rn(r,s)}}async function Ev(e,t){let n=await ee(Te(e));if(n===null||await Z(Kn(e)))return;let i=await I(t);await Li(Kn(t),{force:!0}),await Li(Te(t),{force:!0}),await Kl({pmRoot:t,filePath:Te(t),raw:n,op:"settings:write",author:G(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function xn(e){if(!await Z(e))return 0;let t=0,n=await Jc(e,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||nN.has(i.name))continue;let r=Y.join(e,i.name),s;try{s=await Jc(r,{withFileTypes:!0})}catch{continue}for(let o of s)o.isFile()&&It.some(a=>o.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function zN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function WN(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let i of n){if(i.startsWith("[")&&i.endsWith("]")){let r=Number.parseInt(i.slice(1,-1),10);if(!Number.isInteger(r)||r<0)return[];t.push(r);continue}t.push(i)}return t}function Tv(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let i=WN(n);if(i.length===0)return{found:!1,value:void 0};let r=e;for(let s of i){if(typeof s=="number"){if(!Array.isArray(r)||s>=r.length)return{found:!1,value:void 0};r=r[s];continue}if(typeof r!="object"||r===null||!Object.prototype.hasOwnProperty.call(r,s))return{found:!1,value:void 0};r=r[s]}return{found:!0,value:r}}function BN(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function VN(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?st(e,t):Object.is(e,t)}function HN(e,t,n){let i=[];i.push(...Av("stdout",t,e.assert_stdout_contains)),i.push(...Cv("stdout",t,e.assert_stdout_regex)),i.push(...Av("stderr",n,e.assert_stderr_contains)),i.push(...Cv("stderr",n,e.assert_stderr_regex)),i.push(...YN(t,e.assert_stdout_min_lines));let r=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(r).length>0||Object.keys(s).length>0))return i;let a;try{a=JSON.parse(t)}catch(c){return i.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),i}for(let[c,d]of Object.entries(r)){let l=Tv(a,c);if(!l.found){i.push(`assert_json_field_equals missing path "${c}"`);continue}let u=BN(d);VN(l.value,u)||i.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(u)} actual=${JSON.stringify(l.value)})`)}for(let[c,d]of Object.entries(s)){let l=Tv(a,c);if(!l.found){i.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof l.value!="number"||!Number.isFinite(l.value)){i.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}l.value<d&&i.push(`assert_json_field_gte failed at "${c}" (expected >= ${d}, actual ${l.value})`)}return i}function Av(e,t,n){let i=[];for(let r of n??[])t.includes(r)||i.push(`${e} missing required text: "${r}"`);return i}function Cv(e,t,n){let i=[];for(let r of n??[])try{new RegExp(r,"m").test(t)||i.push(`${e} failed regex assertion: /${r}/m`)}catch(s){i.push(`${e} regex assertion is invalid: /${r}/ (${s instanceof Error?s.message:String(s)})`)}return i}function YN(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var XN=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],JN=[/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu,/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu,/\bTests?\s+[1-9]\d*\s+passed\b/iu,/\b[1-9]\d*\s+passed\b/iu,/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu];function QN(e,t){let n=`${e}
|
|
23
|
+
${t}`;for(let i of XN)if(i.regex.test(n))return{code:i.code};return null}function ZN(e,t){let n=`${e}
|
|
24
|
+
${t}`;return JN.some(i=>i.test(n))}function Iv(e){let t=Ni(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Dt(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&nd(n))}function eD(e){return{root:e,schemaProjectPmPath:Y.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:Y.join(e,"schema","global"),trackerProjectPmPath:Y.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:Y.join(e,"tracker","global"),workspaceSnapshotRoot:Y.join(e,"workspace","project"),workspaceIsolatedRoot:Y.join(e,"workspace","isolated")}}function tD(e,t,n){return e.some(i=>Pv(i,t,n)==="snapshot")}async function nD(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await so(Y.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await Yc(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(r){let s=Y.relative(t,r);return s?!s.split(Y.sep).some(o=>n.has(o)):!0}});let i=Y.join(t,"node_modules");await Z(i)&&await Dv(i,Y.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function iD(e,t){let n=Y.join(e,".agents"),i=Y.join(n,"pm");await so(n,{recursive:!0}),await Li(i,{recursive:!0,force:!0}),await Dv(t,i,process.platform==="win32"?"junction":"dir")}async function rD(e,t=Jo,n=!0){let i={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},i),await t(void 0,{path:e.schemaGlobalPmPath},i),n&&(await t(void 0,{path:e.trackerProjectPmPath},i),await t(void 0,{path:e.trackerGlobalPmPath},i))}async function sD(e,t,n){t&&(await kv(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await kv(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Sv(t.projectPmRoot,e.trackerProjectPmPath),await Sv(t.globalPmRoot,e.trackerGlobalPmPath),await Ev(t.projectPmRoot,e.trackerProjectPmPath),await Ev(t.globalPmRoot,e.trackerGlobalPmPath)))}function oD(e,t,n){return e.some(i=>{let r=i.command??"",s=r.length>0&&Uv(r),o=n?.autoPmContext===!0&&s?"auto":Fv(i,t,n?.overrideLinkedPmContext===!0);return $v(o,s)==="tracker"})}async function aD(e,t){return{sourceProjectItemCount:t?await xn(t.projectPmRoot):0,sourceGlobalItemCount:t?await xn(t.globalPmRoot):0,schemaProjectItemCount:await xn(e.schemaProjectPmPath),schemaGlobalItemCount:await xn(e.schemaGlobalPmPath),trackerProjectItemCount:await xn(e.trackerProjectPmPath),trackerGlobalItemCount:await xn(e.trackerGlobalPmPath)}}function cD(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,i=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,r=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,o=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":o;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:i,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:r,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==r||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:o,source_workspace_root:a,trust:e.trust}}async function dD(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?oo(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,i=n?yN(n):!1,r=i&&n?Uv(n):!1,s=e.options?.autoPmContext===!0&&r,o=s?"auto":Fv(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=$v(o,r),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await iD(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await Ga(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Ga(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:cD({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:i,isPmTrackerReadCommand:r,requestedPmContextMode:o,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function xv(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Zc(e,t,n,i){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...i?{stdout:i.stdout,stderr:i.stderr}:{},error:n}}function lD(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function uD(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let i=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return lD(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${i}`)}function mD(e){if(!e.linkedTest.command)return xv(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=kN(e.linkedTest.command);return t?xv(e.linkedTest,e.executionContext,t):null}function _D(e){let t=mD(e);if(t)return t;let n=uD(e);if(n)return n;let i=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,r=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(i||r){let s=fN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Zc(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${s}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!pN(e.linkedTest)?Zc(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function pD(e){let t=qN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return bv(n,e.runtimeDirectives),bv(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&GN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Xn]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Xn]="read_only"),n}function fD(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function Rv(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function gD(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:zN(e.execution),failure_category:UN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:FN(e.execution,e.timeoutMs)}}function hD(e){if(e.options?.failOnEmptyTestRun===!0||Iv(e.linkedTest.command??"")){let n=QN(e.execution.stdout,e.execution.stderr);if(n)return Rv({...e,emptyRunSignal:n});if(Iv(e.linkedTest.command??"")&&!ZN(e.execution.stdout,e.execution.stderr))return Rv({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let t=HN(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Zc(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):fD(e.linkedTest,e.executionContext,e.execution)}async function yD(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,i=await PN(t,n,pD(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return i.exitCode===0&&!i.timedOut&&!i.maxBufferExceeded?hD({...e,execution:i}):gD({...e,execution:i,timeoutMs:n})}async function id(e,t,n){let i=[],r=await Nv(Y.join(Mv(),"pm-linked-test-")),s=eD(r),o=oo(n?.pmContext),a=_N(n?.workspaceContext),c=n?.progress===!0?"always":"auto",d=KN(n?.envSet,n?.envClear,n?.sharedHostSafe),l=n?.sourceRoots,u=pi(),_=oD(e,o,n),f=tD(e,a,n?.overrideLinkedWorkspaceContext===!0),g=await _i(u);try{await rD(s,Jo,_),await so(s.workspaceIsolatedRoot,{recursive:!0}),await sD(s,l,_),f&&await nD(s,u);let h=await aD(s,l);for(let y=0;y<e.length;y+=1){let v=e[y],w=Pv(v,a,n?.overrideLinkedWorkspaceContext===!0),S=await dD({linkedTest:v,layout:s,counts:h,sourceRoots:l,runLevelPmContextMode:o,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:w,currentSourceRef:g,sourceWorkspaceRoot:u}),E=_D({linkedTest:v,executionContext:S.executionContext,runLevelPmContextMode:o,linkedOverridePmContextMode:S.linkedOverridePmContextMode,options:n});if(E){i.push(E);continue}i.push(await yD({linkedTest:v,index:y,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:d,progressMode:c,executionContext:S.executionContext,options:n}))}}finally{await Li(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return i}async function vD(e){let{id:t,pmRoot:n,settings:i,typeToFolder:r}=e,s=await Q(n,t,i.id_prefix,i.item_format,r);if(!s)throw new p(`Item ${t} not found`,m.NOT_FOUND);let o=await be(s,{schema:i.schema});return{itemId:s.id,tests:o.document.metadata.tests??[],testRuns:o.document.metadata.test_runs??[],changed:!1,removed:0}}function wD(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function bD(e,t){let n=[...e];for(let i of t)n.some(r=>wD(r,i))||n.push(i);return n}function kD(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let i=new Set(n),r=e.filter((s,o)=>i.has(o+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:r,removed:e.length-r.length}}function SD(e,t,n,i){return kD(bD(e,t),n,i)}function ED(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function TD(e){if(ED(e)&&e.run!==!0)throw new p("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",m.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new p("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",m.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new p("--match, --only-index, and --only-last require --run",m.USAGE)}async function AD(e){let{id:t,options:n,pmRoot:i,settings:r,typeToFolder:s,adds:o,removes:a,removeIndexes:c}=e;if(o.length===0&&a.length===0&&c.length===0)return vD({id:t,pmRoot:i,settings:r,typeToFolder:s});let d=0,l=await le({pmRoot:i,settings:r,id:t,op:o.length>0?"tests_add":"tests_remove",author:G(n.author,r.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let _=u.metadata.tests??[],f=SD(_,o,a,c);if(d=f.removed,(a.length>0||c.length>0)&&d===0)throw new p("No linked tests matched the requested removal selector",m.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(g=>`${g.kind}=${g.value}`),...c.map(g=>`index=${g}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return u.metadata.tests=f.tests,{changedFields:st(_,f.tests)?[]:["tests"]}}});return{itemId:l.item.id,tests:l.item.tests??[],testRuns:l.item.test_runs??[],changed:l.changedFields.length>0,removed:d}}function CD(e,t){TD(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Vc(e.onlyIndex),onlyLast:e.onlyLast},i=e.run===!0?fv(t,n):void 0,r=e.timeout===void 0?void 0:_e(e.timeout,"timeout");if(r!==void 0&&r<=0)throw new p("Test timeout must be a positive number",m.USAGE);return{defaultTimeoutSeconds:r,pmContextMode:oo(e.pmContext),runSelection:i,testsToRun:i?.selected??t}}async function ID(e){let{options:t,runOptions:n,pmRoot:i}=e;return t.run!==!0?[]:await id(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:i,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:i,globalPmRoot:Ye(process.cwd())}})}function xD(e,t,n){let i=[];if(t&&t.selector!==null&&i.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let r=td(n);i.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)}return i}function RD(e){let t=uN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),i=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),r=R(),s=Oi(e.options.measure,r);return{run_id:lN("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:r,recorded_at:r,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:i&&i.length>0?i:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(o=>o.command?.trim()).slice(0,32).map(o=>({command:o.command.trim(),requested_pm_context_mode:o.execution_context?.requested_pm_context_mode,pm_context_mode:o.execution_context?.pm_context_mode,workspace_context_mode:o.execution_context?.workspace_context_mode,trust_reason:o.execution_context?.trust.reason}))}}async function OD(e){let{options:t,pmRoot:n,settings:i,itemId:r,runStartedAt:s,runResults:o,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let d=RD({options:t,runStartedAt:s,runResults:o,failOnSkippedTriggered:a});if(i.testing.record_results_to_items!==!0)return d;try{return await to({pmRoot:n,settings:i,itemId:r,author:G(t.author,i.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),d}catch(l){return c.push(`test_result_tracking_failed:${r}:${l instanceof Error?l.message:String(l)}`),d}}function Ov(e,t,n){let i;if(e.metricBelow!==void 0){let r=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,r).trim(),o=e.metricBelow.slice(r+1).trim(),a=Number(o);if(r<=0||s.length===0||o.length===0||!Number.isFinite(a))throw new p("--metric-below must use name=value",m.USAGE);i=Zy(t,s,a)}return{measurements:n?.measurements,metric_below:i,metric_diff:e.metricDiff===void 0?void 0:ev(t,e.metricDiff)}}async function LD(e,t,n){if(e.acknowledgeLinkedTests===!0)return vf(t,n,R())}async function Bv(e,t,n){let i=en(),r=x(process.cwd(),n.path);await P(r);let s=await I(r);if((t.measure?.length??0)>0&&t.run!==!0)throw new p("--measure requires --run",m.USAGE);Oi(t.measure,"validation"),Ov(t,[],void 0);let o=$(s,M()),a=await i.resolveList(t.add,"--add"),c=await i.resolveList(t.addJson,"--add-json"),d=await i.resolveList(t.remove,"--remove"),l=[...SN(a),...AN(c)],u=await kn(l,G(t.author,s.author_default),R())??[],_=CN(d),f=IN(t.removeIndex),g=await AD({id:e,options:t,pmRoot:r,settings:s,typeToFolder:o.type_to_folder,adds:u,removes:_,removeIndexes:f}),h=CD(t,g.tests),y=await LD(t,r,g.tests),v=t.run===!0?R():void 0,w=await ID({options:t,runOptions:h,pmRoot:r,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests}),S=ao(w),E=t.run===!0&&t.failOnSkipped===!0&&w.some(L=>L.status==="skipped"),T=xD(t,h.runSelection,w);y&&T.push(`linked_test_trust_acknowledged:${y.acknowledged}`);let A=await OD({options:t,pmRoot:r,settings:s,itemId:g.itemId,runStartedAt:v,runResults:w,failOnSkippedTriggered:E,warnings:T}),k=A?Bc([...g.testRuns,A]):g.testRuns,b=Ov(t,k,A);return{ok:w.every(L=>L.status!=="failed")&&E!==!0,id:g.itemId,tests:g.tests,run_results:w,failure_categories:S,selection:h.runSelection?{selector:h.runSelection.selector,requested:h.runSelection.requested,selected_indexes:h.runSelection.selected_indexes,selected_count:h.runSelection.selected_count,skipped_count:h.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:E?!0:void 0,warnings:T.length>0?T:void 0,changed:g.changed,count:g.tests.length,...g.removed>0?{removed:g.removed}:{},...b}}(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]="e3e3a1d4-4552-5f3c-9b02-c33ae72ea32b")}catch{}})();var ND=(e,t)=>{if(e===void 0)return;let n=se(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new p(`Invalid --status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n},DD=e=>{if(e===void 0)return;let t=_e(e,"timeout");if(t<=0)throw new p("timeout must be a positive number",m.USAGE);return t},Vv=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new p(`${t} must be a non-negative integer`,m.USAGE);return n},MD=e=>e instanceof Error?e.message:String(e),PD=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},FD=e=>e.trim().replaceAll(/\s+/g," "),$D=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),UD=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),jD=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},GD=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},co=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Hv=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),qD=e=>typeof e=="number"?e:void 0,KD=e=>{let t={assert_stdout_contains:co(e.assert_stdout_contains),assert_stdout_regex:co(e.assert_stdout_regex),assert_stderr_contains:co(e.assert_stderr_contains),assert_stderr_regex:co(e.assert_stderr_regex),assert_stdout_min_lines:qD(e.assert_stdout_min_lines),assert_json_field_equals:Hv(e.assert_json_field_equals),assert_json_field_gte:Hv(e.assert_json_field_gte)};return JSON.stringify(t)},zD=e=>{let t=rd(e.command);return t!==void 0?`command:${e.scope}:${FD(t)}`:`path:${e.scope}:${rd(e.path)??""}`},Yv=e=>{let t=$D(e.env_set),n=UD(e.env_clear),i=jD(e.pm_context_mode),r=GD(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",o=KD(e);return`${zD(e)}:${t}:${n}:${i}:${r}:${s}:${o}`},WD=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,BD=e=>{let t=0,n=0,i=0;for(let r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"){n+=1;continue}i+=1}return{passed:t,failed:n,skipped:i}},VD=(e,t)=>{for(let[n,i]of Object.entries(t))e[n]+=i},lo=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
25
|
+
`)}catch{}},HD=async(e,t,n)=>{let i=[],r=0;for(let s of e){let o=await Bv(s.id,{run:!1},{...t,path:n});r+=o.tests.length,i.push({item:s,tests:o.tests})}return{itemTests:i,linkedTests:r}},YD=async e=>{let t=K(e.settings.schema),n=$(e.settings,M()),i=ND(e.options.status,t),r=Vv(e.options.limit,"--limit"),s=Vv(e.options.offset,"--offset")??0,a=(await ke(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>i?d.status===i:!0).sort((d,l)=>d.id.localeCompare(l.id));return{filteredItems:r===void 0?a.slice(s):a.slice(s,s+r),statusFilter:i,limitFilter:r,offsetFilter:s}},XD=e=>{let t=new Map;for(let{tests:n}of e)for(let i of n){let r=Yv(i);if(!t.has(r)){t.set(r,i.timeout_seconds);continue}t.set(r,WD(t.get(r),i.timeout_seconds))}return t},JD=async(e,t)=>{let n=[],i=e.tests.map(l=>{let u=Yv(l),_=t.seenTestKeys.has(u);if(!_){t.seenTestKeys.add(u);let f=t.effectiveTimeoutByKey.get(u);n.push(f===void 0?l:{...l,timeout_seconds:f})}return{test:l,key:u,duplicate:_}}),r=n.length>0?await id(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],s=0,o=i.map(({test:l,key:u,duplicate:_})=>{if(!_){let f=r[s];return s+=1,f}return{command:l.command,path:l.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),a=BD(o),c=ao(o),d=await eM(e,a,o,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:d,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:o,failure_categories:c}}},QD=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),ZD=e=>e?!0:void 0,eM=async(e,t,n,i)=>{if(!i.trackingEnabled)return[];try{let r=QD(t,i.options);await to({pmRoot:i.pmRoot,settings:i.settings,itemId:e.item.id,author:i.trackingAuthor,message:`Track test-all run summary (${i.trackingRunId})`,entry:{run_id:i.trackingRunId,kind:"test-all",status:r?"failed":"passed",started_at:i.runStartedAt,finished_at:R(),recorded_at:R(),attempt:i.trackingAttempt,resumed_from:i.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:ZD(i.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}})}catch(r){return[`test_result_tracking_failed:${e.item.id}:${MD(r)}`]}return[]},tM=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},rd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},nM=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:Ye(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:XD(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:G(e.options.author,e.settings.author_default),trackingRunId:PD(),trackingAttempt:tM(),trackingResumedFrom:rd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),iM=(e,t,n)=>{let i={results:[],passed:0,failed:0,skipped:0,failureCategories:ao([]),trackingWarnings:[]},r=e.failOnEmptyTestRun===!0&&t===0;return r&&(i.failed+=1,i.failureCategories.empty_run+=1,i.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:i,failOnEmptyTestRunTriggered:r}},rM=async(e,t,n)=>{for(let[i,r]of e.entries()){lo(t.options,`item ${i+1}/${e.length} start id=${r.item.id} linked_tests=${r.tests.length}`);let s=await JD(r,t);VD(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),lo(t.options,`item ${i+1}/${e.length} end id=${r.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}},sM=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(r=>r.run_results),i=td(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${i.checked_pm_commands};tracker_read_commands=${i.tracker_read_commands};mismatches=${i.mismatches};auto_remediated=${i.auto_remediated}`)},oM=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),aM=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),cM=async(e,t)=>{let n=x(process.cwd(),t.path);await P(n);let i=await I(n),r=await YD({pmRoot:n,settings:i,options:e}),s=DD(e.timeout),o=R(),a=await HD(r.filteredItems,t,n);return lo(e,aM({...r,linkedTests:a.linkedTests})),{pmRoot:n,settings:i,filteredItems:r.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:s,runStartedAt:o}},dM=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},VB=async(e,t)=>{let n=await cM(e,t),{accumulation:i,failOnEmptyTestRunTriggered:r}=iM(e,n.linkedTests,n.filteredItems),s=nM({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await rM(n.itemTests,s,i),sM(e,i);let o=dM({options:e,accumulation:i,failOnEmptyTestRunTriggered:r});return lo(e,`end status=${o.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${i.passed} failed=${i.failed} skipped=${i.skipped}`),oM({ok:o.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:i,failOnSkippedTriggered:o.failOnSkippedTriggered,failOnEmptyTestRunTriggered:r})};import UM from"node:os";import On from"node:fs/promises";import{spawn as ew}from"node:child_process";import{createHash as lM,randomBytes as uM}from"node:crypto";import Di 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]="2c2a4576-a5d8-57c1-84e8-ca8b9019c84e")}catch{}})();var tw=new Set(["queued","running"]),cd=new Set(["passed","failed","stopped","canceled"]),mM=3e3,_M=3e3,pM=3e4,nw=100,Xv=100;function iw(){return Date.now()}function rw(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function fM(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function gM(){let e=Date.now().toString(36),t=uM(3).toString("hex");return`tr-${e}-${t}`}function hM(e,t,n){let i={kind:e,command:rw(t),pm_root:Di.resolve(n)};return lM("sha256").update(JSON.stringify(i)).digest("hex")}function Ln(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function yM(e){await gt(Wd(e)),await gt(So(e)),await gt(Bd(e)),await gt(Vd(e)),await gt(Xd(e))}async function sw(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new p(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,m.GENERIC_FAILURE)}}async function nt(e,t){let n={...t,updated_at:R()};await Ve(Eo(e,t.id),`${JSON.stringify(n,null,2)}
|
|
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
|
+
`);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
|
+
`)}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
|