@unbrained/pm-cli 2026.8.22 → 2026.8.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +28 -0
  3. package/dist/cli/error-guidance.d.ts +13 -0
  4. package/dist/cli/error-guidance.js +62 -6
  5. package/dist/cli/main.js +13 -4
  6. package/dist/cli/register-mutation.js +6 -6
  7. package/dist/cli/register-operations.d.ts +73 -0
  8. package/dist/cli/register-operations.js +39 -14
  9. package/dist/cli/register-setup.js +3 -3
  10. package/dist/cli/schema-registration-helpers.d.ts +8 -1
  11. package/dist/cli/schema-registration-helpers.js +14 -5
  12. package/dist/cli-bundle/bundle-manifest.json +155 -155
  13. package/dist/cli-bundle/chunks/chunk-3ENVHX6C.js +36 -0
  14. package/dist/cli-bundle/chunks/{chunk-QI2CT3IX.js → chunk-DW2CGEMU.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-WG4STC36.js → chunk-EG6CLDZT.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-MYYI3ZOA.js → chunk-F3AI2JFL.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-U6GQ4VMV.js → chunk-HWZ6CELB.js} +4 -4
  18. package/dist/cli-bundle/chunks/chunk-HZBMLSZI.js +201 -0
  19. package/dist/cli-bundle/chunks/chunk-JB4KZWBF.js +3 -0
  20. package/dist/cli-bundle/chunks/chunk-KPH73XXJ.js +2 -0
  21. package/dist/cli-bundle/chunks/{chunk-BWX4SK46.js → chunk-KXPMB2YL.js} +58 -58
  22. package/dist/cli-bundle/chunks/{chunk-MZTZQTMS.js → chunk-QDVHNHAQ.js} +2 -2
  23. package/dist/cli-bundle/chunks/chunk-TFI5V5N2.js +13 -0
  24. package/dist/cli-bundle/chunks/{register-list-query-HZKBQNWW.js → register-list-query-UJB5FMV2.js} +2 -2
  25. package/dist/cli-bundle/chunks/register-mutation-NX5XE4VX.js +20 -0
  26. package/dist/cli-bundle/chunks/register-operations-RXIJIYXC.js +2 -0
  27. package/dist/cli-bundle/chunks/{register-setup-QK4OTOXN.js → register-setup-GFUZEKRE.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-2POVTNLY.js → chunk-37Z4OEAP.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/chunk-3UPTYG44.js +8 -0
  30. package/dist/cli-bundle/focused-chunks/{chunk-E2EWYPY6.js → chunk-5S7E72FY.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-GMYPD4FX.js → chunk-AUFH5H35.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/chunk-E7X25GC3.js +2 -0
  33. package/dist/cli-bundle/focused-chunks/{chunk-3LKU6PTJ.js → chunk-FQCSTBWE.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-6S2MO3Q3.js → chunk-FZS4H32O.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/chunk-IFLWKY2R.js +156 -0
  36. package/dist/cli-bundle/focused-chunks/{chunk-PMGJUFNQ.js → chunk-JOWDB2MH.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/chunk-LYVSW5VM.js +2 -0
  38. package/dist/cli-bundle/focused-chunks/chunk-MRCNF3U6.js +2 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-A2BC5PQL.js → chunk-OFVUGTLJ.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-2ARQGDDW.js → chunk-OGLQBL46.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-R6SR45XU.js → chunk-OY7QAV4Y.js} +48 -47
  42. package/dist/cli-bundle/focused-chunks/chunk-QGFNI65N.js +26 -0
  43. package/dist/cli-bundle/focused-chunks/{chunk-D6RBZEJJ.js → chunk-R27IDGHD.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-UYRFYCDQ.js +5 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-PH2OXXVZ.js → chunk-ZHVA42R5.js} +9 -9
  46. package/dist/cli-bundle/main.js +13 -13
  47. package/dist/cli-bundle/sdk-authoring.js +1 -1
  48. package/dist/cli-bundle/sdk-contracts.js +2 -2
  49. package/dist/cli-bundle/sdk-core.js +40 -40
  50. package/dist/cli-bundle/sdk-governance.js +1 -1
  51. package/dist/cli-bundle/sdk-graph.js +1 -1
  52. package/dist/cli-bundle/sdk-merge.js +33 -32
  53. package/dist/cli-bundle/sdk-query.js +1 -1
  54. package/dist/cli-bundle/sdk-runtime.js +1 -1
  55. package/dist/cli-bundle/sdk-testing.js +1 -1
  56. package/dist/cli-bundle/sdk.js +5 -5
  57. package/dist/core/config/nested-settings.js +8 -2
  58. package/dist/core/config/positional-value.d.ts +1 -1
  59. package/dist/core/config/positional-value.js +5 -2
  60. package/dist/core/history/history.js +3 -3
  61. package/dist/core/item/item-format.js +66 -12
  62. package/dist/core/reproducibility/context.d.ts +4 -0
  63. package/dist/core/reproducibility/context.js +14 -8
  64. package/dist/core/shared/author.d.ts +55 -1
  65. package/dist/core/shared/author.js +333 -16
  66. package/dist/core/shared/constants.js +3 -2
  67. package/dist/core/store/settings-validator.d.ts +1 -0
  68. package/dist/core/store/settings-validator.js +6 -3
  69. package/dist/core/store/settings.js +5 -2
  70. package/dist/mcp/server.d.ts +1 -1
  71. package/dist/mcp/server.js +30 -9
  72. package/dist/sdk/agent/identity-config.d.ts +63 -0
  73. package/dist/sdk/agent/identity-config.js +107 -0
  74. package/dist/sdk/agent/refusal-corpus-contracts.d.ts +76 -0
  75. package/dist/sdk/agent/refusal-corpus-contracts.js +194 -0
  76. package/dist/sdk/cli-contracts/agent-output-contracts.js +6 -4
  77. package/dist/sdk/cli-contracts/enum-contracts.d.ts +4 -0
  78. package/dist/sdk/cli-contracts/enum-contracts.js +9 -2
  79. package/dist/sdk/cli-contracts/flag-contracts.js +9 -2
  80. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +4 -4
  81. package/dist/sdk/cli-contracts/registration-helpers.js +5 -2
  82. package/dist/sdk/cli-contracts/tool-parameter-tables.js +22 -2
  83. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  84. package/dist/sdk/cli-contracts/tool-schema.js +14 -3
  85. package/dist/sdk/cli-contracts.d.ts +3 -3
  86. package/dist/sdk/cli-contracts.js +4 -4
  87. package/dist/sdk/config.d.ts +6 -1
  88. package/dist/sdk/config.js +119 -14
  89. package/dist/sdk/context-intent-contracts.js +4 -2
  90. package/dist/sdk/core-governance.d.ts +1 -1
  91. package/dist/sdk/core-governance.js +3 -3
  92. package/dist/sdk/extension/scaffold.js +11 -5
  93. package/dist/sdk/flag-invocation-contracts.js +4 -2
  94. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +50 -2
  95. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +87 -38
  96. package/dist/sdk/governance/assurance-action.js +30 -10
  97. package/dist/sdk/governance/validate.d.ts +2 -2
  98. package/dist/sdk/governance/validate.js +39 -14
  99. package/dist/sdk/index.d.ts +7 -2
  100. package/dist/sdk/index.js +8 -3
  101. package/dist/sdk/lifecycle/create.js +6 -3
  102. package/dist/sdk/lifecycle/update.js +5 -3
  103. package/dist/sdk/merge/three-way.js +105 -26
  104. package/dist/sdk/read-output-budget.d.ts +21 -0
  105. package/dist/sdk/read-output-budget.js +39 -2
  106. package/dist/sdk/read-output-contracts.d.ts +5 -3
  107. package/dist/sdk/read-output-contracts.js +20 -12
  108. package/dist/sdk/reproducibility/process.d.ts +19 -0
  109. package/dist/sdk/reproducibility/process.js +88 -0
  110. package/dist/sdk/runtime-primitives.d.ts +1 -1
  111. package/dist/sdk/runtime-primitives.js +3 -3
  112. package/dist/sdk/runtime.js +6 -5
  113. package/dist/sdk/test/batch.d.ts +6 -0
  114. package/dist/sdk/test/batch.js +15 -3
  115. package/dist/sdk/test/entry.d.ts +1 -1
  116. package/dist/sdk/test/entry.js +3 -2
  117. package/dist/sdk/test/execution.d.ts +28 -3
  118. package/dist/sdk/test/execution.js +193 -34
  119. package/dist/sdk/test/parsers.d.ts +6 -0
  120. package/dist/sdk/test/parsers.js +21 -2
  121. package/dist/sdk/test/trust.d.ts +33 -0
  122. package/dist/sdk/test/trust.js +207 -0
  123. package/dist/types.d.ts +23 -0
  124. package/dist/types.js +2 -2
  125. package/docs/AGENT_PROVENANCE_ADR.md +41 -5
  126. package/docs/CONFIGURATION.md +4 -0
  127. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +19 -2
  128. package/docs/MERGE_SAFETY.md +15 -1
  129. package/docs/READ_OUTPUT_CONTRACTS.md +11 -1
  130. package/docs/REPRODUCIBLE_WORKSPACES.md +42 -8
  131. package/docs/SDK.md +9 -0
  132. package/docs/SDK_AGENT_SESSION_CONTEXT.md +6 -4
  133. package/docs/SDK_EVIDENCE_TRACEABILITY.md +1 -1
  134. package/docs/TESTING.md +75 -8
  135. package/docs/agent-task-token-baseline.json +2 -2
  136. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  137. package/marketplace.json +2 -2
  138. package/package.json +2 -2
  139. package/packages/pm-beads/package.json +1 -1
  140. package/packages/pm-calendar/package.json +1 -1
  141. package/packages/pm-command-kit/package.json +1 -1
  142. package/packages/pm-digital-twin/package.json +1 -1
  143. package/packages/pm-governance-audit/package.json +1 -1
  144. package/packages/pm-guide-shell/package.json +1 -1
  145. package/packages/pm-kanban/package.json +1 -1
  146. package/packages/pm-lifecycle-hooks/package.json +1 -1
  147. package/packages/pm-linked-test-adapters/package.json +1 -1
  148. package/packages/pm-search-advanced/package.json +1 -1
  149. package/packages/pm-templates/package.json +1 -1
  150. package/packages/pm-todos/package.json +1 -1
  151. package/packages/pm-vcs/package.json +1 -1
  152. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  153. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  154. package/sdk/public-surface.json +427 -17
  155. package/dist/cli-bundle/chunks/chunk-EMWDM5FI.js +0 -13
  156. package/dist/cli-bundle/chunks/chunk-HYG6LRL4.js +0 -200
  157. package/dist/cli-bundle/chunks/chunk-SMWXHMVB.js +0 -35
  158. package/dist/cli-bundle/chunks/chunk-VMMIL3SI.js +0 -2
  159. package/dist/cli-bundle/chunks/chunk-YBPJAOQQ.js +0 -3
  160. package/dist/cli-bundle/chunks/register-mutation-HTKEEGRD.js +0 -20
  161. package/dist/cli-bundle/chunks/register-operations-6EMRWJJY.js +0 -2
  162. package/dist/cli-bundle/focused-chunks/chunk-2AZT5WXZ.js +0 -2
  163. package/dist/cli-bundle/focused-chunks/chunk-5SHSBMX2.js +0 -2
  164. package/dist/cli-bundle/focused-chunks/chunk-C4S4A4JJ.js +0 -5
  165. package/dist/cli-bundle/focused-chunks/chunk-L5LDSRO2.js +0 -155
  166. package/dist/cli-bundle/focused-chunks/chunk-MB37AYN6.js +0 -26
  167. package/dist/cli-bundle/focused-chunks/chunk-MCOR37QK.js +0 -2
  168. package/dist/cli-bundle/focused-chunks/chunk-WZE4LIPW.js +0 -8
@@ -0,0 +1,36 @@
1
+ import{Ca as jm,Ma as xa,e as Am,i as Pn,j as Pm,na as Ea,q as Zt,s as Fm,t as $m,u as oi,xa as Um,ya as Sa,za as Ta}from"./chunk-HWZ6CELB.js";import{Bc as Jm,Ca as Dm,Da as ba,E as Cm,F as Dn,G as Mn,Ga as Gm,H as be,J as si,M as ai,N as Im,P as va,Pa as qm,Q as Rm,S as Om,Sa as Km,Ta as Fn,Wa as zm,Xa as Wm,Ya as Bm,Za as Vm,Zb as Hm,_b as Ym,ja as Nm,ka as Lm,yc as Xm}from"./chunk-TFI5V5N2.js";import{$a as kd,$g as yl,$h as Ol,$k as Nu,A as Ir,Aa as wd,Aj as Bl,Ak as ou,Al as nm,B as Sn,Ba as vd,Bg as _l,Bj as Vl,Bk as cu,Bl as rm,C as f,Ca as Qs,Ci as Pl,Cj as Hl,Ck as du,Cl as im,Dj as Yl,Dk as lu,Dl as sm,E as p,Ec as Md,Ek as uu,El as am,Fc as Pd,Fj as Xl,Fk as mu,Fl as om,Fm as Mm,G as re,Gh as ni,Gk as fu,Gl as cm,H as dd,Hi as Fl,Hk as pu,Hl as dm,Hm as ka,Ic as it,Ik as _u,Il as lm,Ja as Zs,Jc as Fd,Jg as Wr,Jh as kl,Ji as $l,Jk as gu,Jl as um,Ka as xn,Kc as Me,Kd as Hd,Kg as Vt,Kh as El,Kj as Jl,Kk as hu,Kl as mm,La as Ee,Lc as $d,Lg as ye,Lh as Sl,Lj as Ql,Lk as yu,Ll as fm,Mc as Ud,Mf as dl,Mg as Br,Mh as Tl,Mi as ca,Mk as wu,Ml as pm,N as ld,Nc as jd,Nd as In,Ng as gl,Nj as ii,Nk as vu,Nl as ha,Oa as U,Ob as J,Od as Rn,Oi as Ul,Oj as Zl,Ok as bu,Ol as _m,Pa as tt,Pb as rt,Pe as ra,Pg as Ht,Ph as xl,Pk as ku,Qa as Lr,Qb as Cn,Qg as Yt,Qh as R,Ql as ya,R as x,Ra as Kt,Rh as Al,Rk as Eu,Rl as gm,S as ud,Sa as An,Sc as pt,Sh as Cl,Sk as ga,Sl as hm,Ta as xt,Tc as Fr,Te as Qd,Tk as Su,Tl as ym,U as md,Uc as $r,Ue as Zd,Uk as Tu,Ul as wm,Vc as Gd,Ve as el,Vk as xu,Vl as vm,W as ue,Wa as I,We as tl,Wk as Au,Wl as gt,Xa as nt,Xe as nl,Xg as _t,Xh as Il,Xk as Cu,Xl as bm,Ya as We,Yd,Ye as rl,Yf as ll,Yg as hl,Yh as Rl,Yk as Iu,Yl as km,Za as je,Ze as Be,Zk as Ru,Zl as Em,_a as bd,_e as il,_g as Vr,_k as Ou,_l as Sm,ab as ft,ae as na,ah as Hr,ai as ri,al as Lu,am as Tm,b as Ue,bb as Dr,be as K,bh as Yr,bi as Nl,bl as Du,c as z,cb as Ed,cd as Ur,ce as Bt,ch as Xr,cl as Mu,d as Cr,da as Rr,db as Sd,df as sl,dh as Jr,dl as Pu,e as $,ea as Xs,eb as ea,ed as X,ef as al,eh as wl,el as Fu,f as ne,fb as ta,fd as jr,ff as ia,fh as Qr,fi as F,fj as da,fl as $u,g as le,gb as Td,gc as Mr,gd as zt,gh as vl,gi as Z,gj as la,gl as Uu,h as nd,hb as xd,hh as Q,hi as we,hj as ua,hk as fa,hl as ju,i as rd,ia as fd,ib as Ad,ic as Pr,id as Gr,ih as Xt,ii as Jt,ij as ma,ik as eu,il as Gu,jb as Cd,jd as qd,je as Xd,jg as ul,jh as _e,ji as ve,jl as qu,jm as wa,kb as Id,kd as Kd,kh as Ve,ki as Qt,kj as jl,kl as Ku,lb as Rd,lh as me,li as Ll,lk as tu,ll as zu,md as zd,mf as ol,mg as aa,mh as Zr,mi as Nn,mk as pa,ml as Wu,nd as qr,nh as ei,nk as Ct,nl as Bu,nm as xm,oa as Js,oi as Dl,oj as Ln,ol as Vu,pe as Jd,pg as ml,ph as ti,pi as ce,pk as nu,pl as Hu,qd as Kr,qf as cl,ql as Yu,ra as Tn,rb as Od,rc as Dd,rd as ae,rg as fl,ri as oa,rj as Gl,rl as Xu,s as id,sa as De,sg as pl,sh as bl,si as Ml,t as sd,ta as Or,tb as Nd,td as oe,tj as ql,ua as Nr,ud as Wt,uj as Kl,uk as _a,v as ad,va as pd,vb as At,vd as Wd,vf as sa,vh as On,vj as zl,vl as Ju,wa as _d,wj as Wl,wk as ru,wl as Qu,x as od,xa as gd,xb as Ld,xd as zr,xk as iu,xl as Zu,ya as hd,yd as Bd,yk as su,yl as em,z as cd,za as yd,zc as P,zd as Vd,zk as au,zl as tm}from"./chunk-HZBMLSZI.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]="d2d5135a-8110-527e-8530-653b25b792a4")}catch{}})();var N=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Ie=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},He=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 en(e){try{return await e()}catch(t){throw t instanceof N?new p(t.message,f.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Qm(e){try{return await e()}catch(t){throw t instanceof Ie?new p(t.message,f.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as mv}from"node:crypto";import fv 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]="b911b43d-d14d-5e4f-a35e-5020b1a84542")}catch{}})();var tn=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]="d4c380ce-031e-5b2d-aaa8-658bb4aa3087")}catch{}})();var ef=1,st=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],$n=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],pv=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],_v=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,ci=30,di=5e3,tf=4,gv=50;function at(e,t){if(!_v.test(e))throw new N(`${t} must be a stable lowercase id`)}function hv(e,t){if(!Number.isFinite(e)||e<0)throw new N(`${t} must be a finite non-negative number`)}function Un(e){let t=pv.filter(i=>e[i]!==void 0);if(t.length!==1)throw new N(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function Ca(e,t){return J(e)===J(t)}function nf(e,t){if(t.polarity==="equals")return Ca(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function rf(e){let t=Un(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>nf(r.observed,t)===(r.expected==="pass"))}function yv(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!Ca(e.value,t.value)}function wv(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||J(e.scope)!==J(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return yv(Un(e),Un(t))||n[t.enforcement]<n[e.enforcement]||r}function vv(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,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new N("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new N("items source equals/state requires field")}function bv(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 kv(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 Ia(e){at(e.id,"measurement.id"),e.max_cost!==void 0&&hv(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 ${$n.join(", ")}`);let n=Reflect.get(t,"kind");if(!$n.includes(n))throw new N(`measurement.source.kind must be one of ${$n.join(", ")}`);let r=t;if(r.kind==="items"&&vv(r),r.kind==="dependency_kind"&&bv(r),r.kind==="prose_edge_gap"&&kv(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new N(`${r.kind} source requires field`);return r.kind==="provider"&&(at(r.provider,"provider source provider"),at(r.key,"provider source key")),e}function Ra(e){if(at(e.id,"assertion.id"),at(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new N("assertion.owner_item_id is required");let t=Un(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"&&at(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new N("assertion negative control requires pass and fail cases");if(!rf(e))throw new N(`assertion ${e.id} negative control does not prove its bound`);return e}function Ev(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)at(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(!st.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 sf(e){if(at(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)at(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new N(`gate.triggers is required and must be an array of ${st.join(", ")}`);if(e.triggers.length===0)throw new N("gate requires at least one trigger");for(let t of e.triggers)if(!st.includes(t))throw new N(`gate trigger must be one of ${st.join(", ")}`);return e.provider_policy&&Ev(e.provider_policy),e}function nn(e){if(e.version!==ef)throw new N(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Ia(r),t.has(`measurement:${r.id}`))throw new N(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(Ra(r),t.has(`assertion:${r.id}`))throw new N(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){sf(r);let i=r.assertion_ids.filter(s=>!e.assertions.some(a=>a.id===s));if(i.length>0)throw new N(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new N(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of af(e))if(!n.has(r))throw new N(`${i.join(", ")} references missing measurement ${r}`);return e}function Oa(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)Oa(n,t)}function af(e){let t=new Map,n=(r,i)=>{let s=t.get(r)??[];s.push(i),t.set(r,s)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];Oa(r.source.expression,i);for(let s of i)n(s,`derived measurement ${r.id}`)}return t}function Sv(e,t){let n=e.assertion_ids.flatMap(s=>{let a=t.assertions.find(o=>o.id===s);return[a.measurement_id,...a.scope.kind==="filter"?[a.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let s=n.pop();if(r.has(s))continue;r.add(s);let a=t.measurements.find(o=>o.id===s);a.source.kind==="provider"?i.add(a.source.provider):a.source.kind==="derived"&&Oa(a.source.expression,n)}return i}function jn(){return{version:ef,measurements:[],assertions:[],gates:[]}}function Tv(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let s=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?s:!s}return Ca(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function xv(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 Av(e,t){let n=[],r=At(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let s of i.dependencies??[]){let a=At(s.kind)??s.kind.trim().toLowerCase(),o=s.source_kind?.trim();a===r&&xv(e,o)&&n.push(`${i.id}->${s.id}${o?`@${o}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Cv(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let s=Reflect.get(i,"text");typeof s=="string"&&t.push(s)}}}return t}function Iv(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function Aa(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Rv(e){let t=new Map,n=new Set,r=[],i=/\b[a-z][a-z0-9]*-[a-z0-9]+\b/giu,s=0;for(let a of e){t.set(a.id.toLowerCase(),a.id);for(let o of a.dependencies??[])n.add(Aa(a.id,o.id));for(let o of[a.parent,a.blocked_by])typeof o=="string"&&n.add(Aa(a.id,o));for(let o of Cv(a)){let c=[...o.matchAll(i)].map(d=>d[0]);s+=c.length,r.push({holder_id:a.id,segment:o,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:s}}function Ov(e,t){let n=Rv(t.items),r=new Map;for(let a of n.prose_mentions){let o=a.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==a.holder_id),c=[...new Set(o)];for(let d of c){let l=Aa(a.holder_id,d);if(n.linked_pairs.has(l)||Iv(e.exemptions??[],a.holder_id,d,a.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${a.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],s=i.map(a=>a.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:i.filter(a=>a.explicit).length,implicit_subject:i.filter(a=>!a.explicit).length}}}function Nv(e,t){return{value:t.history.filter(r=>(e.op===void 0||r.op===e.op)&&(e.author===void 0||r.author===e.author)&&(e.harness===void 0||r.agent_harness===e.harness)&&(e.model===void 0||r.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function Lv(e,t){let n=t.items.filter(r=>{let i=r[e.link],s=Array.isArray(i)&&i.length>0;return e.state==="present"?s:!s});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Dv(e,t){let n=e.source;return n.kind==="items"?Tv(n,t):n.kind==="dependency_kind"?Av(n,t):n.kind==="prose_edge_gap"?Ov(n,t):n.kind==="history"?Nv(n,t):n.kind==="links"?Lv(n,t):null}function of(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function Mv(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function cf(e,t,n){let r=new Array(e.length),i=0,s=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let a=i;i+=1,r[a]=await n(e[a],a)}});return await Promise.all(s),r}async function df(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let a=n.find(d=>d.id===e.measurement);if(!a)throw new TypeError(`derived measurement references missing ${e.measurement}`);let o=await lf(a,t,n,r,i);if(typeof o.value!="number")throw new TypeError(`derived measurement ${a.id} is not numeric`);let c=i.charged.has(a.id)?[]:[o.cost];return i.charged.add(a.id),{value:o.value,costs:c,population_size:o.population_size,contributors:o.contributors}}let s=await cf(e.operands,tf,a=>df(a,t,n,r,i));return{value:Mv(e.operator,s.map(a=>a.value)),costs:s.flatMap(a=>a.costs),population_size:Math.max(0,...s.map(a=>a.population_size)),contributors:[...new Set(s.flatMap(a=>a.contributors))]}}async function Pv(e,t,n,r,i){Ia(e);let s=Date.now(),a,o=[],c=0;if(e.source.kind==="derived"){let u=await df(e.source.expression,t,n,[...r,e.id],i);a={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},o=u.costs}else{let u=Dv(e,t);u!==null?a=u:(a=await t.external(e.source),c=1)}let d={units:a.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=of([...o,d],Date.now()-s);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Ie(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${mv("sha256").update(J(e)).digest("hex")}`,value:a.value,population_size:a.population_size,cost:l,contributors:a.contributors??[],...a.partitions?{partitions:a.partitions}:{}}}function lf(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let s=i.cache.get(e.id);if(s)return s;let a=Pv(e,t,n,r,i).catch(o=>{if(o instanceof He&&o.measurement_id===void 0){let c={measurement_id:e.id,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}},d=new He(o.message,c);throw d.cause=o,d}throw o});return i.cache.set(e.id,a),a}async function Na(e,t,n=[e]){return lf(e,t,n,[],{cache:new Map,charged:new Set})}function Fv(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 $v(e,t,n={}){Ra(e);let r=Un(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:Fv(t.value,r),verdict:i?"retired":nf(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:rf(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Uv(e,t,n,r){let i=Sv(e,t);if(i.size===0)return;let s=e.provider_policy,a=s?.triggers[r];if(!s||!a)throw new Ie(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let o=new Set(s.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!o.has(d))throw new Ie(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Ie(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[a.max_cost_class])throw new Ie(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!a.allow_network)throw new Ie(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function Zm(e,t,n,r,i){try{return await Na(n,r,i)}catch(s){if(s instanceof He){let a=s.check?` check ${s.check}`:"",o=s.measurement_id??n.id,c=new Ie(`assurance gate ${e} assertion ${t} measurement ${o} source ${s.source_kind}${a} field ${s.field} could not resolve: ${s.message}`,{gate_id:e,assertion_id:t,measurement_id:o,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}});throw c.cause=s,c}throw s}}async function uf(e,t,n,r){nn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new Ie(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new Ie(`assurance gate ${e} does not declare trigger ${r.trigger}`);Uv(i,t,n,r.trigger);let s=await cf(i.assertion_ids,tf,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(b=>b.id===g),y=await Zm(i.id,d.id,h,n,t.measurements),w=new Set(y.contributors);u={...n,items:n.items.filter(b=>w.has(b.id))}}let m=n.items.find(g=>g.id===d.owner_item_id),_=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return $v(d,await Zm(i.id,d.id,l,u,t.measurements),{owner_terminal:_})}),a=s.some(c=>c.verdict==="fail"&&c.enforcement==="block"),o=s.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:a?"block":o?"warn":"pass",exit_code:a?1:0,assertions:s,assertions_total:s.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:of(s.map(c=>c.cost),Math.max(0,...s.map(c=>c.cost.duration_ms)))}}function li(e){return fv.join(e,"assurance.json")}async function mf(e){let t=await ne(li(e));return t===null?jn():ui(t)}function ui(e){try{return nn(JSON.parse(e))}catch(t){throw new p("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",f.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 mi(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function jv(e,t){e==="measurement"?Ia(t):e==="assertion"?Ra(t):sf(t)}async function Gn(e,t){let n=structuredClone(mi(await mf(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function La(e,t,n){let r=mi(await mf(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function fi(e,t,n,r={}){jv(t,n);let i=await R(e),s=K(r.author,i.author_default),a=await Yt({pmRoot:e,filePath:li(e),op:`assurance:${t}:put`,author:s,message:r.message,lockTtlSeconds:ci,lockWaitMs:di,mutate:o=>{let c=o===null?jn():ui(o),d=mi(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&wv(d[l],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new N(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),nn(c),{raw:`${JSON.stringify(c,null,2)}
2
+ `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...a.result,changed:a.changed}}async function Da(e,t,n={}){let r=jn();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),nn(r);let i=await R(e),s=K(n.author,i.author_default),a=await Yt({pmRoot:e,filePath:li(e),op:"assurance:bundle:apply",author:s,message:n.message,lockTtlSeconds:ci,lockWaitMs:di,mutate:o=>{let c=o===null?jn():ui(o),d=[],l=[],u=(m,_,g)=>{for(let h of _){let y=m.find(w=>w.id===h.id);if(!y){m.push(structuredClone(h)),d.push(`${g}:${h.id}`);continue}if(J(y)!==J(h))throw new N(`assurance bundle refuses to replace divergent ${g} ${h.id}`);l.push(`${g}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),nn(c),{raw:`${JSON.stringify(c,null,2)}
3
+ `,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...a.result,changed:a.changed}}async function ff(e,t,n,r={}){let i=await R(e),s=K(r.author,i.author_default),a=await Yt({pmRoot:e,filePath:li(e),op:`assurance:${t}:remove`,author:s,message:r.message,lockTtlSeconds:ci,lockWaitMs:di,mutate:o=>{let c=o===null?jn():ui(o);if(t==="measurement"){let u=af(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=mi(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),nn(c),{raw:`${JSON.stringify(c,null,2)}
4
+ `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...a.result,changed:a.changed}}async function pf(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await R(e);await Ht({pmRoot:e,op:"assurance:gate:verdict",author:K(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:ci,lockWaitMs:di})}async function _f(e,t={}){let n=t.limit??gv;if(!Number.isInteger(n)||n<1||n>tn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${tn}`);return(await Bt(Br(e),ye)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="05c29627-6763-5aee-8579-71e563a98780")}catch{}})();var qn=["software-delivery","research","agent-evaluation","operations"];function gf(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function pi(e,t,n,r,i){let s=`preset-${e}`,a=i.map(c=>({id:`${s}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),o=a.map(c=>gf(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:a,assertions:o,gates:[{id:`${s}-readiness`,description:n,assertion_ids:o.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function _i(e,t){return e==="software-delivery"?pi(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?pi(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?pi(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):pi(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function hf(e,t,n,r={}){return Da(e,_i(t,n).declarations,r)}async function yf(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(s=>!n.has(s.status))};return await Promise.all(["files","tests","docs"].map(async s=>{let a={id:`derived-active-missing-${s}`,description:`Observed active items missing ${s} evidence.`,source:{kind:"links",link:s,state:"missing"}},c=(await Na(a,r)).value,d=gf(`${a.id}-ceiling`,a.id,t,c,"observe"),l=`active-missing-${s}`;return{id:l,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[a],assertions:[d],gates:[{id:`derived-${l}`,description:`Observe the accepted ${s} evidence baseline.`,assertion_ids:[d.id],triggers:["ci","scheduled"]}]}}}))}function wf(e,t,n={}){return Da(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function vf(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return fi(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Ef from"node:fs/promises";import{createRequire as Gv}from"node:module";import Re 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]="c21b1a94-1d80-57c0-b090-c4831fc505a2")}catch{}})();function bf(e,t){let n=Re.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Re.sep}`)&&!Re.isAbsolute(n))return n.split(Re.sep).join("/");let r=Re.resolve(e),i=0xcbf29ce484222325n;for(let a=0;a<r.length;a+=1)i^=BigInt(r.charCodeAt(a)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Re.basename(Re.dirname(e))}/package.json`}function qv(e){return e.includes(`${Re.sep}.pnpm${Re.sep}`)?"pnpm":e.includes(`${Re.sep}node_modules${Re.sep}`)?"npm":"other"}async function kf(e){try{let t=JSON.parse(await Ef.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 Ma(e){try{return await Ef.realpath(e)}catch{return Re.resolve(e)}}async function Sf(e,t,n=fd(import.meta.url,["../../.."])){let r=await Ma(t),i=await Ma(Re.join(n,"package.json")),s=await kf(i),a=new Map;s!==void 0&&a.set(i,{version:s,path:bf(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=Gv(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await Ma(l),m=await kf(u);if(m===void 0)continue;let _=u,g=a.get(_);if(g){g.consumers.includes(d.name)||(g.consumers.push(d.name),g.consumers.sort((h,y)=>h.localeCompare(y)));continue}a.set(_,{version:m,path:bf(u,r),layout:qv(u),consumers:[d.name]})}catch{}let o=[...a.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=s===void 0?[]:o.filter(d=>d.version!==s);return{host_version:s??null,copies:o,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]="0e153ece-4fc0-5134-97f0-c2315aff0031")}catch{}})();function O(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function te(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 Kv(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Kn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $a(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new p(`${t} must be a finite integer.`,f.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.`,f.USAGE);return n}}function oP(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 cP(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:te(e,"outputLimit"),outputBudget:te(e,"outputBudget"),outputSession:O(e,"outputSession"),outputCursor:O(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var zv=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Wv=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"]),Bv=new Set(["files","files-discover","docs","test","test-all"]),Vv=new Set(["claim","release","start-task","pause-task","close-task"]),Hv={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"],append:["body"]},Yv=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function xf(e,t){let n={},r=t!==void 0&&Bv.has(t),i=t==="files"||t==="files-discover"||t==="docs";for(let[s,a]of Object.entries(e)){if(Array.isArray(a)&&zv.has(s)){n[s]=a.join(",");continue}if(s==="note"&&i){n[s]=a;continue}if(typeof a=="string"&&Wv.has(s)){n[s]=[a];continue}if(typeof a=="string"&&r&&(s==="add"||s==="remove")){n[s]=[a];continue}n[s]=a}return n}function dP(e,t){let n=ld(e.options),r={},i=c=>{n[c]!==void 0||e[c]===void 0||(r[c]=e[c])};for(let c of Hv[t??""]??[])i(c);for(let c of Yv)i(c);let s=xf({...r,...n},t),a=O(e,"author"),o=t!==void 0&&Vv.has(t)?O(e,"assignee")??O(s,"assignee"):void 0;return a&&s.author===void 0?{...s,author:a}:o&&s.author===void 0?{...s,author:o}:s}function lP(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 uP(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 mP(e){let t=[],n=!0;for(let r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function fP(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 pP(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[s,a]of Object.entries(e))n.has(s)||(r[s]=a);let i={...r,...t};return delete i.args,i}function _P(e,t){return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:{...t}}}function Fa(e){return{type:te(e,"filterType"),tag:te(e,"filterTag"),priority:te(e,"filterPriority"),deadlineBefore:te(e,"filterDeadlineBefore"),deadlineAfter:te(e,"filterDeadlineAfter"),updatedAfter:te(e,"filterUpdatedAfter"),updatedBefore:te(e,"filterUpdatedBefore"),createdAfter:te(e,"filterCreatedAfter"),createdBefore:te(e,"filterCreatedBefore"),ids:Kv(e,"ids"),assignee:te(e,"filterAssignee"),assigneeFilter:te(e,"filterAssigneeFilter")??te(e,"filterAssignee_filter"),parent:te(e,"filterParent"),sprint:te(e,"filterSprint"),release:te(e,"filterRelease"),limit:te(e,"limit"),offset:te(e,"offset")}}function Pa(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return Ua(e)}function gi(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function gP(e){let t=Pa(e.kind),n=Pa(e.exemptIsolate),r=Pa(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:gi(e.maxDepth),limit:gi(e.limit),after:O(e,"after"),direction:O(e,"direction"),maxPaths:gi(e.maxPaths),sample:gi(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function hP(e){return{status:O(e,"filterStatus"),list:Kn(e.list)?ka(e.list):Fa(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 Xv=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 Tf(e){let t={};for(let[n,r]of Object.entries(e))Xv.has(n)||(t[n]=r);return Af(t)}function Af(e){let t=xf(e,"update-many");for(let n of ii)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return Mm(t)}function yP(e){if(Kn(e.list)||Kn(e.update)){let t=Kn(e.update)?e.update:Tf(e);return{status:te(e,"filterStatus"),list:Kn(e.list)?ka(e.list):Fa(e),update:Af(t),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:te(e,"filterStatus"),list:Fa(e),update:Tf(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 If}from"node:crypto";import zn 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]="b389e521-f689-5895-a5f4-08c3866b3ea3")}catch{}})();function Pe(e,t){throw new p(e,f.USAGE,t)}var Jv="2026-07-15T06:22:12.276Z",Qv=Date.parse(Jv),Zv=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Cf=e=>typeof e=="string"?e:"",Rf=e=>{let t=e??{},n=Cf(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Cf(t.ts))>=Qv);return Zv[r][i]};function Of(e,t,n=20,r=new Set,i=!1){let s=[],a=[],o={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,_]of t.split(/\r?\n/).entries()){let g;try{g=JSON.parse(_)}catch{continue}d+=1;let h=Rf(g);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}o[h]+=1,i&&h==="actionable_unknown"&&a.push({item_id:e,line:m+1}),s.length<c&&s.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:o.legacy_unknown,actionable_unknown_event_count:o.actionable_unknown,acknowledged_actionable_event_count:u,samples:s,samples_truncated:o.legacy_unknown+o.actionable_unknown>s.length,actionable_events:a}}var CP=(e,t,n=20,r=new Set)=>Of(e,t,n,r);function Nf(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let s=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof s!="object"||s===null||!Array.isArray(s.events)))for(let a of s.events)typeof a=="object"&&a!==null&&typeof a.item_id=="string"&&Number.isSafeInteger(a.line)&&t.add(`${a.item_id}:${String(a.line)}`)}return t}var Bn=async(e,t=20,n=!1)=>{let r=Wn.join(e,"history"),i;try{i=(await zn.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,b)=>w.localeCompare(b))}catch{i=[]}let s=new Set,a=[],o=[],c=0,d=0,l=0,u=0,m=0,_=0,g="_workspace.jsonl",h=new Set;if(i.includes(g))try{h=Nf(await zn.readFile(Wn.join(r,g),"utf8"))}catch{h=new Set}for(let w of i){let b;try{b=await zn.readFile(Wn.join(r,w),"utf8")}catch{continue}let E=w.slice(0,-6),v=Of(E,b,t-a.length,h,n);c+=1,d+=v.checked_events,l+=v.unknown_event_count,u+=v.legacy_unknown_event_count,m+=v.actionable_unknown_event_count,_+=v.acknowledged_actionable_event_count,v.unknown_event_count>0&&s.add(E),a.push(...v.samples),n&&o.push(...v.actionable_events)}let y=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:_,affected_item_ids:[...s].sort((w,b)=>w.localeCompare(b)),samples:a,samples_truncated:y>a.length,...n?{actionable_events:o}:{}}};function eb(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 tb(e){try{return Nf(await zn.readFile(Wn.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function nb(e){return(e.item_id===ye||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function rb(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Pe(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Rf(i)!=="actionable_unknown"&&Pe(`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:If("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Lf(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Pe("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Pe("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Pe("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let s=eb(t.all_actionable===!0?(await Bn(e,0,!0)).actionable_events:r),a=await tb(e),o=new Map;for(let m of s)if(nb(m)||Pe(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!o.has(m.item_id))try{o.set(m.item_id,(await zn.readFile(Wn.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Pe(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=s.map(m=>rb(m,a,o.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=If("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="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 IP(e,t,n=50){return(await Lf(e,t,n)).plan}function ib(e,t){let n=e.length>0;return n&&t&&Pe("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&&Pe("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:sb(e),all_actionable:t}}function sb(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),s=r===ye||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!s||!Number.isSafeInteger(i)||i<1)&&Pe(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function RP(e,t){let n=ib(Ua(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return ab(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 ab(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",s=await Lf(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:f.SUCCESS,plan:s.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Pe("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Pe("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.",f.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let o=s.completeCoordinates.filter(({disposition:u})=>s.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:m})=>({item_id:u,line:m}));if(o.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:f.NO_EFFECT,plan:s.plan};let c=await R(e),d=await Ht({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:o,attributed_author:r}},message:i,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:f.PARTIAL_EFFECT}:{outcome:"effect",exit_code:f.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:o.length,...l,plan:s.plan,history_path:d.historyPath}}import ja from"node:fs/promises";import Ga 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]="6efed404-acd2-5c3a-a008-856df67c8b77")}catch{}})();var ob=8388608,cb=new Set(["resolved","failed"]),db=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function Ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qa(e){return db.find(t=>t.matches(e))?.kind}function DP(e){let t=new Map,n=0,r=0;return{entries:e.map(s=>{let a=Ye(s.agent_provenance)?s.agent_provenance:void 0;if(a===void 0)return s;let o={},c=!1;for(let[l,u]of Object.entries(a)){let m=Ye(u)?qa(u.value):void 0;if(m===void 0){o[l]=u;continue}c=!0,r+=1;let _=s.agent_harness??"unknown",g=`${_}\0${l}\0${m}`,h=t.get(g)??{harness:_,dimension:l,kind:m,count:0};h.count+=1,t.set(g,h)}if(!c)return s;n+=1;let d={...s};return Object.keys(o).length===0?delete d.agent_provenance:d.agent_provenance=o,d}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((s,a)=>s.harness.localeCompare(a.harness)||s.dimension.localeCompare(a.dimension)||s.kind.localeCompare(a.kind))}}}async function MP(e){let t=[];for(let n of await Df(e))try{let r=await ja.readFile(Ga.join(e,"history",n),"utf8");for(let i of r.split(`
5
+ `)){if(i.trim().length===0)continue;let s=Mf(i);if(s===null||!Ye(s.agent_provenance))continue;if(Object.values(s.agent_provenance).some(o=>Ye(o)&&qa(o.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Df(e){try{return(await ja.readdir(Ga.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function lb(e,t,n){let r;try{r=await ja.open(Ga.join(e,"history",t),"r");let i=(await r.stat()).size,s=Math.min(i,Math.max(0,n)),a=Buffer.alloc(s),{bytesRead:o}=await r.read(a,0,s,0),c=a.subarray(0,o).toString("utf8"),d=o>=i,l=c.lastIndexOf(`
6
+ `),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:o,complete:d}}catch{return null}finally{await r?.close()}}function Mf(e){try{let t=JSON.parse(e);return Ye(t)?t:null}catch{return null}}function ub(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=Ye(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([a,o])=>{if(!Ye(o))return;let c=qa(o.value);if(!c)return;let d=`${r}\0${a}\0${c}`,l=n.get(d)??{harness:r,dimension:a,kind:c,count:0};l.count+=1,n.set(d,l)}),!Ye(e.context))return;let s=e.context.agent_provenance_outcomes;Ye(s)&&Object.entries(s).forEach(([a,o])=>{if(!Ye(o)||typeof o.resolver!="string"||!cb.has(String(o.status)))return;let c=`${r}\0${a}\0${o.resolver}`,d=t.get(c)??{harness:r,dimension:a,resolver:o.resolver,attempts:0,successes:0};d.attempts+=1,o.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function mb(e,t,n,r,i){let s=i;for(let a of e.split(`
7
+ `)){if(a.trim().length===0)continue;if(s>=r)return{eventsRead:s,truncated:!0};s+=1;let o=Mf(a);o&&ub(o,t,n)}return{eventsRead:s,truncated:!1}}async function Pf(e,t=1e4){let n=new Map,r=new Map,i=0,s=0,a=!1;for(let d of await Df(e)){let l=await lb(e,d,Math.max(0,ob-s));if(l===null)continue;s+=l.bytesRead;let u=mb(l.content,n,r,t,i);if(i=u.eventsRead,u.truncated){a=!0;break}if(!l.complete){a=!0;break}}let o=[...n.values()].sort((d,l)=>d.harness.localeCompare(l.harness)||d.dimension.localeCompare(l.dimension)||d.resolver.localeCompare(l.resolver)),c=[...r.values()].sort((d,l)=>d.harness.localeCompare(l.harness)||d.dimension.localeCompare(l.dimension)||d.kind.localeCompare(l.kind));return{outcomes:o,invalid_values:c,warnings:a?[]:[...o.filter(d=>d.attempts>0&&d.successes===0).map(d=>`provenance_resolver_zero_success:${d.harness}:${d.dimension}:${d.resolver}:${String(d.attempts)}`),...c.map(d=>`provenance_value_domain_invalid:${d.harness}:${d.dimension}:${d.kind}:${String(d.count)}`)],events_read:i,truncated:a}}import{execFile as fb}from"node:child_process";import{randomUUID as pb}from"node:crypto";import{readdir as _b,readFile as Uf}from"node:fs/promises";import Oe from"node:path";import{promisify as gb}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]="7b87b458-164a-5332-8803-6b0695481644")}catch{}})();var hb=gb(fb);async function Ka(e){try{let{stdout:t}=await hb("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function jf(e,t){let n=Oe.dirname(Oe.resolve(e,t));for(let r=0;r<12;r+=1){if(await z(Oe.join(n,"settings.json")))return n;let i=Oe.dirname(n);if(i===n)break;n=i}return null}function za(e){return Oe.join(e,"merge-receipts")}function hi(e){return`${e}.json`}function yb(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Ff(t.retained)??Cn(J(t.retained)),discarded_hash:Ff(t.discarded)??Cn(J(t.discarded))}))}}function Ff(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}async function WP(e){let t=await Ka(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,i=Oe.basename(r,Oe.extname(r)),s={version:1,id:pb(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:x(),value_availability:"clone_local"};await Ue(t),await le(Oe.join(t,hi(s.id)),`${JSON.stringify(s,null,2)}
8
+ `);let a=await jf(e.cwd,s.item_path);if(a!==null){let o=za(a),c=yb(s),d={...s,decisions:c.decisions.map(l=>({field:l.field,base:null,ours:null,theirs:null,retained:{pm_value_hash:l.retained_hash},discarded:{pm_value_hash:l.discarded_hash}})),value_availability:"hash_only"};await Ue(o),await le(Oe.join(o,hi(s.id)),`${JSON.stringify(d,null,2)}
9
+ `)}return s}async function $f(e,t){if(!await z(e))return[];let n;try{n=await _b(e)}catch{return[]}let r=[];for(let i of n.sort((s,a)=>s.localeCompare(a)))if(i.endsWith(".json"))try{let s=JSON.parse(await Uf(Oe.join(e,i),"utf8")),{preferred:a,...o}=s,c={...o,requested_preference:s.requested_preference??a??"ours",conflict_resolution:s.conflict_resolution??"preferred_side"};c.version===1&&(t.includeReconciled||c.state==="pending")&&(t.includeLossless!==!1||c.decisions.length>0)&&r.push(c)}catch{}return r}async function Vn(e,t={}){let n=await Ka(e),r=n===null?[]:await $f(n,t),i=t.pmRoot??Oe.join(e,".agents","pm"),s=await $f(za(i),t),a=new Map(s.map(o=>[o.id,o]));for(let o of r)a.set(o.id,o);return[...a.values()].sort((o,c)=>o.created_at.localeCompare(c.created_at))}function yi(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function BP(e,t){let n=await Ka(e);if(n===null)return;await le(Oe.join(n,hi(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:x()},null,2)}
10
+ `);let r=await jf(e,t.item_path);if(r!==null){let i=Oe.join(za(r),hi(t.id));if(await z(i)){let s=JSON.parse(await Uf(i,"utf8"));await le(i,`${JSON.stringify({...s,state:"reconciled",reconciled_at:x()},null,2)}
11
+ `)}}}async function VP(e){let t=await Vn(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:x()}}import ot from"node:fs/promises";import Se from"node:path";import rn from"node:fs/promises";import{createHash as wb}from"node:crypto";import qf 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]="32538934-2cbb-50fe-b721-ad9197cef7d8")}catch{}})();var Kf=4,vb="history-drift-cache.json";function zf(e){return qf.join(e,"runtime",vb)}async function bb(e){try{let t=await rn.readFile(zf(e),"utf8"),n=JSON.parse(t);return n.version!==Kf||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}async function kb(e,t,n,r,i){let s=Br(e),a;try{a=await rn.stat(s)}catch(d){return $(d)||i.unreadableStreams.push(ye),!1}let o=i.missingStreams.length,c=await Bf({itemId:ye,historyPath:s,stat:a,cached:t[ye],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.chainOk||i.chainMismatches.push(ye),n[ye]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(i.missingStreams.splice(o),c.cacheDirty)}function Wf(e){return wb("sha256").update(e).digest("hex")}async function Eb(e){let t=await rn.readFile(e,"utf8");return Wf(t)}async function Sb(e){let t=await rn.readFile(e,"utf8"),n=Wf(t);if(t.trim().length===0)return null;let r=[],i=null;for(let a of t.split(/\r?\n/)){let o=a.trim();if(o.length===0)continue;let c=JSON.parse(o);if(typeof c.after_hash!="string"||c.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(c),i=c.after_hash}if(!i)return null;let s=_l(r);return{latestAfterHash:i,chainOk:s.ok,contentHash:n,itemHashVersion:s.item_hash_version??aa}}function Tb(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Gf(e,t,n){try{let r=await Sb(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Bf(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Tb(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Gf(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await Eb(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else r=t;return!e.verifyCacheHitByContent||r===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:r,itemHashVersion:e.cached.item_hash_version??aa},cacheDirty:!1}:{verification:await Gf(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function xb(e,t,n,r){let i=ft(e,t.id),s;try{s=await rn.stat(i)}catch(l){return($(l)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let a=await Bf({itemId:t.id,historyPath:i,stat:s,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!a.verification)return a.cacheDirty;a.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:a.verification.contentHash,latest_after_hash:a.verification.latestAfterHash,chain_ok:a.verification.chainOk,item_hash_version:a.verification.itemHashVersion};let{body:o,...c}=t;return ml({metadata:c,body:o},a.verification.itemHashVersion)!==a.verification.latestAfterHash&&r.hashMismatches.push(t.id),a.cacheDirty}async function Ab(e,t){if(!(t.unreadableStreams.includes(ye)||t.chainMismatches.includes(ye)))try{let n=await gl(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(ye)}}async function wi(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},s=(await bb(e))?.entries??{},a={},o=!1,c=n.cacheHitVerification!=="metadata",d={previousEntries:s,nextEntries:a,verifyCacheHitByContent:c};for(let m of t)await xb(e,m,d,r)&&(o=!0);let l=await kb(e,s,a,c,r);if(o||=l,await Ab(e,r),o||Object.keys(s).length!==Object.keys(a).length){let m=zf(e);try{await rn.mkdir(qf.dirname(m),{recursive:!0}),await le(m,JSON.stringify({version:Kf,entries:a}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[ye]:[]])].sort((m,_)=>m.localeCompare(_));return{...r,driftedItems:u}}import Hn from"node:fs/promises";import vi 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]="79f9ccbd-48d1-5eb3-82ae-3dd62427041c")}catch{}})();function Cb(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:r,owner:i,created_at:s,ttl_seconds:a}=n;return typeof r!="string"||typeof i!="string"||typeof s!="string"||typeof a!="number"||!Number.isFinite(a)?null:{id:r,owner:i,created_at:s,ttl_seconds:a}}function Vf(e,t,n){let r=Cb(t);if(r===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 i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let s=n-i,a=Math.floor(s/1e3),o=s>r.ttl_seconds*1e3;return{detail:o?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:a,stale:o,reason:o?"expired":"active"}}}async function Hf(e,t){let n=t??Date.now(),r=vi.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},s;try{s=(await Hn.readdir(r)).filter(o=>o.endsWith(".lock")).sort()}catch(a){if($(a))return i;throw a}for(let a of s){let o;try{o=await Hn.readFile(vi.join(r,a),"utf8")}catch(d){if($(d))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=Vf(a,o,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function Yf(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=vi.join(e,"locks"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},o;try{o=(await Hn.readdir(s)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if($(c))return a;throw c}for(let c of o){a.scanned+=1;let d=vi.join(s,c),l=`locks/${c}`;if(r?.onRead){let _=await r.onRead(d);a.warnings.push(..._)}let u;try{u=await Hn.readFile(d,"utf8")}catch(_){if($(_)){a.scanned-=1;continue}a.warnings.push(`lock_unreadable:${c}`),a.retained.push(l),a.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=Vf(c,u,i);if(m.detail==="unparseable_json"){a.warnings.push(`lock_unparseable:${c}`),a.retained.push(l),a.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){a.warnings.push(`lock_invalid_timestamp:${c}`),a.retained.push(l),a.entries.push(m.entry);continue}if(m.detail==="active"){a.retained.push(l),a.entries.push(m.entry);continue}if(!n){try{await Hn.unlink(d)}catch(_){if(!$(_)){a.warnings.push(`lock_remove_failed:${c}`),a.retained.push(l),a.entries.push(m.entry);continue}}if(r?.onWrite){let _=await r.onWrite(d);a.warnings.push(..._)}}a.removed.push(l),a.entries.push(m.entry)}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]="bc9e5edf-c275-5172-8900-fafee9b4a2db")}catch{}})();var Ib=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:"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_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_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 Wa(e){if(typeof e!="string")return;let t=e.trim();for(let n of Ib)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Ba(e){let t={};for(let n of e){let r=Wa(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Xf(e){return Object.values(Ba(e))}import{execFile as Rb}from"node:child_process";import{realpath as Ob}from"node:fs/promises";import Jf from"node:path";import{promisify as Nb}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]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var Lb=Nb(Rb),Db=32*1024*1024,Mb=1e4,Pb=["search/eval-queries.json"];function Va(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Fb(e){return`'${e.replaceAll("'","'\\''")}'`}async function $b(e,t=Ob){return t(e).catch(()=>Jf.resolve(e))}async function bi(e){let t=await Zt(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 $b(e),r=Va(Jf.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=Am.map(s=>`${r}/${Va(s)}`);try{let{stdout:s}=await Lb("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:Db,windowsHide:!0,timeout:Mb}),a=new Set(Pb.map(d=>`${r}/${d}`)),o=[...new Set(s.split("\0").filter(d=>d.length>0&&!a.has(Va(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>o.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:o,tracked_path_count:o.length,remediation_command:o.length===0?null:`git rm --cached -r -- ${c.map(d=>Fb(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,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]="f7b3ff92-1fc7-55e9-aa76-af956714998f")}catch{}})();var Ub=new Set(zl),Zf=25,an=8,Yn=100,jb=Se.join("runtime","telemetry","events.jsonl"),Gb=Se.join("runtime","telemetry","state.json"),qb=2500,Kb=500,ep=Kl-3,zb=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Za(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 eo(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function on(e){return e.trim().toLowerCase()}function Xa(e,t){let n=on(e),r=on(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function to(e){try{return(await ot.stat(e)).isDirectory()}catch{return!1}}async function Wb(e){let t=(await ot.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>ot.readdir(Se.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>xt.some(s=>i.name.endsWith(s))).map(i=>Se.parse(i.name).name)))}async function Bb(e,t,n,r){let i=await Me({path:e,scope:"project"}),s=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!s)return{warnings:i,overThreshold:!1,classification:"live"};let a;try{a=await ot.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let o="live";if(s){let d=a.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{o=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{o="orphaned"}}let c=n.enabled?a.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:o}}async function Vb(e,t,n){let r=Se.join(e,"history");if(!await to(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await ot.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),a=t.enabled?t.max_entries:null,o=[],c=[],d=[],l=[];for(let u of i){let m=Se.join(r,u),_=u.slice(0,-6),g=await Bb(m,_,t,n);o.push(...g.warnings),g.classification==="tombstone"&&d.push(_),g.classification==="orphaned"&&l.push(_),g.overThreshold&&c.push(_)}return{count:i.length,warnings:[...o,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:a,tombstones:d,orphaned:l}}function Ja(e,t){return Se.relative(e,t).replaceAll("\\","/")}async function tp(e,t){let n=[...new Set(Object.values(t))].sort((i,s)=>i.localeCompare(s)),r=[];for(let i of n){let s=Se.join(e,i),a=[];try{a=await ot.readdir(s)}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&$(o))continue;continue}for(let o of a)xt.some(c=>o.toLowerCase().endsWith(c))&&r.push(Se.join(s,o))}return r.sort((i,s)=>Ja(e,i).localeCompare(Ja(e,s))),r}function Hb(e){return!(typeof e=="object"&&e!==null&&"code"in e&&$(e))}async function Yb(e,t,n){let r=await tp(e,t),i=[],s=[],a=[],o=[],c=pt(P());for(let d of r){let l=Ja(e,d),u;try{u=await ot.readFile(d,"utf8")}catch{i.push(l);continue}let m=Wt(u);if(m){s.push({path:l,...m});continue}try{let _=zr(u,{format:kd(d),schema:n,extensionFieldNames:c});o.push({ref:l,version:qr(_.metadata)})}catch{a.push(l)}}return{paths:r,unreadable:i,conflictMarkers:s,parseFailures:a,formatVersions:o}}async function Xb(e){let t=Se.join(e,"history"),n=[],r=[],i=[],s=[];try{s=(await ot.readdir(t)).filter(a=>a.endsWith(".jsonl")).sort((a,o)=>a.localeCompare(o))}catch(a){Hb(a)&&n.push("history")}for(let a of s){let o=a.slice(0,-6),c;try{c=await ot.readFile(Se.join(t,a),"utf8")}catch{n.push(o);continue}let d=Wt(c);if(d){r.push({id:o,...d});continue}c.split(/\r?\n/).forEach((l,u)=>{if(l.trim())try{JSON.parse(l)}catch{i.push({id:o,line:u+1})}})}return{files:s,unreadable:n,conflictMarkers:r,invalidJson:i}}function np(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function Jb(e,t,n,r,i){let s=await Yb(e,t,n),a=await Xb(e),o=Kr(s.formatVersions),c=X(n),d=si(i,v=>oe(v,c),be()),l=await bi(e),u=await Zt(e),m=u===null?null:await oi(u),_=u===null?[]:await Vn(u,{includeLossless:!0,pmRoot:e}),{pendingDecisions:g,lossless:h}=yi(_),y=m?.status==="missing"&&m.missing_keys.length===5&&m.drifted_keys.length===0,w=[...s.unreadable.map(v=>`integrity_item_unreadable:${v}`),...s.conflictMarkers.map(v=>`integrity_item_conflict_marker:${v.path}:L${v.line}`),...s.parseFailures.map(v=>`integrity_item_parse_failed:${v}`),...a.unreadable.map(v=>`integrity_history_unreadable:${v}`),...a.conflictMarkers.map(v=>`integrity_history_conflict_marker:${v.id}:L${v.line}`),...a.invalidJson.map(v=>`integrity_history_invalid_json:${v.id}:L${v.line}`),...o.outdated.map(v=>`integrity_item_outdated_format_version:${v}`),...o.ahead.map(v=>`integrity_item_ahead_format_version:${v}`),...np(d),...l.tracked_path_count>0?[`tracked_runtime_cache_files:${l.tracked_path_count}`]:[],...m!==null&&m.status!=="ok"?[`merge_driver_configuration_${y?"missing":"drift"}:${m.missing_keys.length+m.drifted_keys.length}`]:[],...g.length>0?[`merge_decisions_unreviewed:${g.length}`]:[]],b=[...new Set(w)].sort((v,T)=>v.localeCompare(T)),E=b.filter(v=>!v.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:E.length===0?"ok":"warn",ok:E.length===0,details:{checked_item_files:s.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:s.unreadable.length,item_conflict_markers:s.conflictMarkers.length,item_parse_failures:s.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:o.outdated.length,item_ahead_format_version:o.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:m===null||m.status==="ok"?0:m.missing_keys.length+m.drifted_keys.length,pending_merge_decisions:g.length,lossless_merge_receipts:h.length},item_unreadable:s.unreadable,item_conflict_markers:s.conflictMarkers,item_parse_failures:s.parseFailures,item_outdated_format_version:o.outdated,item_ahead_format_version:o.ahead,hierarchy_integrity:{...d,relations:Xe(d.relations,an)},history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.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:m===null?null:{...m,required:r},pending_merge_decision_items:[...new Set(g.map(v=>v.item_id))].sort((v,T)=>v.localeCompare(T)),lossless_merge_receipt_items:[...new Set(h.map(v=>v.item_id))].sort((v,T)=>v.localeCompare(T))}},warnings:b}}function Qb(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function Zb(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:Qb(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function ek(e,t){let n=re(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function tk(e){let n=re(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function nk(e){return re(e.reason)??re(e.error)??re(e.message)}function Ha(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function rk(e){let t=[],n=[],r=[];e.forEach((s,a)=>{let o=ek(s.definition,a),c=tk(s.definition);if(c==="applied"){t.push({layer:s.layer,name:s.name,id:o,status:c});return}if(c==="failed"){r.push({layer:s.layer,name:s.name,id:o,status:c,reason:nk(s.definition)});return}n.push({layer:s.layer,name:s.name,id:o,status:c})}),t.sort(Ha),n.sort(Ha),r.sort(Ha);let i=[...r.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:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function rp(e,t,n,r,i,s,a,o,c){let d=[...new Set(e)].sort((y,w)=>y.localeCompare(w)),l=[...new Set(d.map(y=>eo(y)))].sort((y,w)=>y.localeCompare(w)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,m=c.length>0,_=m?"partial":"full",g=[],h=Um(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."),(r.failed_count>0||r.pending_count>0)&&g.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>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: ${rd.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."),m?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>."):a.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:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:s,unmanaged_loaded_extension_count:a.length,unmanaged_loaded_extensions:a,unmanaged_expected_extension_count:o.length,unmanaged_expected_extensions:o,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:_,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:g}}async function ik(e,t,n){let r=await Mr({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),i=r.loaded.map(k=>Zb(k)),s=await Sf(r.loaded,nt(e)),a=await Pr({...r,loaded:r.loaded}),[o,c]=await Promise.all([Ea(r.roots.project),Ea(r.roots.global)]);await jm(e,a.registrations.migrations);let d=rk(a.registrations.migrations),l={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:d.summary,managed_extensions:{project:{path:o.path,count:o.state.entries.length,entries:o.state.entries},global:{path:c.path,count:c.state.entries.length,entries:c.state.entries}}},u=new Set(o.state.entries.map(k=>on(k.name))),m=new Set(c.state.entries.map(k=>on(k.name))),_=[...new Map(r.loaded.filter(k=>!(k.layer==="project"?u:m).has(on(k.name))).map(k=>[`${k.layer}:${k.name}`,{layer:k.layer,name:k.name,directory:k.directory}])).values()].sort((k,S)=>{let A=`${k.layer}:${k.name}`,L=`${S.layer}:${S.name}`;return A.localeCompare(L)}),g=_.map(k=>`${k.layer}:${k.name}`).sort((k,S)=>k.localeCompare(S)),h=_.filter(k=>Xa(k.name,k.directory)).map(k=>`${k.layer}:${k.name}`).sort((k,S)=>k.localeCompare(S)),y=_.filter(k=>!Xa(k.name,k.directory)).map(k=>`${k.layer}:${k.name}`).sort((k,S)=>k.localeCompare(S)),w=y.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${y.length}`]:[],b=[...r.warnings,...l.warnings,...d.warnings,...o.warnings,...c.warnings,...w,...s.warnings],E=Sa(b),v=Ta(),T=rp(b,r.failed.length,a.failed.length,d.summary,o.warnings.length+c.warnings.length,o.state.entries.length+c.state.entries.length,g,h,y);return{check:{name:"extensions",status:b.length===0?"ok":"warn",ok:b.length===0,details:{...r,loaded:i,warnings:b,activation:l,triage:T,...d.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:v,capability_guidance:E,host_version_census:s}},warnings:b}}function sk(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Xe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function ak(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 ki(e,t){let n=Xe(e,t);return{...n,sample:n.sample.map(r=>ak(r))}}function W(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function ok(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 ck={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:W(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:W(e.missing_required,t),missing_optional:W(e.missing_optional,t),missing:W(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:W(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:ki(e.discovered,t),effective:ki(e.effective,t),loaded:ki(e.loaded,t),failed:Xe(e.failed,t),warnings:W(e.warnings,t),activation:{failed:Xe(n.failed,t),warnings:W(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:ok(n.migration_status)},triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Xe(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:W(n.affected_item_ids,t),samples:Xe(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:W(e.item_unreadable,t),item_conflict_markers:Xe(e.item_conflict_markers,t),item_parse_failures:W(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:W(n.tracked_paths,t)},history_unreadable:W(e.history_unreadable,t),history_conflict_markers:Xe(e.history_conflict_markers,t),history_invalid_json:Xe(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>({checked_items:e.checked_items,counts:e.counts,drifted_items:W(e.drifted_items,t),missing_streams:W(e.missing_streams,t),unreadable_streams:W(e.unreadable_streams,t),hash_mismatches:W(e.hash_mismatches,t),chain_mismatches:W(e.chain_mismatches,t),workspace_state_mismatches:W(e.workspace_state_mismatches,t),workspace_state_missing:W(e.workspace_state_missing,t),workspace_state_unreadable:W(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:W(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:W(e.stale_items_after,t),skipped:e.skipped})};function ip(e,t){let n=ck[e.name];return n?n(e.details,t):e.details}function dk(e){let t=W(e.warnings,an);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:ip(n,an)})),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:an},generated_at:e.generated_at}}function Qf(e){return e.details.skipped===!0}function lk(e){let t=W(e.warnings,an),n=e.checks.filter(Qf).map(r=>r.name);return{ok:e.ok,checks:e.checks.filter(r=>!Qf(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:e.findings.filter(r=>t.sample.includes(r.warning)||e.failed_because.includes(r.warning)),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:an,omitted_checks:n},generated_at:e.generated_at}}function Qa(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=sk(e,Zf);return{values:n.values,truncated:n.truncated,total:e.length}}function sn(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 Ub.has(e)?e:null}function Ei(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 sp(e){let t=0,n=0,r=0,i=0,s=0;for(let a of e.split(`
12
+ `)){let o=a.trim();if(o.length!==0){r+=1;try{let c=JSON.parse(o);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>=ep&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:s}}function mk(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function fk(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 pk(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await ap(n)}}function _k(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,s=n.last_failed_flush_at,a=s&&(!i||s>i),o=!i,c=t.validEntries>=Kb;return(a||o||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function gk(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function hk(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>ql?[`telemetry_schema_version_behind:${t}`]:[]}function yk(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function wk(){return{telemetry_disabled:sn("PM_TELEMETRY_DISABLED")||sn("PM_NO_TELEMETRY"),pm_no_telemetry:sn("PM_NO_TELEMETRY"),telemetry_otel_disabled:sn("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:sn("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:uk()}}function vk(e,t){return e.telemetry.enabled&&t.validEntries>0}function bk(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function ap(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(qb)});return{probe_url:Ei(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of zb){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:Ei(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function kk(e,t){let n=We(process.cwd()),r=Se.join(n,jb),i=Se.join(n,Gb),s=await ne(r),a=s!==null,o=s?Buffer.byteLength(s,"utf8"):0,c=s?sp(s):mk(),d=await ne(i),{runtimeState:l,stateParseFailed:u}=fk(d),m=e.telemetry.endpoint.trim(),_=Ei(m),g=await pk(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(..._k(e,c,l),...gk(g),...hk(g),...yk(e,l));let y=vk(e,c),w=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:_,global_pm_root:n,queue_path:r,queue_exists:a,queue_entries:c.validEntries,queue_draining:bk(y,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:o,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:ep,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:g??{attempted:!1},env_overrides:wk()}},warnings:h}}async function Ek(e){let t;try{t=await Hf(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function Sk(e,t){let n="metadata",{missingStreams:r,unreadableStreams:i,hashMismatches:s,chainMismatches:a,driftedItems:o,workspaceStateMismatches:c,workspaceStateMissing:d,workspaceStateUnreadable:l}=await wi(e,t,{cacheHitVerification:n}),u=[...r.map(m=>`history_drift_missing_stream:${m}`),...i.map(m=>`history_drift_unreadable_stream:${m}`),...s.map(m=>`history_drift_hash_mismatch:${m}`),...a.map(m=>`history_drift_chain_mismatch:${m}`),...c.map(m=>`history_drift_workspace_state_mismatch:${m}`),...d.map(m=>`history_drift_workspace_state_missing:${m}`),...l.map(m=>`history_drift_workspace_state_unreadable:${m}`)];return{check:{name:"history_drift",status:u.length===0?"ok":"warn",ok:u.length===0,details:{checked_items:t.length,cache_hit_verification:n,drifted_items:o,counts:{drifted:o.length,missing_streams:r.length,unreadable_streams:i.length,hash_mismatches:s.length,chain_mismatches:a.length,workspace_state_mismatches:c.length,workspace_state_missing:d.length,workspace_state_unreadable:l.length},missing_streams:r,unreadable_streams:i,hash_mismatches:s,chain_mismatches:a,workspace_state_mismatches:c,workspace_state_missing:d,workspace_state_unreadable:l}},warnings:u}}function Tk(e,t){let n=Cl(e),r=Ml(n.settings),i=Pl(n.settings,t),s=r.active?Fl(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:s,semanticRuntimeAvailable:!!(r.active&&i.active)}}function xk(){return{refreshed:[],skipped:[],warnings:[]}}async function Ak(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?xk():Ul(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function Ck(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&$l(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function Ik(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function Rk(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function op(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:oa(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:oa(r,e.vector_store?.adapter??null)}}function Ok(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function Nk(e,t,n){return e.enabled&&n.length>0&&t}async function Lk(e,t,n,r,i){let s=Tk(t,e),a=await ca(e),o=s.semanticRuntimeAvailable?ba(n,a.entries):[],c=await Ak({pmRoot:e,snapshot:s,refreshPolicy:r,staleBefore:o}),d=await ca(e),l=s.semanticRuntimeAvailable?ba(n,d.entries):[],u=!s.runtimeDefaults.auto_ollama_defaults_applied,m=Ck({strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,ledgerBefore:a,runtimeEmbeddingIdentity:s.runtimeEmbeddingIdentity}),_=Ik({ledgerBefore:a,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),g=Qa(o,i),h=Qa(l,i),y=Nk(r,s.semanticRuntimeAvailable,o);return{check:{name:"vectorization",status:_.length===0?"ok":"warn",ok:_.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:Ok(r),...op(t,s),embedding_identity_changed:m,embedding_identity_before:a.embedding??null,embedding_identity_runtime:s.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(a.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Zf,stale_items_before_total:g.total,stale_items_before:g.values,stale_items_before_truncated:g.truncated,refresh_attempted:y,refresh_skipped_reason:Rk(r,s.semanticRuntimeAvailable,o),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:_}}function Dk(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 cp(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new p("--check-only cannot be combined with --refresh-vectors",f.USAGE);if(n&&e.noRefresh===!0)throw new p("--no-refresh cannot be combined with --refresh-vectors",f.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var Mk=new Set(["extensions","locks","search"]);function Pk(e){let t=new Set(ad.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(od));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of Mk)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,s)=>i.localeCompare(s)),optionalDirs:[...n].sort((i,s)=>i.localeCompare(s)),optionalDirSet:n}}async function Fk(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:s}=Pk(t),a=[],o=[],c=[];for(let d of[...r,...i]){let l=Se.join(e,d);c.push(...await Me({path:l,scope:"project"})),!await to(l)&&(s.has(d)?o.push(d):a.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:a,missingOptionalDirs:o,missingDirs:n?[...a,...o]:[...a],hookWarnings:c}}function dp(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function $k(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?ve(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):Qt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Ya(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function Uk(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 jk(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 Gk(e){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e}}}var no=e=>e.unknown_event_count??0,ro=e=>e.actionable_unknown_event_count??no(e);function qk(e,t,n,r,i,s,a){let o=no(r),c=ro(r),d=o>0,l=c>0,u=i.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:r}:{},...u?{stale_in_progress:i}:{},...s.length>0?{provenance_resolver_outcomes:s}:{},...a.length>0?{provenance_invalid_values:a}:{},...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 lp(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function Kk(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 zk(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function Wk(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.over_threshold.map(t=>`history_stream_over_compact_threshold:${t}`),...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 up(e){let t=new Map;for(let[i,s]of Object.entries(e.remediationSources))for(let a of s)t.has(a)||t.set(a,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let s=t.get(i)??"integrity",a=Wa(i)?.code??eo(i),o=n.get(s)?.details,d=(typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{})[a],l=Za(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:a,check:s,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function Bk(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))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 Vk(e){for(let t of e.checks){let n=Ba(e.remediationSources[t.name]);Bk({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}function mp(e,t,n){let r=e.warning_count??e.warnings.length,i={...e,warning_count:r,warning_limit:Yn,warnings_truncated:r>Yn,warnings:e.warnings.slice(0,Yn),findings:(e.findings??[]).filter(a=>e.warnings.slice(0,Yn).includes(a.warning)||e.failed_because.includes(a.warning))},s=n?lk(i):t.brief===!0?dk(i):i;return{...s,warning_count:r,warning_limit:Yn,warnings_truncated:r>s.warnings.length,...s.projection?{projection:{...s.projection,warning_count:r,warnings_truncated:r>s.warnings.length}}:{}}}async function fp(e,t={}){let n=I(process.cwd(),e.path);await F(n);let r=je(n),{settings:i,warnings:s}=await xl(n),a=[...new Set(s)],o=U(i,P()),c=t.strictDirectories===!0,d=cp(t),l=await Fk(n,o,c),u=Dk(i),m=await kk(i,{checkTelemetry:t.checkTelemetry===!0}),_=await ik(n,i,!!e.noExtensions),g=dp(t),h=[],y=await $k({pmRoot:n,settings:i,typeRegistry:o,skipPolicy:g,itemReadWarnings:h}),w=y,b=[...new Set(h)],E=g.skipDrift?{warnings:[]}:await Wr({pmRoot:n,settings:i,itemIds:y.map(Ne=>Ne.id),commandLabel:"health"}),v=await Vb(n,i.history.compact_policy,await Wb(n)),T=await Bn(n,20,t.verboseAuthorEvents===!0),k=ro(T),S=k>0?[`history_unknown_author_events:${k}`]:[],A=lp(await jl(n,y,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),L=await Pf(n),H=L.outcomes,j=L.invalid_values,C=L.warnings,G=await Ek(n),de=g.skipIntegrity?Ya("integrity"):await Jb(n,o.type_to_folder,i.schema,t.requireMergeDrivers===!0,y),ie=g.skipDrift?Ya("history_drift"):await Sk(n,w),pe=g.skipVectors?Ya("vectorization"):await Lk(n,i,w,d,t.verboseStaleItems===!0),qe=[Uk(r,i,a),jk(l,c),Gk(u),m.check,_.check,qk(y,i,v,T,A.scan,H,j),G.check,de.check,ie.check,pe.check],St=Kk({directoryState:l,normalizedSettingsReadWarnings:a,settingWarnings:u,normalizedItemReadWarnings:b,telemetryCheck:m,extensionCheck:_,historyPolicyWarnings:E.warnings,historySummary:v,authorAttributionWarnings:S,staleInProgressWarnings:A.warnings,provenanceWarnings:C,locksCheck:G,integrityCheck:de,historyDriftCheck:ie,vectorizationCheck:pe}),ut=Wk({directoryState:l,normalizedSettingsReadWarnings:a,settingWarnings:u,normalizedItemReadWarnings:b,telemetryCheck:m,extensionCheck:_,historyPolicyWarnings:E.warnings,historySummary:v,authorAttributionWarnings:S,staleInProgressWarnings:A.warnings,provenanceWarnings:C,locksCheck:G,integrityCheck:de,historyDriftCheck:ie,vectorizationCheck:pe});Vk({checks:qe,remediationSources:ut,historyDriftedCount:zk(ie),overThresholdCount:v.over_threshold.length});let Ke=St.filter(Ne=>!Za(Ne,t.requireMergeDrivers===!0)),Er=up({warnings:St,checks:qe,remediationSources:ut,requireMergeDrivers:t.requireMergeDrivers===!0}),he={ok:Ke.length===0,checks:qe,warnings:St,findings:Er,failed_because:Ke,generated_at:x()};return mp(he,t,g.summaryMode)}var s$={buildHierarchyIntegrityWarnings:np,buildExtensionHealthTriageSummary:rp,buildHealthFindings:up,buildCapabilityContractMetadata:Ta,buildStaleInProgressHealthSummary:lp,buildVectorizationProviderDetails:op,collectUnknownCapabilityGuidance:Sa,isAdvisoryHealthWarning:Za,isDirectory:to,isExpectedUnmanagedExtension:Xa,listItemDocumentPaths:tp,normalizeEndpointForDisplay:Ei,normalizeExtensionNameForMatch:on,parseTelemetryQueue:sp,probeTelemetryEndpointHealth:ap,projectHealthResult:mp,resolveActionableUnknownAuthorEventCount:ro,resolveHealthSkipPolicy:dp,resolveUnknownAuthorEventCount:no,resolveVectorRefreshPolicy:cp,selectStaleItemDetail:Qa,summarizeHealthCheckDetails:ip,summarizeExtensionList:ki,summarizeRecordList:Xe,summarizeStringList:W,telemetryEnvFlagEnabled:sn,warningCode:eo};import cn from"node:fs/promises";import dn 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]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function Hk(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let s;try{s=await cn.readdir(dn.join(e,i))}catch{return}for(let a of s)for(let o of xt)if(a.toLowerCase().endsWith(o)){r.push({relativePath:`${i}/${a}`,id:a.slice(0,-o.length)});break}})),r.sort((i,s)=>i.relativePath.localeCompare(s.relativePath))}function Yk(e,t){let{id:n,relativePath:r,liveItemIds:i,out:s}=e,a=Wt(t);if(a){s.conflictMarkers.push({id:n,path:r,line:a.line,detail:`unresolved merge conflict marker ${a.marker}`});return}let o=null,c=t.split(/\r?\n/).map((d,l)=>({content:d.trim(),number:l+1})).filter(d=>d.content.length>0);for(let d of c)try{let l=JSON.parse(d.content);if(typeof l!="object"||l===null||Array.isArray(l))throw new TypeError("history entry must be an object");o=l}catch{s.unparseable.push({id:n,path:r,line:d.number,detail:"history line is not a valid JSON object"});return}o!==null&&(o.op==="delete"&&i.has(n)&&s.resurrected.push({id:n,deleted_at:typeof o.ts=="string"?o.ts:"",deleted_by:typeof o.author=="string"?o.author:""}),o.op==="history_repair"&&Array.isArray(o.patch)&&o.patch.length>0&&(s.repairReconciliations+=1))}function io(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 Xk(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await cn.readdir(dn.join(e,"history"))}catch{return n}for(let i of r.sort((s,a)=>s.localeCompare(a))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await cn.readFile(dn.join(e,"history",i),"utf8")}catch(a){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:io("history stream",a)});continue}Yk({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},s)}return n}function pp(e){let t=Wt(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 Jk(e){let t=[],n=0,r=null;try{r=await ne(je(e))}catch(s){n+=1,t.push({path:"settings.json",detail:io("configuration file",s)})}if(r!==null){n+=1;let s=pp(r);s!==null&&t.push({path:"settings.json",detail:s})}let i;try{i=await cn.readdir(dn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of i.sort((a,o)=>a.localeCompare(o))){if(!s.endsWith(".json"))continue;n+=1;let a;try{a=await cn.readFile(dn.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:io("configuration file",c)});continue}let o=pp(a);o!==null&&t.push({path:`schema/${s}`,detail:o})}return{scanned:n,unparseable:t}}async function _p(e,t,n,r={}){let i=await Hk(e,n),s=new Set(i.map(u=>u.id)),a=new Map;for(let u of i){let m=a.get(u.id);m===void 0?a.set(u.id,[u.relativePath]):m.push(u.relativePath)}let o=[...a.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((_,g)=>_.localeCompare(g))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=dn.join(e,u.relativePath);return zr(await cn.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await Xk(e,s),l=await Jk(e);return{item_files_on_disk:i.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:o,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 Zk from"node:fs/promises";import Fe from"node:path";import eE 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]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var Qk=/^[a-z][a-z0-9+.-]+:\/\//i;function Xn(e){return Qk.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]="1832e2b3-0ece-523d-8f38-598303d3f590")}catch{}})();var tE=["path","scope","note"],nE=["pattern","glob","path","scope","note"],rE=["path"],iE=["from","to"],sE=new Set(["note","scope"]);function hp(e){let t=e??"project";if(!De.includes(t))throw new p(`Invalid scope "${e}". Valid scopes: ${De.join(", ")} (default: project).`,f.USAGE);return t}function ao(e){if(e.startsWith("```")||e.includes(`
13
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf("=");return t>=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(n=>n>=0&&n<t))?!1:e.includes("=")||Xt(e)}function aE(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||ao(n)||!n.includes(",")?[t]:Ln(n)})}function oE(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function cE(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!ao(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&&oE(s))return{path:s,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function dE(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let i=cE(r);if(i!==void 0)return[i]}return aE([n]).map(i=>{let s=i.trim(),a=ao(s)?Q(i,"--add"):{path:s};if(_e(a,"--add",tE),!a.path)throw new p(`--add requires path=<value> or a bare ${t} path`,f.USAGE);return{path:a.path,scope:hp(a.scope),note:a.note?.trim()||void 0}})}):[]}function lE(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--add-glob requires a glob pattern value",f.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=Q(n,"--add-glob");_e(r,"--add-glob",nE);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new p("--add-glob key/value form requires pattern=<glob>",f.USAGE);return{pattern:i,scope:hp(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function uE(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires a path value",f.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=Q(n,"--remove"),i=Object.keys(r).filter(s=>sE.has(s.toLowerCase()));if(i.length>0)throw new p(`--remove identifies a linked artifact by path only and does not accept ${i.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,f.USAGE);if(_e(r,"--remove",rE),!r.path)throw new p("--remove key/value form requires path=<value>",f.USAGE);return r.path}return n}):[]}function mE(e){return e?e.map(t=>{let n=Q(t,"--migrate");_e(n,"--migrate",iE);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new p("--migrate requires from=<value> and to=<value>",f.USAGE);return{from:r,to:i}}):[]}function Jn(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function fE(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(s=>Jn(s.path,n))),i=[...new Set(t.map(s=>Jn(s,n)).filter(s=>r.has(s)))].sort((s,a)=>s.localeCompare(a));if(i.length!==0)throw new p(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,f.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 ct(e){return e.split(Fe.sep).join("/")}function so(e,t,n=process.cwd()){let r=e.trim();if(Xn(r))return r;if(Fe.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return ct(r.replaceAll("\\",Fe.sep));let i=Fe.relative(t,n);return i.startsWith(`..${Fe.sep}`)||i===".."||Fe.isAbsolute(i)?ct(Fe.normalize(r)):ct(Fe.relative(t,Fe.resolve(n,r)))}async function pE(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){let s=Fe.isAbsolute(i.pattern),a=await eE(i.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),o=[...new Set(a.map(c=>so(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of o)r.push({path:c,scope:i.scope,note:i.note})}return r}function _E(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)",f.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function gE(e){return`${e.path}::${e.scope}`}function oo(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function co(e){return[...new Map(e.map(t=>[gE(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function hE(e,t=process.cwd()){let n=[...new Set(e)].sort((o,c)=>o.localeCompare(c)),r=[],i=[],s=[],a=[];for(let o of n){if(Xn(o)){a.push(o.trim());continue}let c=Fe.isAbsolute(o)?o:Fe.resolve(t,o);try{(await Zk.stat(c)).isFile()?r.push(o):s.push(o)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&Cr(d)){i.push(o);continue}s.push(o)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:s,remote_references:a}}function yE(e,t,n,r){let i=0;for(let a=0;a<e.length;a+=1){let o=Jn(e[a].path,r);o!==e[a].path&&(e[a]={...e[a],path:o},i+=1)}return{adds:t.map(a=>{let o=Jn(a.path,r);return o!==a.path&&(i+=1),{...a,path:o}}),removes:n.map(a=>Jn(a,r)),count:i}}function wE(e,t,n,r){for(let s of t)e.some(a=>a.path===s.path&&a.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 i=co(e);return r?i:oo(i)}async function gp(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?await hE(t,e.workspaceRoot):void 0}}async function Si(e,t,n,r){let{metadataKey:i}=r,s=Ve(),a=I(process.cwd(),n.path),o=nt(a),c=process.cwd();await F(a);let d=await R(a),l=U(d,P()),u=await s.resolveList(t.add,"--add"),m=await s.resolveList(t.addGlob,"--add-glob"),_=await s.resolveList(t.remove,"--remove"),g=await s.resolveList(t.migrate,"--migrate"),h=dE(u,r.bareNoun).map(j=>({...j,path:so(j.path,o,c)})),y=lE(m),w=await pE(y,o,c),b=_E([...h,...w],t.note,h.length>0||y.length>0),E=uE(_).map(j=>so(j,o,c)),v=mE(g);if(fE(b,E,v),!(b.length>0||E.length>0||v.length>0)){let j=await Z(a,e,d.id_prefix,d.item_format,l.type_to_folder);if(!j)throw new p(`Item ${e} not found`,f.NOT_FOUND);let G=(await we(j,{schema:d.schema})).document.metadata[i]??[];return gp({id:j.id,artifacts:G,changed:!1,options:t,workspaceRoot:o})}let k=K(t.author,d.author_default),S=await ce({pmRoot:a,settings:d,id:e,op:r.op,author:k,message:t.message,force:t.force,skipNoop:!0,mutate(j){let C=j.metadata,G=C[i]??[],de=[...G],ie=yE(de,b,E,v),pe=wE(de,ie.adds,ie.removes,r.supportsAppendStable&&t.appendStable===!0);pe.length>0?C[i]=pe:delete C[i];let qe=!rt(G,pe);return{changedFields:qe?[i]:[],warnings:qe&&ie.count>0?[`path_migrations_applied:${ie.count}`]:[]}}}),A=S.item[i]??[],L=S.warnings.find(j=>j.startsWith("path_migrations_applied:")),H=L?Number(L.slice(24)):0;return gp({id:S.item.id,artifacts:A,changed:S.changedFields.includes(i),migrationsApplied:H,options:t,workspaceRoot:o})}function Ti(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;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]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function yp(e,t,n){let r=await Si(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Ti(r,"docs")}import{execFile as vE}from"node:child_process";import wp 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]="b8b3f729-be32-5a77-b08f-f616ee068e0f")}catch{}})();function vp(e,t){return new Promise((n,r)=>{vE("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,s)=>{i?r(i):n(s)})})}function bp(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 U$(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(bp(n),!n)throw new RangeError("Source line range must use start:end.");return n}function bE(e){let t=new Map;for(let n of e.split(`
14
+ `)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function kE(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let s=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((a,o)=>a.localeCompare(o));n.set(i,s)}return n}async function EE(e){let t=wp.relative(e.workspaceRoot,wp.resolve(e.workspaceRoot,e.sourcePath)),n=await vp(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await vp(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:bE(n),commitItems:kE(r),available:!0}}function SE(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let s=i.source===t,a=s?i.target:i.source;if((e.visitedDepth.get(a)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(a,n);let o=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,a],kinds:[...e.current.kinds,s?i.kind:o.inverse??i.kind]};e.details.get(a)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function TE(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let s=t.shift(),a=s.kinds.length;i!==void 0&&a>=i||a>=e.maxDepth||(i=SE({current:s,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((s,a)=>s.nodes.join("\0").localeCompare(a.nodes.join("\0"))),r}function xE(e,t,n){let r=Om(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=TE({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(o=>[o.id,o]))}),s=i[0];if(!s)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let a=[...new Set(i.map(o=>o.nodes.at(-1)))];return{status:a.length===1?"found":"ambiguous",nodes:s.nodes,kinds:s.kinds,alternative_decision_ids:a.slice(1)}}async function AE(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 CE(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 IE(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function kp(e){bp(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 AE(e),r=IE(n),i=new Map;for(let s of e.candidates){let a=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(s.item.id)),o=a.reduce((l,[,u])=>l+u,0),c=xE(s.item.id,e.corpus,t),d=CE({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:o,decisionStatus:c.status});i.set(s.item.id,{score:o*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:o,evidence:[...s.files.map(l=>({kind:"linked_file",reference:l.path})),...a.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:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}import Ep from"node:fs/promises";import $e 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]="ed504f2b-8b78-5fca-a4a7-7b0709a65533")}catch{}})();var RE=32768;function lo(e){return ct($e.normalize(e))}async function xi(e){try{return await Ep.realpath(e)}catch{return $e.resolve(e)}}function ln(e,t){let n=$e.isAbsolute(e.path)?$e.resolve(e.path):$e.resolve(t,e.path);return`${lo(n)}::${e.scope}`}function Ai(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>Ai(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))Ai(i,t?`${t}.${r}`:r,n)}function OE(e){let t=[];return Ai(e.metadata,"metadata",t),Ai(e.body,"body",t),t}function NE(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,r=/(?:\.{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 i of e){let s=new Set,a=i.value.slice(0,RE);for(let[o,c]of[[n,i.value],[r,a]]){o.lastIndex=0;for(let d of c.matchAll(o)){let l=NE(d[0]);!l||s.has(l)||(s.add(l),t.push({field:i.field,value:l}))}}}return t}async function DE(e,t,n=t){let r=$e.isAbsolute(e)?$e.resolve(e):$e.resolve(n,e),i;try{i=await Ep.stat(r)}catch{return}if(!i.isFile())return;let[s,a]=await Promise.all([xi(t),xi(r)]);if(Xs(s,a)){let o=$e.relative(s,a);return!o||o.startsWith("..")||$e.isAbsolute(o)?void 0:{path:lo(o),scope:"project"}}return{path:lo(r),scope:"global"}}async function ME(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>ln(c,t))),i=new Map,s=LE(OE(e)),a=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{a.set(c,await DE(c,t,n))}));let o=s.map(c=>({reference:c,resolved:a.get(c.value)}));for(let{reference:c,resolved:d}of o){if(!d)continue;let l=ln(d,t),u=i.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,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.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 Sp(e,t,n){let r=await Si(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Ti(r,"files")}async function PE(e,t){let n=await xi(t),r=await Promise.all(e.map(async s=>{let a=s.trim();if(!a)throw new p("Files lookup paths must not be empty.",f.USAGE);if(!$e.isAbsolute(a))return ct(a);let o=await xi(a);return Xs(n,o)?ct($e.relative(n,o)):ct(o)})),i=[...new Set(r)].sort((s,a)=>s.localeCompare(a));if(i.length===0)throw new p("Files lookup requires at least one path.",f.USAGE);return i}function FE(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new p(`Files lookup ${r} must be a non-negative integer.`,f.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 Tp(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function xp(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function $E(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(ct(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(xp)}async function UE(e){if(e.explain)return kp({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 jE(e){if([e.strictRead,e.noTruncate,e.explain,$d()].includes(!0))return null;let t=await ri(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Il({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function GE(e){let t=[],n=await Jt(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=$E({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&i.length>0)throw new p(`Files lookup could not read every item: ${i.join("; ")}`,f.GENERIC_FAILURE);let s=await UE({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),o=(s?[...r].sort((c,d)=>{let l=s.explanations.get(d.item.id).score-s.explanations.get(c.item.id).score;return l!==0?l:xp(c,d)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:o.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+o.length<r.length,truncated:e.offset+o.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:o.map(c=>({item:Tp(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=I(process.cwd(),t.path),r=nt(n);await F(n);let i=await PE(e.paths,r);if(e.lineRange&&i.length!==1)throw new p("Files lookup line attribution requires exactly one source path.",f.USAGE);let s=await R(n),a=U(s,P()),{offset:o,limit:c}=FE(e),d=await jE({pmRoot:n,typeToFolder:a.type_to_folder,paths:i,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:o,limit:c,has_more:o+d.matches.length<d.total,truncated:o+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:Tp(l.item),files:l.files}))}:GE({pmRoot:n,settings:s,typeToFolder:a.type_to_folder,paths:i,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function iU(e,t,n){let r=I(process.cwd(),n.path),i=nt(r);await F(r);let s=await R(r),a=U(s,P()),o=await Z(r,e,s.id_prefix,s.item_format,a.type_to_folder);if(!o)throw new p(`Item ${e} not found`,f.NOT_FOUND);let c=await we(o,{schema:s.schema}),d=await ME(c.document,i,process.cwd()),l=d.filter(A=>A.status==="addable"),u=d.filter(A=>A.status==="already_linked"),m=t.apply===!0,_=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let A=c.document.metadata.files??[];return{id:o.id,files:A,changed:!1,apply:m,count:A.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=K(t.author,s.author_default),h=l.map(A=>({path:A.path,scope:A.scope,note:_})),y=[],w=new Set,b=await ce({pmRoot:r,settings:s,id:e,op:"files_discover",author:g,message:t.message??"Discover referenced file links",force:t.force,mutate(A){let L=[...A.metadata.files??[]],H=new Set(L.map(G=>ln(G,i)));y=[],w.clear();for(let[G,de]of h.entries()){let ie=ln(de,i);H.has(ie)||(L.push(de),H.add(ie),y.push(de),w.add(G))}let j=co(L),C=t.appendStable?j:oo(j);return C.length>0?A.metadata.files=C:delete A.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==h.length?[`files_discover_skipped_existing:${h.length-y.length}`]:[]}}}),E=b.item.files??[],v=new Set(y.map(A=>ln(A,i))),T=E.filter(A=>v.has(ln(A,i))),k=l.filter((A,L)=>!w.has(L)),S=[...u,...k];return{id:b.item.id,files:E,changed:T.length>0,apply:!0,count:E.length,candidate_count:d.length,addable_count:l.length,added_count:T.length,skipped_existing_count:S.length,candidates:d,added:T,skipped_existing:S}}import{readFileSync as qE}from"node:fs";import Ci 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]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var KE=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),uo=new Set(["--pm-path","--path","--author"]),zE={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"])},WE=new Set(["-p","--package"]),BE=new Set(["-c","--call"]),mo=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),fo=new Set(["-C","--prefix","--userconfig","--cache"]),Ap=new Set(["--cwd"]),Cp=new Set(["--cwd"]),VE=new Set(["exec","x"]),Ip=new Set(["run","run-script"]),Rp=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function un(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function Ii(e,t=process.cwd()){let n=Ri(e.split(" ").filter(a=>a.length>0));if(n.length===0)return null;let[r,...i]=n;if(Qn(r)||Zn(r,t))return i;if(r==="node"&&i[0]&&Zn(i[0],t))return i.slice(1);let s=r==="npx"||r==="bunx"?It(i):r==="pnpm"?Ni(i):r==="npm"?Li(i):null;return s&&(Qn(s.command)||_o(s.command))?s.args:null}var po=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),a=new Set;for(let o of un(s)){let c=Ii(o),d=c?go(c):null,l=d&&KE.has(d.subcommand)?YE(d.remaining,zE[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&a.add(l)}return[...a].sort((o,c)=>o.localeCompare(c))};function Ri(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 Oi(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(uo.has(n)){t+=2;continue}t+=1;continue}return n}}function Qn(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function HE(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function _o(e){let t=HE(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Zn(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 r=Ci.resolve(t,e);try{return JSON.parse(qE(Ci.join(Ci.dirname(Ci.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function It(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let s=i[1];return s?{command:s,args:e.slice(t+1)}:null}if(BE.has(r)){t+=1;break}t+=WE.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function ht(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function Ni(e){let t=ht(e,mo);return t?.subcommand!=="dlx"?null:It(t.args)}function Li(e){let t=ht(e,fo);return!t||!VE.has(t.subcommand)?null:It(t.args)}function go(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(uo.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function YE(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(uo.has(r)||t.has(r))&&(n+=1)}}import{execFile as XE}from"node:child_process";import{readFile as JE}from"node:fs/promises";import Np from"node:path";import{promisify as QE}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]="30a61f26-5db8-50ba-af37-1990a4742ce8")}catch{}})();var ZE=QE(XE),ho=1,eS="linked-test-trust.json";function yo(e){return Np.join(Ed(e),eS)}function Op(){return{version:ho,acknowledged:{}}}async function wo(e){try{let t=JSON.parse(await JE(yo(e),"utf8"));return t.version!==ho||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Op():{version:ho,acknowledged:t.acknowledged}}catch{return Op()}}async function tr(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 ZE("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function nr(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function tS(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&ud(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function er(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function nS(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function mn(e,t,n){if(!e||e.length===0)return e;let r=nr();return nS(e,t,n,await tr(r))}function Lp(e){return Cn(J({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 vo(e,t,n){let r=await wo(e);return Dp(t,n,r)}function Dp(e,t,n){let r=Lp(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let s=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!tS(e.provenance)?s?{fingerprint:r,trusted:!0,reason:"acknowledged",...er(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...er(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...er(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:s?{fingerprint:r,trusted:!0,reason:"acknowledged",...er(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...er(i,t)}}async function Mp(e,t,n){let r=await wo(e);return t.map(i=>Dp(i,n,r))}async function Pp(e,t,n){let r=await wo(e),i=t.filter(s=>typeof s.command=="string"&&s.command.length>0).map(Lp);for(let s of i)r.acknowledged[s]={acknowledged_at:n};return await Ue(Np.dirname(yo(e))),await le(yo(e),`${JSON.stringify(r,null,2)}
15
+ `),{acknowledged:i.length,fingerprints:i}}import Ro from"node:fs/promises";import{realpathSync as mS}from"node:fs";import{execFile as fS}from"node:child_process";import Te from"node:path";import{promisify as pS}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]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var rS=["metadata","resolution"],bo=["metadata","resolution","estimates","lifecycle"],iS="completed";function ko(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Fp(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function $p(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Fp(n.close_reason)??iS;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${ko(r)}`,gate:"resolution"})}return t}function Up(e){let t=[];for(let n of e){let r=Fp(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${ko(r)}`,gate:"metadata"})}return t}function jp(e,t){return e.map(n=>{let r=Tl(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function Gp(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 qp(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${ko(n.path)}`})}return t}function Kp(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new p(`--fix-scope values must not be empty. Supported values: ${bo.join(", ")}.`,f.USAGE);return new Set(rS)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(bo.includes(i)){n.add(i);continue}throw new p(`Unknown --fix-scope value "${r}". Supported values: ${bo.join(", ")}.`,f.USAGE)}return n}function zp(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function rr(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]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var sS=/^([A-Z][A-Z0-9]*-\d+)\b/;function aS(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=sS.exec(t);return n?n[1]:null}function Wp(e){return typeof e=="string"&&e.trim().length>0}function Bp(e){let t=new Map;for(let r of e){if(typeof r.title!="string"||Wp(r.duplicate_of))continue;let i=aS(r.title);if(i===null)continue;let s=t.get(i);s||(s=[],t.set(i,s)),s.some(a=>a.id===r.id)||s.push({id:r.id,title:r.title,parent:Wp(r.parent)?r.parent.trim():null})}let n=[];for(let[r,i]of t){if(i.length<2)continue;let s=new Set(i.map(c=>c.id.toLowerCase())),a=i.filter(c=>c.parent===null||!s.has(c.parent.toLowerCase()));if(a.length<2)continue;let o=[...a].sort((c,d)=>c.id.localeCompare(d.id));n.push({code:r,count:o.length,ids:o.map(c=>c.id),titles:o.map(c=>c.title)})}return n.sort((r,i)=>r.code.localeCompare(i.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]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function Vp(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,s)=>i.localeCompare(s))){let i=t.get(r),s={};for(let a of[...i.keys()].sort((o,c)=>o.localeCompare(c)))s[a]=i.get(a);n[r]=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]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var Hp=3;function Yp(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Xp(e,t,n=Hp){let r=Number.isFinite(n)&&n>=1?Math.floor(n):Hp,i=new Map;for(let s of t){let a=Yp(s);if(a.length===0)continue;let o=i.get(a);o?o.push(s):i.set(a,[s])}return e.map(s=>{let a=(i.get(Yp(s))??[]).filter(o=>o!==s).sort((o,c)=>o.localeCompare(c));return a.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:a.slice(0,r),candidates_truncated:a.length>r}})}function Jp(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function oS(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function Qp(e){return`${e.item_id} ${e.link_kind}`}function Zp(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=oS(i.classification,r.classification),i.owners.set(Qp(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[Qp(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(s=>{let a=t(s.item_id);return{id:s.item_id,type:a?.type??"Unknown",title:a?.title??"",status:a?.status??"",field:s.link_kind}}).sort((s,a)=>{let o=s.id.localeCompare(a.id);return o!==0?o:s.field.localeCompare(a.field)})}))}function cS(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function e_(e){let t=[];for(let n of e)for(let r of n.items)t.push(`${n.path}:${n.classification} owner=${r.id} status=${r.status} field=${r.field} title="${cS(r.title)}"`);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]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function t_(e){return e.includeBody?Qt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Jt(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]="a1261d65-222c-5c6c-8634-a4413a91aba9")}catch{}})();var dS=5;async function n_(e,t,n){let r=await wi(e,t),s=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),a=n?Number.POSITIVE_INFINITY:dS,o=r.driftedItems.slice(0,a);return{check:{name:"history_drift",status:s.length===0?"ok":"warn",ok:s.length===0,details:{checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:o,drifted_items_truncated:o.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable}},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]="77a3c404-bbcd-5a5e-80bf-cb61c45af55d")}catch{}})();function Di(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],s=new Set([n]),a=o=>{for(let c of(t.get(o)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!s.has(c)){if(s.add(c),i.push(c),a(c))return!0;i.pop(),s.delete(c)}}return!1};return a(n)?[...i]:[...e,n]}function lS(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function uS(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let s=r.resolve(i.kind);if(!s?.hierarchy)continue;let a=n.get(i.id.toLowerCase());a&&(s.hierarchyDirection==="source_parent"?t.get(a).push(e.id):t.get(e.id).push(a))}}function Eo(e,t=be()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((s,a)=>s.id.localeCompare(a.id))){let s=r.get(i.id),a=lS(i.parent,n);a&&s.push(a),uS(i,r,n,t)}for(let[i,s]of r)r.set(i,[...new Set(s)].sort());return r}function So(e,t,n=be()){let r=si(e,a=>t?Gr(a,t):a==="closed"||a==="canceled",n),i=Eo(e,n),s=r.cycles.map(a=>a.item_ids);return{cycle_count:s.length,active_cycle_count:r.cycles.filter(a=>!a.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(a=>a.legacy_terminal).length,cycle_item_ids:[...new Set(s.flat())].sort(),cycle_sample_paths:s.map(a=>Di(a,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(a=>!a.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(a=>a.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(a=>`${a.child_id}:${a.parent_ids.join(",")}:${a.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(a=>!a.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(a=>a.legacy_terminal).length,parent_divergence_rows:r.divergences.map(a=>`${a.child_id}:scalar=${a.scalar_parent_id}:dependencies=${a.dependency_parent_ids.join(",")}:${a.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]="aca69fd7-c47a-5424-b58f-f305f690edd9")}catch{}})();var _S=["src","tests","docs"],gS=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],hS=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),yS=["resolution","expected_result","actual_result"],wS=["default","tracked-all","tracked-all-strict"],r_=["core","strict","custom"],Fi=["off","warn","error"],Ao=["author","acceptance_criteria","estimated_minutes","close_reason"],o_=[...Ao,"reviewer","risk","confidence","sprint","release"],Oo=Array.from(new Set(o_)),vS={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"},bS={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"},kS={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"},ES={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"},SS={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"},TS=32*1024*1024,xS=1e4,c_=40,vt=5,AS=4096,CS=255,IS=pS(fS);function d_(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?d_(r):r);return t}function RS(e){return{...e,checks:e.checks.map(t=>({...t,details:d_(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 Rt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function i_(e){return Rt(e).replace(/\/+$/,"")}function Je(e){let t=re(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Ui(e,t){return ae(e,t)??e}function ir(e,t){return t.terminal_statuses.has(Ui(e,t))}function yt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Mi(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function OS(e){let t=yt(cd),n={blocked_reason:yt(Ir.blocked_reason),resolution:yt(Ir.resolution),actual_result:yt(Ir.actual_result)},r=yt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:yt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:yt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:yt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Mi(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Mi(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Mi(i.resolution,n.resolution)?"default":"settings",actual_result:Mi(i.actual_result,n.actual_result)?"default":"settings"}}}function l_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(r_.includes(t))return t;throw new p(`Unknown --metadata-profile value "${e}". Supported values: ${r_.join(", ")}.`,f.USAGE)}function u_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Fi.includes(t))return t;throw new p(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Fi.join(", ")}.`,f.USAGE)}function m_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Fi.includes(t))return t;throw new p(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Fi.join(", ")}.`,f.USAGE)}function NS(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>vS[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function LS(e,t,n){let r=NS(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Ao],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...o_],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Ao],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var DS=new Set(["acceptance_criteria","estimated_minutes"]);function f_(e,t,n,r){return!r&&DS.has(t)&&ir(e.status,n)?!1:t==="author"?!re(e.author):t==="acceptance_criteria"?!re(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ui(e.status,n)===n.close_status&&!re(e.close_reason):t==="reviewer"?!re(e.reviewer):t==="risk"?!re(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!re(e.confidence):t==="sprint"?!re(e.sprint):!re(e.release)}function p_(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: ${wS.join(", ")}.`,f.USAGE)}function __(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Te.resolve(t);let n=Te.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Te.dirname(Te.dirname(n));let i=Te.resolve(process.cwd()),s=s_(n),a=s_(i),o=Te.relative(s,a);return o.length===0||!o.startsWith("..")&&!Te.isAbsolute(o)?n:i}function s_(e){try{return mS.native(e)}catch{return Te.resolve(e)}}function MS(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function No(e,t,n){let r=t.length>0?Te.join(e,t):e,i;try{i=await Ro.readdir(r,{withFileTypes:!0})}catch(s){if($(s))return;throw s}for(let s of i){if(s.name.startsWith("."))continue;let a=t.length>0?Te.join(t,s.name):s.name;if(s.isDirectory()){if(hS.has(s.name))continue;await No(e,a,n);continue}s.isFile()&&n.push(Rt(a))}}async function Co(e){let t=[];for(let n of _S)await No(e,n,t);for(let n of gS){let r=Te.join(e,n);try{(await Ro.stat(r)).isFile()&&t.push(Rt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function g_(e){try{let{stdout:t}=await IS("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:TS,windowsHide:!0,timeout:xS}),n=t.split("\0").map(r=>Rt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function PS(e,t){let n=new Set,r=i_(sd);r.length>0&&n.add(r);let i=i_(Te.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((s,a)=>s.localeCompare(a))}function a_(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function FS(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await g_(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Co(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Co(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ee(e,t=vt){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function wt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ee(e,c_);return{values:n.values,truncated:n.truncated,total:e.length}}var $S={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},US={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function jS(e){let t=e.missing_fields.map(n=>`${$S[n]} "${US[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function h_(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(a=>typeof a=="string"):Xf(t);if(i.length===0)return;let s=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...s?{fix_hints_truncated:!0}:{}}}function y_(e){let t=new Set;return 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("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var GS="validate_metadata_duplicate_issue_codes";function w_(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:vt,r=e.slice(0,n);return{rows:r.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:r.length<e.length,warnings:[`${GS}:${e.length}`]}}function qS(){return Object.fromEntries(Oo.map(e=>[e,[]]))}function KS(e,t,n){let r=qS();for(let i of e)for(let s of Oo)f_(i,s,t,n)&&r[s].push(i.id);return r}function zS(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let s=t[i];s.length>0&&r.push(`${bS[i]}:${s.length}`)}return r.push(...n),r}function v_(e,t){let n={};for(let r of e.required_fields){let i=t[r],s=i?i.length:0,a=kS[r];n[a]=s}return n}function b_(e,t,n){let r=[];for(let i of e.required_fields){let s=t[i];if(s)for(let a of s){let o=n.get(a)?.type,c=typeof o=="string"&&o.length>0?o:"Unknown";r.push({item_type:c,field:i})}}return r}function WS(e,t,n,r){for(let i of t.required_fields){let s=n[i];if(!s||s.length===0)continue;let a=ES[i],o=SS[i];if(!a||!o)continue;let c=ee(s,r?s.length:vt);e[a]=c.values,e[o]=c.truncated}}function k_(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:re(n.get(i)?.resolution)})):[]}function E_(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:re(n.get(i)?.type)})):[]}function BS(e,t,n,r){let i=new Map(e.map(y=>[y.id,y])),s=t.profile==="strict",a=KS(e,n,s),o=Bp(e),c=w_(o,r),d=zS(t,a,c.warnings),l=v_(t,a),u=b_(t,a,i),m=Vp(u),_={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:[...Oo],counts:l,missing_by_type:m,duplicate_issue_codes_count:o.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(_.configured_custom_required_fields=[...t.configured_custom_fields]),WS(_,t,a,r);let g=k_(t,a,i),h=E_(t,a,i);return{check:{name:"metadata",status:d.length===0?"ok":"warn",ok:d.length===0,details:_},warnings:d,closeReasonBackfillRows:g,estimateBackfillRows:h}}function VS(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Ui(m.status,t))),s=[],a=[];for(let m of i){let _=yS.filter(g=>!re(m[g]));_.length!==0&&(s.push({id:m.id,missing_fields:_}),a.push({id:m.id,missing_fields:_,close_reason:re(m.close_reason)}))}let o=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:vt,d=ee(s.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=s.map(m=>jS(m)),u=ee(l,c);return{check:{name:"resolution",status:o.length===0?"ok":"warn",ok:o.length===0,details:{checked_closed_items:i.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:o,resolutionBackfillRows:a}}function S_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function T_(e,t="pm",n=Nd()){let r=new Set(e.map(s=>s.id)),i=[...e].sort((s,a)=>s.id.localeCompare(a.id));return new Map(i.map(s=>{let a=new Set,o=Je(s.blocked_by);o&&r.has(o)&&a.add(o),(s.dependencies??[]).filter(d=>{let l=Je(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Je(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>a.add(d));let c=Je(s.definition_of_ready);return A_(c??"",t).filter(d=>r.has(d)).forEach(d=>a.add(d)),[s.id,[...a].sort((d,l)=>d.localeCompare(l))]}))}function x_(e,t,n){let r=Rm(e,n?l=>ir(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),s=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),a=t?Number.POSITIVE_INFINITY:vt,o=ee(i,a),c=ee(s,a),d=ee(r.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>'`),a);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+s.length,active_dangling_reference_count:i.length,dangling_reference_rows:o.values,dangling_reference_rows_truncated:o.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:r.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:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function A_(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${S_(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,s)=>i.localeCompare(s))}function C_(e){let t=0,n=new Map,r=new Map,i=[],s=new Set,a=[],o=l=>{n.set(l,t),r.set(l,t),t+=1,i.push(l),s.add(l);for(let m of e.get(l)??[])n.has(m)?s.has(m)&&r.set(l,Math.min(r.get(l),n.get(m))):(o(m),r.set(l,Math.min(r.get(l),r.get(m))));if(r.get(l)!==n.get(l))return;let u=[];for(;i.length>0;){let m=i.pop();if(s.delete(m),u.push(m),m===l)break}u.sort((m,_)=>m.localeCompare(_)),a.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||o(l);return a.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 I_(e,t="pm"){let n=T_(e,t),r=C_(n),i=[...new Set(r.flat())].sort((a,o)=>a.localeCompare(o)),s=r.map(a=>Di(a,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:s}}function R_(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 $i(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function O_(e,t){let n=$i(e).split("/").filter(Boolean),r=$i(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function HS(e,t){let n=$i(t),r=$i(e),i=t.endsWith("/")?t:`${t}/`,s=e.startsWith(i),a=n.length>0&&n===r,o=O_(e,t);return!s&&!a&&o===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:a?{score:o+500,confidence:"same_directory"}:{score:o,confidence:"shared_directory"}}function YS(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function XS(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(s=>(r==="docs"?s.docs??[]:s.files??[]).map(a=>({item:s,link:a}))).forEach(({item:s,link:a})=>{if(a.scope!=="project")return;let o=Rt(a.path);if(o.length===0||o===e)return;let c=HS(e,o);c!==null&&YS(i,s,c.score)&&(i={item:s,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function N_(e,t){return e.map(n=>{let r=R_(n),i=r==="docs_unowned"?"docs":"files",s=XS(n,r,t),a=s?.id??"<id>";return{path:n,classification:r,owner_candidate:s,remediation_hint:`pm ${i} ${a} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function L_(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function JS(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Je(e[n]);return i?r.some(s=>i.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function QS(e,t,n,r,i){let s=Je(t.parent),a=s?n.get(r.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:a?.id,grandparent_active:a!==void 0&&!ir(a.status,i)}}function ZS(e,t,n,r){let i=Je(e.blocked_by),s=Je(e.blocked_reason),a=s?.toLowerCase(),o=Ui(e.status,n),c=[];return t.has(o)?(!i&&!s&&c.push("blocked_status_missing_blocker_context"),a?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),a&&r.stale_blocker_reason_patterns.some(d=>a.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function eT(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),a=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),o={activeItems:e.filter(c=>!ir(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of o.activeItems){let d=JS(c,r);d.length>0&&o.closureLikeRows.push({id:c.id,fields:d});let l=Je(c.parent),u=l?i.get(s.get(l.toLowerCase())??l):void 0;if(u&&ir(u.status,n)&&(o.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),o.terminalParentFixRows.push(QS(c,u,i,s,n))),t){let m=ZS(c,a,n,r);m.length>0&&o.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((_,g)=>_.localeCompare(g))})}}return o}function tT(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 Pi(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function To(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function nT(e,t,n,r,i){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 a=Pi("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),o=Pi("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=Pi("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=Pi("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=To("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=To("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=To("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...s,...a?[a]:[],...o?[o]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function D_(e){let t=Rt(e);return t.length>AS||t.split(/[\\/]/).some(n=>n.length>CS)}async function rT(e,t){let n=Te.isAbsolute(t)?t:Te.resolve(e,t);if(D_(n))return!1;try{let r=await Ro.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return MS(r,["ENOENT","ENOTDIR"])}}async function iT(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(s=>({item:i,artifact:s,link_kind:"files"})),...(i.docs??[]).map(s=>({item:i,artifact:s,link_kind:"docs"}))]);for(let{item:i,artifact:s,link_kind:a}of r){if(s.scope!=="project")continue;if(Xn(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let o=Rt(s.path);o.length!==0&&(n.linkedProjectPaths.add(o),await rT(t,s.path)&&(n.missingLinkedPaths.push(o),n.staleLinkRows.push({item_id:i.id,path:o,link_kind:a})))}return n}function sT(e,t,n,r,i,s){let a=r==="tracked-all-strict",o=a&&!i,c=i||a,d=c?[]:PS(t,n),l=d.length===0?[]:e.candidateFiles.filter(_=>a_(_,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(_=>!a_(_,d)),m={};if(l.length>0){let _=wt(l,s);m.pm_internals={count:l.length,paths:_.values,paths_truncated:_.truncated,paths_total:_.total}}return{strictTrackedAllMode:a,strictModeForcesPmInternals:o,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function M_(e,t,n,r,i,s,a,o="pm"){let c=eT(e,t,i,s);tT(c);let d=I_(c.activeItems,o),l=So(e,i),u=nT(c,t,n,r,{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}),m=a?Number.POSITIVE_INFINITY:vt,_=ee(c.closureLikeRows.map(S=>`${S.id}:${S.fields.join(",")}`),m),g=ee(c.terminalParentRows.map(S=>`${S.id}:${S.parent_id}:${S.parent_status}`),m),h=ee(c.staleBlockerRows.map(S=>`${S.id}:${S.status}:${S.reasons.join(",")}`),m),y=ee(d.cycle_item_ids,m),w=ee(d.cycle_sample_paths,m),b=ee(l.cycle_item_ids,m),E=ee(l.cycle_sample_paths,m),v=ee(l.cardinality_violation_rows,m),T=ee(l.parent_divergence_rows,m),k=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:k?"error":u.length===0?"ok":"warn",ok:!k&&u.length===0,details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:_.values,active_closure_like_metadata_rows_truncated:_.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:g.values,active_terminal_parent_rows_truncated:g.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:h.values,stale_blocker_rows_truncated:h.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:y.values,dependency_cycle_item_ids_truncated:y.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:r,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:b.values,parent_cycle_item_ids_truncated:b.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:v.values,hierarchy_cardinality_violation_rows_truncated:v.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:T.values,hierarchy_parent_divergence_rows_truncated:T.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:u,terminalParentFixRows:c.terminalParentFixRows}}async function P_(e,t,n,r,i,s){let a=await iT(e,t),o=new Map(e.map(C=>[C.id,C])),c=[...new Set(a.missingLinkedPaths)].sort((C,G)=>C.localeCompare(G)),d=await FS(t,r),l=sT(d,n,t,r,i,s),u=l.candidateFiles.filter(C=>!a.linkedProjectPaths.has(C)),m=N_(u,e),_=Xp(c,l.candidateFiles),g=new Map(_.map(C=>[C.path,C.classification])),h=_.filter(C=>C.classification==="moved").length,y=a.staleLinkRows.map(C=>({...C,classification:g.get(C.path)??"deleted"})).sort((C,G)=>C.item_id.localeCompare(G.item_id)||C.path.localeCompare(G.path)||C.link_kind.localeCompare(G.link_kind)),w=[];l.strictModeForcesPmInternals&&w.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&w.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&w.push(`validate_files_orphaned_paths:${u.length}`);let b=[...a.remoteLinkedPaths].sort((C,G)=>C.localeCompare(G)),E=wt(b,s),v=wt(c,s),T=wt(u,s),k=wt(m.map(C=>`${C.path}:${C.classification}:owner_candidate=${C.owner_candidate?.id??"unowned"}`),s),S=s?m:wt(L_(m),!1).values,A=wt(Jp(_),s),L=y.map(C=>({item_id:C.item_id,path:C.path,link_kind:C.link_kind,classification:C.classification})),H=Zp(L,C=>{let G=o.get(C);return G?{type:G.type,title:G.title,status:G.status}:void 0}),j=s?H:wt(e_(H),!1).values;return{check:{name:"files",status:w.length===0?"ok":"warn",ok:w.length===0,details:{workspace_root:t,scan_mode_requested:d.requestedMode,scan_mode_applied:d.appliedMode,strict_tracked_all_mode:l.strictTrackedAllMode,strict_mode_forces_pm_internals:l.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:l.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:c_,candidate_scan_source:d.source,include_pm_internals:l.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:l.pmInternalCandidatePrefixes,pm_internal_excluded_count:l.excludedPmInternalPaths.length,excluded_total:l.excludedPmInternalPaths.length,excluded_by_reason:l.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:b.length,remote_linked_paths_total:E.total,remote_linked_paths:E.values,remote_linked_paths_truncated:E.truncated,candidate_total_raw:d.candidateTotal,candidate_scanned_raw:d.candidateScanned,candidate_total:l.candidateFiles.length,candidate_scanned:l.candidateFiles.length,scanned_candidate_files:l.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:v.total,missing_linked_paths:v.values,missing_linked_paths_truncated:v.truncated,missing_linked_paths_moved_count:h,missing_linked_paths_deleted_count:c.length-h,missing_linked_path_classifications:A.values,missing_linked_path_classifications_truncated:A.truncated,missing_linked_path_rows_count:H.length,missing_linked_path_rows:j,orphaned_paths_count:u.length,orphaned_paths_total:T.total,orphaned_paths:T.values,orphaned_paths_truncated:T.truncated,orphaned_path_classifications:k.values,orphaned_path_classifications_truncated:k.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:S}},warnings:w,staleLinkPruneRows:y}}function F_(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function aT(e,t,n){return`${e}:${t}:${F_(n)}`}function oT(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},s)=>{let a=t[s];if(a.trusted)return;let o=F_(i.command??"");n.push(`${r.id}:${a.source_ref??"unknown"}->${a.current_source_ref??"unknown"}:${o}`)}),n}async function $_(e,t,n,r){let i=new Set(e.map(T=>T.id.toLowerCase())),s=0,a=0,o=new Set,c=[],d=e.flatMap(T=>(T.tests??[]).map(k=>({item:T,linkedTest:k}))),l=await tr(nr()),u=await Mp(r,d.map(({linkedTest:T})=>T),l),m=oT(d,u);for(let{item:T,linkedTest:k}of d){if(typeof k.command!="string"||k.command.trim().length===0)continue;s+=1;let S=po(k.command,t);if(S.length!==0){a+=S.length;for(let A of S)o.add(A),i.has(A.toLowerCase())||c.push(aT(T.id,A,k.command))}}let _=[...new Set(c)].sort((T,k)=>T.localeCompare(k)),g=[...new Set(_.map(T=>T.split(":")[1]??""))].filter(T=>T.length>0).sort((T,k)=>T.localeCompare(k)),h=[];_.length>0&&h.push(`validate_command_references_stale_pm_ids:${_.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let y=n?Number.POSITIVE_INFINITY:vt,w=ee(_,y),b=ee(g,y),E=ee([...o].sort((T,k)=>T.localeCompare(k)),y),v=ee(m,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:a,unique_referenced_pm_ids_count:o.size,unique_referenced_pm_ids:E.values,unique_referenced_pm_ids_truncated:E.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:v.values,untrusted_linked_tests_truncated:v.truncated,stale_pm_id_references_count:_.length,stale_pm_ids_count:g.length,stale_pm_ids:b.values,stale_pm_ids_truncated:b.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:h}}function cT(e,t){let n=Kr(e.map(c=>({ref:c.id,version:qr(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:vt,s=ee(n.outdated,i),a=ee(n.ahead,i),o=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:o,ok:o==="ok",details:{checked_items:e.length,current_format_version:zd,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:a.values,ahead_items_truncated:a.truncated}},warnings:r}}var Io="pm validate auto-fix";async function U_(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Io};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new p("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",f.USAGE);await n.runUpdate(e.item_id,r,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 xo(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function j_(e,t,n){let r=[],i=[],s=new Map;for(let a of e.filter(o=>xo(o)===null))try{await U_(a,t,n),r.push(a)}catch(o){i.push({fix:a,error:o})}for(let a of e.filter(o=>xo(o)!==null)){let o=xo(a),c=s.get(o);c?c.push(a):s.set(o,[a])}for(let a of s.values()){let o=a[0];if(!o)continue;let c=a.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{o.kind==="prune_file_link"?await Sp(o.item_id,{remove:c,message:Io},t):await yp(o.item_id,{remove:c,message:Io},t),r.push(...a)}catch(d){i.push(...a.map(l=>({fix:l,error:d})))}}return{applied:r,failed:i}}var bj={applyValidateFix:U_,applyValidateFixes:j_,attachValidateFixHints:h_,buildCommandReferencesCheck:$_,buildDependencyReferencesCheck:x_,buildCloseReasonBackfillRows:k_,buildFilesCheck:P_,buildLifecycleCheck:M_,buildLifecycleDependencyGraph:T_,buildLifecycleParentGraph:Eo,buildEstimateBackfillRows:E_,buildMetadataCounts:v_,buildMissingFieldOccurrences:b_,buildOrphanedPathRows:N_,classifyOrphanedPath:R_,collectDefaultProjectFileCandidates:Co,collectTrackedGitFileCandidates:g_,detectLifecycleDependencyCycles:I_,detectLifecycleParentCycles:So,escapeRegExp:S_,extractItemIds:A_,findLifecycleDependencyCycleComponents:C_,isMetadataFieldMissing:f_,linkedArtifactPathExceedsFilesystemLimits:D_,listFilesRecursive:No,resolveDependencyCycleSeverity:u_,resolveParentCycleSeverity:m_,resolveFileScanMode:p_,resolveLifecycleDependencyCycleSamplePath:Di,resolveRequestedChecks:y_,resolveValidateMetadataProfile:l_,resolveWorkspaceRoot:__,sharedDirectoryPrefixLength:O_,summarizeOrphanedPathRows:L_,summarizeDuplicateIssueCodes:w_,toMeaningfulString:Je};async function dT(e,t,n,r){let i=await _p(e,new Set(t.map(h=>h.id)),n,{schema:r.schema,extensionFieldNames:pt(P())}),s=[];i.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let a=s.length,o=await bi(e);o.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${o.tracked_path_count}`);let c=await $m(e,Fm(r));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Zt(e),l=d===null?null:await oi(d);l!==null&&l.status!=="ok"&&s.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=d===null?[]:await Vn(d,{includeLossless:!0,pmRoot:e}),{pendingDecisions:m,lossless:_}=yi(u);m.length>0&&s.push(`validate_merge_decisions_unreviewed:${m.length}`);let g=a>0?"error":s.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:g,ok:g==="ok",details:{...i,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:m.length,pending_merge_decision_items:[...new Set(m.map(h=>h.item_id))].sort((h,y)=>h.localeCompare(y)),lossless_merge_receipt_count:_.length,lossless_merge_receipt_items:[...new Set(_.map(h=>h.item_id))].sort((h,y)=>h.localeCompare(y)),tracked_runtime_cache:{tracker_relative_root:o.tracker_relative_root,tracked_paths:o.tracked_paths,tracked_path_count:o.tracked_path_count,remediation_command:o.remediation_command}}},warnings:s}}function dt(e,t,n){n&&h_(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function lT(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let i=BS(e.items,e.metadataPolicy,e.statusRegistry,r);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,dt(t,i,n)}if(e.requestedChecks.has("resolution")){let i=VS(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,dt(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=M_(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,dt(t,i,n),dt(t,x_(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await P_(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=i.staleLinkPruneRows,dt(t,i,n)}return e.requestedChecks.has("command_references")&&dt(t,await $_(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&dt(t,await n_(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&dt(t,cT(e.items,r),n),e.requestedChecks.has("storage_integrity")&&dt(t,await dT(e.pmRoot,e.items,U(e.settings,P()).type_to_folder,e.settings),n),t}function uT(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...Up(t.closeReasonBackfillRows)),r.push(...$p(t.resolutionBackfillRows)),r.push(...jp(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Gp(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...qp(t.staleLinkPruneRows)),r}async function mT(e,t,n,r,i,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let a=uT(e,t,n),{applicable:o,gated:c}=zp(a,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await j_(o,i,s);l.push(...m.applied.map(rr)),u.push(...m.failed.map(({fix:_,error:g})=>({...rr(_),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:[...r].sort((m,_)=>m.localeCompare(_)),planned_count:a.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:a.map(rr),applied_fixes:l,gated_fixes:c.map(m=>({...rr(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function G_(e,t,n={}){Jd(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new p("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",f.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new p("--fix-scope requires --auto-fix.",f.USAGE);let i=Kp(e.fixScope),s=I(process.cwd(),t.path);await F(s);let a=await R(s),o=X(a.schema),c=U(a,P()),d=y_(e),l=[],u=await t_({includeBody:d.has("history_drift"),pmRoot:s,settings:a,typeToFolder:c.type_to_folder,warnings:l});if(d.has("history_drift")){let L=await Bn(s);L.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${L.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",_=l_(typeof e.metadataProfile=="string"?e.metadataProfile:a.validation.metadata_profile),g=LS(_,m,a.validation.metadata_required_fields),h=OS(a),y=u_(e.dependencyCycleSeverity),w=m_(e.parentCycleSeverity),b=p_(e.scanMode),E=__(s),v=await lT({requestedChecks:d,options:e,global:t,pmRoot:s,workspaceRoot:E,settings:a,items:u,statusRegistry:o,metadataPolicy:g,lifecyclePatternPolicy:h,dependencyCycleSeverity:y,parentCycleSeverity:w,fileScanMode:b,initialWarnings:[...new Set(l)]}),T=r?await mT(e,v,a,i,t,n):void 0,k=[...new Set(v.warnings)].sort((L,H)=>L.localeCompare(H)),A={ok:!v.checks.some(L=>L.status==="error"),has_warnings:k.length>0,checks:v.checks,warnings:k,...T!==void 0?{fixes:T}:{},generated_at:x(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?A:{...RS(A),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 pT}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]="f9c26dab-b2fb-5ca0-b575-682b4b0bb830")}catch{}})();var _T=pT(fT),gT=16,hT=3e4;function yT(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 wT(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let s of Object.entries(i).filter(([,a])=>a.required===!0).map(([a])=>a))if(!Object.hasOwn(r,s))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${s}`);for(let[s,a]of Object.entries(r)){let o=i[s];if(!o)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${s}`);if(a===null||typeof a!==o.type)throw new TypeError(`assurance provider ${e.id} parameter ${s} must be ${o.type}`)}return{...r}}async function vT(e,t,n,r){let i=wT(e,t),s=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Dd(n)}));s.catch(()=>{});let a;try{let o=await Promise.race([s,new Promise((c,d)=>{a=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??hT),a.unref?.()})]);return yT(e,t.key,o)}finally{clearTimeout(a)}}function K_(e,t,n,r){let i=e;for(let s of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new He(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[s]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(s=>typeof s=="string"))return i;throw new He(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function q_(e,t,n,r){let i=e.checks.find(a=>a.name===t);if(!i)throw new He(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:K_(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function bT(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await _T("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function kT(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(gT,t.length)},async()=>{for(;r<t.length;){let s=r;r+=1;let a=t[s],o=await Bt(ft(e,a.id),a.id);n[s]=o.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function sr(e,t={}){let n=await R(e),r=U(n),i=X(n.schema),a=(await Jt(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(_=>({..._,id:_.id,status:_.status,type:_.type})),o={path:e},c=P(),d=Object.fromEntries((c?.assurance_providers??[]).map(_=>[_.definition.id,{cost_class:_.runtime_definition.cost_class,network:_.runtime_definition.network}])),l=new Map,u,m;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await bT(e,t.tree_id),items:a,history:t.include_history===!1?[]:await kT(e,a),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async _=>{if(_.kind==="graph"){let y=J({operation:_.operation,parameters:_.parameters??{}}),w=l.get(y);w===void 0&&(w=Dm(_.operation,void 0,void 0,{..._.parameters,full:!0},o),l.set(y,w));let b=await w;return{value:K_(b,_.field,_.kind),population_size:a.length,cost:a.length}}if(_.kind==="validate"){u??=G_({counts:!0},o);let y=await u;return q_(y,_.check,_.field,_.kind)}if(_.kind==="health"){m??=fp(o,{checkOnly:!0,full:!0});let y=await m;return q_(y,_.check,_.field,_.kind)}let g=t.providers?.[_.provider];if(g)return g(_);let h=Gd(c,_.provider);if(!h)throw new TypeError(`assurance provider ${_.provider} is not registered`);return vT(h.runtime_definition,_,e,t.trigger??"sdk")}}}import{createHash as ET}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]="e78c3363-1741-52b9-8bd5-729e3ccada50")}catch{}})();function ji(e){return{files:(Array.isArray(e.files)?e.files:[]).flatMap(t=>{if(typeof t!="object"||t===null||Array.isArray(t))return[];let n=t.path;return typeof n=="string"?[n]:[]}),package_names:Array.isArray(e.package_names)?e.package_names.filter(t=>typeof t=="string"):[],item_ids:[e.id],tags:Array.isArray(e.tags)?e.tags.filter(t=>typeof t=="string"):[],error_codes:Array.isArray(e.error_codes)?e.error_codes.filter(t=>typeof t=="string"):[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59f5918f-108e-5cad-905b-7f690c3c4794")}catch{}})();var qi=["production_defect","nightly_regression","scanner_finding","review_caught_late"],Do=["gate_added","gate_strengthened","explicit_waiver"],z_=256,ST=1024,ar=new Map,TT=["files","package_names","item_ids","tags","error_codes"];function xe(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t<n?-1:1)}function W_(e){return ET("sha256").update(J(e)).digest("hex")}function Lo(e,t){if(typeof e!="string"||!e.trim())throw new TypeError(`${t} must be a non-empty string`)}function or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fn(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function V_(e,t){if(!or(e))throw new TypeError(`${t} must be an object`);for(let n of TT)if(e[n]!==void 0&&!fn(e[n]))throw new TypeError(`${t}.${n} must be an array of strings`);return e}function xT(e,t){if(!or(e))throw new TypeError(`defect recurrence family ${t} triggers must be an object`);for(let r of["package_names","item_ids","tags","error_codes"])if(e[r]!==void 0&&!fn(e[r]))throw new TypeError(`defect recurrence family ${t} triggers.${r} must be an array of strings`);let n=e.file_patterns;if(n!==void 0&&!fn(n))throw new TypeError(`defect recurrence family ${t} triggers.file_patterns must be an array of strings`);for(let r of n??[])if(r.length>z_)throw new TypeError(`defect recurrence family ${t} file pattern exceeds ${z_} characters`)}function AT(e,t){if(Lo(e.id,"defect recurrence family id"),t.has(e.id))throw new TypeError(`Duplicate defect recurrence family ${e.id}`);if(t.add(e.id),!Number.isInteger(e.version)||e.version<1)throw new TypeError(`defect recurrence family ${e.id} version must be a positive integer`);if(!qi.includes(e.escape_class))throw new TypeError(`defect recurrence family ${e.id} has an invalid escape class`);Lo(e.title,`defect recurrence family ${e.id} title`),Lo(e.owner_item_id,`defect recurrence family ${e.id} owner_item_id`)}function CT(e){if(!fn(e.historical_item_ids)||e.historical_item_ids.length===0||e.historical_item_ids.some(t=>!t.trim()))throw new TypeError(`defect recurrence family ${e.id} requires historical_item_ids`);if(xT(e.triggers,e.id),!or(e.checks)||!fn(e.checks.local)||!fn(e.checks.hosted)||e.checks.local.length===0||e.checks.hosted.length===0||e.checks.local.some(t=>!t.trim())||e.checks.hosted.some(t=>!t.trim()))throw new TypeError(`defect recurrence family ${e.id} checks must contain nonempty local and hosted string arrays`)}function IT(e){if(!or(e.budget)||typeof e.budget.max_escape_rate!="number"||!Number.isFinite(e.budget.max_escape_rate)||typeof e.budget.max_false_positive_rate!="number"||!Number.isFinite(e.budget.max_false_positive_rate))throw new TypeError(`defect recurrence family ${e.id} requires numeric budgets`);if(e.budget.max_escape_rate<0||e.budget.max_escape_rate>1||e.budget.max_false_positive_rate<0||e.budget.max_false_positive_rate>1)throw new TypeError(`defect recurrence family ${e.id} budgets must be between 0 and 1`)}function RT(e){let t=V_(e.negative_control,`defect recurrence family ${e.id} negative_control`);if(Po(e,t,{}).length===0)throw new TypeError(`defect recurrence family ${e.id} negative_control must select its own family`)}function Mo(e){if(e.version!==1)throw new TypeError(`Unsupported defect recurrence policy version ${e.version}`);if(typeof e.evidence_epoch!="string"||!Number.isFinite(Date.parse(e.evidence_epoch)))throw new TypeError("defect recurrence evidence_epoch must be an ISO timestamp");let t=new Set;for(let n of e.families){if(!or(n))throw new TypeError("defect recurrence family must be an object");AT(n,t),CT(n),IT(n),RT(n)}}function OT(e,t){let n=ar.get(e);if(n===void 0){if(ar.size>=ST){let i=ar.keys().next().value;ar.delete(i)}let r=e.replaceAll("**","\0").replaceAll(/[|\\{}()[\]^$+?./]/gu,"\\$&").replaceAll("*","[^/]*").replaceAll("\0",".*");n=new RegExp(`^${r}$`,"u"),ar.set(e,n)}return n.test(t)}function NT(e,t){let n=[],r=xe(e.triggers.file_patterns??[]);for(let i of xe(t.files??[]))for(let s of r)OT(s,i)&&n.push({signal:"file",value:i,matched:s});return n}function LT(e,t){let n=[{signal:"package",values:xe(t.package_names??[]),triggers:xe(e.triggers.package_names??[])},{signal:"tag",values:xe(t.tags??[]),triggers:xe(e.triggers.tags??[])},{signal:"error_code",values:xe(t.error_codes??[]),triggers:xe(e.triggers.error_codes??[])}],r=[];for(let i of n){let s=new Set(i.triggers);for(let a of i.values)s.has(a)&&r.push({signal:i.signal,value:a,matched:a})}return r}function DT(e,t,n){let r=new Set(e.triggers.item_ids??[]);return xe(t.item_ids??[]).flatMap(i=>r.has(i)||n[i]?.includes(e.id)?[{signal:"item",value:i,matched:e.id}]:[])}function Po(e,t,n){return[...NT(e,t),...LT(e,t),...DT(e,t,n)].sort((i,s)=>i.signal!==s.signal?i.signal.localeCompare(s.signal):i.value!==s.value?i.value.localeCompare(s.value):i.matched.localeCompare(s.matched))}function MT(e,t){if(!e)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("defect change-risk cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n)||n.index_fingerprint!==t||!Number.isInteger(n.offset)||n.offset<0)throw new TypeError("defect change-risk cursor does not match this index");return n.offset}function PT(e){return[e.files,e.package_names,e.item_ids,e.tags,e.error_codes].reduce((t,n)=>t+(n?.length??0),0)}function H_(e,t,n={}){Mo(e);let r=[...e.families].sort((l,u)=>l.id<u.id?-1:1),i=W_({...e,families:r}),s=new Set(n.changed_item_ids??[]),a=n.previous_index?.policy_fingerprint===i,o=a?Object.fromEntries(Object.entries(n.previous_index?.item_families??{}).filter(([l])=>!s.has(l))):{},c=a?Object.keys(o).length:0;for(let l of t){let u=ji(l),m=r.filter(_=>_.historical_item_ids.includes(l.id)||Po(_,u,{}).length>0).map(_=>_.id);m.length>0?o[l.id]=m:delete o[l.id]}let d=Object.fromEntries(Object.entries(o).sort(([l],[u])=>l<u?-1:1).map(([l,u])=>[l,xe(u)]));return{version:1,policy_fingerprint:i,index_fingerprint:W_({policy_fingerprint:i,item_families:d}),families:r,item_families:d,build:{items_scanned:t.length,items_reused:c,items_indexed:Object.keys(d).length}}}function Y_(e,t,n={}){let r=n.limit??25;if(!Number.isInteger(r)||r<1||r>100)throw new TypeError("defect change-risk limit must be an integer from 1 through 100");let i=MT(n.cursor,e.index_fingerprint),s=e.families.flatMap(l=>{let u=Po(l,t,e.item_families);return u.length===0?[]:[{family_id:l.id,family_version:l.version,owner_item_id:l.owner_item_id,escape_class:l.escape_class,reasons:u,local_checks:xe(l.checks.local),hosted_checks:xe(l.checks.hosted),budget:l.budget}]}),a=s.slice(i,i+r),o=i+a.length,c=o<s.length?Buffer.from(JSON.stringify({index_fingerprint:e.index_fingerprint,offset:o})).toString("base64url"):void 0,d={risk_detected:s.length>0,index_fingerprint:e.index_fingerprint,items:a,total:s.length,...c?{next_cursor:c}:{},required_local_checks:xe(s.flatMap(l=>l.local_checks)),required_hosted_checks:xe(s.flatMap(l=>l.hosted_checks)),row_contract:{row_keys:["items"],jq_selector:".items[]"}};return{...d,cost:{families_evaluated:e.families.length,signals_evaluated:PT(t),families_selected:s.length,estimated_output_tokens:Math.ceil(JSON.stringify(d).length/4)}}}function FT(e){return typeof e.type=="string"&&e.type.toLowerCase()==="issue"||(Array.isArray(e.tags)?e.tags:[]).some(t=>typeof t=="string"&&["bug","defect","security"].includes(t.toLowerCase()))}function Gi(e){return typeof e=="string"&&e.trim().length>0}function B_(e){return Array.isArray(e)&&e.length>0&&e.every(Gi)}function $T(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,expired:!1};let n=e;if(!Do.includes(n.disposition)||typeof n.owner!="string"||!n.owner.trim())return{valid:!1,expired:!1};if(n.disposition==="explicit_waiver"){let r=Date.parse(n.waiver_expires_at??"");return{valid:Gi(n.waiver_reason)&&Number.isFinite(r)&&r>=t,expired:Number.isFinite(r)&&r<t}}return{valid:Gi(n.gate_id)&&Gi(n.negative_control)&&B_(n.local_checks)&&B_(n.hosted_checks),expired:!1}}function UT(e,t){let n=[];if(!Number.isFinite(Date.parse(typeof e.completed_at=="string"?e.completed_at:""))&&!Number.isFinite(Date.parse(typeof e.closed_at=="string"?e.closed_at:""))&&n.push({item_id:e.id,kind:"invalid_completion_timestamp",detail:`${e.id} requires a valid completed_at or closed_at timestamp after the defect-evidence epoch.`}),typeof e.escape_class!="string"?n.push({item_id:e.id,kind:"missing_escape_class",detail:`${e.id} requires escape_class after the defect-evidence epoch.`}):qi.includes(e.escape_class)||n.push({item_id:e.id,kind:"invalid_escape_class",detail:`${e.id} has unsupported escape_class ${e.escape_class}.`}),e.gate_evidence===void 0)return n.push({item_id:e.id,kind:"missing_gate_evidence",detail:`${e.id} requires structured gate_evidence after the defect-evidence epoch.`}),n;let r=$T(e.gate_evidence,t);return r.valid||n.push({item_id:e.id,kind:r.expired?"expired_waiver":"invalid_gate_evidence",detail:r.expired?`${e.id} carries an expired gate-evidence waiver.`:`${e.id} gate_evidence does not prove a gate or explicit waiver.`}),n}function $j(e,t,n,r=new Date){Mo(t);let i=Date.parse(t.evidence_epoch),s=new Set(n),a=e.filter(m=>s.has(m.status)&&FT(m)),o=a.filter(m=>{let _=Date.parse(typeof m.completed_at=="string"?m.completed_at:"");if(Number.isFinite(_))return _>=i;let g=Date.parse(typeof m.closed_at=="string"?m.closed_at:"");if(Number.isFinite(g))return g>=i;let h=Date.parse(typeof m.created_at=="string"?m.created_at:"");return!Number.isFinite(h)||h>=i}),c=Object.fromEntries(qi.map(m=>[m,0])),d=Object.fromEntries(Do.map(m=>[m,0])),l=a.filter(m=>typeof m.escape_class=="string"&&qi.includes(m.escape_class));for(let m of l)if(c[m.escape_class]+=1,typeof m.gate_evidence=="object"&&m.gate_evidence!==null&&!Array.isArray(m.gate_evidence)){let _=m.gate_evidence.disposition;typeof _=="string"&&Do.includes(_)&&(d[_]+=1)}let u=o.flatMap(m=>UT(m,r.getTime()));return u.sort((m,_)=>m.item_id!==_.item_id?m.item_id.localeCompare(_.item_id):m.kind.localeCompare(_.kind)),{ok:u.length===0,governed_item_count:o.length,classified_item_count:l.length,class_counts:c,evidence_disposition_counts:d,findings:u}}function jT(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("defect recurrence policy must be an object");let t=e;if(!Array.isArray(t.families))throw new TypeError("defect recurrence policy families must be an array");return Mo(t),t}function X_(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("defect change-risk request must be an object");let t=e,n=V_(t.change,"defect change-risk request.change");if(t.cursor!==void 0&&typeof t.cursor!="string")throw new TypeError("defect change-risk request.cursor must be a string");if(t.limit!==void 0&&!Number.isInteger(t.limit))throw new TypeError("defect change-risk request.limit must be an integer");return{policy:jT(t.policy),change:n,...t.cursor===void 0?{}:{cursor:t.cursor},...t.limit===void 0?{}:{limit:t.limit}}}import{createHash as GT}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]="f66a964d-1352-5523-ab91-5177d0d93ce8")}catch{}})();var Fo,J_=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk"],$o=["measurement","assertion","gate"];function qT(e){if(J_.includes(e))return e;throw Rr({command_path:"assurance",token:e,allowed:J_,display_name:"assurance action"})}function pn(e,t,n){throw new p(t,f.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function KT(e){if(!e)return pn("kind",`Assurance declaration kind is required. Expected: ${$o.join(", ")}`,"pm assurance list measurement");if($o.includes(e))return e;throw new p(`Assurance declaration kind is required. Expected: ${$o.join(", ")}`,f.USAGE)}function Q_(e){if(!e)return pn("preset",`Assurance preset is required. Expected: ${qn.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(qn.includes(e))return e;throw new p(`Assurance preset is required. Expected: ${qn.join(", ")}`,f.USAGE)}function Uo(e){return e.owner?.trim()?e.owner.trim():pn("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(r){throw new p("assurance definition must be valid JSON",f.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new p("assurance put requires a JSON object definition",f.USAGE);return n}async function WT(e){let[t,n,r]=await Promise.all([Gn(e,"measurement"),Gn(e,"assertion"),Gn(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Z_(e,t){return t===!0?{id:e.id}:e}async function BT(e,t){let n=t.authorization_decision;if(!n)return[];let r=await sr(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(a=>a.id===n),s=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!s.has(i.status))throw new p(`Assurance authorization ${n} must name a terminal Decision item`,f.USAGE);return[i.id]}async function VT(e,t){let n=$a(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>tn))throw new p(`assurance verdict limit must be an integer from 1 through ${tn}`,f.USAGE);let r=await _f(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function HT(e,t,n){if(e==="presets"){if(t.preset??t.id)return _i(Q_(t.preset??t.id),Uo(t));let i=qn.map(s=>{let a=_i(s,"pm-owner");return{id:s,title:a.title,description:a.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return en(()=>hf(n,Q_(t.preset??t.id),Uo(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await yf(await sr(n,{resolve_tree:!1,trigger:"derive"}),Uo(t)),s=t.apply?await en(()=>wf(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...s?{applied:s}:{}}}if(!t.id)return pn("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",f.USAGE);let r=await La(n,"assertion",t.id);return en(()=>vf(n,r,t.enforcement,{author:t.author,message:t.message}))}async function YT(e,t,n){if(!e.id)return pn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new p("assurance run requires a trigger",f.USAGE);if(!st.includes(e.trigger))throw new p(`Unknown assurance trigger ${e.trigger}. Expected: ${st.join(", ")}`,f.USAGE);let i=e.trigger,[s,a]=await Promise.all([WT(t),sr(t,{...n.workspace,tree_id:e.tree,trigger:i})]),o=await Qm(()=>uf(r,s,a,{trigger:i,dry_run:e.dry_run===!0}));return o.dry_run||await pf(t,o,{author:e.author,message:e.message}),o}function eg(e){throw e instanceof p?e:new p(e instanceof Error?e.message:"assurance risk request is invalid",f.USAGE)}function XT(e){if(e.limit!==void 0)throw new p("assurance risk does not accept --limit; set limit inside the risk definition",f.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new p("assurance risk definition must be valid JSON",f.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return X_(t)}catch(n){return eg(n)}}function JT(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function QT(e,t,n){let r=J(t.policy),i=Fo?.pm_root===e?Fo:void 0,s=new Map(n.map(d=>[d.id,GT("sha256").update(J(ji(d))).digest("hex")])),a=i?.policy_serialized===r?i:void 0,o=a?JT(a,s):new Set,c=H_(t.policy,a?n.filter(d=>o.has(d.id)):n,a?{previous_index:a.index,changed_item_ids:[...o]}:{});return Fo={pm_root:e,policy_serialized:r,item_fingerprints:s,index:c},c}async function ZT(e,t){let n=XT(e),r=await sr(t,{include_history:!1,resolve_tree:!1});try{return Y_(QT(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit})}catch(i){return eg(i)}}async function ex(e,t={},n={}){let r=qT(e.action),i=I(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return HT(r,e,i);if(r==="verdicts")return VT(e,i);if(r==="run")return YT(e,i,n);if(r==="risk")return ZT(e,i);let s=KT(e.kind);if(r==="list")return Gn(i,s);if(!e.id)return pn("id",`assurance ${r} requires an id`,`pm assurance ${r} ${s} <id>`);let a=e.id;if(r==="show")return La(i,s,a);if(r==="remove"){let l=await en(()=>ff(i,s,a,{author:e.author,message:e.message}));return Z_(l,e.idOnly)}let o=zT(s,e.definition);if(o.id!==a)throw new p(`Assurance definition id ${o.id} does not match requested id ${a}`,f.USAGE);let c={author:e.author,message:e.message,...s==="assertion"?{authorized_decision_ids:await BT(i,o)}:{}},d=await en(()=>fi(i,s,o,c));return Z_(d,e.idOnly)}function e1(e,t,n){let r={...e,...t};return ex({action:O(r,"subcommand")??O(r,"assuranceAction")??O(r,"operation")??"",kind:O(r,"kind"),id:O(r,"id"),definition:r.definition,trigger:O(r,"trigger"),tree:O(r,"treeId")??O(r,"tree"),gate:O(r,"gate"),limit:$a(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:O(r,"author"),message:O(r,"message"),preset:O(r,"preset"),owner:O(r,"owner"),apply:r.apply===!0,enforcement:O(r,"enforcement")},n)}import{readFile as tx}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]="eac75dc5-80b4-50d2-b615-4f96edca7346")}catch{}})();function g1(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,t}function tg(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}.`,f.USAGE,{code:"structured_event_immutable"})}function nx(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Ot(e,t){let n=e[t];return Array.isArray(n)?n:[]}function h1(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let s=Q(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function rx(e){return typeof e=="object"&&e!==null&&"code"in e}async function ix(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`,f.USAGE);let r=Ve();if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add")??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let i=e.file.trim();if(!i)throw new p("--file path cannot be empty",f.USAGE);try{return{value:await tx(i,"utf8"),emptyFlag:"--file"}}catch(s){if(rx(s)&&Cr(s))throw new p(`--file path not found: ${i}`,f.USAGE);let a=s instanceof Error?s.message:String(s);throw new p(`Failed to read --file path "${i}": ${a}`,f.USAGE)}}async function y1(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new p("Specify only one of --edit or --delete",f.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",f.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new p("--delete must be a positive integer",f.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",f.USAGE);let n=await ix(e,t);if(e.edit!==void 0){if(!n)throw new p("--edit requires replacement text from --add, --stdin, or --file",f.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function cr(e,t){throw e instanceof p&&e.exitCode===f.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 rg(e){return e==="comments"?"--stdin":"--add -"}function sx(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let i=rg(t.collectionKey),s=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new p(`--add value "${r}" looks like an option, not annotation text. Use ${i} to read stdin, or use text=${r} for literal dash-leading text.`,f.USAGE,{code:"annotation_flag_like_value",required:`Use ${i} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${s} ${i}`,`${s} --add text=${r}`]})}function ax(e,t){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.`,f.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> ${rg(e.collectionKey)}`]})}async function w1(e,t,n,r){ax(r,t);let i=I(process.cwd(),n.path);await F(i);let s=await R(i),a=U(s,P()),o=On(t.limit);if(r.input.mode==="list"){let _=await Z(i,e,s.id_prefix,s.item_format,a.type_to_folder);if(!_)throw new p(`Item ${e} not found`,f.NOT_FOUND);let g=await we(_,{schema:s.schema}),h=Ot(g.document.metadata,r.collectionKey);return Ki(_.id,r.collectionKey,h,o,t.includeMeta===!0)}let c=K(t.author,s.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,g;try{g=await ce({pmRoot:i,settings:s,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(y){let w=Ot(y.metadata,r.collectionKey),b=ng(r.input.index,w.length,r.collectionKey);return tg(w[b],"deleted"),w.splice(b,1),y.metadata[r.collectionKey]=w,{changedFields:[r.collectionKey]}}})}catch(y){cr(y,r.conflictGuidance)}let h=Ot(g.item,r.collectionKey);return Ki(g.item.id,r.collectionKey,h,o,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let d=r.input.rawValue??r.input.value??"";sx(d,r);let l=r.parseText(r.input.value??"");if(!l.trim())throw new p(`${r.input.emptyFlag??"--add"} text cannot be empty`,f.USAGE);if(r.input.mode==="edit"){let _=r.editOp??r.op,g;try{g=await ce({pmRoot:i,settings:s,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(y){let w=Ot(y.metadata,r.collectionKey),b=ng(r.input.index,w.length,r.collectionKey),E=w[b];return tg(E,"edited"),w[b]={...E,text:l,edited_at:x()},y.metadata[r.collectionKey]=w,{changedFields:[r.collectionKey]}}})}catch(y){cr(y,r.conflictGuidance)}let h=Ot(g.item,r.collectionKey);return Ki(g.item.id,r.collectionKey,h,o,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:h[r.input.index-1]},t.fullHistory===!0)}let u;try{u=await ce({pmRoot:i,settings:s,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(_){let g=Ot(_.metadata,r.collectionKey),h={created_at:x(),author:c,text:l};return g.push(r.createEntry(h)),_.metadata[r.collectionKey]=g,{changedFields:[r.collectionKey]}}})}catch(_){cr(_,r.conflictGuidance)}let m=Ot(u.item,r.collectionKey);return Ki(u.item.id,r.collectionKey,m,o,t.includeMeta===!0,{action:"add",entryIndex:m.length,entry:m.at(-1)},t.fullHistory===!0)}function ng(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),i=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,s=t===1?`1 ${r}`:`${t} ${n}`;throw new p(`${i} index ${e??"(missing)"} out of range (item has ${s})`,f.USAGE)}return e-1}function Ki(e,t,n,r,i,s,a=!1){let o=s===void 0||a?nx(n,s!==void 0&&a?void 0:r):s.entry===void 0?[]:[s.entry],c=s!==void 0&&o.length<n.length;return{id:e,[t]:o,count:o.length,...[i,s!==void 0].includes(!0)?{total_count:n.length,returned_count:o.length,has_more:c||o.length<n.length,...r!==void 0?{limit:r}:{}}:{},...s===void 0?{}:{mutation_receipt:{action:s.action,entry_index:s.entryIndex,changed_count:1,full_history_included:!c},omission_receipt:{has_omissions:c,omitted_field_group_count:c?1:0,omitted_field_groups:c?[{name:`${t}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0579277-f123-5f96-8664-dfe05ade1b24")}catch{}})();async function ig(e,t,n){return[...await Bt(ft(e,t),t).catch(()=>[])].reverse().find(s=>s.patch.some(a=>a.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]="1a61bf25-e320-5adc-8f5a-a427bc89af1a")}catch{}})();var sg="no_available_next_item";function ox(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 cx(e,t,n,r={}){let i=I(process.cwd(),n.path);await F(i);let s=await R(i),a=X(s.schema),o=K(r.author,s.author_default),c=na(o),d=null,l=!1,u=[],m=await ce({pmRoot:i,settings:s,id:e,op:"claim",author:o,message:r.message,force:t,skipNoop:!0,async mutate(_){let h=_.metadata.assignee??"",y=_.metadata.claim_principal?.trim()||h;if(d=h.trim().length>0?h:null,Gr(_.metadata.status,a)&&!t)throw new p(`Cannot claim terminal item ${_.metadata.id} without --force`,f.CONFLICT);if(d!==null&&y!==c){if(r.ifAvailable===!0)return l=!0,u.push(`claim_skipped_held_by:${d}`),{changedFields:[]};if(!t){let b=await ig(i,_.metadata.id,h);throw new p(`Item ${_.metadata.id} is already ${b}. Use --force to take over, or --if-available to skip without failing.`,f.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}->${o}`)}return _.metadata.assignee=o,_.metadata.claim_principal=c,{changedFields:["assignee","claim_principal"],warnings:u}}});return l||await Hm({pmRoot:i,settings:s,principal:c,itemId:m.item.id}),{item:m.item,claimed_by:l&&d!==null?d:o,previous_assignee:d,forced:t,...l?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function R1(e,t,n={},r={}){let i=dx(n.maxAttempts),s=await R(I(process.cwd(),t.path)),a={...n,author:K(n.author,s.author_default)},o=await Xm({...r,callerAuthor:a.author,limit:String(i)},t),c=[o.recommended,...o.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return lx(c.slice(0,i),e,t,a)}function dx(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",f.USAGE);return t}async function lx(e,t,n,r={},i=cx){let s=0;for(let o of e){s+=1;try{let c=await i(o.id,t,n,r),d={...c,recommendation:o,attempts:s,available:!0};if(!c.skipped)return d}catch(c){if(!ox(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:K(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[sg]};let a=s===0;throw new p(a?"No actionable items matched the selection filters":"No actionable item remained available to claim",a?f.NOT_FOUND:f.CONFLICT,{code:sg,why:a?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[a?"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 O1(e,t,n,r={}){let i=I(process.cwd(),n.path);await F(i);let s=await R(i),a=K(r.author,s.author_default),o=na(a),c=r.ownershipReleaseBypass===!0,d=null,l;try{l=await ce({pmRoot:i,settings:s,id:e,op:"release",author:a,message:r.message,force:t,bypassAssigneeConflict:c,mutate(u){return d=u.metadata.assignee??null,!d&&!u.metadata.claim_principal?{changedFields:[]}:(delete u.metadata.assignee,delete u.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(u){cr(u,{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."]})}return await Ym({pmRoot:i,principal:o,itemId:l.item.id}),{item:l.item,released_by:a,previous_assignee:d,forced: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]="a7ae3c89-b50b-5e4f-8273-8318bc976d84")}catch{}})();var M1=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function ux(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 r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function og(e,t){return jo(e,t,{operation:"close"})}function jo(e,t,n){let r=ux(e);if(!t||r.closeReason!==void 0)return r;let i=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",f.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:i,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 cg(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,i=e.dependencies??[],s=i.filter(d=>d.kind==="blocked_by"),a=e.blocked_reason!==void 0,o=[];if(r&&(delete e.blocked_by,o.push("blocked_by")),a&&(delete e.blocked_reason,o.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let d=i.filter(l=>l.kind!=="blocked_by");d.length>0?e.dependencies=d:delete e.dependencies,o.push("dependencies")}let c=[...new Set([...n?[n]:[],...s.map(d=>d.id)])];return c.length===0?{changedFields:o,warnings:[]}:{changedFields:o,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]="781b5118-7b07-53c7-802f-c889cb797a96")}catch{}})();var mx=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function fx(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")`,f.USAGE)}function px(e){let t=[];for(let n of mx){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function _x(e,t,n){let r=new Set,i=t;for(;typeof i=="string"&&i.trim().length>0;){let s=i.trim();if(s===n)return!0;if(r.has(s))return!1;r.add(s),i=(await e(s))?.duplicate_of}return!1}function gx(e){return typeof e!="string"||e.trim().length===0}async function hx(e,t,n,r){let i=n?.trim();if(!i)return;if(i===r)throw new p("An item cannot be closed as a duplicate of itself.",f.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=U(t,P()),a=new Map,o=async d=>{if(a.has(d))return a.get(d)??null;let l=await Z(e,d,t.id_prefix,t.item_format,s.type_to_folder);if(!l)return a.set(d,null),null;let{document:u}=await we(l,{schema:t.schema});return a.set(d,u.metadata),u.metadata},c=await o(i);if(!c)throw new p(`Duplicate target "${i}" was not found. Create or locate the canonical item first.`,f.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 ${r} "Duplicate of ${i}" --duplicate-of ${i}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await _x(o,c.duplicate_of,r))throw new p(`Circular duplicate reference detected. Target "${i}" points back to "${r}".`,f.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 "${i}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,f.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "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 yx(e,t,n){return e.filter(r=>r.parent===t&&!oe(r.status,n)).map(r=>r.id).sort((r,i)=>r.localeCompare(i))}function wx(e,t,n){let r=new Map(e.map(o=>[o.id.trim().toLowerCase(),o])),i=Gm(e),s=t.trim().toLowerCase(),a=n.blocked_statuses;return e.filter(o=>a.has(o.status)).map(o=>({item:o,blockerIds:i.get(o.id.trim().toLowerCase())})).filter(({blockerIds:o})=>o.includes(s)).filter(({blockerIds:o})=>o.every(c=>{if(c===s)return!0;let d=r.get(c);return d!==void 0&&oe(d.status,n)})).map(({item:o,blockerIds:c})=>({id:o.id,blocker_ids:c})).sort((o,c)=>o.id.localeCompare(c.id))}async function vx(e,t,n,r,i,s){let a=wx(n,r,s),o=[];for(let c of a)try{let d=await ce({pmRoot:e,settings:t,id:c.id,op:"update",author:i,message:`Auto-unblocked after blocker ${r} closed`,mutate(l){let u=l.metadata.dependencies??[],m=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 ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,m.length>0?l.metadata.dependencies=m:delete l.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return m.length!==u.length&&_.push("dependencies"),{changedFields:_}}});o.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";o.push(`auto_unblock_failed:${c.id}:${l}`)}return o}function bx(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:i,key:s}of r){if(typeof i!="string")continue;let a=i.trim();a.length!==0&&(e[s]=a,n.push(s))}return n}function kx(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{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:i,value:s}of r)gx(e[i])&&(e[i]=s,n.push(i));return n}function Ex(e,t,n,r){let i=[];if(t!=="off"){let s=px(e);if(s.length>0){let a=s.map(o=>o.label);if(t==="strict"){let o=s.map(d=>`--${d.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...o.flatMap(d=>[d,"<value>"])];throw new p(`Cannot close item ${e.id}: missing ${a.join(", ")}. Populate fields or use --validate-close warn.`,f.USAGE,{code:"close_validation_missing_fields",recovery:{missing:o,suggested_retry:Xd(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."]})}i.push(`close_validation_missing_fields:${e.id}:${a.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.`,f.USAGE);i.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return i}return n.length>0&&i.push(`closed_with_active_children:${e.id}:${n.join(",")}`),i}function Sx(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function Tx(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function xx(e,t){if(oe(e.status,t.statusRegistry)&&!t.force)throw new p(`Item ${e.id} is already terminal; use --force to close again.`,f.CONFLICT);let n=bx(e,t.options),r=kx(e,t.duplicateOf),i=Ex(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 a=["status","closed_at",...s?["completed_at"]:[],...Sx(e,t.closeReason),...n];if(Gl(e)&&(e.plan_mode="completed",a.push("plan_mode")),t.duplicateOf!==void 0){a.push("duplicate_of");for(let c of r)a.includes(c)||a.push(c)}a.push(...Tx(e));let o=cg(e,t.lifecyclePolicy);return a.push(...o.changedFields),i.push(...o.warnings),{changedFields:a,...i.length>0?{warnings:i}:{}}}async function Ax(e,t,n,r){let i=I(process.cwd(),r.path);await F(i);let s=await R(i),a=X(s.schema),o=K(n.author,s.author_default),c=U(s,P()).type_to_folder,d=await Z(i,e,s.id_prefix,s.item_format,c);if(!d)throw await Nn(i,e,s.id_prefix,c);let l=await hx(i,s,n.duplicateOf,d.id),u={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},m=og({explicit:t,duplicateOf:l,resolution:n.resolution,message:n.message},u.requireCloseReason).closeReason,_=fx(n.validateClose)??s.governance.close_validation_default,g=await ve(i,s.item_format,c,void 0,s.schema),h=yx(g,d.id,a),y=new Date().toISOString(),w=n.completedAt===void 0?y:ue(n.completedAt,new Date(y),"completed-at"),b=await ce({pmRoot:i,settings:s,id:d.id,op:"close",author:o,message:n.message,force:n.force,mutate(E){return xx(E.metadata,{pmRoot:i,statusRegistry:a,force:n.force,options:n,duplicateOf:l,validateCloseMode:_,activeChildIds:h,closeReason:m,closedAt:y,completedAt:w,lifecyclePolicy:u})}});return{item:b.item,changed_fields:b.changedFields,warnings:[...b.warnings,...await vx(i,s,g,d.id,o,a)]}}function dg(e,t,n,r){return Ax(e,t,n,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]="5bbc21f0-f517-571a-8ecf-45f20f0e793d")}catch{}})();var Go=[{exit_code:f.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:f.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:f.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:f.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:f.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:f.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:f.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:f.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],lg=[f.SUCCESS,f.GENERIC_FAILURE,f.USAGE,f.NOT_FOUND,f.CONFLICT,f.DEPENDENCY_FAILED],Cx=new Set(["close-many","update-many"]),mg=Be.map(e=>({command:e,exit_codes:Cx.has(e)?[...lg,f.NO_EFFECT,f.PARTIAL_EFFECT]:[...lg]})),ug=new Map(mg.map(e=>[e.command,e])),Ix=[f.SUCCESS,f.NO_EFFECT,f.PARTIAL_EFFECT];function B1(e){return Ix.includes(e)}function V1(e){return Go.some(t=>t.exit_code===e)}function fg(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return ug.get(t)??ug.get(t.split(" ")[0])}function H1(e,t=Be,n=mg){let r=new Map(n.map(d=>[d.command,d])),i=t.filter(d=>!r.has(d)),s=e.filter(d=>{let l=r.get(d.command)??r.get(d.command.split(" ")[0]);return l===void 0||!l.exit_codes.includes(d.exit_code)}),a=new Set(e.map(d=>d.exit_code)),c=[...new Set(n.flatMap(d=>d.exit_codes))].filter(d=>!a.has(d)).sort((d,l)=>d-l);return{ok:i.length===0&&s.length===0&&c.length===0,missing_commands:i,undeclared_observations:s,unreachable_exit_codes:c}}function Y1(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:f.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:f.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:f.PARTIAL_EFFECT}:{outcome:"effect",exit_code:f.SUCCESS}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="94e8b95b-35fa-5fc7-843a-481497e09b54")}catch{}})();function pg(e){return[...e].sort().join("\0")}function Rx(e,t,n){let r=e.successors.get(t);r?r.push(n):e.successors.set(t,[n]);let i=e.predecessors.get(n);i?i.push(t):e.predecessors.set(n,[t])}function _g(e,t,n,r,i){let s=t.resolve(i);if(s?.ordering!==!0)return;let a=Im(r),o=a===void 0?void 0:e.canonicalIds.get(a.toLowerCase());if(o===void 0)return;let c=(s.precedence??"source_before_target")==="source_before_target";Rx(e,c?n:o,c?o:n)}function Ox(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},r=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0);for(let i of r){let s=i.id.trim();n.canonicalIds.set(s.toLowerCase(),s)}for(let i of r){let s=i.id.trim();_g(n,t,s,i.blocked_by,"blocked_by");for(let a of i.dependencies??[])typeof a!="object"||a===null||_g(n,t,s,a.id,typeof a.kind=="string"?a.kind:"related")}for(let i of[n.successors,n.predecessors])for(let s of i.values())s.sort();return n}function Nx(e,t){let n=new Set([t]),r=[t];for(;r.length>0;){let i=r.pop();for(let s of[e.successors,e.predecessors])for(let a of s.get(i)??[])n.has(a)||(n.add(a),r.push(a))}return n}function Lx(e,t){let n=new Map;for(let r of t){let i=(e.successors.get(r)??[]).filter(s=>t.has(s));i.length>0&&n.set(r,i)}return n}function gg(e,t,n){let r=Ox(e,t),i=r.canonicalIds.get(n.trim().toLowerCase());if(i===void 0)return{cycles:[],successors:new Map,canonical:n};let s=Lx(r,Nx(r,i));return{cycles:Nm(s).filter(a=>a.includes(i)),successors:s,canonical:i}}function Dx(e,t,n){let r=new Set(t),i=r.has(n)?n:t[0];if(e.get(i)?.includes(i))return[i,i];for(let s of e.get(i)??[]){if(!r.has(s))continue;let a=Mx(e,r,i,s);if(a)return a}return[...t,t[0]]}function Mx(e,t,n,r){let i=[[r]],s=new Set([n,r]);for(;i.length>0;){let a=i.shift(),o=a.at(-1);for(let c of e.get(o)??[]){if(c===n)return[n,...a,n];!t.has(c)||s.has(c)||(s.add(c),i.push([...a,c]))}}}function zi(e,t,n){let r=be(),i=gg(e,r,n),s=gg(t,r,n),a=new Set(i.cycles.map(pg)),o=new Set(va(e,void 0,r).map(d=>`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`));return[...va(t,void 0,r).filter(d=>d.holder_id.toLowerCase()===n.trim().toLowerCase()&&!o.has(`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`)).map(d=>`ordering_storage_contradiction_created:${Lm(d)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...s.cycles.filter(d=>!a.has(pg(d))).map(d=>`ordering_cycle_created:${Dx(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]="33a43890-abcf-58fc-bf9d-bf2619d4cf35")}catch{}})();var Px=3,hg=20,Fx=.8,$x=100,yg=1e3,wg=1e6;function vg(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 Ux(e,t){let n=e.items[0],r=I(t.cwd??process.cwd(),t.pmRoot),i=X((await R(r)).schema);return oe(n.status,i)?{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 bg(e){let t=e.limit??Px,n=e.threshold??Fx;if(!Number.isSafeInteger(t)||t<0||t>hg)throw new p(`Similarity limit must be an integer from 0 to ${hg}.`,f.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new p("Similarity threshold must be a number from 0 to 1.",f.USAGE);return{limit:t,threshold:n}}function jx(e){let t=e.limit??$x;if(!Number.isSafeInteger(t)||t<0||t>yg)throw new p(`Duplicate cluster limit must be an integer from 0 to ${yg}.`,f.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.",f.USAGE);return{limit:t,since:n}}async function Gx(e,t){let n=I(e.cwd??process.cwd(),e.pmRoot),r=await R(n),i=U(r),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.",f.USAGE);let a=X(r.schema),o=s?.map(u=>{if(u==="all")return u;let m=ae(u,a);if(!m)throw new p(`Unknown duplicate-cluster status "${u}". Allowed: all, ${a.definitions.map(_=>_.id).join(", ")}.`,f.USAGE);return m}),c=o?.includes("all")===!0;if(c&&o?.some(u=>u!=="all"))throw new p('The "all" status cannot be combined with other statuses.',f.USAGE);let d=c?void 0:o,l=d?new Set(d):void 0;return{items:(await ve(n,r.item_format,i.type_to_folder,void 0,r.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())).sort((u,m)=>u.id.localeCompare(m.id)).map(u=>({item:u,prepared:la(u.title)})),statuses:d}}function kg(e,t=wg){let n=new Set,r=[new Map,new Map,new Map];for(let[i,s]of e.entries()){let a=[[s.prepared.normalized],s.prepared.issueCodes,s.prepared.tokens];for(let[o,c]of a.entries())for(let d of c){let l=r[o].get(d)??[];for(let u of l)n.add(`${u}:${i}`);if(n.size>t)throw new p(`Duplicate sweep exceeded ${wg} candidate pairs; narrow it with statuses or since.`,f.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the batch duplicate query until its deterministic candidate set fits the disclosed safety bound."});l.push(i),r[o].set(d,l)}}return n}var fG={buildDuplicateClusters:Sg,collectDuplicateCandidatePairs:kg,createDuplicateUnionFind:Eg};function Eg(e){let t=Array.from({length:e},(r,i)=>i);return{parent:t,findRoot:r=>{let i=r;for(;t[i]!==i;)i=t[i];for(;t[r]!==r;){let s=t[r];t[r]=i,r=s}return i}}}function qx(e,t,n,r){let i=[];for(let s of t){let[a,o]=s.split(":").map(u=>Number.parseInt(u,10)),c=ma(e[a].prepared,e[o].prepared);if(c.score<n)continue;let d=r.findRoot(a),l=r.findRoot(o);d!==l&&(r.parent[l]=d),i.push({left_id:e[a].item.id,right_id:e[o].item.id,...c})}return i}function Sg(e,t,n,r){let i=new Map;for(let s of e.keys()){let a=n.findRoot(s),o=i.get(a)??[];o.push(s),i.set(a,o)}return[...i.values()].filter(s=>s.length>1).map(s=>{let a=new Set(s.map(c=>e[c].item.id)),o=t.filter(c=>a.has(c.left_id)&&a.has(c.right_id)).sort((c,d)=>d.score-c.score||c.left_id.localeCompare(d.left_id)||c.right_id.localeCompare(d.right_id));return{id:e[s[0]].item.id,items:s.map(c=>{let d=e[c].item;return{id:d.id,title:d.title,status:d.status,type:d.type}}),matches:o,max_score:o[0]?.score??0}}).sort((s,a)=>a.max_score-s.max_score||s.id.localeCompare(a.id)).slice(0,r)}function Kx(e,t,n,r,i){return t.filter(s=>!n.has(s.id)).map(s=>({id:s.id,title:s.title,status:s.status,type:s.type,...ua(e,s.title)})).filter(s=>s.score>=r).sort((s,a)=>a.score-s.score||s.id.localeCompare(a.id)).slice(0,i)}async function zx(e,t={}){let n=e.title.trim();if(n.length===0)throw new p("Similarity candidate title must not be empty.",f.USAGE);let{limit:r,threshold:i}=bg(t),s=I(t.cwd??process.cwd(),t.pmRoot),a=await R(s),o=U(a),c=await ri(s,Object.values(o.type_to_folder)),d=da(n),l=c&&d.length>0?await Rl({pmRoot:s,expectedSourceCursor:c.source_cursor,query:d.map(_=>`"${_.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(r*10,50)}):null,u=l===null?await ve(s,a.item_format,o.type_to_folder,void 0,a.schema):l.items,m=Kx(n,u,new Set(e.excludeIds??[]),i,r);return{items:m,count:m.length,threshold:i,source:l?"persistent_index":"metadata_fallback"}}async function Tg(e={}){let{threshold:t}=bg({...e,limit:void 0}),{limit:n,since:r}=jx(e),{items:i,statuses:s}=await Gx(e,r),a=kg(i),o=Eg(i.length),c=qx(i,a,t,o),d=Sg(i,c,o,n);return{clusters:d,count:d.length,threshold:t,source:"metadata_scan",filters:{statuses:s??null,since:e.since??null},cost:{item_count:i.length,candidate_pairs:a.size,scored_pairs:a.size}}}async function qo(e,t){if(t.mode==="off")return;let n=await zx(e,t);if(n.count===0)return;let r=await Ux(n,t),i=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!i){let s=n.items.map(o=>`${o.id} (${o.status}): ${o.title}`).join("; "),a=r.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new p(`Likely duplicate item(s) found: ${s}. ${a} or pass --allow-duplicate with explicit intent.`,f.CONFLICT,{code:"likely_duplicate",required:`${a}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:r.command,suggested_retry_args:r.args}})}return{mode:t.mode,bypassed:i,result:n,recovery: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]="44e6a87d-0ca5-53af-b199-b66bb2b98fb5")}catch{}})();var Nt=["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"],Wx=new Set(Nt),Bx=Nt.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),Vx=new RegExp(`^(?:[-*+]\\s+)?(?:${Bx})\\s*[:=]`,"i");function Wi(e){return e.startsWith("```")||e.includes(`
16
+ `)?!0:Vx.test(e)}function Bi(e,t){let n={},r=[];for(let[i,s]of Object.entries(e)){let a=i.toLowerCase();if(!Wx.has(a)){r.push(i);continue}if(Object.hasOwn(n,a))throw new p(`${t} provides key "${i}" more than once after case normalization`,f.USAGE);n[a]=s}if(r.length>0)throw new p(`${t} does not recognize key${r.length>1?"s":""} ${r.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${Nt.join(", ")}.`,f.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`,f.USAGE);let{cmd:i,...s}=n;return{...s,command:s.command??i}}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]="64adcc3c-3646-5990-9442-4c4374a2dc7d")}catch{}})();var Mt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Pn,Pm,"FORCE_COLOR"]),Yi=/^[A-Za-z_][A-Za-z0-9_]*$/,Dt=["schema","tracker","auto"],xg=["source","isolated","snapshot"];function dr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} env_set must include at least one KEY=VALUE assignment`,f.USAGE);let r=Object.create(null);for(let i of n){let s=i.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`,f.USAGE);let a=i.slice(0,s).trim(),o=i.slice(s+1);if(!Yi.test(a))throw new p(`${t} env_set key "${a}" is invalid`,f.USAGE);if(Mt.has(a.toUpperCase()))throw new p(`${t} env_set key "${a}" is reserved for sandbox safety`,f.USAGE);r[a]=o}return Object.keys(r).length>0?r:void 0}function lr(e,t){if(!e)return;let n=Ln(e,{separators:/[;,\n]/});if(n.length===0)throw new p(`${t} env_clear must include at least one environment variable name`,f.USAGE);for(let r of n){if(!Yi.test(r))throw new p(`${t} env_clear key "${r}" is invalid`,f.USAGE);if(Mt.has(r.toUpperCase()))throw new p(`${t} env_clear key "${r}" is reserved for sandbox safety`,f.USAGE)}return n}function Xi(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new p(`${t} ${n} must be one of true|false|1|0|yes|no`,f.USAGE)}function Ji(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Dt.includes(n))return n;throw new p(`${t} pm_context_mode must be one of: ${Dt.join(", ")}`,f.USAGE)}function Pt(e,t){if(!e)return;let n=e.trim().toLowerCase();if(xg.includes(n))return n;throw new p(`${t} workspace_context_mode must be one of: ${xg.join(", ")}`,f.USAGE)}function Ft(e){if(!e)return;let t=Ln(e,{separators:/[;\n]/});return t.length>0?t:void 0}function _n(e,t,n){let r=Ft(e);if(!(!r||r.length===0)){for(let i of r)try{new RegExp(i,"m")}catch(s){throw new p(`${t} ${n} includes invalid regex "${i}": ${s instanceof Error?s.message:String(s)}`,f.USAGE)}return r}}function Qi(e,t){if(!e)return;let n=me(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new p(`${t} assert_stdout_min_lines must be an integer >= 0`,f.USAGE);return n}function Zi(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} assert_json_field_equals must include at least one path=value assignment`,f.USAGE);let r=Object.create(null);for(let i of n){let s=i.indexOf("=");if(s<=0)throw new p(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,f.USAGE);let a=i.slice(0,s).trim(),o=i.slice(s+1).trim();if(a.length===0||o.length===0)throw new p(`${t} assert_json_field_equals entries must include non-empty path and value`,f.USAGE);r[a]=o}return Object.keys(r).length>0?r:void 0}function es(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} assert_json_field_gte must include at least one path=value assignment`,f.USAGE);let r=Object.create(null);for(let i of n){let s=i.indexOf("=");if(s<=0)throw new p(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,f.USAGE);let a=i.slice(0,s).trim(),o=i.slice(s+1).trim();if(a.length===0||o.length===0)throw new p(`${t} assert_json_field_gte entries must include non-empty path and value`,f.USAGE);let c=Number(o);if(!Number.isFinite(c))throw new p(`${t} assert_json_field_gte value for "${a}" must be numeric`,f.USAGE);r[a]=c}return Object.keys(r).length>0?r:void 0}var Hx=new Set(Nt);function ts(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yx(e,t){let n={},r=[];for(let[i,s]of Object.entries(e)){let a=i.toLowerCase();if(!Hx.has(a)){r.push(i);continue}if(Object.hasOwn(n,a))throw t(`provides key "${i}" more than once after case normalization`);n[a]=s}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${Nt.join(", ")}.`);return n}function Lt(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function Vi(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let i=typeof r=="string"?[r]:r;if(!Array.isArray(i)||i.some(a=>typeof a!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=i.filter(a=>a.length>0);return s.length>0?s:void 0}function Ag(e,t,n){let r=Vi(e,t,n);if(r){for(let i of r)try{new RegExp(i,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${i}": ${s instanceof Error?s.message:String(s)}`)}return r}}function Hi(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function Xx(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let i=n===void 0?void 0:Hi(n,"timeout_seconds",t),s=r===void 0?void 0:Hi(r,"timeout",t);if(i!==void 0&&s!==void 0&&i!==s)throw t("timeout and timeout_seconds must match when both are provided");let a=i??s;if(!Number.isInteger(a)||a<=0)throw t("timeout_seconds must be a positive integer");return a}function Jx(e,t){let n=Lt(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 Qx(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!ts(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[i,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${i}" must be a string`);if(!Yi.test(i))throw t(`field "env_set" key "${i}" is invalid`);if(Mt.has(i.toUpperCase()))throw t(`field "env_set" key "${i}" is reserved for sandbox safety`);r[i]=s}return Object.keys(r).length>0?r:void 0}function Zx(e,t){let n=Vi(e,"env_clear",t);if(n){for(let r of n){if(!Yi.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(Mt.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function eA(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function tA(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=Hi(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function nA(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!ts(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[i,s]of Object.entries(n)){if(i.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 "${i}" must be a string, number, or boolean`);r[i]=String(s)}return Object.keys(r).length>0?r:void 0}function rA(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!ts(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[i,s]of Object.entries(n)){if(i.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[i]=Hi(s,`assert_json_field_gte.${i}`,t)}return Object.keys(r).length>0?r:void 0}function iA(e,t,n){let r=m=>new p(`${n} ${t} ${m}`,f.USAGE);if(!ts(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Nt.join(", ")}.`);let i=Yx(e,r),s=Lt(i,"command",r),a=Lt(i,"cmd",r);if(s!==void 0&&a!==void 0&&s!==a)throw r("command and cmd must match when both are provided");let o=s??a;if(o===void 0||o.trim().length===0)throw r('requires a non-empty "command" string');let c=Lt(i,"path",r),d=Lt(i,"pm_context_mode",r);if(d!==void 0&&!Dt.includes(d))throw r(`field "pm_context_mode" must be one of: ${Dt.join(", ")}`);let l=Pt(Lt(i,"workspace_context_mode",r),`${n} ${t}`),u=Lt(i,"note",r);return{command:o,path:c!==void 0&&c.length>0?c:void 0,scope:Jx(i,r),timeout_seconds:Xx(i,r),pm_context_mode:d,workspace_context_mode:l,env_set:Qx(i,r),env_clear:Zx(i,r),shared_host_safe:eA(i,"shared_host_safe",r),assert_stdout_contains:Vi(i,"assert_stdout_contains",r),assert_stdout_regex:Ag(i,"assert_stdout_regex",r),assert_stderr_contains:Vi(i,"assert_stderr_contains",r),assert_stderr_regex:Ag(i,"assert_stderr_regex",r),assert_stdout_min_lines:tA(i,r),assert_json_field_equals:nA(i,r),assert_json_field_gte:rA(i,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function Cg(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`,f.USAGE);let r;try{r=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}'.`,f.USAGE)}let i=Array.isArray(r)?r:[r];if(i.length===0)throw new p(`${t} array must include at least one linked-test entry object`,f.USAGE);return i.map((s,a)=>iA(s,i.length>1?`entry ${a+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]="002f45a2-edc3-5aa0-9af8-d9b1dfecc097")}catch{}})();var sA={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 aA(e){return sA[e]}function Ko(e){return aA(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]="39a36d42-29b1-5f0f-a8b2-f3bfc0ef78c2")}catch{}})();var oA="hierarchy-integrity";async function ns(e){let t=e.required?await Vt(e.pmRoot,oA,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]="dcbb6070-7457-5454-abf1-fa8153c8efd6")}catch{}})();function rs(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function is(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function ss(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(pd.includes(t))return t;let n=me(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",f.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",f.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]="afc4f3d5-ba5e-5dd7-abc9-531b319cdb4e")}catch{}})();var cA=new Set(["none","null"]);function os(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 Ge(e){return e===void 0?!1:cA.has(e.trim().toLowerCase())}function cs(e,t,n){if(!Ge(e))return;let r=n?` ${n}`:"";throw new p(`${t} no longer accepts "none" or "null".${r}`.trim(),f.USAGE)}function Ae(e,t,n){if(!e||e.length===0||!e.some(s=>Ge(s)))return;let i=n?` ${n}`:"";throw new p(`${t} no longer accepts "none" or "null".${i}`.trim(),f.USAGE)}function ds(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(o=>typeof o=="string"))throw new p(`${n.valueFlag} entries must be strings.`,f.USAGE);let i=r;if(!i.some(o=>Ge(o)))continue;if(i.filter(o=>!Ge(o)).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.`,f.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]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var dA=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Ig(e,t,n,r){if(dA.has(t.trim().toLowerCase())||n!==r.open_status)return;let i=jr("in_progress",r);if(!(i===void 0||i===r.open_status))return{command:`pm start-task ${e}`,to_status: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]="0062e981-158a-5e6a-b028-6c7cef0f59ba")}catch{}})();var zo=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Wo=[{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"}],Rg=[...zo,...Wo],ls=[{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 us(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let i=r.trim().toLowerCase();if(!i)throw new p("--unset values must not be empty",f.USAGE);if(Ge(i))throw new p('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',f.USAGE);let s=e.resolveDefinition(i);if(!s)throw new p(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,f.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function ms(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let i=n.command_to_fields?.get(t)??[];for(let s of i){if(s.allow_unset===!1)continue;let a=new Set;if(typeof s.key=="string"&&s.key.length>0&&a.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&a.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(a.add(s.cli_flag.replaceAll("-","_").toLowerCase()),a.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let o of s.cli_aliases)typeof o!="string"||o.length===0||(a.add(o.replaceAll("-","_").toLowerCase()),a.add(o.toLowerCase()));if(a.has(r))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]="2fcfbe50-039b-5031-8b18-a208908a0d87")}catch{}})();function Ng(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`,f.USAGE)}function Bo(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Ce(e,t,n){if(!t.includes(e))throw new p(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,f.USAGE);return e}var Lg=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function lA(e,t){return t==="defined"?e!==void 0:!!e}function Og(e,t,n){if(!lA(e,n))return;let r=me(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new p(`--event ${t} must be an integer >= 1`,f.USAGE);return r}function uA(e,t,n){let r=e?ue(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new p("--event recur_until must be at or after start",f.USAGE);return r}function mA(e){return Array.from(new Set(Bo(e).map(t=>Ce(t.toLowerCase(),vd,"event weekday")))).sort((t,n)=>Qs(t)-Qs(n))}function fA(e){return Array.from(new Set(Bo(e).map(t=>{let n=me(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",f.USAGE);return n}))).sort((t,n)=>t-n)}function pA(e,t){return Array.from(new Set(Bo(e).map(n=>ue(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Dg(e,t,n,r){let i=e.recur_freq?.trim(),s=e.recur_interval?.trim(),a=e.recur_count?.trim(),o=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![i,s,a,o,c,d,l].some(E=>E!==void 0))return;if(!i)throw new p("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",f.USAGE);let m=Ce(i.toLowerCase(),wd,"event recurrence frequency"),_=Og(s,"recur_interval",r),g=Og(a,"recur_count",r),h=uA(o,t,n),y=mA(c),w=fA(d),b=pA(l,n);return{freq:m,interval:_,count:g,until:h,by_weekday:y.length>0?y:void 0,by_month_day:w.length>0?w:void 0,exdates:b.length>0?b: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]="d6f359cb-2bc9-5f96-8789-db91512d0bd5")}catch{}})();function ur(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>.`,f.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 mr(e,t,n=be()){for(let r of t??[])try{Ld(e,r.id,r.kind,n)}catch(i){throw new p(dd(i),f.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Mg(e,t){return(await we(e,{schema:t})).document.metadata.created_at}async function _A(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await Z(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Mg(n,t.schema)}function gA(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}`,f.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 hA(e){let t=e.dependencies.filter(i=>e.registry.resolve(i.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(i.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:i,located:s})=>s===null?[]:[[i,s]])),r=new Map(await Promise.all([...new Set(t.map(({id:i})=>i))].map(async i=>[i,await Mg(n.get(i),e.context.schema)])));for(let i of e.holders){let s=await _A(i,e.context);if(s!==void 0)for(let a of t){let o=r.get(a.id),c=Date.parse(s),d=Date.parse(o);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw gA({holder:i,dependency:a,sourceCreatedAt:s,targetCreatedAt:o,registry:e.registry})}}}async function fs(e){let t=e.registry??be(),n=(e.dependencies??[]).filter(a=>!Cm(a.source_kind)),r=[...new Set(n.map(a=>a.id))],i=await Promise.all(r.map(async a=>({target:a,located:await Z(e.pmRoot,a,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=i.filter(({located:a})=>a===null).map(({target:a})=>a).sort((a,o)=>a<o?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new p(`Dependency target${s.length===1?"":"s"} not found: ${s.join(", ")}`,f.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 hA({dependencies:n,missingTargets:s,resolutions:i,holders:e.holders??[],registry:t,context:e}),s.map(a=>`dependency_target_unresolved:${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]="8248687e-ba97-5e1b-afbf-a322a72eb1aa")}catch{}})();var Pg="--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.",yA="--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).",wA=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,vA=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,$g=1e3,Vo=60*$g,bA=60*Vo;function Fg(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.`,f.USAGE);return n.toISOString()}function kA(e,t){let n=new Date(e),r=t.trim(),i=wA.exec(r);if(i){let o=i[1]==="-"?-1:1,c=Number.parseInt(i[2],10)*o;return Fg(n.getTime()+c*Vo,r)}let s=vA.exec(r);if(s){let[,o,c,d,l]=s;if(c||d||l){let m=o==="-"?-1:1,_=Number.parseInt(c??"0",10),g=Number.parseInt(d??"0",10),h=Number.parseInt(l??"0",10),y=_*bA+g*Vo+h*$g;return Fg(n.getTime()+m*y,r)}}let a=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return ue(a,n,"event.duration")}function Ug(e,t,n,r){if(t&&n)throw new p(yA,f.USAGE);if(n){let s=kA(e,n);if(s<e)throw new p(Pg,f.USAGE);return s===e?void 0:s}if(!t)return;let i=ue(t,r,"event.end");if(i<e)throw new p(Pg,f.USAGE);if(i!==e)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]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var EA=["at","date","text","title"],SA=["start","date","end","duration","title","description","location","timezone","all_day",...Lg],TA=["key","value"];function jg(e,t){return t==="trimmed"?e?.trim():e}function xA(e,t){return t==="defined"?e!==void 0:!!e}function ps(e,t,n){return e.map(r=>{let i=Q(r,"--reminder");_e(i,"--reminder",EA);let s=jg(i.at??i.date,n.valueMode),a=jg(i.text??i.title,n.valueMode);if(!s||!a)throw new p("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",f.USAGE);let o=a.trim();if(!o)throw new p("--reminder text must not be empty",f.USAGE);return{at:ue(s,t,"reminder.at"),text:o}})}function _s(e,t,n){return e.map(r=>{let i=Q(r,"--event");_e(i,"--event",SA);let s=(i.start??i.date)?.trim();if(!s)throw new p("--event requires start=<iso|relative> or date=<iso|relative>",f.USAGE);let a=ue(s,t,"event.start"),o=i.end?.trim(),c=i.duration?.trim(),d=Ug(a,o,c,t),l=i.title,u=i.description,m=i.location,_=i.timezone,g=l?.trim(),h=u?.trim(),y=m?.trim(),w=_?.trim(),b=[["title",l,g],["description",u,h],["location",m,y],["timezone",_,w]];for(let[k,S,A]of b)if(S!==void 0&&!A)throw new p(`--event ${k} must not be empty`,f.USAGE);let E=i.all_day?.trim(),v=Dg(i,a,t,n.recurrenceEmptyNumericGuard),T=xA(E,n.allDayEmptyGuard)?Ng(E,"--event all_day"):void 0;return{start_at:a,end_at:d,title:g,description:h,location:y,all_day:T,timezone:w,recurrence:v}})}function gs(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new p("--type-option values must not be empty",f.USAGE);let i,s;if(r.includes(",")||r.includes(`
17
+ `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let o=Q(r,"--type-option");_e(o,"--type-option",TA),i=o.key?.trim(),s=o.value?.trim()}else{let o=r.indexOf("="),c=r.indexOf(":"),d=o;if(o<=0&&c>0&&(d=c),d<=0||d===r.length-1)throw new p("--type-option requires key=value or key=<name>,value=<value> entries",f.USAGE);i=r.slice(0,d).trim(),s=r.slice(d+1).trim()}if(!i||!s)throw new p("--type-option requires key and value",f.USAGE);t[i]=s}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[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]="f8c8e154-737b-58db-9a8b-7f4399342e83")}catch{}})();var AA=["strict","progressive"],CA=["lightweight"],zg=new Set(["Reminder","Meeting","Event"]),IA=new Set(["author","created_at","text"]),Yo=[...Rg,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...ls],RA=(()=>{let e=new Map;for(let t of Yo)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),hs=new Map(Yo.map(e=>[e.optionKey,e.canonical])),OA=Yo.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function NA(e,t){let n=ae(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,f.USAGE)}return n}function LA(e,t){let n=e.default_status;if(n!==void 0){let r=ae(n,t);if(r)return r}return t.open_status}function Ho(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}"`,f.USAGE);return new Date(n).toISOString()}var DA=os();function Wg(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let s=t.unset?[...t.unset]:[];s.includes(i)||s.push(i),t.unset=s};Ge(t.template)&&(t.template=void 0);let r=new Set([...hs.keys(),"rank"]);for(let i of r){let s=t[i];if(typeof s!="string"||!Ge(s))continue;let a=i==="rank"?"order":hs.get(i)??i;n(a),t[i]=void 0}return ds(t,DA)}function ge(e){if(e!==void 0)return e}function MA(e,t){return us({raw:e,supportedFields:OA,resolveDefinition:n=>RA.get(n)??ms(n,"create",t)})}var Gg=["id","kind","type","author","created_at","source_kind"],ys=["path","scope","note"];function PA(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let a=s.trim(),o=Xo(a,Gg);ur(a,o);let c=o?Q(s,"--dep"):{id:a,kind:"related"};o&&_e(c,"--dep",Gg);let d=ge(c.id),l=FA(ge(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",f.USAGE);if(d.trim().toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,f.USAGE);let u=Dn(ge(c.source_kind)),m=ge(c.author);return{id:Mn(d,n,u),kind:Ce(l,Tn,"dependency kind"),created_at:Ho(c.created_at,t),author:m??r,source_kind:u??"cli:create:dep",author_source:m?"asserted":"detected"}}),explicitEmpty:!1})}function FA(e){return typeof e=="string"?At(e)??e.trim():e}function Xo(e,t){if(e.startsWith("```")||e.includes(`
18
+ `))return!0;let n=t.map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${n})\\s*[:=]`,"i").test(e)?!0:Xt(e)}function Ut(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Ae(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(a=>{let o=a.trim(),c=()=>{if(o.length===0)throw new p(`${e} requires text=<value>`,f.USAGE);return{created_at:n,author:r,text:o}},d;try{d=Q(a,e)}catch(m){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw m}if(Object.keys(d).filter(m=>!IA.has(m)).length>0)return{created_at:Ho(d.created_at,n),author:ge(d.author)??r,text:o};let u=d.text??"";if(u==="")throw new p(`${e} requires text=<value>`,f.USAGE);return{created_at:Ho(d.created_at,n),author:ge(d.author)??r,text:u}}),explicitEmpty:!1})}function Jo(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),i=Xo(r,ys),s=i?Q(n,"--file"):{path:r};if(i&&_e(s,"--file",ys),!s.path)throw new p("--file requires path=<value> or a bare file path",f.USAGE);return{path:s.path,scope:Ce(s.scope??"project",De,"file scope"),note:ge(s.note)}}),explicitEmpty:!1})}function Qo(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),i=Wi(r)?Bi(Q(n,"--test"),"--test"):{command:r},s=ge(i.command),a=ge(i.path);if(!s)throw new p("--test requires command=<value> or a bare command (path=<value> is optional metadata)",f.USAGE);let o=ge(i.timeout_seconds),c=ge(i.timeout);if(o&&c&&o!==c)throw new p("--test timeout and timeout_seconds must match when both are provided",f.USAGE);let d=o??c;return{command:s,path:a,scope:Ce(i.scope??"project",De,"test scope"),timeout_seconds:d?me(d,"timeout_seconds"):void 0,pm_context_mode:Ji(i.pm_context_mode,"--test"),workspace_context_mode:Pt(i.workspace_context_mode,"--test"),env_set:dr(i.env_set,"--test"),env_clear:lr(i.env_clear,"--test"),shared_host_safe:Xi(i.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Ft(i.assert_stdout_contains),assert_stdout_regex:_n(i.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Ft(i.assert_stderr_contains),assert_stderr_regex:_n(i.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Qi(i.assert_stdout_min_lines,"--test"),assert_json_field_equals:Zi(i.assert_json_field_equals,"--test"),assert_json_field_gte:es(i.assert_json_field_gte,"--test"),note:ge(i.note)}}),explicitEmpty:!1})}function Zo(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),i=Xo(r,ys),s=i?Q(n,"--doc"):{path:r};if(i&&_e(s,"--doc",ys),!s.path)throw new p("--doc requires path=<value> or a bare doc path",f.USAGE);return{path:s.path,scope:Ce(s.scope??"project",De,"doc scope"),note:ge(s.note)}}),explicitEmpty:!1})}function $A(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--reminder","Use --clear-reminders to clear reminders."),{values:ps(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function UA(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--event","Use --clear-events to clear linked events."),{values:_s(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function jA(e,t,n,r=[]){let i=[...id.filter(s=>e[s]!==void 0),...r.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(i))}function GA(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function qg(e,t,n){let r=xn("create",e);if(!r)throw new p(`Unsupported ${n} entry "${e}" for type "${t}"`,f.CONFLICT);return r}function qA(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 Bg(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 KA(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(qg(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(qg(r,e.name,"required_create_repeatables"));return n}function zA(e,t,n,r){for(let i of e)if(!(!Bg(t,i)&&!n.has(i)))throw new p(`Option ${Ee("create",i)} is disabled for type "${r}" by command_option_policies`,f.USAGE)}function WA(e,t,n){if(t!=="strict")return;let r=e.filter(s=>n.has(s)&&!Ko(s));if(r.length===0)return;let i=[...new Set(r.map(s=>Ee("create",s)))].sort((s,a)=>s.localeCompare(a));throw new p(`Strict create mode requires concrete values for ${i.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,f.USAGE)}function BA(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:gs(e),explicitEmpty:!1})}async function VA(e){let t=Ve();return{...e,body:await t.resolveValue(e.body,"--body"),dep:await t.resolveList(e.dep,"--dep"),comment:await t.resolveList(e.comment,"--comment"),note:await t.resolveList(e.note,"--note"),learning:await t.resolveList(e.learning,"--learning"),file:await t.resolveList(e.file,"--file"),test:await t.resolveList(e.test,"--test"),doc:await t.resolveList(e.doc,"--doc"),reminder:await t.resolveList(e.reminder,"--reminder"),event:await t.resolveList(e.event,"--event"),typeOption:await t.resolveList(e.typeOption,"--type-option"),field:await t.resolveList(e.field,"--field")}}function HA(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: ${AA.join(", ")}`,f.USAGE)}function YA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new p("--schedule-preset must not be empty",f.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new p(`Invalid --schedule-preset value "${e}". Allowed: ${CA.join(", ")}`,f.USAGE)}function XA(e,t,n){let r=HA(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new p("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",f.USAGE);return"progressive"}function JA(e,t,n,r){let i=e.name,s=qA(t),a=KA(e,n),o=Kt(e,"create",a);if(o.errors.length>0)throw new p(o.errors.join("; "),f.CONFLICT);zA(o.disabled,s,r,i),WA(o.required,n,r);let c=l=>l==="status"&&e.default_status!==void 0||r.has(l)&&Ko(l)?!0:Bg(s,l),d=o.required.filter(l=>!c(l));return[...new Set(d.map(l=>Ee("create",l)))].sort((l,u)=>l.localeCompare(u))}var Vg=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function QA(e,t){let n=[];for(let r of e){let i=r.match(Vg);i&&i[2]===t&&n.push(i[1])}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function ZA(e,t){return e.filter(n=>{let r=n.match(Vg);return!r||r[2]!==t})}function eC(e,t,n,r){let i=ZA(e,t);if(i.length===0)return;let s=Hg(n,[],[],r.open_status);throw new p(i.join("; "),f.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 tC(e,t){let r=e.options.find(i=>i.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function nC(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 Hg(e,t,n,r){let i=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],a=[...new Set([...s,...t])],o=new Set(["--title","--description","--type"]);for(let c of a)o.has(c)||(i.push(...nC(c,e.name,r)),o.add(c));for(let c of n){let d=tC(e,c);i.push("--type-option",`${c}=${d}`)}return i.join(" ")}function ec(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.",f.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.',f.USAGE):new p(`Missing required option ${t}`,f.USAGE);return n}function rC(e){return ei(e)}function iC(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=Array.isArray(i)?[...i]:i;for(let[r,i]of Object.entries(t))i!==void 0&&(n[r]=Array.isArray(i)?[...i]:i);return n}function sC(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function aC(){let e=P();return e?e.commands.some(t=>t.action==="templates-show"||sC(t.command)==="templates show"):!1}function oC(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.`,f.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}".`,f.GENERIC_FAILURE);let r={};for(let[i,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[i]=s;continue}if(Array.isArray(s)&&s.every(a=>typeof a=="string")){r[i]=[...s];continue}throw new p(`Templates package returned unsupported option value for "${i}" in template "${t}".`,f.GENERIC_FAILURE)}return r}async function cC(e,t,n){if(!aC())throw new p("--template requires the templates package. Install it first (for example: pm install templates --project).",f.USAGE);let r=await jd({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let i=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new p(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${i}`,f.USAGE)}return oC(r.result,e)}function dC(e){return F(e)}function B(e,t,n){return e.has(t)||n===void 0?void 0:ge(n)}function $t(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var lC=new Set(["milestone","meeting","reminder","event"]);function Yg(e,t,n,r){let i=t!==void 0,s=n!==void 0&&n.length>0,a=r!==void 0&&r.length>0;return lC.has(e.toLowerCase())&&!i&&!s&&!a}function uC(e,t,n,r,i){let s=[];return e.toLowerCase()==="event"&&(i===void 0||i.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),Yg(e,n,r,i)&&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 mC(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let i=await Hd(r);return i===void 0?{parent:e,parentSource:void 0}:{parent:i,parentSource:"focus"}}async function fC(e,t,n,r,i,s){let a=Vr(i);if(Yr(r,a,t.id_prefix),await Z(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let c=_t(a,t.id_prefix);return{parent:a,warnings:Hr(c,s).warnings}}async function pC(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await fC(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function _C(e){if(e.explicitId===void 0)return hl(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",f.USAGE);let t=e.explicitId.trim();if(t.length===0||yl(t))throw new p("--id must not be empty or use a placeholder token",f.USAGE);let n=_t(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",f.USAGE);return n}function Kg(e,t,n,r,i){let s=B(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let a=ti(r,s,i);return{value:a.value,warnings:a.warnings}}async function gC(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:i,blockedBy:s,status:a,statusExplicit:o,nowValue:c,author:d}=e,l=e.dependencyValues;if(s===void 0)return{dependencyValues:l,status:a};let u=_t(s,n.id_prefix),m=await Z(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!m)return{dependencyValues:l,status:a};if((l??[]).some(h=>h.id===m.id&&h.kind==="blocked_by")||(l=[...l??[],{id:m.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),o)return{dependencyValues:l,status:a};let g=i.blocked_statuses.has("blocked")?"blocked":[...i.blocked_statuses].sort((h,y)=>h.localeCompare(y))[0]??i.open_status;return{dependencyValues:l,status:g}}function hC(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let i=t.governance.create_default_type?.trim();if(i&&i.length>0&&tt(i,n)){e.type=i;return}tt("Task",n)&&(e.type="Task")}function yC(e,t){return e.options.filter(n=>xn("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new p(`Template custom type option "${n.key}" must be a string, number, or boolean value`,f.USAGE)})}async function wC(e,t,n,r,i){let s=e,a=[];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.",f.USAGE);let h=await cC(g,t,n);s=Wg(iC(h,s))}if(s.type===void 0&&hC(s,r,i),s.type===void 0)throw new p("Missing required option --type <value>",f.USAGE);let o=tt(s.type,i);if(!o){let g=bl(s.type),h=g?tt(g,i):void 0;if(h)a.push(`type_coercion:${s.type.trim()}:${h}`),s.type=h,o=h;else throw new p(ni(s.type,i.types,Ur(n,r.schema)),f.USAGE)}let c=Lr(o,i);if(!c)throw new p(`Invalid type value "${s.type}"`,f.USAGE);let d=c.name,l=yC(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 m=YA(s.schedulePreset);if(m!==void 0&&!zg.has(d))throw new p(`--schedule-preset ${m} is only supported for Reminder, Meeting, or Event types`,f.USAGE);let _=XA(s.createMode,m,r.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:d,schedulePreset:m,createMode:_,warnings:a}}function vC(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),i=[{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 i)if(s.enabled){if(s.values&&s.values.length>0)throw new p(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,f.USAGE);n.add(s.metadataKey),r.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function bC(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[r,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let s=hs.get(r)??r;throw new p(`Cannot combine --unset ${s} with ${Ee("create",r)}`,f.USAGE)}}function kC(e){let t=(n,r)=>{let i=hs.get(r),s=i?`Use --unset ${i} to clear this field.`:void 0;cs(n,Ee("create",r),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 EC(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,f.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,f.USAGE)}function SC(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:i,openStatus:s,type:a,createMode:o,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(_=>{let g=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${g}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),l=[Hg(n,r,i,s),...d.map(_=>_.example)].join(" "),u=[`Run "pm create --help --type ${a}" for type-aware required option guidance.`];t.includes("--title")&&u.push('Title can also be passed as the first positional argument (example: pm create "Your title" --type '+a+")."),o==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),zg.has(a)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(_=>_.description).join("; ")}.`);let m=t.length===1?`Missing required option ${t[0]} for type "${a}"`:`Missing required options ${t.join(", ")} for type "${a}"`;throw new p(m,f.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${a}" in one invocation.`,examples:[l],nextSteps:u,recovery:o==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:["--create-mode progressive",...t]}:void 0})}function TC(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",f.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Xr(t.tags):[];return Qr(n,t.addTags)}function xC(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",f.USAGE);let n=t.order??t.rank,r=$t(e,"order",n,i=>me(i,"order"));if(r!==void 0&&!Number.isInteger(r))throw new p("Order must be an integer",f.USAGE);return r}function AC(e,t,n,r,i,s){if(r.completedAt!==void 0&&e!==t.close_status)throw new p("--completed-at requires a terminal create status.",f.USAGE);let a=e!==t.close_status?void 0:r.completedAt===void 0?s:ue(r.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:a,warnings:[]};let o=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:i}:{explicit:r.closeReason};return{closeReason:jo(o,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:a,warnings:[]}}async function CC(e){let{pmRoot:t,type:n,id:r,settings:i,typeRegistry:s,author:a,extensionFieldNames:o,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:m,similarityCandidate:_,allowDuplicate:g}=e,h=bd(t,n,r,i.item_format,s.type_to_folder),y=ft(t,r),w=be(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(k=>w.resolve(k.kind)?.hierarchy),E=await ns({pmRoot:t,author:a,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:b}),v=b,T=[];try{let k=await Vt(t,r,i.locks.ttl_seconds,a,!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let S=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await ve(t,i.item_format,s.type_to_folder,void 0,i.schema):void 0;if(await Z(t,r,i.id_prefix,i.item_format,s.type_to_folder))throw new p(`Item "${r}" already exists`,f.CONFLICT);if(S){let j=X(i.schema);ai(S,[...S,c.metadata],r,C=>oe(C,j),w)}await Fd({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:Ll({pmRoot:t,settings:i,typeToFolder:s.type_to_folder})});let L=await Ol(t,a,{required:i.governance.duplicate_detection_mode==="strict"&&g!==!0}),H=[];try{i.governance.duplicate_detection_mode==="strict"&&g!==!0&&await qo(_,{pmRoot:t,mode:"strict",threshold:i.governance.duplicate_detection_threshold,limit:i.governance.duplicate_detection_limit,allowDuplicate:!1}),await le(h,Bd(c,{format:i.item_format,schema:i.schema,extensionFieldNames:o}));try{let j=fl({nowIso:m,author:a,op:"create",before:d,after:c,message:l});await pl(y,j)}catch(j){throw await nd(h),j}v&&(await E(),v=!1),H=await Nl({pmRoot:t,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:h,document:c})}finally{await L()}T=[...S?zi(S,[...S,c.metadata],r):[],...H,...await it({path:h,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await it({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],Md({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Pd(c.metadata,u),changed_fields:u})}finally{await k()}}finally{v&&await E()}return T}async function tc(e,t){let n=Wg(await VA(e)),r=I(process.cwd(),t.path);await dC(r);let i=await R(r),s=X(i.schema),a=zt(i.schema),o=U(i,P()),c=await wC(n,t,r,i,o);n=c.resolvedOptions;let{typeDefinition:d,type:l,createMode:u}=c,m=MA(n.unset,a),{explicitUnsets:_,clearOptionKeys:g}=vC(n,m);bC(n,m),kC(n);let h=JA(d,n,u,g),y=x(),w=K(ge(n.author),i.author_default),b=PA(n.dep,y,i.id_prefix,w),E=Ut("--comment",n.comment,y,w),v=Ut("--note",n.note,y,w),T=Ut("--learning",n.learning,y,w),k=Jo(n.file),S=Qo(n.test);S.values=await mn(S.values,w,y);let A=Zo(n.doc),L=$A(n.reminder,y),H=UA(n.event,y),j=BA(n.typeOption),C=An(l,j.values,o),G=P(),de=pt(G),ie=Fr(n.field,G),pe=qd(n,a,l),qe=new Set(pe.missing_required_flags),St=a.definitions.filter(Y=>qe.has(`--${Y.cli_flag}`));EC(ie,pe,m);let ut=QA(C.errors,l),Ke=ut.map(Y=>`--type-option ${Y}=<value>`),Er=[...new Set([...h,...Ke,...pe.missing_required_flags])].sort((Y,Ys)=>Y.localeCompare(Ys));SC({combinedMissingFlags:Er,typeDefinition:d,missingRequiredCreateFlags:h,missingRequiredTypeOptionKeys:ut,openStatus:s.open_status,type:l,createMode:u,missingRequiredRuntimeFields:St}),eC(C.errors,l,d,s);let he=await _C({pmRoot:r,settings:i,typeRegistry:o,explicitId:n.id}),Ne=n.status!==void 0?NA(n.status,s):LA(d,s),Gs=n.priority!==void 0?rC(n.priority):2,D=m.metadataKeys,Le=TC(D,n),et=$t(D,"deadline",n.deadline,Y=>ue(Y,new Date(y),"deadline")),Sr=$t(D,"estimated_minutes",n.estimatedMinutes,Y=>Zr(Y,"estimated-minutes")),mt=B(D,"acceptance_criteria",n.acceptanceCriteria),qs=B(D,"definition_of_ready",n.definitionOfReady),ze=xC(D,n),Ks=B(D,"goal",n.goal),Tr=B(D,"objective",n.objective),Ow=B(D,"value",n.value),Nw=B(D,"impact",n.impact),Lw=B(D,"outcome",n.outcome),Dw=B(D,"why_now",n.whyNow),Mw=B(D,"assignee",n.assignee),Pw=D.has("author")?void 0:ge(n.author)??w,Fw=B(D,"parent",n.parent),zc=await mC(Fw,n,D,r),zs=zc.parent,$w=zc.parentSource,Uw=B(D,"reviewer",n.reviewer),jw=$t(D,"risk",n.risk,Y=>Ce(rs(Y),Or,"risk")),Gw=$t(D,"confidence",n.confidence,Y=>ss(Y)),qw=n.allowMissingParent===!0&&i.validation.parent_reference==="strict_error"?"warn":i.validation.parent_reference,Wc=i.validation.sprint_release_format,Tt=[...c.warnings,...uC(l,he,et,L.values,H.values)],Bc=await pC({itemId:he,parent:zs,pmRoot:r,settings:i,typeRegistry:o,policy:qw});zs=Bc.parent,Tt.push(...Bc.warnings);let Vc=Kg(D,"sprint",n.sprint,"sprint",Wc),Kw=Vc.value;Tt.push(...Vc.warnings);let Hc=Kg(D,"release",n.release,"release",Wc),zw=Hc.value;Tt.push(...Hc.warnings);let Yc=B(D,"blocked_by",n.blockedBy),Xc=await gC({pmRoot:r,settings:i,typeRegistry:o,statusRegistry:s,blockedBy:Yc,dependencyValues:b.values,status:Ne,statusExplicit:n.status!==void 0,nowValue:y,author:w}),Ws=Xc.dependencyValues;mr(he,Ws),Tt.push(...await fs({pmRoot:r,dependencies:Ws,idPrefix:i.id_prefix,itemFormat:i.item_format,typeToFolder:o.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:he,createdAt:y}],schema:i.schema})),Ne=Xc.status;let Ww=B(D,"blocked_reason",n.blockedReason),Bw=B(D,"unblock_note",n.unblockNote),Vw=B(D,"reporter",n.reporter),Hw=$t(D,"severity",n.severity,Y=>Ce(is(Y),Nr,"severity")),Yw=B(D,"environment",n.environment),Xw=B(D,"repro_steps",n.reproSteps),Jc=B(D,"resolution",n.resolution),Jw=B(D,"expected_result",n.expectedResult),Qw=B(D,"actual_result",n.actualResult),Zw=B(D,"affected_version",n.affectedVersion),ev=B(D,"fixed_version",n.fixedVersion),tv=B(D,"component",n.component),nv=$t(D,"regression",n.regression,Y=>as(Y)),rv=B(D,"customer_impact",n.customerImpact),Bs=ec(n.title,"--title"),Vs=n.description??"",xr=n.body??"",Qc=await qo({title:Bs,description:Vs,body:xr},{pmRoot:r,mode:i.governance.duplicate_detection_mode,threshold:i.governance.duplicate_detection_threshold,limit:i.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Tt.push(...vg(Qc));let Hs=AC(Ne,s,i,n,Jc,y),iv=Hs.closeReason,sv=Ne===s.close_status?y:void 0,av=Hs.completedAt;Tt.push(...Hs.warnings);let Ar=Wd({id:he,title:Bs,description:Vs,type:l,type_options:C.normalized,status:Ne,closed_at:sv,completed_at:av,close_reason:iv,priority:Gs,tags:Le,created_at:y,updated_at:y,deadline:et,assignee:Mw,author:Pw,estimated_minutes:Sr,acceptance_criteria:mt,definition_of_ready:qs,order:ze,goal:Ks,objective:Tr,value:Ow,impact:Nw,outcome:Lw,why_now:Dw,parent:zs,reviewer:Uw,risk:jw,confidence:Gw,sprint:Kw,release:zw,blocked_by:Yc,blocked_reason:Ww,unblock_note:Bw,reporter:Vw,severity:Hw,environment:Yw,repro_steps:Xw,resolution:Jc,expected_result:Jw,actual_result:Qw,affected_version:Zw,fixed_version:ev,component:tv,regression:nv,customer_impact:rv,dependencies:Ws,comments:E.values,notes:v.values,learnings:T.values,files:k.values,tests:S.values,docs:A.values,reminders:L.values,events:H.values,...ie,...pe.values});try{$r(Ar,G)}catch(Y){throw new p(Y instanceof Error?Y.message:"Invalid extension item field values",f.USAGE)}let ov=Vd({metadata:Ar,body:xr},{schema:i.schema,extensionFieldNames:de}),cv={metadata:{},body:""},Zc=[..._].sort((Y,Ys)=>Y.localeCompare(Ys)),dv=GA(n.message,Zc),ed=jA(Ar,xr,Zc,[...Object.keys(ie),...Object.keys(pe.values??{})]),lv=await CC({pmRoot:r,type:l,id:he,settings:i,typeRegistry:o,author:w,extensionFieldNames:de,afterDocument:ov,beforeDocument:cv,historyMessage:dv,changedFields:ed,nowValue:y,similarityCandidate:{title:Bs,description:Vs,body:xr},allowDuplicate:n.allowDuplicate}),td=structuredClone(Ar);u==="strict"&&_.has("dependencies")&&(td.dependencies=[]);let uv=Ig(he,l,Ne,s);return Yg(l,et,L.values,H.values)&&ul(`[pm] warning: ${l} '${he}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${he} --deadline <ISO>' or 'pm update ${he} --event "start=<ISO>,end=<ISO>"'.`),{item:td,changed_fields:ed,warnings:[...Tt,...lv],...Object.fromEntries([["parent_source",$w],["next_transition",uv],["similarity_advisory",Qc]].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]="c88f01be-6abe-5fa2-9792-3f54e61bb282")}catch{}})();var sc=[...zo,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Wo,...ls],IC=(()=>{let e=new Map;for(let t of sc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),ws=new Map(sc.map(e=>[e.optionKey,e.canonical])),RC=sc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),OC=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),NC=os({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function LC(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let s=t.unset?[...t.unset]:[];s.includes(i)||s.push(i),t.unset=s},r=new Set([...ws.keys(),"rank"]);for(let i of r){let s=t[i];if(typeof s!="string"||!Ge(s))continue;let a=i==="rank"?"order":ws.get(i)??i;n(a),t[i]=void 0}return ds(t,NC)}function rh(e,t,n=[]){return us({raw:e,supportedFields:RC,resolveDefinition:r=>{let i=n.find(a=>{let o=a.toLowerCase();return o===r||o.replaceAll("_","-")===r||o.replaceAll("-","_")===r});return IC.get(r)??ms(r,"update",t)??(i?{optionKey:"field",metadataKey:i}:void 0)}})}var Xg=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 Jg(e){let t=e.disallowedFlags.flatMap(r=>{let i=Xg.get(r);return i?[i(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let i=Xg.get(r);return i?[`Replace ${r} with: ${i(e.id)}`]:[]});return new p(e.message,f.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function DC(e,t,n){let r=t.ownershipMetadataBypass===!0,i=t.ownershipDependencyBypass===!0;if(!r&&!i)return;if(r&&i)throw new p("Choose only one package-provided ownership bypass mode.",f.USAGE);let s=(c,d,l)=>{c&&l.push(d)};if(i){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",f.USAGE);if(c.length>0)throw Jg({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 a=[];s(t.status!==void 0,"--status",a),s(t.closeReason!==void 0,"--close-reason",a),s(t.assignee!==void 0,"--assignee",a),s(t.parent!==void 0,"--parent",a),s(t.blockedBy!==void 0,"--blocked-by",a),s(t.blockedReason!==void 0,"--blocked-reason",a),s(t.unblockNote!==void 0,"--unblock-note",a),s(t.dep!==void 0,"--dep",a),s(t.depRemove!==void 0,"--dep-remove",a),s(t.replaceDeps===!0,"--replace-deps",a),s(t.replaceTests===!0,"--replace-tests",a),s(t.replaceFiles===!0,"--replace-files",a),s(t.replaceDocs===!0,"--replace-docs",a),s(t.note!==void 0,"--note",a),s(t.learning!==void 0,"--learning",a),s(t.test!==void 0,"--test",a),s(t.reminder!==void 0,"--reminder",a),s(t.event!==void 0,"--event",a),s(t.clearDeps===!0,"--clear-deps",a),s(t.clearComments===!0,"--clear-comments",a),s(t.clearNotes===!0,"--clear-notes",a),s(t.clearLearnings===!0,"--clear-learnings",a),s(t.clearFiles===!0,"--clear-files",a),s(t.clearTests===!0,"--clear-tests",a),s(t.clearDocs===!0,"--clear-docs",a),s(t.clearReminders===!0,"--clear-reminders",a),s(t.clearEvents===!0,"--clear-events",a);let o=[...n].filter(c=>OC.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(a.push(...o),a.length>0)throw Jg({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: ${a.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:a})}function MC(e,t){let n=ae(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,f.USAGE)}return n}function PC(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=El({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=ae(e.fromStatus,e.statusRegistry)??e.fromStatus,r=ae(e.toStatus,e.statusRegistry)??e.toStatus,i=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Sl(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new p(i,f.USAGE);return`workflow_transition_not_allowed: ${i}`}function FC(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:ih(e)}function ih(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new p(`Invalid dependency created_at timestamp "${e}"`,f.USAGE);return new Date(t).toISOString()}function gn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var $C=["id","kind","type","author","created_at","source_kind"],UC=["id","kind","type","author","created_at","source_kind"];function sh(e){return e.startsWith("```")||e.includes(`
19
+ `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Xt(e)}function ah(e){return typeof e=="string"?At(e)??e.trim():e}function jC(e,t,n,r){return e?(Ae(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let a=s.trim(),o=sh(a);ur(a,o);let c=o?Q(s,"--dep"):{id:a,kind:"related"};o&&_e(c,"--dep",$C);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",f.USAGE);if(d.toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,f.USAGE);let u=Dn(gn(c.source_kind)),m=gn(c.author);return{id:Mn(d,t,u),kind:Ce(l,Tn,"dependency kind"),created_at:FC(c.created_at,n),author:m??r,source_kind:u??"cli:update:dep",author_source:m?"asserted":"detected"}})}):{additions:[]}}function GC(e,t){return e?(Ae(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new p("--dep-remove requires id or key/value selectors",f.USAGE);let i=sh(r);if(ur(r,i,"--dep-remove"),i){let s=Q(r,"--dep-remove");_e(s,"--dep-remove",UC);let a=s.id?.trim();if(!a)throw new p("--dep-remove key/value form requires id=<value>",f.USAGE);if(a.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${a}"`,f.USAGE);let o=ah(gn(s.kind??s.type)),c=Dn(gn(s.source_kind)),d=gn(s.author),l=gn(s.created_at);return{id:Mn(a,t,c),kind:o?Ce(o,Tn,"dependency kind"):void 0,source_kind:c,author:d,created_at:l?ih(l):void 0}}if(r.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${r}"`,f.USAGE);return{id:_t(r,t)}})):[]}function vs(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function qC(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",i=Date.parse(r),s=Number.isFinite(i)?new Date(i).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function KC(e,t,n,r){let i=[...e??[]],s=!1;if(t===void 0){let a=i.filter(o=>o.kind!=="blocked_by");return a.length!==i.length&&(i=a,s=!0),s?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}return i.some(a=>a.kind==="blocked_by"&&a.id===t)||(i.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}async function zC(e,t,n,r,i,s){if(e===void 0||t)return{};let a=e.trim();if(a.length===0)return{};let o=await Z(n,_t(a,r),r,i,s);return o?{id:o.id}:{unresolved:a}}function WC(e,t,n,r,i){let s=KC(e.dependencies,t,n,r);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,i.includes("dependencies")||i.push("dependencies"))}function BC(e){return`${e.path}::${e.scope}`}function VC(e){return`${e.path}::${e.scope}`}function HC(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function oh(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 YC(e){return ei(e)}function Qg(e,t){let n=xn("update",e);if(!n)throw new p(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,f.CONFLICT);return n}function XC(e,t,n){let r=new Set,i=(s,a)=>{a&&r.add(s)};if(i("title",e.title!==void 0),i("description",e.description!==void 0),i("body",e.body!==void 0),i("status",e.status!==void 0),i("closeReason",e.closeReason!==void 0),i("priority",e.priority!==void 0),i("type",e.type!==void 0),i("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),i("deadline",e.deadline!==void 0),i("estimatedMinutes",e.estimatedMinutes!==void 0),i("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),i("definitionOfReady",e.definitionOfReady!==void 0),i("order",e.order!==void 0||e.rank!==void 0),i("goal",e.goal!==void 0),i("objective",e.objective!==void 0),i("value",e.value!==void 0),i("impact",e.impact!==void 0),i("outcome",e.outcome!==void 0),i("whyNow",e.whyNow!==void 0),i("author",e.author!==void 0),i("message",e.message!==void 0),i("assignee",e.assignee!==void 0),i("parent",e.parent!==void 0),i("reviewer",e.reviewer!==void 0),i("risk",e.risk!==void 0),i("confidence",e.confidence!==void 0),i("sprint",e.sprint!==void 0),i("release",e.release!==void 0),i("blockedBy",e.blockedBy!==void 0),i("blockedReason",e.blockedReason!==void 0),i("unblockNote",e.unblockNote!==void 0),i("reporter",e.reporter!==void 0),i("severity",e.severity!==void 0),i("environment",e.environment!==void 0),i("reproSteps",e.reproSteps!==void 0),i("resolution",e.resolution!==void 0),i("expectedResult",e.expectedResult!==void 0),i("actualResult",e.actualResult!==void 0),i("affectedVersion",e.affectedVersion!==void 0),i("fixedVersion",e.fixedVersion!==void 0),i("component",e.component!==void 0),i("regression",e.regression!==void 0),i("customerImpact",e.customerImpact!==void 0),i("dep",e.dep!==void 0),i("depRemove",e.depRemove!==void 0),i("dep",e.replaceDeps===!0),i("comment",e.comment!==void 0),i("note",e.note!==void 0),i("learning",e.learning!==void 0),i("file",e.file!==void 0),i("test",e.test!==void 0),i("test",e.replaceTests===!0),i("file",e.replaceFiles===!0),i("doc",e.replaceDocs===!0),i("doc",e.doc!==void 0),i("reminder",e.reminder!==void 0),i("event",e.event!==void 0),i("typeOption",e.typeOption!==void 0),i("field",e.field!==void 0),i("force",e.force===!0),i("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),i("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),i("dep",e.clearDeps===!0),i("comment",e.clearComments===!0),i("note",e.clearNotes===!0),i("learning",e.clearLearnings===!0),i("file",e.clearFiles===!0),i("test",e.clearTests===!0),i("doc",e.clearDocs===!0),i("reminder",e.clearReminders===!0),i("event",e.clearEvents===!0),i("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=rh(e.unset,t,n);for(let a of s.optionKeys)i(a,!0)}return r}function JC(e,t,n,r,i){let s=Lr(e,n);if(!s)throw new p(`Invalid type value "${e}"`,f.USAGE);let a=Kt(s,"update",[]);if(a.errors.length>0)throw new p(a.errors.join("; "),f.CONFLICT);let o=XC(t,r,i);for(let c of a.disabled)if(o.has(Qg(c,e)))throw new p(`Option ${Ee("update",c)} is disabled for type "${e}" by command_option_policies`,f.USAGE);for(let c of a.required)if(!o.has(Qg(c,e)))throw new p(`Missing required option ${Ee("update",c)} for type "${e}"`,f.USAGE)}var QC=new Set(["order","rank"]),ZC=Zs.filter(e=>!QC.has(e)),ch=["tags","closeReason",...ZC],eI=["title","description","body","status","closeReason","completedAt","priority","type",...Zs,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],tI=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>ue(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Zr(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"}],nI=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Ce(rs(e),Or,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>ss(e)}],rI=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Ce(is(e),Nr,"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 ic(e,t,n){for(let r of e){let i=t[r.optionKey],s=n.clearItemMetadataKeys.has(r.metadataKey);if(!(i===void 0&&!s)){if(s){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof i!="string")throw new p(`${Ee("update",String(r.optionKey))} must be a string value`,f.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(i,n):i.trim(),n.changedFields.push(r.metadataKey)}}}async function iI(e){let t=Ve();return LC({...e,body:await t.resolveValue(e.body,"--body"),dep:await t.resolveList(e.dep,"--dep"),depRemove:await t.resolveList(e.depRemove,"--dep-remove"),comment:await t.resolveList(e.comment,"--comment"),note:await t.resolveList(e.note,"--note"),learning:await t.resolveList(e.learning,"--learning"),file:await t.resolveList(e.file,"--file"),test:await t.resolveList(e.test,"--test"),doc:await t.resolveList(e.doc,"--doc"),reminder:await t.resolveList(e.reminder,"--reminder"),event:await t.resolveList(e.event,"--event"),typeOption:await t.resolveList(e.typeOption,"--type-option"),field:await t.resolveList(e.field,"--field")})}function sI(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 nc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new p(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,f.USAGE);if(e.enabled&&e.clearEnabled)throw new p(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,f.USAGE)}function aI(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.",f.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",f.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new p("--replace-deps cannot be combined with --dep-remove",f.USAGE);nc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),nc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),nc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function oI(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}`,f.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function cI(e){let t={};for(let n of ch)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function dI(e,t){let n=cI(e);for(let[r,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let s=ws.get(r)??r;throw new p(`Cannot combine --unset ${s} with ${Ee("update",r)}`,f.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",f.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --remove-ac",f.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",f.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new p("Cannot combine --unset tags with --remove-tags",f.USAGE)}}function lI(e){let t=(n,r)=>{let i=ws.get(r),s=i?`Use --unset ${i} to clear this field.`:void 0;cs(n,Ee("update",r),s)};for(let n of ch)t(e[n],String(n));t(e.order??e.rank,"order"),Ae(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Ae(e.event,"--event","Use --clear-events to clear linked events.")}function uI(e,t){let n={};for(let r of eI)n[String(r)]=e[r]!==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 mI(e){let t=await Z(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Nn(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await we(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function fI(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return ve(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function pI(e){e.before&&ai(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>oe(t,e.statusRegistry),be())}async function _I(e){await F(e)}function gI(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",f.USAGE)}async function hI(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Vr(e.options.parent);if(Yr(e.id,t,e.settings.id_prefix),await Z(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=_t(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:Hr(r,e.parentReferencePolicy).warnings}}function yI(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function wI(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await Z(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Nn(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await we(t,{schema:e.settings.schema}),r=e.options.type!==void 0?tt(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",i=PC({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return i?[i]:[]}async function vI(e){if(!e.fieldFlags.status||ae(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([o,c])=>c&&o!=="status"&&o!=="closeReason"&&o!=="completedAt").map(([o])=>o),r=[],i=[];if(n.length>0){let o=await BI(e.id,{...e.options,status:void 0,closeReason:void 0,message:void 0},e.global);i=o.changed_fields,r.push(...o.warnings)}let s=await dg(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),a=[...e.workflowTransitionWarnings,...r,...s.warnings,"auto_routed_from_update_to_close"];return{item:s.item,changed_fields:[...i,...s.changed_fields],warnings:a}}function bI(e,t,n,r){return t.title!==void 0&&(e.metadata.title=ec(t.title,"--title"),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),ae(e.metadata.status,n)??e.metadata.status}function kI(e,t,n,r,i){let s=MC(n,t.statusRegistry);if(e.metadata.status=s,i.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,i.push("closed_at","completed_at");return}!oe(s,t.statusRegistry)&&oe(r,t.statusRegistry)&&e.metadata.closed_at!==void 0&&(delete e.metadata.closed_at,i.push("closed_at"),e.metadata.completed_at!==void 0&&(delete e.metadata.completed_at,i.push("completed_at")))}function EI(e,t,n,r){if(t.options.status!==void 0&&kI(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!oe(e.metadata.status,t.statusRegistry))throw new p("--completed-at can only be set on a terminal item",f.USAGE);e.metadata.completed_at=ue(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function SI(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let i=t.options.closeReason?.trim()??"";if(i.length===0)throw new p("--close-reason must not be empty",f.USAGE);e.metadata.close_reason=i}r.push("close_reason");return}t.options.status!==void 0&&oe(n,t.statusRegistry)&&!oe(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function TI(e,t,n,r){EI(e,t,n,r),SI(e,t,n,r)}function xI(e,t,n){let r=tt(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=YC(t.options.priority),n.push("priority")),t.options.type!==void 0){let i=tt(t.options.type,t.typeRegistry);if(!i)throw new p(ni(t.options.type,t.typeRegistry.types,Ur(t.pmRoot,t.settings.schema)),f.USAGE);e.metadata.type=i,r=i,n.push("type")}return JC(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),AI(e,t,r,n),r}function AI(e,t,n,r){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=gs(t.options.typeOption??[]),a=An(n,s,t.typeRegistry);if(a.errors.length>0)throw new p(a.errors.join("; "),f.USAGE);e.metadata.type_options=a.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let i=An(n,e.metadata.type_options,t.typeRegistry);if(i.errors.length>0)throw new p(`Current type options are incompatible with type "${n}". ${i.errors.join("; ")}. Use --clear-type-options to clear them.`,f.USAGE);e.metadata.type_options=i.normalized}function CI(e,t){let n=new Set(t.map(i=>vs(i))),r=new Set;return e.filter(i=>{if(!n.has(vs(i)))return!0;let s=qC(i);return r.has(s)?!1:(r.add(s),!0)})}function II(e,t,n){let r=t.filter(i=>!e.some(s=>oh(s,i)));if(r.length!==0)throw new p(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,f.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(i=>({id:i.id,kind:i.kind,source_kind:i.source_kind,author:i.author,created_at:i.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 RI(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=CI(r,t.dependencyUpdates.additions);let i=new Set(r.map(s=>vs(s)));for(let s of t.dependencyUpdates.additions){let a=vs(s);i.has(a)||(r.push(s),i.add(a))}}t.dependencyRemovals.length>0&&(II(r,t.dependencyRemovals,e.metadata.id),r=r.filter(i=>!t.dependencyRemovals.some(s=>oh(i,s)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function OI(e,t,n){rc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),rc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),rc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function rc(e,t,n,r,i,s){n===void 0&&!i.has(t)||(i.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],s.push(t))}function NI(e,t,n){Zg(e,"files",t.options.file,t.fileUpdates.values,BC,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),LI(e,t,n),Zg(e,"docs",t.options.doc,t.docUpdates.values,VC,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Zg(e,t,n,r,i,s,a,o){if(!(n===void 0&&!a.has(t))){if(s)e.metadata[t]=r;else if(a.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>i(l)));for(let l of r){let u=i(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}o.push(t)}}function LI(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=eh(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=eh([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function eh(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let i=HC(r);n.has(i)||(t.push(r),n.add(i))}return t}function DI(e,t,n){let r=t.options.addTags,i=t.options.removeTags,s=Array.isArray(r)&&r.length>0||Array.isArray(i)&&i.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let a=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Xr(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=vl(Qr(a,r),i),n.changedFields.push("tags")}ic(tI,t.options,n),PI(e,t,n.changedFields)}function MI(e,t,n){let r=t.options.addAc,i=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(i)&&i.length>0))return;let s=wl(Jr(e.metadata.acceptance_criteria),r,i);if(s.unmatchedRemovals.length>0)throw new p(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,f.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 a=s.criteria.join("; ");e.metadata.acceptance_criteria!==a&&(a===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=a,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function PI(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let i=me(r??"","order");if(!Number.isInteger(i))throw new p("Order must be an integer",f.USAGE);e.metadata.order=i}n.push("order")}}function FI(e,t,n,r){$I(e,t,n.changedFields),UI(e,t,n.changedFields),ic(nI,t.options,n),th(e,t,"sprint",r,n.changedFields),th(e,t,"release",r,n.changedFields),jI(e,t,n.changedFields),ic(rI,t.options,n)}function $I(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new p("--assignee must not be empty. Use --unset assignee to clear it.",f.USAGE);e.metadata.assignee=r}n.push("assignee")}}function UI(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 th(e,t,n,r,i){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=ti(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,r.push(...s.warnings)}i.push(n)}}function jI(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)&&WC(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function GI(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=ps(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=_s(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function qI(e,t,n){nh(e,t.runtimeFieldRegistry.definitions.map(i=>i.metadata_key),t.clearItemMetadataKeys,n),nh(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[i,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(i)){let a=i.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(d=>d.metadata_key===i)?.cli_flag??a;throw new p(`Cannot combine --unset ${a} with --${c}`,f.USAGE)}rt(e[i],s)||(e[i]=s,n.push(i))}let r=Fr(t.options.field,t.extensionRegistrations);for(let i of Object.keys(r))if(t.clearItemMetadataKeys.has(i))throw new p(`Cannot combine --unset ${i.replaceAll("_","-")} with --field ${i}=...`,f.USAGE);for(let[i,s]of Object.entries(r))rt(e[i],s)||(e[i]=s,n.push(i))}function nh(e,t,n,r){for(let i of t)!n.has(i)||e[i]===void 0||(delete e[i],r.push(i))}function KI(e,t){let n=structuredClone(e.metadata),r=e.body,i=[],s=[],a=bI(e,t.options,t.statusRegistry,i),o=e.metadata,c={metadataRecord:o,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:i,nowValue:t.nowValue};TI(e,t,a,i),xI(e,t,i),RI(e,t,i),OI(e,t,i),NI(e,t,i),DI(e,t,c),MI(e,t,c),FI(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"))&&mr(e.metadata.id,e.metadata.dependencies),ae(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,i.includes("assignee")||i.push("assignee")),GI(e,t,i),qI(o,t,i);try{$r(o,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(u){throw new p(u instanceof Error?u.message:"Invalid extension item field values",f.USAGE)}let d=e.metadata,l=[...new Set(i)].filter(u=>u==="body"?e.body!==r:!rt(n[u],d[u]));return t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${Jr(n.acceptance_criteria).length}:${Jr(d.acceptance_criteria).length}`),{changedFields:l,warnings:s}}async function dh(e,t,n,r={}){t=await iI(t);let i=I(process.cwd(),n.path);await _I(i);let s=await R(i),a=X(s.schema),o=zt(s.schema),c=P(),d=pt(c),l=U(s,c),u=s.governance.workflow_enforcement??"off",m=u==="off"?[]:kl(s.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],g=rh(t.unset,o,d),h=new Set(g.optionKeys),y=new Set(g.metadataKeys);aI(t),oI({definitions:sI(t),options:t,clearOptionKeys:h,clearItemMetadataKeys:y}),DC(e,t,y),dI(t,g),lI(t);let w=K(t.author,s.author_default),b=new Date,E=b.toISOString(),v=jC(t.dep,s.id_prefix,E,w);mr(e,v.additions);let T=await fs({pmRoot:i,dependencies:v.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:l.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),k=GC(t.depRemove,s.id_prefix),S=Ut("--comment",t.comment,E,w),A=t.ownershipMetadataBypass===!0&&S.values?{...S,values:S.values.map(Le=>({...Le,author:w}))}:S,L=Ut("--note",t.note,E,w),H=Ut("--learning",t.learning,E,w),j=Jo(t.file),C=Qo(t.test);C.values=await mn(C.values,w,E);let G=Zo(t.doc),de=[],ie=await hI({id:e,options:t,unsetTargets:g,pmRoot:i,settings:s,typeRegistry:l,parentReferencePolicy:_}),pe=await zC(t.blockedBy,y.has("blocked_by"),i,s.id_prefix,s.item_format,l.type_to_folder),qe=pe.id,St=[...ie.warnings,...yI(pe)],ut=Kd(t,o,t.runtimeFieldCommands),Ke=uI(t,ut);if(!Object.values(Ke).some(Boolean))return mI({pmRoot:i,id:e,settings:s,typeRegistry:l});de.push(...await wI({options:t,fieldFlags:Ke,workflowEnforcement:u,typeWorkflows:m,statusRegistry:a,typeRegistry:l,pmRoot:i,id:e,settings:s}));let he=await vI({options:t,fieldFlags:Ke,statusRegistry:a,workflowTransitionWarnings:de,global:n,id:e});if(he)return he;gI(t);let Ne=be(),Gs=Ke.parent&&!y.has("parent")||v.additions.some(Le=>Ne.resolve(Le.kind)?.hierarchy),D=await ns({pmRoot:i,author:w,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Gs});try{let Le=await fI({fieldFlags:Ke,clearedMetadataKeys:y,pmRoot:i,settings:s,typeToFolder:l.type_to_folder}),et,Sr,mt=await Dl({pmRoot:i,settings:s,typeToFolder:l.type_to_folder,id:e,op:zI(t,r),author:w,message:t.message,resolveHistoryContext:()=>Sr,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:d,skipNoop:!0,mutate(ze){et=WI({document:ze,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:a}),Sr=et?{recurrence:et}:void 0,Le=Le?.map(Tr=>Tr.id===ze.metadata.id?structuredClone(ze.metadata):Tr);let Ks=KI(ze,{options:t,settings:s,typeRegistry:l,statusRegistry:a,runtimeFieldRegistry:o,extensionRegistrations:c,extensionFieldNames:d,clearItemMetadataKeys:y,dependencyUpdates:v,dependencyRemovals:k,commentUpdates:A,noteUpdates:L,learningUpdates:H,fileUpdates:j,testUpdates:C,docUpdates:G,resolvedParentValue:ie.resolvedParentValue,resolvedBlockedByDependencyId:qe,runtimeFieldUpdates:ut,nowValue:b,nowIso:E,author:w,pmRoot:i});return pI({before:Le,document:ze,statusRegistry:a}),Ks}});await D();let qs=Le?zi(Le,Le.map(ze=>ze.id===mt.item.id?mt.item:ze),mt.item.id):[];return{item:mt.item,changed_fields:mt.changedFields,warnings:[...de,...St,...T,...qs,...mt.warnings],...et===void 0?{}:{lifecycle_transition:et}}}finally{await D()}}function zI(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function WI(e){if(e.recurrenceReason===void 0)return;let t=ae(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!oe(t,e.statusRegistry))throw new p(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,f.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,r=ae(n,e.statusRegistry)??n,i=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(a=>{let o=i[a];return typeof o=="string"?[[a,o]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:s}}async function BI(e,t,n){return dh(e,t,n)}async function Bq(e,t,n,r){let i=await dh(e,t,n,{recurrenceReason:r});if(i.lifecycle_transition===void 0)throw new p(`Item ${e} did not produce the required recurrence receipt.`,f.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{...i,lifecycle_transition:i.lifecycle_transition}}import ac from"node:fs/promises";import lh 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]="7df80849-51e1-5efa-b40a-b44088f941a9")}catch{}})();var VI=1440*60*1e3,HI=new Set(["committed","compensated"]);function YI(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 XI(e,t,n,r,i){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 a=r-s;return HI.has(t)?a>i?{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"active"},remove:!1}}async function JI(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],s=YI(await ac.readFile(e,"utf8")),a=XI(t,s.status,s.updatedAt,r.nowMs,r.retentionMs);return a.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),a.remove&&!r.dryRun&&(await ac.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:a,warnings:i}}async function uh(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=Math.max(0,t.retentionDays)*VI,a=lh.join(e,"transactions","sdk"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await ac.readdir(a)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if($(d))return o;throw d}for(let d of c){let l=lh.join(a,d),u=`transactions/sdk/${d}`,m=await JI(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:s});o.warnings.push(...m.warnings),o.scanned+=1;let{decision:_}=m;if(!_.remove){o.retained.push(u),o.entries.push(_.entry);continue}o.removed.push(u),o.entries.push(_.entry)}return o}import hn from"node:fs/promises";import ks from"node:path";import bs from"node:fs/promises";import oc 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]="b26cf702-330e-5cf5-8371-204220d5c5c9")}catch{}})();var QI=864e5;function ZI(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 eR(e,t){let n;try{n=await bs.readdir(e,{withFileTypes:!0})}catch(i){if($(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let s=oc.join(e,i.name),a;try{a=await bs.readdir(s)}catch(o){$(o)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let o of a)o.endsWith(".json")&&r.push(`${i.name}/${o}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function mh(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=Math.max(0,t.retentionDays)*QI,a=oc.join(e,"checkpoints"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await eR(a,o.warnings);for(let d of c){let l=oc.join(a,d),u=`checkpoints/${d}`;o.scanned+=1,r?.onRead&&o.warnings.push(...await r.onRead(l));let m;try{m=await bs.readFile(l,"utf8")}catch(w){if($(w)){o.scanned-=1;continue}o.warnings.push(`checkpoint_unreadable:${d}`),o.retained.push(u),o.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let _=ZI(m),g=_===null?Number.NaN:Date.parse(_);if(!Number.isFinite(g)){o.warnings.push(`checkpoint_unparseable:${d}`),o.retained.push(u),o.entries.push({file:u,created_at:_,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=i-g,y={file:u,created_at:_,age_seconds:Math.floor(h/1e3),stale:h>s,reason:h>s?"expired":"active"};if(!y.stale){o.retained.push(u),o.entries.push(y);continue}if(!n){try{await bs.unlink(l)}catch(w){if(!$(w)){o.warnings.push(`checkpoint_remove_failed:${d}`),o.retained.push(u),o.entries.push(y);continue}}r?.onWrite&&o.warnings.push(...await r.onWrite(l))}o.removed.push(u),o.entries.push(y)}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]="76f8405f-138d-5119-a300-f068354394a5")}catch{}})();var fr=["index","embeddings","runtime","locks","checkpoints","transactions"],tR=1440*60*1e3,nR=[{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 rR(e,t,n){let r=t.relativePath,i=ks.join(e,r),s=await Me({path:i,scope:"project"});try{let a=await hn.stat(i);if(t.kind==="file"&&!a.isFile())return{removed:!1,warnings:[...s,`not_a_file:${r}`]};if(t.kind==="directory"&&!a.isDirectory())return{removed:!1,warnings:[...s,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:s};t.kind==="file"?await hn.unlink(i):await hn.rm(i,{recursive:!0,force:!0});let o=await it({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...s,...o]}}catch(a){if($(a))return{removed:!1,warnings:s};throw a}}async function iR(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],s=[],a=Date.now()-tR;for(let o of n){let c=ks.join(e,o.relativePath);if(!await z(c))continue;let d=(await hn.readdir(c)).filter(l=>l.startsWith(o.prefix)).sort();for(let l of d){let u=ks.posix.join(o.relativePath,l),m=ks.join(c,l);s.push(...await Me({path:m,scope:"project"}));let _=await hn.stat(m).catch(g=>{if(!$(g))throw g});if(_){if(_.mtimeMs>a){i.push(u);continue}r.push(u),!t&&(await hn.rm(m,{recursive:!0,force:!0}),s.push(...await it({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:s}}function sR(e){if(!e||e.length===0)return[...fr];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new p(`--scope requires at least one value (${fr.join(",")})`,f.USAGE);let n=new Set;for(let r of t){if(!fr.includes(r))throw new p(`Invalid --scope value "${r}". Expected one or more of: ${fr.join(", ")}`,f.USAGE);n.add(r)}return fr.filter(r=>n.has(r))}function aR(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"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&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(i=>i.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(i=>i.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 _K(e,t={}){let n=I(process.cwd(),e.path);await F(n);let r=await R(n),i=t.dryRun===!0,s=sR(t.scope),a=nR.filter(g=>s.includes(g.scope)),o=[],c=[],d=[];for(let g of a){let h=await rR(n,g,i);h.removed?o.push(g.relativePath):c.push(g.relativePath),d.push(...h.warnings)}if(s.includes("runtime")){let g=await iR(n,i);o.push(...g.removed),c.push(...g.retained),d.push(...g.warnings)}let l;if(s.includes("locks")){let g=await Yf(n,{dryRun:i,hooks:{onRead:h=>Me({path:h,scope:"project"}),onWrite:h=>it({path:h,scope:"project",op:"gc:lock_remove"})}});o.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=r.checkpoints.retention_days,h=await uh(n,{dryRun:i,retentionDays:g,hooks:{onRead:y=>Me({path:y,scope:"project"}),onWrite:y=>it({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});o.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 m;if(s.includes("checkpoints")){let g=r.checkpoints.retention_days,h=await mh(n,{dryRun:i,retentionDays:g,hooks:{onRead:y=>Me({path:y,scope:"project"}),onWrite:y=>it({path:y,scope:"project",op:"gc:checkpoint_remove"})}});o.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),m={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:g}}d.push(...await Ud({mode:i?"gc:dry-run":"gc",total_items:a.length}));let _=aR({dryRun:i,scopes:s,removed:o});return{ok:d.length===0,dry_run:i,scope:s,removed:o,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:_,generated_at:x()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32223457-5f57-5049-99cf-c5d766413fb6")}catch{}})();var oR="1h",cR="now",dR="+1d";function bt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function fh(e,t,n){return{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}}async function ph(e,t,n,r){let i=fh(e,t,n),s=[];return bt(s,"start",n.start??cR),n.end!==void 0?bt(s,"end",n.end):bt(s,"duration",n.duration??oR),bt(s,"location",n.location),bt(s,"timezone",n.timezone),n.allDay===!0&&bt(s,"all_day","true"),i.event=[s.join(",")],tc(i,r)}function yK(e,t,n){return ph("Meeting",e,t,n)}function wK(e,t,n){return ph("Event",e,t,n)}function vK(e,t,n){let r=fh("Reminder",e,t),i=[];return bt(i,"at",t.at??dR),bt(i,"text",t.text??e),r.reminder=[i.join(",")],tc(r,n)}import{constants as kt}from"node:os";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1c74b5a9-67b8-597c-98de-a4487691081f")}catch{}})();var _h=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),lR=/^[a-z][a-z0-9_]{0,63}$/u,uR=new Map([[kt.errno.EACCES,"EACCES"],[kt.errno.EDQUOT,"EDQUOT"],[kt.errno.EMFILE,"EMFILE"],[kt.errno.ENFILE,"ENFILE"],[kt.errno.ENOMEM,"ENOMEM"],[kt.errno.ENOSPC,"ENOSPC"],[kt.errno.EPERM,"EPERM"],[kt.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),mR={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function fR(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&_h.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:uR.get(Math.abs(t.errno))??null}function pR(e,t,n={}){let r=fR(e);if(r===null)return null;if(!lR.test(t))throw new p("Host environment operation labels must be bounded identifiers.",f.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let i=_h.get(r);return new p(`Host filesystem operation ${t} ${i.summary}.`,f.GENERIC_FAILURE,{code:n.codes?.[i.category]??mR[i.category].code,reason:r,required:i.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[i.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function Es(e,t,n={}){try{return await t()}catch(r){throw pR(r,e,n)??r}}import _r from"node:crypto";import{cp as gh,lstat as _R,mkdir as jt,readFile as yn,readdir as dc,rename as wh,rm as uc,writeFile as Ss}from"node:fs/promises";import M 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]="2580e043-8675-5070-b57e-30cae333228c")}catch{}})();var vh="https://schema.unbrained.dev/pm/workspace-snapshot/v1",PK=["create","list","inspect","restore","delete"],bh=M.join("runtime","workspace-snapshots"),gR=new Set(["checkpoints","locks","runtime","search","transactions"]),hR=/^[a-z0-9][a-z0-9._-]*$/,pr="sdk-workspace-transaction",cc={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},kh={renameEntry:wh,removeEntry:async e=>{await uc(e,{recursive:!0,force:!0})}},lc=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*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 yn(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!==pr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await le(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
20
+ `)}};async function Eh(e,t=""){let n=await dc(M.join(e,t),{withFileTypes:!0}),r=[];for(let i of n.sort((s,a)=>s.name.localeCompare(a.name))){if(t.length===0&&gR.has(i.name))continue;let s=M.posix.join(t.replaceAll(M.sep,"/"),i.name);if(i.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${s}`);if(i.isDirectory())r.push(...await Eh(e,s));else if(i.isFile())r.push(s);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${s}`)}return r}async function Sh(e){let t=await Eh(e),n=_r.createHash("sha256"),r=[],i=0;for(let a of t){let o=await yn(M.join(e,a));r.push(o),i+=o.byteLength,n.update(a),n.update("\0"),n.update(String(o.byteLength)),n.update("\0"),n.update(o)}let s=n.digest("hex");return{manifest:{schema:vh,fingerprint:s,files:t,bytes:i},contents:r}}function hh(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
21
+ `).filter(t=>t.trim().length>0).length}async function yR(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let i=t.slice(r,r+32),s=await Promise.all(i.map(async a=>[a,await yn(M.join(e,a))]));for(let[a,o]of s)n.set(a,o)}return n}function mc(e){if(!hR.test(e))throw new p("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",f.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 Th(e,t){return Es(`workspace_snapshot_${e}`,t,{codes:{capacity:cc.capacity.code,permission:cc.permission.code,resource:cc.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 Gt(e){return M.join(e,bh)}function xh(e){return new p(`Unknown workspace snapshot: ${e}`,f.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 Ah(e,t){try{return JSON.parse(await yn(e,"utf8"))}catch(n){throw $(n)?xh(t):n}}async function yh(e,t,n){try{await uc(e,{recursive:n})}catch(r){throw $(r)?xh(t):r}}async function wR(e,t,n=kh){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function vR(e,t,n,r,i){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await i?.()}catch(s){throw await r.renameEntry(n,t),await r.removeEntry(e),s}await r.removeEntry(n)}async function bR(e,t){return mc(t),/^[a-f0-9]{64}$/.test(t)?t:(await Ah(M.join(Gt(e),"refs",`${t}.json`),t)).fingerprint}async function kR(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",f.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:r}=await Sh(e),i=Gt(e),s=M.join(i,"objects",n.fingerprint),a=!1;try{a=(await _R(s)).isDirectory()}catch(o){if(!(o instanceof Error&&"code"in o&&$(o)))throw o}if(!a){let o=M.join(i,"objects",`.create-${process.pid}-${_r.randomUUID()}`);await Th("create_object",async()=>{await jt(M.join(o,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let l=M.join(o,"files",d);await jt(M.dirname(l),{recursive:!0}),await Ss(l,r[c])}await Ss(M.join(o,"manifest.json"),`${JSON.stringify(n,null,2)}
22
+ `,"utf8"),await jt(M.dirname(s),{recursive:!0})}),a=await wR(o,s)}if(t.name!==void 0){let o={name:t.name,fingerprint:n.fingerprint},c=M.join(i,"refs");await jt(c,{recursive:!0});let d=M.join(c,`.ref-${process.pid}-${_r.randomUUID()}`);await Ss(d,`${JSON.stringify(o,null,2)}
23
+ `,"utf8"),await wh(d,M.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:a}}async function fc(e,t){let n=await bR(e,t),r=await Ah(M.join(Gt(e),"objects",n,"manifest.json"),t);if(r.schema!==vh||r.fingerprint!==n)throw new p(`Snapshot manifest identity mismatch: ${t}`,f.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 r}async function ER(e){let t=Gt(e),n=await dc(M.join(t,"objects")).catch(i=>{if(i instanceof Error&&"code"in i&&$(i))return[];throw i}),r=await dc(M.join(t,"refs")).catch(i=>{if(i instanceof Error&&"code"in i&&$(i))return[];throw i});return{objects:await Promise.all(n.filter(i=>/^[a-f0-9]{64}$/.test(i)).sort().map(i=>fc(e,i))),references:await Promise.all(r.filter(i=>i.endsWith(".json")).sort().map(async i=>JSON.parse(await yn(M.join(t,"refs",i),"utf8"))))}}async function SR(e,t){let n=await fc(e,t),{manifest:r,contents:i}=await Sh(e),s=new Map(r.files.map((u,m)=>[u,i[m]])),a=await yR(M.join(Gt(e),"objects",n.fingerprint,"files"),n.files),o=new Set(r.files),c=new Set(n.files),d=new Set([...o,...c]);for(let u of d){let m=s.get(u),_=a.get(u);m!==void 0&&_!==void 0&&m.equals(_)&&d.delete(u)}let l=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let m=hh(s.get(u)),_=hh(a.get(u));return{path:u,current_entries:m,target_entries:_,removed_entries:Math.max(0,m-_)}}).filter(u=>u.removed_entries>0).sort((u,m)=>u.path.localeCompare(m.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:d.size,removed_file_count:[...o].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!o.has(u)).length,removed_item_count:[...o].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:l.length,removed_history_entry_count:l.reduce((u,m)=>u+m.removed_entries,0),affected_history_streams:l,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function TR(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",f.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 r=n.author?.trim()||"pm-sdk",i=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,a=await Vt(e,pr,i,r,!1,!1,s),o=new lc(Dr(e,pr),r,i);o.start(),await o.refreshNow();let c,d=!1,l=!1;try{let u=await SR(e,t),m=await fc(e,t),_=await kR(e),g=m.fingerprint,h=Gt(e),y=M.join(h,"objects",g,"files"),w=M.dirname(e),b=M.basename(e);c=M.join(w,`.${b}.restore-${_r.randomUUID()}`);let E=M.join(w,`.${b}.backup-${_r.randomUUID()}`);await Th("restore_stage",async()=>{await jt(c,{recursive:!0}),await gh(y,c,{recursive:!0,force:!1}),await jt(M.join(c,"runtime"),{recursive:!0}),await gh(h,M.join(c,bh),{recursive:!0,force:!1})});let v=await Ht({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:_.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:i,lockWaitMs:s}),T=M.relative(c,v.historyPath).replaceAll("\\","/");await o.stop(),l=!0;let k=Dr(c,pr);return await jt(M.dirname(k),{recursive:!0}),await Ss(k,await yn(Dr(e,pr)),{flag:"wx"}),d=!0,await vR(c,e,E,kh,async()=>{o.start(),l=!1,await o.refreshNow()}),await o.stop(),l=!0,{manifest:m,plan:u,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:T,audit_operation:"workspace_snapshot_restore"}}catch(u){throw c!==void 0&&!d&&await Promise.allSettled([uc(c,{recursive:!0,force:!0})]),u}finally{try{l||await o.stop()}catch{}finally{await a()}}}async function FK(e,t){return(await TR(e,t,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function $K(e,t){mc(t);let n=Gt(e);if(!/^[a-f0-9]{64}$/.test(t))return await yh(M.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await ER(e);if(r.some(i=>i.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await yh(M.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]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function GK(e){return jr("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]="32dca84c-9a21-570c-a0e0-0f0356c84c0d")}catch{}})();var xR=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),AR=new Set(["--add","--body","--comment","--dep","--description","--doc","--field","--file","--learning","--note","--remove","--test","--type-option"]),CR=new Set(["append","comments","create","docs","files","learnings","notes","test","update"]),IR=["--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"],RR=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"]),OR=new Set(["--only-index"]),NR=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),LR=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),DR=new Set(["--regression"]);function MR(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:t.endsWith("-file")?["argv","file"]:AR.has(t)&&CR.has(e)?["argv","stdin"]:["argv"]}function PR(e,t){let n=NR.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,r=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-"))||IR.some(i=>t.flag.startsWith(i));return n||OR.has(t.flag)||!RR.has(t.flag)&&!r}function FR(e,t){let n=PR(e,t),r=MR(e,t.flag),i=t.description??xR[t.flag]??`${n?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:i,takes_value:n,value_required:n&&!DR.has(t.flag)&&!LR.has(`${e}:${t.flag}`),...n?{value_name:t.value_name??"value"}:{},value_type:n?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:"-"}:{}}}function Ch(e,t){return t.map(n=>FR(e,n))}function KK(e,t,n){let r=e.trim().toLowerCase(),i=[],s=new Map,a=0;for(let c of n)if(c.command.trim().toLowerCase()===r){if(a+=1,s.has(c.flag)){i.push({code:"duplicate_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} was observed more than once.`});continue}s.set(c.flag,c)}let o=new Set(t.map(({flag:c})=>c));for(let c of t){let d=s.get(c.flag);if(!d){i.push({code:"missing_observation",command:r,flag:c.flag,detail:`${r} ${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]&&i.push({code:u,command:r,flag:c.flag,detail:`${r} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of s.values())o.has(c.flag)||i.push({code:"undeclared_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} is executable but absent from invocation contracts.`});return i.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:i.length===0,declared_count:t.length,observed_count:a,findings: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]="5e77c121-35a2-57d1-9a3e-f33447535c03")}catch{}})();var $R=new Set(["claim","close","context","create","get","help","list","next","plan","release","search","update","validate"]),UR=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"]),jR=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-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"])}),GR=new Set(["extension","install","package","packages","upgrade"]);function qR(e){let t=e.trim().toLowerCase();for(let[n,r]of Object.entries(jR))if(r.has(t))return n;return GR.has(t)?"extensions":"internal"}var pc=Object.freeze([...Be.flatMap(e=>e==="item"?["item-reopen"]:[e]).map(e=>({command:e,tier:$R.has(e)?"core":UR.has(e)?"standard":"full",family:qR(e)})),{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"}]),Rh=pc,Ih={core:0,standard:1,full:2,internal:3},KR=new Map(Rh.map(({command:e,tier:t})=>[e,t]));function Oh(e,t="standard"){return KR.get(e.trim().toLowerCase())??t}function zR(e){let t=Ih[e];return Rh.filter(n=>n.tier!=="internal"&&Ih[n.tier]<=t).map(n=>n.command)}function BK(e){return pc.filter(t=>t.family===e).map(t=>t.command)}var WR=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_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 VK(e,t){if(t==="full")return[...e];let n=new Set(zR(t));return e.filter(r=>{let i=WR[r];return i!==void 0&&n.has(i)})}var HK=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"}]),YK=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 XK(){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 |","| --- | --- | --- |",...pc.map(({command:t,tier:n,family:r})=>`| \`${t}\` | ${n} | ${r} |`),""].join(`
24
+ `)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c76fa303-6672-5c1e-9cf5-3a08bd3a7814")}catch{}})();var BR=[{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"}],VR=new Map(BR.map(e=>[e.exit_code,e.class]));function Ts(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function HR(e){if(!e)return[];let t=new Set,n=new Set;return e.map(r=>{let i=r.state.trim(),s=r.probe_id.trim(),a=Ts(r.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(i)||!/^[a-z][a-z0-9-]*$/.test(s)||a.length===0||t.has(i)||n.has(s))throw new TypeError("Invalid pm refusal state contract");return t.add(i),n.add(s),{state:i,probe_id:s,entrypoints:a,expected_exit_class:r.expected_exit_class}}).sort((r,i)=>r.state.localeCompare(i.state))}function YR(e,t,n,r,i){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(r),i.every(s=>/^[a-z][a-z0-9_]*$/.test(s)),VR.get(e.exit_code)===e.class].includes(!1)}function XR(e,t){let n=e,r=new Set;for(;n.canonical_code!==n.code;){if(r.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);r.add(n.code);let i=t.get(n.canonical_code);if(!i)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=i}return n}function JR(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let r=XR(n,t);if(r.exit_code!==n.exit_code||r.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let i=e.filter(s=>s.code!==r.code&&s.canonical_code===r.code).map(s=>s.code).sort();if(n.code===r.code?JSON.stringify(n.aliases)!==JSON.stringify(i):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function Lh(e){let t=new Set,n=e.map(r=>{let i=r.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(i))throw new TypeError(`Invalid pm error code: ${JSON.stringify(r.code)}`);if(t.has(i))throw new TypeError(`Duplicate pm error code: ${i}`);t.add(i);let s=Ts(r.sources),a=Ts(r.emitting_commands),o=(r.canonical_code??i).trim(),c=Ts(r.aliases??[]),d=HR(r.owned_states);if(!YR(r,s,a,o,c))throw new TypeError(`Invalid pm error code contract: ${i}`);if(d.some(l=>l.expected_exit_class!==r.class))throw new TypeError(`Invalid pm refusal state exit class: ${i}`);return Object.freeze({...r,code:i,meaning:r.meaning.trim(),recovery:r.recovery.trim(),sources:s,emitting_commands:a,canonical_code:o,aliases:c,owned_states:d})});return JR(n),Object.freeze(n.sort((r,i)=>r.code.localeCompare(i.code)))}function QK(e,t){let n=Nh(e,t);return Nh(n.canonical_code??n.code,t)}function Nh(e,t){let n=e.trim(),r=t.find(i=>i.code===n);if(!r)throw new TypeError(`Unknown pm error code "${n}"`);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]="30cf6de5-af9b-54a1-b376-1c9e5d543ae1")}catch{}})();var Dh=[{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_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:"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:"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/similarity.ts"],emitting_commands:["*"],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_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_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_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_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_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:"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:["sdk/environment/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:["sdk/environment/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:["sdk/environment/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:["sdk/environment/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_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_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:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"manifest_unknown_key",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_reconcile_discards_require_acceptance",meaning:"Merge reconcile discards require acceptance condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/reconcile.ts"],emitting_commands:["*"],canonical_code:"merge_reconcile_discards_require_acceptance",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:[]},{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:[]}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9b6149b0-ca3e-5093-aba5-43385d3368f7")}catch{}})();var Mh=[{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_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","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:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"no_version_bounds_declared",aliases:[]},{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_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:"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_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:"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:"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_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_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]="f617ee39-b463-5482-af64-8dc86fe28e71")}catch{}})();var Ph=Lh([...Dh,...Mh]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af86d275-63a8-5205-a8b3-154efdbd8e2a")}catch{}})();var QR=["mutation_receipt","entity","collection","diagnostic","stream"],ZR=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),eO=new Set(["close-many","update-many"]),tO=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),nO=new Set(["aggregate","deps","graph","health","stats","validate"]);function gr(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!QR.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function Fh(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return eO.has(n)?gr({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):ZR.has(n)?gr({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):tO.has(n)?gr({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):nO.has(n)?gr({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):gr({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var rO=Be.map(e=>Fh(e)),iO=new Map(rO.map(e=>[e.command,e]));function $h(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]=t.split(" "),r=iO.get(n);return r?{...r,command:t}:Fh(t)}function sO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aO(e){return sO(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 oz(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(!aO(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]="90896fb6-ee3e-575d-b103-bbc1a83c6672")}catch{}})();var oO=wa("list").properties.outputSession,cO={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:{...oO},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Uh={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},se={type:"string",description:"pm item id, for example pm-abc1."},dO=`Operation name (one of): ${ia.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,lO={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."}},uO={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 q(e,t=[]){return{...Uh,properties:{...Uh.properties,...e},required:t}}var mO=[{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:q({action:{type:"string",enum:[...ia],description:dO},id:se,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."},...cO},["action"])},{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:q({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:q({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, 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:q({query:{type:"string"},options:{type:"object"},...uO},["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:q({options:{type:"object"},...lO})},{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:q({id:se,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:q({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:q({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:q({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:se,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:q({id:se,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:q({id:se,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:q({id:se,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:q({id:se,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:q({id:se,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:q({id:se,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:q({id:se,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. 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:q({id:se,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:q({id:se,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:q({id:se,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List or add structured notes on a pm item. Use options.add to append a note; omit it to list existing notes.",inputSchema:q({id:se,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List or add learnings on a pm item. Use options.add to capture a learning/insight; omit it to list existing learnings.",inputSchema:q({id:se,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:q({id:se,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:q({subcommand:{type:"string",enum:[...il]},id:se,target:se,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:q({id:se,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:q({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:q({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:q({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. Schema mutations write workspace config files, not item history.",inputSchema:q({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"],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or custom field key (show-field/add-field/remove-field). Required for those subcommands."},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:[...Js]},description:`Lifecycle roles for add-status: ${Js.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."}},["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:q({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:q({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:q({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."}})}],fO={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"},pO=mO.map(e=>{let t=fO[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:wa(t,{properties:n,required:r})}});function jh(){return pO.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,i)=>r.localeCompare(i)):[];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]="e8f1efca-4e83-570f-8c33-96f0405035b0")}catch{}})();var Gh=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"]]]),_O=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Jh=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),As=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"]),hr=new Set(["cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),Qh=new Map([["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"],["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"]]),Zh=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"]]),ey=new Map([...Zh.entries()].flatMap(([e,t])=>lt(t).map(n=>[n,e]))),ty=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],ny=new Map(ty.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),gO=10,hO=20,qh=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["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 work through typed operations."],["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 portable workspace primitives."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),ry=[["init",Eu],["install",Tu],["uninstall",xu],["explore",Au],["manage",Lu],["describe",Cu],["reload",Du],["doctor",Mu],["catalog",Pu],["adopt",Fu],["adopt-all",Iu],["activate",Ru],["deactivate",Ou],["migrate",Nu]],yO=ry.map(([e,t])=>e==="init"?[e,Su]:[e,t]),wO=[...ry.map(([e,t])=>[`extension ${e}`,t]),...yO.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",vu],["config",bu],["extension",ku],["package",ga],["packages",ga],["install",$u],["create",om],["item mutate",cm],["item complete",dm],["item reopen",lm],["copy",um],["focus",mm],["update",fm],["update-many",pm],["upgrade",Uu],["calendar",ha],["cal",ha],["context",ya],["ctx",ya],["get",gm],["search",km],["eval",vm],["workspace",gt],["workspace snapshot",gt],["workspace snapshot create",gt],["workspace snapshot list",gt],["workspace snapshot inspect",gt],["workspace snapshot restore",gt],["workspace snapshot delete",gt],["next",bm],["aggregate",su],["deps",ym],["graph",wm],["guide",hm],["reindex",ju],["history",uu],["history-compact",gu],["history-redact",fu],["history-repair",pu],["history-author-acknowledge",_u],["merge",mu],["schema",hu],["profile",yu],["plan",wu],["restore",Wu],["delete",Bu],["close",Gu],["close-many",qu],["append",Ku],["claim",zu],["release",Vu],["start-task",Hu],["pause-task",Yu],["close-task",Xu],["comments",au],["notes",ou],["learnings",cu],["files",du],["docs",lu],["test",Ju],["test-all",Qu],["telemetry",Zu],["test-runs",em],["gc",tm],["stats",nm],["duplicates",rm],["validate",sm],["health",im],["assurance",am],...Tm,["contracts",Em],["completion",Sm],["activity",_m],...[...Jh].map(e=>[e,iu])],yc=new Map(wO);function vO(e){let t=ey.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Kh(e){return Be.includes(e)?ke(e):e.startsWith("extension-")?ke(`extension ${e.slice(10)}`):e.startsWith("package-")?ke(`package ${e.slice(8)}`):e.startsWith("item-")?ke(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ke(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ke(`templates ${e.slice(10)}`):As.has(e)?Zh.get(e)??ke(e):null}function bO(e,t){return e.command_path===null?!1:lt(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `)||t.startsWith(`${n} `))}function lt(e){return e.split("|").map(t=>ke(t)).filter(t=>t.length>0)}function kO(e,t){let n=new Set(t),r=new Set;for(let i of e)if(i.command_path)for(let s of lt(i.command_path)){let a=s.split(" ").filter(o=>o.length>0);if(a.length!==0)for(let o=a.length;o>0;o-=1){let c=a.slice(0,o).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((i,s)=>i.localeCompare(s))}function xs(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function yr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function EO(e,t){if(!t)return{...e};let r=yr(e).filter(i=>{let s=i.properties;if(typeof s!="object"||s===null)return!1;let a=s.action;return typeof a!="object"||a===null?!1:a.const===t});return{...e,oneOf:r}}function _c(e,t){let r=yr(e).filter(i=>{let s=i.properties;if(typeof s!="object"||s===null)return!1;let a=s.action;if(typeof a!="object"||a===null)return!1;let o=a.const;return typeof o=="string"&&t.has(o)});return{...e,oneOf:r}}function ke(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function iy(e){return e.replace(/\s+/g,"-")}function Qe(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function zh(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let i=Qe(r);!i||n.has(i)||(n.add(i),t.push(i))}return t}function gc(e,t,n){n&&(e[t]=!0)}function Wh(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 SO(e){let t=Wh(e.long,"long"),n=Wh(e.short,"short"),r=t??n;if(!r)return null;let i={flag:r};n&&t&&(i.short=n),gc(i,"required",e.required===!0),gc(i,"repeatable",e.repeatable===!0),gc(i,"list",e.list===!0);let s=Qe(e.description);s&&(i.description=s);let a=Qe(e.value_name);a&&(i.value_name=a);let o=[Qe(e.value_type),Qe(e.type),a?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return o&&(i.value_type=o),i}function sy(e){let t=new Map;for(let r of e){let i=ke(r.target_command);if(i.length===0)continue;let s=t.get(i)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},a=`${r.layer}:${r.name}`;s.sourceDedupe.has(a)||(s.sourceDedupe.add(a),s.sources.push({layer:r.layer,name:r.name}));for(let o of r.flags){let c=SO(o);if(!c)continue;let d=`${c.flag}|${c.short??""}`;s.dedupe.has(d)||(s.dedupe.add(d),s.flags.push(c))}t.set(i,s)}let n=new Map;for(let[r,i]of t.entries())n.set(r,{flags:i.flags,sources:i.sources.sort((s,a)=>{let o=s.layer.localeCompare(a.layer);return o!==0?o:(s.name??"").localeCompare(a.name??"")})});return n}function TO(e){let t=sy(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let a=ke(s.command);if(a.length===0)continue;let o=Qe(s.action)??iy(a),c=Array.isArray(s.arguments)?s.arguments.map(d=>{let l=Qe(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:Qe(d.description)}:null}).filter(d=>d!==null):[];n.set(a,{command:a,action:o,source:{layer:s.layer,name:s.name},description:Qe(s.description),intent:Qe(s.intent),arguments:c,flags:t.get(a)?.flags??[],examples:zh(s.examples),failure_hints:zh(s.failure_hints)})}let r=new Set;for(let s of e.handlers)r.add(ke(s));for(let s of n.keys())r.add(s);for(let s of t.keys())r.add(s);let i=[];for(let s of[...r].sort((a,o)=>a.localeCompare(o))){let a=n.get(s);i.push(xO(s,a,t.get(s)?.flags??[]))}return i}function xO(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:iy(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function AO(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(i,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function CO(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 IO(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",i=e.repeatable===!0||e.list===!0;return{type:i?"array":r,...i?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function RO(e){let t=e.command.split("|").map(i=>i.trim()).filter(i=>i.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let i of e.arguments)n[i.name]=CO(i,e.action),i.required&&r.push(i.name);for(let i of e.flags){let s=AO(i);!s||n[s]!==void 0||(n[s]=IO(i,e.action),i.required===!0&&r.push(s))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function OO(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 NO(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((s,a)=>s.localeCompare(a)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let i=new Set(r.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let a=`${s.flag}|${s.short??""}`;if(!i.has(a))i.add(a),r.flags.push(s);else{let o=r.flags.find(c=>`${c.flag}|${c.short??""}`===a);o&&OO(o,s)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function LO(e,t=R){let n={mode:Sn.extensions.policy.mode,trust_mode:Sn.extensions.policy.trust_mode,default_sandbox_profile:Sn.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=I(process.cwd(),e.path);if(!await z(je(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let i=await t(r),s=await Mr({pmRoot:r,settings:i,cwd:process.cwd(),noExtensions:!1}),a=await Pr({...s,loaded:s.loaded});return{handlers:new Set(a.commands.handlers.map(c=>ke(c.command))),disabledReason:null,commandDefinitions:a.registrations.commands,flagRegistrations:a.registrations.flags,registrations:a.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 DO(e,t={}){let n=new Map;for(let r of sl){let i=As.has(r);if(i&&!t.includePackageOwnedActions)continue;let s=Kh(r);n.set(r,{action:r,provider:i?"extension":"core",requires_extension:i,command_path:s})}if(t.includePackageOwnedActions)for(let r of As)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Kh(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ke(r.command)});return[...n.values()].sort((r,i)=>(r.action??"").localeCompare(i.action??""))}function MO(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?lt(e.command_path):[],r=n.some(a=>t.handlers.has(a)),i=n.map(a=>Qh.get(a)).find(a=>typeof a=="string"),s=t.disabledReason===null&&r;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(i?`optional_package_not_installed:${i}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function ay(e){return yc.get(e)??ru}function PO(e){return hr.has(e)?!1:yc.has(e)}function FO(e){return Jh.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Bh(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function $O(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function UO(e){let t=new Map;for(let r of e.definitions){let i=Bh(r.cli_flag);if(!i)continue;let s=r.cli_aliases.map(o=>$O(o)).find(o=>o!==null),a=r.cli_aliases.map(o=>Bh(o)).filter(o=>o!==null&&o!==i);for(let o of r.commands){let c=t.get(o)??{flags:[],seen:new Set},d=s?{flag:i,short:s}:{flag:i},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of a){let m=`${u}|`;c.seen.has(m)||(c.seen.add(m),c.flags.push({flag:u}))}t.set(o,c)}}let n=new Map;for(let[r,i]of t.entries())n.set(r,_a(i.flags));return n}function Vh(e,t){let n=[],r=new Set;for(let i of[...e,...t]){let s=`${i.flag}|${i.short??""}`;r.has(s)||(r.add(s),n.push(i))}return _a(n)}function jO(e,t,n,r){return e.map(i=>{let s=PO(i),a=s?ay(i):[],o=n.get(FO(i))??[],c=t.get(i),d=Vh(a,o),l=Vh(d,c?.flags??[]),u=a.length>0&&(c?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:i,flags:l,...r?{canonical_command:hc(i),visibility:Oh(hc(i)),positionals:eu(i)?.slots??[],flag_invocations:Ch(i,l)}:{},provider:u,extension_sources:c?.sources}}).sort((i,s)=>i.command.localeCompare(s.command))}function GO(e,t=ra){let n=new Set(e),r=new Map;for(let i of ty){let s=i.aliases.filter(a=>n.has(a));r.set(i.canonical,{canonical:i.canonical,aliases:s,contracts:[]})}for(let i of t){if(!n.has(i.canonical)||i.registration==="commander"&&!n.has(i.alias))continue;let s=r.get(i.canonical)??{canonical:i.canonical,aliases:[],contracts:[]};s.aliases.includes(i.alias)||s.aliases.push(i.alias),s.contracts.push(i),r.set(i.canonical,s)}return[...r.values()].map(({contracts:i,...s})=>i.length===0?s:{...s,contracts:i}).sort((i,s)=>i.canonical.localeCompare(s.canonical))}function qO(){return{create_string_options:Jl,create_repeatable_options:Ql,update_string_options:ii,update_repeatable_options:Zl,list_string_options:Bl,search_string_options:Vl,calendar_string_options:Hl,context_string_options:Yl,activity_string_options:Xl}}function Hh(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let o of e.required_create_fields)n.add(o);for(let o of e.required_create_repeatables)n.add(o)}let r=Kt(e,"create",n),i=[...new Set(r.required)].sort((o,c)=>o.localeCompare(c)),s=[...new Set(i.map(o=>Ee("create",o)))].sort((o,c)=>o.localeCompare(c)),a=[...new Set(e.options.filter(o=>o.required===!0).map(o=>o.key))].sort((o,c)=>o.localeCompare(c));return{required_option_keys:i,required_flags:s,required_type_options:a,policy_errors:[...new Set(r.errors)].sort((o,c)=>o.localeCompare(c))}}function KO(e){let t={},n={};for(let r of[...e.types].sort((i,s)=>i.localeCompare(s))){let i=e.by_type[r];t[r]=Hh(i,"strict"),n[r]=Hh(i,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function zO(e,t){let n=yr(e);if(n.length===0)return e;let r=!1,i=n.map(s=>{let a=s.properties;if(typeof a!="object"||a===null)return s;let o=a.action;return typeof o!="object"||o===null||o.const!=="create"?s:(r=!0,{...s,"x-create-required-options":t})});return r?{...e,oneOf:i}:e}function WO(e){let t=xs(e.action)!==void 0||xs(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,i=e.schemaOnly===!0,s=e.flagsOnly===!0,a=e.availabilityOnly===!0,o=e.runtimeOnly===!0,c=e.full===!0,d=xs(e.action),l=xs(e.command),u=!r&&!c&&!i&&!s&&!a&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:r,schemaOnly:i,flagsOnly:s,availabilityOnly:a,runtimeOnly:o,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function BO(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.",f.USAGE)}async function VO(e,t=R){try{return await t(e)}catch{return structuredClone(Sn)}}async function HO(e,t){let n=await VO(t),r=await LO(e),i=U(n,r.registrations??P()),s=zt(n.schema),a=TO(r);return{settings:n,runtimeProbe:r,typeRegistry:i,statusRegistry:X(n.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:UO(s),createRequiredOptionContracts:KO(i),extensionContracts:a,mergedExtensionContracts:NO(a),extensionFlagMap:sy(r.flagRegistrations)}}function Yh(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&As.has(e.selectedAction)||e.selectedCommand!==void 0&&hr.has(e.selectedCommand))}function YO(e,t){let n=DO(t,{includePackageOwnedActions:Yh(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(al);return n.filter(i=>!r.has(i.action))}return Yh(e)&&e.selectedCommand!==void 0&&hr.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:vO(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function XO(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new p(`Unknown action: "${e.selectedAction}".`,f.USAGE)}function JO(e,t){return[...new Set([...Be.filter(n=>!hr.has(n)),...[...yc.keys()].filter(n=>!hr.has(n)),...e.flatMap(n=>n.command_path?lt(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>ke(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function QO(e,t){let n=t.slice(0,gO),r=t.length-n.length,i=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),s=t.slice(0,hO),a=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),o=t[0];return new p(`Command "${e}" is a command namespace. Choose a concrete child command: ${i}.`,f.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:a,nextSteps:[`Retry with a child command, for example: ${a[0]}`],recovery:{suggested_retry:`pm contracts --command "${o}" --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 ZO(e,t){return new p(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,f.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 e0(e){return new p(`Unknown command: "${e}".`,f.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 t0(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(s=>s.startsWith(`${e.selectedCommand} `));if(r.length>0)throw QO(e.selectedCommand,r);let i=Qh.get(e.selectedCommand);throw i?ZO(e.selectedCommand,i):e0(e.selectedCommand)}function n0(e,t){let n=YO(e,t.mergedExtensionContracts);XO(e,n);let r=JO(n,t.mergedExtensionContracts);t0(e,r);let i=e.selectedCommand?ey.get(e.selectedCommand):void 0,s=e.selectedCommand?n.filter(d=>i?d.action===i:bO(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.`,f.USAGE);let a=e.selectedAction?s.filter(d=>d.action===e.selectedAction):s,o=[...new Map(a.map(d=>MO(d,t.runtimeProbe)).map(d=>[i?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?o.filter(d=>d.invocable):o;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:s,scopedActionDescriptors:a,selectedPackageOwnedAction:i,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function r0(e){return new Set(yr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let i=r.const;return typeof i=="string"?i:null}).filter(t=>t!==null))}function i0(e){let t=xm,n=yr(t),r=r0(t),i=e.filter(s=>!r.has(s.action)).map(s=>RO(s));return i.length>0?{...t,oneOf:[...n,...i]}:t}function Xh(e,t,n){let r=new Set(t.actionDescriptors.map(s=>s.action)),i=e.selectedAction?EO(n,e.selectedAction):e.selectedCommand?_c(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):_c(n,r);return e.runtimeOnly&&!e.selectedAction?_c(i,new Set(t.actions)):i}function s0(e,t,n){let r=i0(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?zO(Xh(e,n,r),t.createRequiredOptionContracts):Xh(e,n,r);return{mergedSchema:r,filteredSchema:s}}function a0(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?kO(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function o0(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(ra.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function hc(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":ny.get(t)??t}var c0=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"]]),d0=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function l0(e,t){let n=qh.get(e)??(e.includes(" ")?void 0:qh.get(hc(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>lt(d.command).includes(e));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let i=e.split(" "),s=i.at(-1),a=i.slice(0,-1).join(" "),o=c0.get(s),c=d0.get(e)??a;return{intent:o===void 0||a.length===0?`Run ${e}.`:`${o} ${c}.`,intent_source:"generated"}}function u0(e,t=[],n={}){let r=n.includeFormatBudgets??!0,i=n.includeIntentProvenance??!0;return[...new Set(e.map(ke))].filter(s=>s.length>0).sort((s,a)=>s.localeCompare(a)).map(s=>{let a=sa(s,{generateFallback:!0}),o=s.split(" ")[0],c=ny.get(o)??(o.startsWith("list-")?"list":o.startsWith("history-")?"history":o),d=new Set([...ay(s).map(m=>m.flag),...t.filter(m=>lt(m.command).includes(s)).flatMap(m=>m.flags.map(_=>_.flag))]),l=(Gh.get(s)??Gh.get(c)??_O).filter(m=>d.has(m)),u=l0(s,t);return{command:s,intent:u.intent,...i||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:a.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...a.default_max_estimated_tokens_by_format}}:{}}})}function m0(e){return e.map(t=>({budget:sa(t,{generateFallback:!0}),envelope:$h(t)}))}function f0(e){let t=new Map;for(let n of e){let r=fg(n),i=r===void 0?[f.SUCCESS,f.GENERIC_FAILURE,f.USAGE,f.NOT_FOUND,f.CONFLICT,f.DEPENDENCY_FAILED]:r.exit_codes,s=i.join(","),a=t.get(s)??{commands:[],exit_codes:i};a.commands.push(n),t.set(s,a)}return[...t.values()]}function p0(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>lt(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(i=>lt(i.command).some(s=>r.has(s)))}return t.extensionContracts}function _0(e,t,n,r){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?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function g0(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(i=>i.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(([i])=>r===void 0||i===r).map(([i,s])=>[i,[...new Set(s.map(a=>`--${a.cli_flag}`))].sort((a,o)=>a.localeCompare(o))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Qd],services:[...Zd],policy_modes:[...el],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...rl],trust_modes:[...tl],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...nl],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[..._d],create_modes:[...gd],close_validation_modes:[...hd],workflow_enforcement_modes:[...yd]},e.relationship_kind_contracts=[...Od,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(i=>i.definitions)].sort((i,s)=>i.kind.localeCompare(s.kind)).map(i=>({canonical:i.kind,aliases:[...i.aliases??[]],...i.inverse===void 0?{}:{inverse:i.inverse},ordering:i.ordering,hierarchy:i.hierarchy})))}function h0(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function y0(e,t,n,r,i){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=jO(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let s=new Set(r);e.list_projections=Object.entries(Vm).filter(([a])=>s.has(a)).map(([a,o])=>({command:a,default:o,brief_fields:[...Bm],compact_fields:[...Wm]}))}e.command_aliases=i}}function w0(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=qO();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function v0(e,t,n,r){e.command_summaries=u0(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...ol],allows_unbounded_opt_out:!0},e.grammar_contracts={nouns:Ct.nouns,shared_verbs:Ct.shared_verbs,scope_before_verb:Ct.scope_before_verb,visible_top_level_ceiling:Ct.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Ct.ceiling_raise_requires_pm_item,positional_shape_budget:Ct.positional_shape_budget,positional_shape_count:new Set(pa.map(({slots:i})=>nu(i))).size,positional_action_count:fa.length,positional_action_parents:[...new Set(fa.map(({parent:i})=>i))].sort((i,s)=>i.localeCompare(s)),...r.includePositionalSignatures?{positional_signatures:pa}:{}}}async function Iz(e,t){let n=WO(e);BO(n);let r=I(process.cwd(),t.path),i=await HO(t,r),s=n0(n,i),a=s0(n,i,s),o=a0(n,s),c=o0(n,o),d=_0(n,a,s,c),l=p0(n,i,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&v0(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u}),n.summary)return d;let m=GO(s.commandCatalog);return n.flagsOnly&&!n.fullOutput||g0(d,i,n),h0(d,n,a,l),y0(d,n,i,c,m),w0(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...$n],gate_triggers:[...st]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=tu),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=jh(),d.context_intents=ll(),d.read_output_dimensions=dl,d.error_codes=Ph,d.command_output_contracts=m0(c),d.diagnostic_output_contracts=cl,d.command_exit_contracts={vocabulary:Go,command_sets:f0(c)}),d}import{createHash as k0}from"node:crypto";import{execFile as E0}from"node:child_process";import dy from"node:path";import{promisify as S0}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]="939d5f93-d287-5c1c-bc78-d013f76735f2")}catch{}})();var oy=1;function b0(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 wc(e){if(e===null)return{format_version:oy,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new p("Improvement ledger contains invalid JSON.",f.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==oy||!Array.isArray(t.observations))throw new p("Improvement ledger has an unsupported shape or format version.",f.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!b0(r))throw new p("Improvement ledger contains an invalid observation.",f.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]="c2e1edc9-c454-5cfa-85c8-e9fb0a76a296")}catch{}})();var T0=S0(E0),x0=50,cy=1e3,A0=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function ly(e){let t=e.trim().toLowerCase();if(!A0.test(t))throw new p(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,f.USAGE,{code:"invalid_improvement_metric"});return t}function C0(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new p("Improvement direction must be higher, lower, or target.",f.USAGE,{code:"invalid_improvement_observation"});return t}function wr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new p(`${t} must not exceed 256 characters.`,f.USAGE,{code:"invalid_improvement_observation"});return n}}function I0(e){let t=e??x0;if(!Number.isSafeInteger(t)||t<0||t>cy)throw new p(`Improvement observation limit must be an integer from 0 to ${cy}.`,f.USAGE,{code:"invalid_improvement_observation_limit"});return t}function uy(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`${t} must be an ISO timestamp.`,f.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function R0(e,t,n){if(!Number.isFinite(n.value))throw new p("Improvement observation value must be finite.",f.USAGE,{code:"invalid_improvement_observation"});let r=ly(n.metric),i=C0(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||i==="target"&&n.threshold===void 0)throw new p("Target-directed observations require a finite threshold.",f.USAGE,{code:"invalid_improvement_observation"});let s=await N0(e,n.revision),a=wr(n.source,"source"),o=wr(n.itemId,"itemId"),c=wr(n.unit,"unit"),d=wr(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,r,a??"manual",o??"workspace"].join(":")),l={metric:r,value:n.value,direction:i,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:uy(n.observedAt??x(),"observedAt"),...s,author:K(n.author,t.author_default),...o===void 0?{}:{item_id:o},...a===void 0?{}:{source:a},...d===void 0?{}:{idempotency_key:d}};return{id:k0("sha256").update(J(l)).digest("hex").slice(0,24),...l}}function O0(e,t){let n=t.idempotency_key?e.observations.find(i=>i.idempotency_key===t.idempotency_key):e.observations.find(i=>i.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}.`,f.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(i=>i.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new p(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,f.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function N0(e,t){let n=wr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await T0("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:nt(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function L0(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,i=n.direction==="higher"?r>0:n.direction==="lower"?r<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:r,improved:i,sample_count:e.length}}async function my(e,t={}){let n=I(process.cwd(),t.path);await F(n);let r=await R(n),i=await R0(n,r,e),s=dy.join(n,"improvement-ledger.json"),a=await Yt({pmRoot:n,filePath:s,op:"improvement_observe",author:i.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${i.metric}=${String(e.value)} improvement observation`,mutate:o=>{let c=wc(o),d=O0(c,i);return d?{raw:o,result:d}:(c.observations.push(i),c.observations.sort((l,u)=>l.observed_at.localeCompare(u.observed_at)||l.metric.localeCompare(u.metric)||l.id.localeCompare(u.id)),{raw:`${J(c)}
25
+ `,result:i})}});return{changed:a.changed,observation:a.result,ledger_path:"improvement-ledger.json"}}async function fy(e={}){let t=I(e.cwd??process.cwd(),e.pmRoot);await F(t);let n=e.metric===void 0?void 0:ly(e.metric),r=e.since===void 0?void 0:uy(e.since,"since"),i=I0(e.limit),a=wc(await ne(dy.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),o=new Map;for(let c of a){let d=o.get(c.metric)??[];d.push(c),o.set(c.metric,d)}return{observations:[...a].reverse().slice(0,i),total:a.length,truncated:a.length>i,trends:[...o].map(([,c])=>L0(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]="6162845d-f4b4-5d1f-a210-ddef1a5c38f6")}catch{}})();function D0(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 M0(e,t,n){let r=t,i=new Set([e.id]);for(;r!==void 0&&!i.has(r.id);)i.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function P0(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,i)=>r.entries[0].ts.localeCompare(i.entries[0].ts)||r.id.localeCompare(i.id)),t.push(...n.map(r=>r.children))}}function py(e=Rn,t=In){return t.map(n=>{let r=e.filter(i=>((n==="model"?i.model_environment_keys:i.provenance_environment_keys?.[n])?.length??0)>0||i.provenance_resolvers?.[n]!==void 0).map(i=>i.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function Jz(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let i=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};i.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?i.observed+=1:r.agent_provenance?.model===null?i.unavailable+=1:i.legacy_missing+=1,n.set(r.agent_harness,i)}return[...n.values()].map(r=>{let i=r.observed+r.unavailable;return{...r,coverage:i===0?null:r.observed/i,inert:i>=t&&r.observed===0}}).sort((r,i)=>r.harness.localeCompare(i.harness))}function _y(e,t=In,n=1){let r=new Map;for(let i of e)if(i.agent_harness)for(let s of t){let a=`${i.agent_harness}\0${s}`,o=r.get(a)??{harness:i.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1;let c=i.agent_provenance?.[s];c!=null&&c.value.length>0?o.observed+=1:c===null?o.unavailable+=1:o.legacy_missing+=1,r.set(a,o)}return[...r.values()].map(i=>{let s=i.observed+i.unavailable;return{...i,coverage:s===0?null:i.observed/s,inert:s>=n&&i.observed===0}}).sort((i,s)=>i.harness.localeCompare(s.harness)||i.dimension.localeCompare(s.dimension))}function Qz(e,t={}){let n=t.minimumCoverage??.8,r=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(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let i=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=i.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let m=c.agent_provenance?.[d];m?.value&&(u.observed+=1,u.by_source[m.source]=(u.by_source[m.source]??0)+1),i.set(l,u)}let s=[...i.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)),a=s.filter(c=>c.entries>=r),o=a.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:a.length>0&&o.length===0,minimum_coverage:n,minimum_entries:r,rows:s,failures:o}}function Zz(e){let t=[...e].sort((s,a)=>s.ts.localeCompare(a.ts)||s.author.localeCompare(a.author)||s.op.localeCompare(a.op)||s.before_hash.localeCompare(a.before_hash)||s.after_hash.localeCompare(a.after_hash)),n=new Map,r=new Map;for(let s of t){let a=s.agent_episode,o=D0(s),c=`${o.source}:${o.id}`,d=n.get(c);if(d){d.entries.push(s);continue}let l={id:o.id,...a?.label===void 0?{}:{label:a.label},...a?.parent_id===void 0?{}:{parent_id:a.parent_id},source:o.source,entries:[s],children:[]};n.set(c,l),a!==void 0&&r.set(o.id,l)}let i=[];for(let s of n.values()){let a=s.parent_id?r.get(s.parent_id):void 0;a&&M0(s,a,r)?a.children.push(s):i.push(s)}return P0(i),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]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var F0=1e4,gy=1e5,$0=1e3,U0=30,j0=["append","comment","docs","file","learning","note","test_run"];function G0(e){let t=e??F0;if(!Number.isSafeInteger(t)||t<1||t>gy)throw new p(`History analytics event limit must be an integer from 1 to ${gy}.`,f.USAGE,{code:"invalid_history_analytics_limit"});return t}function hy(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.",f.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function q0(e){let t=e?.trim();if(!t)return new Date(Date.now()-U0*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let i=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(i)||i<1)throw new p("History analytics --since duration must be positive.",f.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-i*s).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new p("History analytics --since must be an ISO timestamp or negative duration such as -30d.",f.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function Cs(e,t){let n=G0(t.eventLimit),r=q0(t.since),i=[],s=r,a=!1;for(;i.length<n;){let o=await Jm({pmRoot:e,since:s,limit:Math.min($0,n-i.length),full:!0}),c=o.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(i.push(...c),a=o.has_more,s=o.next_cursor,!o.has_more)break}return{events:i,receipt:{since:r,events:i.length,truncated:a,...a?{next_cursor:s}:{},source:"history_event_index"}}}function K0(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function z0(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 W0(e){return j0.some(t=>e.startsWith(t))}function yy(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function B0(e,t,n){let r=new Map,i=new Map,s=new Map;for(let a of t){let o=K0(a.entry,e),c=z0(a.entry),d=i.get(a.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&i.set(a.item_id,l),!o)continue;let u=yy(r,o);u.events+=1,W0(a.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,s.set(a.item_id,o)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:r,lastCloseValue:s}}function V0(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let i=new Set((r.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of i){let a=t.get(s);a&&(yy(e,a).defectEscapes+=1)}}}function H0(e,t,n,r){let i=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:i==="available"?t.closes/r:null,rework_rate:i==="available"?t.reopens/t.closes:null,defect_escape_rate:i==="available"?t.defectEscapes/t.closes:null,sample_status:i}}function Y0(e,t,n,r,i,s){let{buckets:a,lastCloseValue:o}=B0(e,t,r);return V0(a,o,n),{dimension:e,status:a.size===0?"unavailable":"available",rows:[...a].map(([c,d])=>H0(c,d,i,s)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function X0(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,i=Date.parse(n),s=Date.parse(r);return!Number.isFinite(i)||!Number.isFinite(s)?1:Math.max(1,(s-i)/864e5)}function J0(e,t,n){let r=py(t),i=_y(e,In,n),s=i.filter(o=>o.inert).map(o=>({harness:o.harness,dimension:o.dimension,explicit_samples:o.observed+o.unavailable})),a=r.filter(o=>!o.covered).map(o=>o.dimension);return{descriptors:r,observations:i,inert:s,undeclared:a,warnings:[...s.map(o=>`provenance_dimension_inert:${o.harness}:${o.dimension}:${String(o.explicit_samples)}`),...a.map(o=>`provenance_dimension_undeclared:${o}`)]}}async function aW(e,t=Rn,n={}){return vc(await Cs(e,n),t,n)}function vc(e,t=Rn,n={}){let r=hy(n.minimumSample);return{...J0(e.events.map(i=>i.entry),t,r),window:e.receipt}}async function oW(e,t,n,r={}){return bc(await Cs(e,r),t,n,r)}function bc(e,t,n,r={}){let i=hy(r.minimumSample),s=X0(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(a=>Y0(a,e.events,t,n,i,s)),minimum_sample:i,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]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var Q0=32;function Z0(e){let t=[];for(let n of e??[]){let r=[];for(let i of n.split(",")){let s=i.slice(0,i.indexOf("=")).trim();r.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(i)}t.push(r.join(","))}return t}function vr(e,t){let n=Z0(e).map(i=>{let[s,...a]=i.split(","),o=s.indexOf("="),c=s.slice(0,o).trim(),d=s.slice(o+1).trim(),l=Number(d);if(o<=0||c.length===0||d.length===0||!Number.isFinite(l))throw new p(`Invalid --measure "${i}"; expected name=value[,unit=...][,threshold=...]`,f.USAGE);let u,m;for(let _ of a){let g=_.indexOf("="),h=_.slice(0,g).trim(),y=_.slice(g+1).trim();if(h==="unit"&&y.length>0)u=y;else if(h==="threshold"&&y.length>0&&Number.isFinite(Number(y)))m=Number(y);else throw new p(`Invalid --measure attribute "${_}"`,f.USAGE)}return{name:c,value:l,unit:u,threshold:m,recorded_at:t}});return[...new Map(n.map(i=>[i.name,i])).values()].sort((i,s)=>i.name.localeCompare(s.name)).slice(0,Q0)}function wy(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(i=>i.name===t&&i.value<n).map(i=>({...i,run_id:r.run_id})))}function vy(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,a)=>a.recorded_at.localeCompare(s.recorded_at)),r=n[0],i=n[1];return{name:t,latest:r?.value??null,previous:i?.value??null,delta:r!==void 0&&i!==void 0?r.value-i.value:null,unit:r?.unit}}import tN from"node:fs/promises";import ky 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]="ed44fc89-8b6e-5c83-a4f4-ced4e9031dac")}catch{}})();function Is(e,t,n,r,i,s="min"){let a=i==="min"?e-t:t-e,o=s==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return a<0||a===0&&r!==null&&o<0}function eN(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,i=null,s=null,a=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;r+=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,m=Date.parse(u);Number.isNaN(m)||(Is(m,a,u,i,"min")&&(a=m,i=u),Is(m,o,u,s,"max","max")&&(o=m,s=u))}return{id:e,bytes:n,lines:r,oldest_ts:i,newest_ts:s}}function by(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),i=e.map(({id:_,raw:g})=>eN(_,g)),s=0,a=0,o=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let _ of i){if(s+=_.lines,a+=_.bytes,_.oldest_ts!==null){let g=Date.parse(_.oldest_ts);Is(g,d,_.id,o?.id??null,"min")&&(d=g,o={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let g=Date.parse(_.newest_ts);Is(g,l,_.id,c?.id??null,"max")&&(l=g,c={id:_.id,ts:_.newest_ts})}}let u=r===0?[]:[...i].sort((_,g)=>g.bytes-_.bytes||_.id.localeCompare(g.id)).slice(0,r),m=r===0?[]:[...i].sort((_,g)=>g.lines-_.lines||_.id.localeCompare(g.id)).slice(0,r);return{total_streams:e.length,total_lines:s,total_bytes:a,largest_by_bytes:u,deepest_by_lines:m,oldest_entry:o,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]="b56db1fc-d989-5d18-8b29-336a03f1e525")}catch{}})();function nN(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function rN(e,t,n,r,i){let s=Fn(e,"type",r),a=new Set(s.rows.map(m=>m.key)),o=t.filter(m=>!a.has(m)),d=(i?[...s.rows,...o.map(m=>({label:m,key:m,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(m=>({type:m.key??m.label,total:m.total,open:m.buckets.open,in_progress:m.buckets.in_progress,blocked:m.buckets.blocked,draft:m.buckets.draft,closed:m.buckets.closed,canceled:m.buckets.canceled,other:m.buckets.other})),l=nN([...n]);for(let m of e)l[m.status]+=1;let u=Object.fromEntries(Object.entries(l).filter(([,m])=>i||m>0));return{byType:d,byStatus:u,omitted:i?0:o.length+Object.values(l).filter(m=>m===0).length}}function iN(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function sN(e){let t=ky.join(e,"history");if(!await z(t))return[];await Me({path:t,scope:"project"});let n=(await tN.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,s)=>i.localeCompare(s)),r=[];for(let i of n){let s=ky.join(t,i),a=await ne(s);a!==null&&(await Me({path:s,scope:"project"}),r.push({id:i.slice(0,-6),raw:a}))}return r}async function aN(e,t){let n=[],r=x();for(let i of vr(t.observe,r))n.push(await my({metric:i.name,value:i.value,direction:t.direction,unit:i.unit,threshold:i.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function oN(e,t,n){let r={};return t.byAssignee&&(r.assignee=Fn(e,"assignee",n)),t.byTag&&(r.tag=Fn(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=Fn(e,"priority",n)),r}async function cN(e,t,n,r,i){let s={since:i.since,eventLimit:i.eventLimit,minimumSample:i.minimumSample},a=i.provenanceCoverage||i.fleetAttribution?await Cs(e,s):void 0;return{provenanceCoverage:i.provenanceCoverage&&a?vc(a,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:i.fleetAttribution&&a?bc(a,t,r,s):void 0}}function dN(e,t,n,r,i){let s=Object.keys(i.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...i.metadataCoverage?{metadata_coverage:i.metadataCoverage}:{},...s?{breakdowns:i.breakdowns}:{},...i.storage?{storage:i.storage}:{},...i.fieldUtilization?{field_utilization:i.fieldUtilization}:{},...i.improvementLedger?{improvement_ledger:i.improvementLedger}:{},...i.recordedObservations.length>0?{recorded_observations:i.recordedObservations}:{},...i.provenanceCoverage?{provenance_coverage:i.provenanceCoverage}:{},...i.fleetAttribution?{fleet_attribution:i.fleetAttribution}:{},generated_at:x()}}async function RW(e,t={}){let n=I(process.cwd(),e.path);await F(n);let r=await R(n),i=await aN(e,t),s=U(r,P()),a=X(r.schema),o=t.fieldUtilization?await Qt(n,r.item_format,s.type_to_folder,void 0,r.schema):await ve(n,r.item_format,s.type_to_folder,void 0,r.schema);await Wr({pmRoot:n,settings:r,itemIds:o.map(E=>E.id),commandLabel:"stats"});let c=qm(a),d=rN(o,s.types,a.definitions.map(E=>E.id),c,t.includeEmpty===!0),l=await sN(n),u=0;for(let E of l)u+=iN(E.raw);let m=t.storage?by(l):void 0,_=t.metadataCoverage?Km(o,c):void 0,g=oN(o,t,c),h=t.fieldUtilization?zm(o):void 0,y=t.measurements===!0||i.length>0?await fy({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:b}=await cN(n,o,r,a.terminal_statuses,t);return dN({items:o.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:_,breakdowns:g,storage:m,fieldUtilization:h,improvementLedger:y,recordedObservations:i,provenanceCoverage:w,fleetAttribution: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]="6152efa9-8338-57f0-b3de-5707befed019")}catch{}})();async function DW(e,t={}){let n=await Tg({pmRoot:I(process.cwd(),e.path),...t.status===void 0?{}:{statuses:t.status.flatMap(r=>r.split(",").map(i=>i.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(r=>{let i=r.id;return{...r,canonical_id:i,close_command:`pm close <duplicate-id> --duplicate-of ${i}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import lN from"node:fs/promises";import Et 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]="ad3110ca-e85b-5a7e-b0a1-591796c298eb")}catch{}})();var Ay=Et.join("runtime","telemetry","events.jsonl"),Cy=Et.join("runtime","telemetry","state.json"),uN=Et.join("runtime","telemetry"),mN=20,Ey=["status","flush","stats","clear"],Sy=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},kc=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Ty=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},fN=e=>({command:kc(e.event.command,"<unknown>"),eventType:kc(e.event.event_type,"unknown"),eventSchemaVersion:Ty(e.event.schema_version),clientSchemaVersion:Ty(e.client_schema_version)}),pN=()=>({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:{}}),_N=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},gN=e=>{let t=e?.command_resolution;return kc(t,"")||void 0},Iy=(e,t)=>{e[t]=(e[t]??0)+1},hN=(e,t)=>{let n=_N(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=gN(t);r!==void 0&&Iy(e.resolution_counts,r)},yN=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,xy=(e,t)=>{t!==void 0&&e.add(t)},wN=(e,t)=>{let n=fN(t),r=e.get(n.command)??pN();r.count+=1,r.max_attempts=Math.max(r.max_attempts,yN(t.attempts)),Iy(r.event_type_counts,n.eventType),xy(r.event_schema_versions,n.eventSchemaVersion),xy(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&hN(r,t.event.payload),e.set(n.command,r)},vN=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((s,a)=>s-a),i=Object.entries(t.resolution_counts).sort((s,a)=>s[0].localeCompare(a[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,a)=>s[0].localeCompare(a[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,a)=>s-a),client_schema_versions:[...t.client_schema_versions].sort((s,a)=>s-a),...r.length>0?{duration_p50_ms:Sy(r,.5),duration_p95_ms:Sy(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...i.length>0?{command_resolution_counts:Object.fromEntries(i)}:{}}},bN=e=>{let t=(e??"status").trim().toLowerCase();if(Ey.includes(t))return t;throw Rr({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Ey,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Ec=()=>{throw new p("--limit must be a positive integer",f.USAGE)},Ry=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Ec():e,kN=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Ec():Ry(Number.parseInt(t,10))},EN=e=>e===void 0?mN:typeof e=="number"?Ry(e):typeof e=="string"?kN(e):Ec(),SN=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},TN=e=>{try{let t=JSON.parse(e);return SN(t)?t:void 0}catch{return}},xN=e=>e===null?[]:e.split(`
26
+ `).map(t=>t.trim()).filter(t=>t.length>0),Oy=e=>{let t=xN(e),n=[],r=0;for(let i of t){let s=TN(i);s===void 0?r+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},AN=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),CN=e=>{try{let t=JSON.parse(e);return AN(t)?t:{}}catch{return{}}},IN=async e=>{let t=await ne(e);return t===null||t.trim().length===0?{}:CN(t)},Rs=e=>e??null,Os=async e=>{let t=await R(e),n=Et.join(e,Ay),r=Et.join(e,Cy),i=await ne(n),s=Oy(i),a=await IN(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(i??"","utf8"),last_attempted_flush_at:Rs(a.last_attempted_flush_at),last_successful_flush_at:Rs(a.last_successful_flush_at),last_failed_flush_at:Rs(a.last_failed_flush_at),last_failed_flush_error:Rs(a.last_failed_flush_error)}},RN=e=>{let t=new Map;for(let n of e)wN(t,n);return[...t.entries()].map(([n,r])=>vN(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},ON=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Os(t.globalPmRoot),generated_at:x()}),NN=async(e,t)=>{let n=await Os(t.globalPmRoot);await Wl(t.globalPmRoot);let r=await Os(t.globalPmRoot),i=Math.max(0,n.queue_entries-r.queue_entries),s=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:i,queue_progressed:i>0,queue_empty:s,queue_drained:s,status:r,generated_at:x()}},LN=async(e,t)=>{let n=EN(e.limit),r=await ne(t.queuePath),i=Oy(r),s=RN(i.entries),a=s.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_rows_total:i.rows_total,truncated:s.length>a.length,stats:a,generated_at:x()}},DN=async(e,t)=>{let n=await R(t.globalPmRoot),r=[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="",r&&await Al(t.globalPmRoot,n,"telemetry:clear");let i=Et.join(t.globalPmRoot,uN),s=await z(i);return await lN.rm(i,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:s&&!await z(i),queue_exists_after:await z(t.queuePath),state_exists_after:await z(t.statePath),status:await Os(t.globalPmRoot),generated_at:x()}},MN={status:ON,flush:NN,stats:LN,clear:DN};async function BW(e,t){let n=bN(e.subcommand),r=We(process.cwd());return MN[n](e,{globalPmRoot:r,queuePath:Et.join(r,Ay),statePath:Et.join(r,Cy)})}import{spawn as Yy}from"node:child_process";import{cp as Ac,mkdir as Ms,mkdtemp as Xy,open as Cc,readdir as Ic,rm as Nc,symlink as Jy}from"node:fs/promises";import{tmpdir as Qy}from"node:os";import V 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]="62af7c1e-c1c7-529e-ab30-117103ac4607")}catch{}})();var Ny=20;function PN(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return Ny;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?Ny:t}function Sc(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,i)=>{let s=md(r.recorded_at,i.recorded_at);if(s!==0)return s;let a=r.run_id.localeCompare(i.run_id);return a!==0?a:r.kind.localeCompare(i.kind)}),n=PN();return t.length>n?t.slice(t.length-n):t}async function Ns(e){await ce({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=Sc([...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]="8a6a3402-dae3-56f8-b9ba-a4f6f8a47cda")}catch{}})();var Ly=100;function Tc(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.`,f.USAGE);return n}function FN(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Ly?n:`${n.slice(0,Ly-3)}...`}function Dy(e){return e.map((t,n)=>`${n+1}. ${FN(t)}`).join("; ")}function $N(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 UN(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function My(e,t){let n=$N(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((i,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(i=>`--${i}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,f.USAGE);let r=n[0];if(e.length===0)throw new p(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,f.USAGE);if(r==="match"){let i=t.match.trim().toLowerCase();if(i.length===0)throw new p("--match requires a non-empty substring to match against linked-test command/path values",f.USAGE);let s=[],a=[];for(let o=0;o<e.length;o+=1)UN(e[o],i)&&(a.push(e[o]),s.push(o+1));if(a.length===0)throw new p(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Dy(e)}`,f.USAGE);return{selector:"match",requested:t.match,selected:a,selected_indexes:s,selected_count:a.length,skipped_count:e.length-a.length}}if(r==="only-index"){let i=Tc(t.onlyIndex);if(i>e.length)throw new p(`--only-index ${i} is out of range: this item has ${e.length} linked test(s). Available entries: ${Dy(e)}`,f.USAGE);return{selector:"only-index",requested:String(i),selected:[e[i-1]],selected_indexes:[i],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]="7659721c-21f5-55da-8cce-31b290de5bfb")}catch{}})();var Ds=20*1024*1024,jN=3e3,GN=1e4,qN=5e3,Py=120,KN=new Set(["locks","extensions","runtime"]),zN=new Set(["history","index","search","extensions","locks","runtime"]),WN=[/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],BN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,VN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,HN=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 Lc(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function YN(){return Lc("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",jN)}function XN(){return Lc("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",GN)}function JN(){return Lc("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",qN)}function QN(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 ZN(e){let t=0,n=0,r=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function Dc(e){let t=0,n=0,r=0,i=0;for(let s of e){let a=s.execution_context;!a||a.is_pm_command!==!0||(t+=1,a.is_pm_tracker_read_command===!0&&(n+=1),a.mismatch_detected===!0&&(r+=1),a.auto_pm_context_applied===!0&&(i+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:i}}function eL(e){let t=e??"project";if(!De.includes(t))throw new p(`Invalid scope "${e}"`,f.USAGE);return t}function Ps(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Dt.includes(t))return t;throw new p(`Invalid --pm-context value "${e}". Expected one of: ${Dt.join(", ")}`,f.USAGE)}function tL(e){return Pt(e??"source","--workspace-context")}function Zy(e,t,n){return n?t:Pt(e.workspace_context_mode,"linked test")??t}function ew(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Ps(e.pm_context_mode)}function tw(e,t){return e==="auto"?t?"tracker":"schema":e}function nL(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 rL(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="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 iL(e,t){let n={};if(!e)return n;for(let r of e){let i=dr(r,t);if(i)for(let[s,a]of Object.entries(i))n[s]=a}return n}function sL(e,t){if(!e)return[];let n=[];for(let r of e){let i=lr(r,t);i&&n.push(...i)}return[...new Set(n)]}function aL(e){let t=Fs(e);return un(t).some(n=>Ii(n)!==null)}function nw(e){let t=Fs(e);return un(t).some(n=>{let r=Ii(n);if(!r)return!1;let i=go(r);return i?HN.has(i.subcommand):!1})}function Ls(e){if(e)return Ip.has(e.subcommand)?ht(e.args,Rp)?.subcommand:e.subcommand}function Fy(e,t){if(e==="npx"||e==="bunx")return It(t)?.command;if(e==="pnpm")return Ls(ht(t,mo));if(e==="npm")return Ls(ht(t,fo));if(e==="yarn")return Ls(ht(t,Ap));if(e==="bun")return Ls(ht(t,Cp))}function $y(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function xc(e){return!e||!Qn(e.command)&&!_o(e.command)?!1:Oi(e.args)==="test-all"}var oL=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])]),cL=new Set(["npx","bunx"]);function rw(e){let t=e.split(" ").filter(a=>a.length>0),n=Ri(t);if(n.length===0)return!1;let[r,...i]=n,s=oL.get(r);if(s){let a=i.findIndex(o=>s.test(o));return a>=0?rw(i.slice(a+1).join(" ")):!1}return Qn(r)||Zn(r)?Oi(i)==="test-all":r==="node"&&i.length>0&&Zn(i[0])?Oi(i.slice(1))==="test-all":cL.has(r)?xc(It(i)):r==="pnpm"?xc(Ni(i)):r==="npm"?xc(Li(i)):!1}function iw(e){let t=Fs(e);return un(t).some(n=>rw(n))}function sw(e){if(iw(e))throw new p('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',f.USAGE)}function Fs(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function dL(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 lL(e){let t=/\bpm_path\s*=/.test(e)||/\$env:pm_path\s*=/.test(e),n=/\bpm_global_path\s*=/.test(e)||/\$env:pm_global_path\s*=/.test(e);return t&&n}function uL(e){let t=e.split(" ").filter(s=>s.length>0),n=Ri(t);if(n.length===0)return!1;let[r,...i]=n;return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?mL(i):fL(r,i)}function mL(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function fL(e,t){return e==="npx"||e==="bunx"?$y(It(t)?.command):e==="pnpm"||e==="npm"?$y((e==="pnpm"?Ni(t):Li(t))?.command)||Fy(e,t)==="vitest":(e==="yarn"||e==="bun")&&Fy(e,t)==="vitest"}function aw(e){let t=Fs(e);if(un(t).some(i=>!dL(i)&&uL(i)&&!lL(i)))throw new p('Linked test runner commands must be sandbox-safe: use "node scripts/run-tests.mjs <test|coverage>", use a package-manager script such as "pnpm test", or include PM_PATH=... PM_GLOBAL_PATH=... INLINE in the command string (exporting them in your shell environment is not checked). Example: "PM_PATH=/tmp/pm-x PM_GLOBAL_PATH=/tmp/pm-x-g vitest run".',f.USAGE)}function pL(e){if(iw(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function _L(e){return e?e.map(gL):[]}function gL(e){let t=e.trim(),n=Wi(t)?Bi(Q(e,"--add"),"--add"):{command:t},r=fe(n.command);if(!r)throw new p("--add requires command=<value> or a bare command (path=<value> is optional metadata)",f.USAGE);return sw(r),aw(r),{command:r,path:fe(n.path),scope:eL(n.scope),timeout_seconds:hL(fe(n.timeout_seconds),fe(n.timeout)),pm_context_mode:Ji(fe(n.pm_context_mode),"--add"),workspace_context_mode:Pt(fe(n.workspace_context_mode),"--add"),env_set:dr(fe(n.env_set),"--add"),env_clear:lr(fe(n.env_clear),"--add"),shared_host_safe:Xi(fe(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Ft(fe(n.assert_stdout_contains)),assert_stdout_regex:_n(fe(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Ft(fe(n.assert_stderr_contains)),assert_stderr_regex:_n(fe(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Qi(fe(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Zi(fe(n.assert_json_field_equals),"--add"),assert_json_field_gte:es(fe(n.assert_json_field_gte),"--add"),note:fe(n.note)}}function fe(e){let t=e?.trim();return t&&t.length>0?t:void 0}function hL(e,t){if(e&&t&&e!==t)throw new p("--add timeout and timeout_seconds must match when both are provided",f.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(me(n,"timeout_seconds"));if(r<=0)throw new p("--add timeout_seconds must be a positive integer",f.USAGE);return r}function yL(e){return e?e.flatMap(t=>{let n=Cg(t,"--add-json");for(let r of n){let i=r.command;if(!i)throw new p("--add-json requires a non-empty command string",f.USAGE);sw(i),aw(i)}return n}):[]}function wL(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires command or path value",f.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let i=n.slice(r[0].length).trim();if(!i)throw new p("--remove requires a non-empty command=<value> or path=<value>",f.USAGE);return{kind:r[1].toLowerCase(),value:i}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new p("--remove structured selectors require command=<value> or path=<value>",f.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let i=Q(n,"--remove"),s=i.path!==void 0?"path":"command",a=i.path??i.command;if(!a?.trim())throw new p("--remove requires command=<value> and/or path=<value>",f.USAGE);return{kind:s,value:a.trim()}}return{kind:"either",value:n}}):[]}function vL(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",f.USAGE);return n}))]:[]}function bL(e){try{e.stdin?.end()}catch{}}function ow(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=Py?t:`${t.slice(0,Py-3)}...`}function cw(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Rc(e){try{process.stderr.write(`${e}
27
+ `)}catch{}}function kL(e,t){if(!cw(t))return null;let n=ow(e.command),r=Date.now();Rc(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let i=setInterval(()=>{let s=Date.now()-r;Rc(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},XN());return i.unref?.(),i}function EL(e,t,n,r){if(!cw(r))return;let i=ow(e.command),s=Date.now()-n,o=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(" ")}`:"";Rc(`[pm test] linked-test ${e.index}/${e.total} end status=${o} exit_code=${d} elapsed_ms=${s}${l} command="${i}"`)}async function Uy(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Yy("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 SL(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function TL(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await Uy(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{Uy(r)},YN()),t.forceKillTimer.unref?.()}}function xL(e){return new Promise(t=>{let n=!1,r=null,i=(s,a=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),a&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,a)=>{n||(r=setTimeout(()=>{i({code:s,signal:a},!0)},JN()),r.unref?.())}),e.on("close",(s,a)=>{i({code:s,signal:a})})})}function AL(e,t,n,r,i){return Yy(e,{cwd:i,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function jy(e){let t=await Cc(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,Ds),i=Buffer.alloc(r);return r>0&&await t.read(i,0,r,0),{text:i.toString("utf8"),truncated:n>Ds}}finally{await t.close()}}async function CL(e,t,n,r,i,s=process.cwd()){let a=Date.now(),o=await Xy(V.join(Qy(),"pm-linked-test-output-"));try{let c=V.join(o,"stdout.log"),d=V.join(o,"stderr.log"),[l,u]=await Promise.all([Cc(c,"w"),Cc(d,"w")]),m;try{m=AL(e,n,l.fd,u.fd,s)}finally{await Promise.all([l.close(),u.close()])}bL(m);let _={heartbeat:kL(r,i),forceKillTimer:null,timedOutTimer:null},g=TL(m,_),h=!1,y;m.on("error",A=>{y=A.message}),_.timedOutTimer=setTimeout(()=>{h=!0,g()},t),_.timedOutTimer.unref?.();let{code:w,signal:b}=await xL(m);SL(_);let[E,v]=await Promise.all([jy(c),jy(d)]),T=E.truncated||v.truncated,k=T?`
28
+ [pm linked-test output truncated at ${Ds} bytes per stream; the child process continued to completion]
29
+ `:"",S={stdout:`${E.text}${k}`,stderr:v.text,exitCode:w,signal:b,timedOut:h,maxBufferExceeded:!1,outputTruncated:T,spawnError:y};return EL(r,S,a,i),S}finally{await Nc(o,{recursive:!0,force:!0})}}function IL(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Ds} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,i=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?i:`${i} ${n.join(" ")}`}function RL(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
30
+ `);return WN.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>BN.test(n)&&VN.test(n))}function OL(e){return RL(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function NL(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function $s(e){let t=NL();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function Gy(e,t){for(let[n,r]of Object.entries(t.env_set))Mt.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)Mt.has(n.toUpperCase())||delete e[n]}function LL(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 DL(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],i=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:i}}function ML(e,t,n){return{env_set:iL(e,"--env-set"),env_clear:sL(t,"--env-clear"),shared_host_safe:n===!0}}async function vn(e,t,n=!1,r=Ms){if(await z(e))try{await Es("seed_linked_test",async()=>{if(await r(V.dirname(t),{recursive:!0}),n){await Ac(e,t,{recursive:!0,force:!0});return}await Ac(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(i){if(typeof i=="object"&&i!==null&&"code"in i&&$(i))return;throw i}}async function qy(e,t,n){await vn(je(n.projectPmRoot),je(e)),await vn(V.join(n.projectPmRoot,"extensions"),V.join(e,"extensions"),!0),await vn(je(n.globalPmRoot),je(t)),await vn(V.join(n.globalPmRoot,"extensions"),V.join(t,"extensions"),!0)}async function Ky(e,t){if(!await z(e))return;let n=await Ic(e,{withFileTypes:!0});for(let r of n){if(KN.has(r.name))continue;let i=V.join(e,r.name),s=V.join(t,r.name);if(r.isDirectory()){await vn(i,s,!0);continue}r.isFile()&&await vn(i,s)}}async function wn(e){if(!await z(e))return 0;let t=0,n=await Ic(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||zN.has(r.name))continue;let i=V.join(e,r.name),s;try{s=await Ic(i,{withFileTypes:!0})}catch{continue}for(let a of s)a.isFile()&&xt.some(o=>a.name.toLowerCase().endsWith(o))&&(t+=1)}return t}function PL(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function FL(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let r of n){if(r.startsWith("[")&&r.endsWith("]")){let i=Number.parseInt(r.slice(1,-1),10);if(!Number.isInteger(i)||i<0)return[];t.push(i);continue}t.push(r)}return t}function zy(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=FL(n);if(r.length===0)return{found:!1,value:void 0};let i=e;for(let s of r){if(typeof s=="number"){if(!Array.isArray(i)||s>=i.length)return{found:!1,value:void 0};i=i[s];continue}if(typeof i!="object"||i===null||!Object.prototype.hasOwnProperty.call(i,s))return{found:!1,value:void 0};i=i[s]}return{found:!0,value:i}}function $L(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 UL(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?rt(e,t):Object.is(e,t)}function jL(e,t,n){let r=[];r.push(...Wy("stdout",t,e.assert_stdout_contains)),r.push(...By("stdout",t,e.assert_stdout_regex)),r.push(...Wy("stderr",n,e.assert_stderr_contains)),r.push(...By("stderr",n,e.assert_stderr_regex)),r.push(...GL(t,e.assert_stdout_min_lines));let i=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(i).length>0||Object.keys(s).length>0))return r;let o;try{o=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,d]of Object.entries(i)){let l=zy(o,c);if(!l.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let u=$L(d);UL(l.value,u)||r.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=zy(o,c);if(!l.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof l.value!="number"||!Number.isFinite(l.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}l.value<d&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${d}, actual ${l.value})`)}return r}function Wy(e,t,n){let r=[];for(let i of n??[])t.includes(i)||r.push(`${e} missing required text: "${i}"`);return r}function By(e,t,n){let r=[];for(let i of n??[])try{new RegExp(i,"m").test(t)||r.push(`${e} failed regex assertion: /${i}/m`)}catch(s){r.push(`${e} regex assertion is invalid: /${i}/ (${s instanceof Error?s.message:String(s)})`)}return r}function GL(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var qL=[{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}];function KL(e,t){let n=`${e}
31
+ ${t}`;for(let r of qL)if(r.regex.test(n))return r.code;return null}function zL(e){return{root:e,schemaProjectPmPath:V.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:V.join(e,"schema","global"),trackerProjectPmPath:V.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:V.join(e,"tracker","global"),workspaceSnapshotRoot:V.join(e,"workspace","project"),workspaceIsolatedRoot:V.join(e,"workspace","isolated")}}function WL(e,t,n){return e.some(r=>Zy(r,t,n)==="snapshot")}async function BL(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await Ms(V.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await Ac(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(i){let s=V.relative(t,i);return s?!s.split(V.sep).some(a=>n.has(a)):!0}});let r=V.join(t,"node_modules");await z(r)&&await Jy(r,V.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function VL(e,t){let n=V.join(e,".agents"),r=V.join(n,"pm");await Ms(n,{recursive:!0}),await Nc(r,{recursive:!0,force:!0}),await Jy(t,r,process.platform==="win32"?"junction":"dir")}async function HL(e,t=xa,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function YL(e,t,n){t&&(await qy(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await qy(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Ky(t.projectPmRoot,e.trackerProjectPmPath),await Ky(t.globalPmRoot,e.trackerGlobalPmPath)))}function XL(e,t,n){return e.some(r=>{let i=r.command??"",s=i.length>0&&nw(i),a=n?.autoPmContext===!0&&s?"auto":ew(r,t,n?.overrideLinkedPmContext===!0);return tw(a,s)==="tracker"})}async function JL(e,t){return{sourceProjectItemCount:t?await wn(t.projectPmRoot):0,sourceGlobalItemCount:t?await wn(t.globalPmRoot):0,schemaProjectItemCount:await wn(e.schemaProjectPmPath),schemaGlobalItemCount:await wn(e.schemaGlobalPmPath),trackerProjectItemCount:await wn(e.trackerProjectPmPath),trackerGlobalItemCount:await wn(e.trackerGlobalPmPath)}}function QL(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,i=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,a=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,o=e.workspaceContextMode==="isolated"?"":a;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:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:i,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==i||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:a,source_workspace_root:o,trust:e.trust}}async function ZL(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Ps(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?aL(n):!1,i=r&&n?nw(n):!1,s=e.options?.autoPmContext===!0&&i,a=s?"auto":ew(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),o=tw(a,i),c=o==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await VL(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await vo(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await vo(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:QL({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:i,requestedPmContextMode:a,effectivePmContextMode:o,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function Vy(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Oc(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function eD(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 tD(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 r=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 eD(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"}). ${r}`)}function nD(e){if(!e.linkedTest.command)return Vy(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=pL(e.linkedTest.command);return t?Vy(e.linkedTest,e.executionContext,t):null}function rD(e){let t=nD(e);if(t)return t;let n=tD(e);if(n)return n;let r=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,i=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(r||i){let s=rL({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),a=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Oc(e.linkedTest,e.executionContext,`${a} (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&&!nL(e.linkedTest)?Oc(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function iD(e){let t=DL(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return Gy(n,e.runtimeDirectives),Gy(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&LL(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[Pn]):(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[Pn]="read_only"),n}function sD(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 aD(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}) while --fail-on-empty-test-run is enabled. Update test selection or disable --fail-on-empty-test-run for this run.`}}function oD(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:PL(e.execution),failure_category:OL(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:IL(e.execution,e.timeoutMs)}}function cD(e){if(e.options?.failOnEmptyTestRun===!0){let n=KL(e.execution.stdout,e.execution.stderr);if(n)return aD({...e,emptyRunSignal:n})}let t=jL(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Oc(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):sD(e.linkedTest,e.executionContext,e.execution)}async function dD(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await CL(t,n,iD(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?cD({...e,execution:r}):oD({...e,execution:r,timeoutMs:n})}async function Mc(e,t,n){let r=[],i=await Xy(V.join(Qy(),"pm-linked-test-")),s=zL(i),a=Ps(n?.pmContext),o=tL(n?.workspaceContext),c=n?.progress===!0?"always":"auto",d=ML(n?.envSet,n?.envClear,n?.sharedHostSafe),l=n?.sourceRoots,u=nr(),m=XL(e,a,n),_=WL(e,o,n?.overrideLinkedWorkspaceContext===!0),g=await tr(u);try{await HL(s,xa,m),await Ms(s.workspaceIsolatedRoot,{recursive:!0}),await YL(s,l,m),_&&await BL(s,u);let h=await JL(s,l);for(let y=0;y<e.length;y+=1){let w=e[y],b=Zy(w,o,n?.overrideLinkedWorkspaceContext===!0),E=await ZL({linkedTest:w,layout:s,counts:h,sourceRoots:l,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:o,workspaceContextMode:b,currentSourceRef:g,sourceWorkspaceRoot:u}),v=rD({linkedTest:w,executionContext:E.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:E.linkedOverridePmContextMode,options:n});if(v){r.push(v);continue}r.push(await dD({linkedTest:w,index:y,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:d,progressMode:c,executionContext:E.executionContext,options:n}))}}finally{await Nc(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function lD(e){let{id:t,pmRoot:n,settings:r,typeToFolder:i}=e,s=await Z(n,t,r.id_prefix,r.item_format,i);if(!s)throw new p(`Item ${t} not found`,f.NOT_FOUND);let a=await we(s,{schema:r.schema});return{itemId:s.id,tests:a.document.metadata.tests??[],testRuns:a.document.metadata.test_runs??[],changed:!1,removed:0}}function uD(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 mD(e,t){let n=[...e];for(let r of t)n.some(i=>uD(i,r))||n.push(r);return n}function fD(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),i=e.filter((s,a)=>r.has(a+1)?!1:!t.some(o=>o.kind==="command"?s.command===o.value:o.kind==="path"?s.path===o.value:s.command===o.value||s.path===o.value));return{tests:i,removed:e.length-i.length}}function pD(e,t,n,r){return fD(mD(e,t),n,r)}function _D(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 gD(e){if(_D(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",f.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new p("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",f.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",f.USAGE)}async function hD(e){let{id:t,options:n,pmRoot:r,settings:i,typeToFolder:s,adds:a,removes:o,removeIndexes:c}=e;if(a.length===0&&o.length===0&&c.length===0)return lD({id:t,pmRoot:r,settings:i,typeToFolder:s});let d=0,l=await ce({pmRoot:r,settings:i,id:t,op:a.length>0?"tests_add":"tests_remove",author:K(n.author,i.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let m=u.metadata.tests??[],_=pD(m,a,o,c);if(d=_.removed,(o.length>0||c.length>0)&&d===0)throw new p("No linked tests matched the requested removal selector",f.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...o.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=_.tests,{changedFields:rt(m,_.tests)?[]:["tests"]}}});return{itemId:l.item.id,tests:l.item.tests??[],testRuns:l.item.test_runs??[],changed:l.changedFields.length>0,removed:d}}function yD(e,t){gD(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Tc(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?My(t,n):void 0,i=e.timeout===void 0?void 0:me(e.timeout,"timeout");if(i!==void 0&&i<=0)throw new p("Test timeout must be a positive number",f.USAGE);return{defaultTimeoutSeconds:i,pmContextMode:Ps(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function wD(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Mc(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:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:We(process.cwd())}})}function vD(e,t,n){let r=[];if(t&&t.selector!==null&&r.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 i=Dc(n);r.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}`)}return r}function bD(e){let t=ZN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),i=x(),s=vr(e.options.measure,i);return{run_id:QN("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:i,recorded_at:i,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r: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(a=>a.command?.trim()).slice(0,32).map(a=>({command:a.command.trim(),requested_pm_context_mode:a.execution_context?.requested_pm_context_mode,pm_context_mode:a.execution_context?.pm_context_mode,workspace_context_mode:a.execution_context?.workspace_context_mode,trust_reason:a.execution_context?.trust.reason}))}}async function kD(e){let{options:t,pmRoot:n,settings:r,itemId:i,runStartedAt:s,runResults:a,failOnSkippedTriggered:o,warnings:c}=e;if(t.run!==!0||!s)return;let d=bD({options:t,runStartedAt:s,runResults:a,failOnSkippedTriggered:o});if(r.testing.record_results_to_items!==!0)return d;try{return await Ns({pmRoot:n,settings:r,itemId:i,author:K(t.author,r.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),d}catch(l){return c.push(`test_result_tracking_failed:${i}:${l instanceof Error?l.message:String(l)}`),d}}function Hy(e,t,n){let r;if(e.metricBelow!==void 0){let i=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,i).trim(),a=e.metricBelow.slice(i+1).trim(),o=Number(a);if(i<=0||s.length===0||a.length===0||!Number.isFinite(o))throw new p("--metric-below must use name=value",f.USAGE);r=wy(t,s,o)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:vy(t,e.metricDiff)}}async function ED(e,t,n){if(e.acknowledgeLinkedTests===!0)return Pp(t,n,x())}async function dw(e,t,n){let r=Ve(),i=I(process.cwd(),n.path);await F(i);let s=await R(i);if((t.measure?.length??0)>0&&t.run!==!0)throw new p("--measure requires --run",f.USAGE);vr(t.measure,"validation"),Hy(t,[],void 0);let a=U(s,P()),o=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),d=await r.resolveList(t.remove,"--remove"),l=[..._L(o),...yL(c)],u=await mn(l,K(t.author,s.author_default),x())??[],m=wL(d),_=vL(t.removeIndex),g=await hD({id:e,options:t,pmRoot:i,settings:s,typeToFolder:a.type_to_folder,adds:u,removes:m,removeIndexes:_}),h=yD(t,g.tests),y=await ED(t,i,g.tests),w=t.run===!0?x():void 0,b=await wD({options:t,runOptions:h,pmRoot:i,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests}),E=$s(b),v=t.run===!0&&t.failOnSkipped===!0&&b.some(L=>L.status==="skipped"),T=vD(t,h.runSelection,b);y&&T.push(`linked_test_trust_acknowledged:${y.acknowledged}`);let k=await kD({options:t,pmRoot:i,settings:s,itemId:g.itemId,runStartedAt:w,runResults:b,failOnSkippedTriggered:v,warnings:T}),S=k?Sc([...g.testRuns,k]):g.testRuns,A=Hy(t,S,k);return{ok:b.every(L=>L.status!=="failed")&&v!==!0,id:g.itemId,tests:g.tests,run_results:b,failure_categories:E,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:v?!0:void 0,warnings:T.length>0?T:void 0,changed:g.changed,count:g.tests.length,...g.removed>0?{removed:g.removed}:{},...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]="5d3405c0-14e6-51f5-97a1-355438fd0199")}catch{}})();var SD=(e,t)=>{if(e===void 0)return;let n=ae(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,f.USAGE)}return n},TD=e=>{if(e===void 0)return;let t=me(e,"timeout");if(t<=0)throw new p("timeout must be a positive number",f.USAGE);return t},lw=(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`,f.USAGE);return n},xD=e=>e instanceof Error?e.message:String(e),AD=()=>{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)}`},CD=e=>e.trim().replaceAll(/\s+/g," "),ID=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),RD=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),OD=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},ND=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Us=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),uw=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),LD=e=>typeof e=="number"?e:void 0,DD=e=>{let t={assert_stdout_contains:Us(e.assert_stdout_contains),assert_stdout_regex:Us(e.assert_stdout_regex),assert_stderr_contains:Us(e.assert_stderr_contains),assert_stderr_regex:Us(e.assert_stderr_regex),assert_stdout_min_lines:LD(e.assert_stdout_min_lines),assert_json_field_equals:uw(e.assert_json_field_equals),assert_json_field_gte:uw(e.assert_json_field_gte)};return JSON.stringify(t)},MD=e=>{let t=Pc(e.command);return t!==void 0?`command:${e.scope}:${CD(t)}`:`path:${e.scope}:${Pc(e.path)??""}`},mw=e=>{let t=ID(e.env_set),n=RD(e.env_clear),r=OD(e.pm_context_mode),i=ND(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",a=DD(e);return`${MD(e)}:${t}:${n}:${r}:${i}:${s}:${a}`},PD=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,FD=e=>{let t=0,n=0,r=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},$D=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},js=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
32
+ `)}catch{}},UD=async(e,t,n)=>{let r=[],i=0;for(let s of e){let a=await dw(s.id,{run:!1},{...t,path:n});i+=a.tests.length,r.push({item:s,tests:a.tests})}return{itemTests:r,linkedTests:i}},jD=async e=>{let t=X(e.settings.schema),n=U(e.settings,P()),r=SD(e.options.status,t),i=lw(e.options.limit,"--limit"),s=lw(e.options.offset,"--offset")??0,o=(await ve(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>r?d.status===r:!0).sort((d,l)=>d.id.localeCompare(l.id));return{filteredItems:i===void 0?o.slice(s):o.slice(s,s+i),statusFilter:r,limitFilter:i,offsetFilter:s}},GD=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let i=mw(r);if(!t.has(i)){t.set(i,r.timeout_seconds);continue}t.set(i,PD(t.get(i),r.timeout_seconds))}return t},qD=async(e,t)=>{let n=[],r=e.tests.map(l=>{let u=mw(l),m=t.seenTestKeys.has(u);if(!m){t.seenTestKeys.add(u);let _=t.effectiveTimeoutByKey.get(u);n.push(_===void 0?l:{...l,timeout_seconds:_})}return{test:l,key:u,duplicate:m}}),i=n.length>0?await Mc(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,a=r.map(({test:l,key:u,duplicate:m})=>{if(!m){let _=i[s];return s+=1,_}return{command:l.command,path:l.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),o=FD(a),c=$s(a),d=await WD(e,o,a,t);return{passed:o.passed,failed:o.failed,skipped:o.skipped,trackingWarnings:d,failureCategories:c,result:{ok:o.failed===0&&!(t.options.failOnSkipped===!0&&o.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:o.passed,failed:o.failed,skipped:o.skipped,run_results:a,failure_categories:c}}},KD=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),zD=e=>e?!0:void 0,WD=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let i=KD(t,r.options);await Ns({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:i?"failed":"passed",started_at:r.runStartedAt,finished_at:x(),recorded_at:x(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:zD(r.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(i){return[`test_result_tracking_failed:${e.item.id}:${xD(i)}`]}return[]},BD=()=>{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},Pc=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},VD=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:We(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:GD(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:K(e.options.author,e.settings.author_default),trackingRunId:AD(),trackingAttempt:BD(),trackingResumedFrom:Pc(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),HD=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:$s([]),trackingWarnings:[]},i=e.failOnEmptyTestRun===!0&&t===0;return i&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:i}},YD=async(e,t,n)=>{for(let[r,i]of e.entries()){js(t.options,`item ${r+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let s=await qD(i,t);$D(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),js(t.options,`item ${r+1}/${e.length} end id=${i.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}},XD=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(i=>i.run_results),r=Dc(n);t.trackingWarnings.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}`)},JD=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}),QD=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(" "),ZD=async(e,t)=>{let n=I(process.cwd(),t.path);await F(n);let r=await R(n),i=await jD({pmRoot:n,settings:r,options:e}),s=TD(e.timeout),a=x(),o=await UD(i.filteredItems,t,n);return js(e,QD({...i,linkedTests:o.linkedTests})),{pmRoot:n,settings:r,filteredItems:i.filteredItems,itemTests:o.itemTests,linkedTests:o.linkedTests,defaultTimeoutSeconds:s,runStartedAt:a}},eM=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}},WB=async(e,t)=>{let n=await ZD(e,t),{accumulation:r,failOnEmptyTestRunTriggered:i}=HD(e,n.linkedTests,n.filteredItems),s=VD({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await YD(n.itemTests,s,r),XD(e,r);let a=eM({options:e,accumulation:r,failOnEmptyTestRunTriggered:i});return js(e,`end status=${a.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),JD({ok:a.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:a.failOnSkippedTriggered,failOnEmptyTestRunTriggered:i})};import RM from"node:os";import bn from"node:fs/promises";import{spawn as hw}from"node:child_process";import{createHash as tM,randomBytes as nM}from"node:crypto";import br 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]="0224a672-e326-5555-a4b4-1fa3550d9e61")}catch{}})();var yw=new Set(["queued","running"]),jc=new Set(["passed","failed","stopped","canceled"]),rM=3e3,iM=3e3,sM=3e4,ww=100,fw=100;function vw(){return Date.now()}function bw(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function aM(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function oM(){let e=Date.now().toString(36),t=nM(3).toString("hex");return`tr-${e}-${t}`}function cM(e,t,n){let r={kind:e,command:bw(t),pm_root:br.resolve(n)};return tM("sha256").update(JSON.stringify(r)).digest("hex")}function kn(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 dM(e){await Ue(Sd(e)),await Ue(ea(e)),await Ue(Td(e)),await Ue(xd(e)),await Ue(Id(e))}async function kw(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)}`,f.GENERIC_FAILURE)}}async function Ze(e,t){let n={...t,updated_at:x()};await le(ta(e,t.id),`${JSON.stringify(n,null,2)}
33
+ `)}async function En(e,t){let n=ta(e,t),r=await ne(n);return r?kw(r,n):null}async function lM(e){let t=ea(e);return await z(t)?(await bn.readdir(t,{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".json")).map(r=>br.join(t,r.name)).sort((r,i)=>i.localeCompare(r)):[]}function uM(e){let t=e.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(t)return Number.parseInt(t[1],10)*1024}async function mM(e){if(process.platform==="linux")try{let t=await bn.readFile(`/proc/${e}/status`,"utf8");return uM(t)}catch{return}}function fM(e){let t=e.lastIndexOf(")");if(t<0)return{};let r=e.slice(t+2).trim().split(/\s+/),i=Number.parseInt(r[11],10),s=Number.parseInt(r[12],10);return!Number.isFinite(i)||!Number.isFinite(s)?{}:{cpu_user_seconds:i/fw,cpu_system_seconds:s/fw}}async function pM(e){if(process.platform!=="linux")return{};try{let t=await bn.readFile(`/proc/${e}/stat`,"utf8");return fM(t)}catch{return{}}}async function $c(e){let t=e.child_pid??e.worker_pid;if(!kn(t))return;let n=await mM(t),r=await pM(t),i=e.started_at?Date.parse(e.started_at):Number.NaN,s=Number.isFinite(i)?Math.max(0,(vw()-i)/1e3):void 0;return{recorded_at:x(),rss_bytes:n,cpu_user_seconds:r.cpu_user_seconds,cpu_system_seconds:r.cpu_system_seconds,uptime_seconds:s}}function Fc(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function _M(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 o=n.totals??{};return{summary:{items:typeof o.items=="number"?o.items:void 0,linked_tests:typeof o.linked_tests=="number"?o.linked_tests:void 0,passed:Fc(o.passed),failed:Fc(o.failed),skipped:Fc(o.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}let r=Array.isArray(n.run_results)?n.run_results:[],i=0,s=0,a=0;for(let o of r){if(!o||typeof o!="object")continue;let c=o.status;if(c==="passed"){i+=1;continue}if(c==="failed"){s+=1;continue}a+=1}return{summary:{passed:i,failed:s,skipped:a,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}function gM(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:x(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}let r=t.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!r)return null;let i=Number.parseInt(r[1],10),s=Number.parseInt(r[2],10),a=r[4]?Number.parseInt(r[4],10):void 0,o=t.match(/\scommand="((?:\\.|[^"\\])*)"/),c=o?o[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:i,linked_test_total:s,current_command:c,elapsed_ms:Number.isFinite(a)?a:void 0,heartbeat_at:x(),phase:r[3]?.toLowerCase()==="end"?"finished":"running"}}function hM(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.length>0)}function Uc(e,t){if(t<=0)return[];let n=hM(e);return n.length<=t?n:n.slice(n.length-t)}async function Ew(e){let t=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(t&&t.length>0){let i=br.resolve(e,t);if(await z(i))return i}let n=br.resolve(e,"dist","cli.js");if(await z(n))return n;let r=process.argv[1]?.trim();if(r&&r.length>0){let i=br.resolve(e,r);if(await z(i))return i}throw new p("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",f.GENERIC_FAILURE)}async function kr(e,t){if(!yw.has(t.status)||kn(t.worker_pid)||t.finished_at)return t;let r={...t,status:"failed",finished_at:x(),error:t.error??"Background test run worker exited before writing terminal status."};return await Ze(e,r),r}async function Gc(e){await dM(e.pmRoot);let t=bw(e.commandArgs);if(t.length===0)throw new p("Background test run requires command arguments.",f.USAGE);let n=cM(e.kind,t,e.pmRoot),r=await Kc(e.pmRoot,{});for(let l of r){let u=await kr(e.pmRoot,l);if(u.fingerprint===n&&!(!yw.has(u.status)||!kn(u.worker_pid)))return{started:!1,run:{...u,duplicate_of:u.id},duplicate_of:u.id}}let i=oM(),s=x(),a=Ad(e.pmRoot,i),o=Cd(e.pmRoot,i),c=Rd(e.pmRoot,i);await bn.writeFile(a,"","utf8"),await bn.writeFile(o,"","utf8");let d={id:i,kind:e.kind,status:"queued",created_at:s,updated_at:s,requested_by:e.requestedBy,fingerprint:n,command_args:t,command_label:aM(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:a,stderr_path:o,result_path:c,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:s}};return await Ze(e.pmRoot,d),{started:!0,run:d}}async function qc(e){let t=await En(e.pmRoot,e.runId);if(!t)throw new p(`Background test run ${e.runId} not found`,f.NOT_FOUND);if(jc.has(t.status))throw new p(`Background test run ${t.id} is already terminal (${t.status}).`,f.CONFLICT);let n=await Ew(process.cwd()),r=[];e.noExtensions===!0&&r.push("--no-extensions"),r.push("--path",t.pm_root,"test-runs-worker",t.id);let i={...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=hw(process.execPath,[n,...r],{cwd:process.cwd(),env:i,detached:!0,stdio:"ignore",windowsHide:!0});s.unref();let a={...t,status:"queued",worker_pid:s.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:x()}};return await Ze(e.pmRoot,a),a}async function pw(e,t,n){await e,await bn.appendFile(t,n,"utf8")}function Sw(e,t){let n=Number.parseInt(process.env[e]??"",10);return Number.isFinite(n)&&n>0?n:t}function yM(e){return{...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,FORCE_COLOR:"0"}}function wM(e,t){return t?["--no-extensions",...e.command_args]:[...e.command_args]}function vM(e,t){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await Ze(e,t)}catch{}})},async flush(){await n}}}function _w(e,t){try{e.kill(t)}catch{}}async function bM(e,t,n,r){if(n.stopRequested)return;n.stopRequested=!0,e.stop_requested_at=x(),e.progress={...e.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:x()},r(),_w(t,"SIGTERM"),setTimeout(()=>_w(t,"SIGKILL"),Sw("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",iM)).unref?.()}function kM(e,t,n){return{phase:n,message:e,heartbeat_at:x(),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 EM(e,t,n,r){return{phase:r,message:e,heartbeat_at:x(),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 gw(e,t,n){let r=gM(t);if(!r)return!1;let i=e.progress?.phase==="stopping"?"stopping":"running";return e.progress=r.item_id?kM(t,r,i):EM(t,e,r,i),r.phase==="finished"&&!n&&(e.progress.phase="running"),!0}function SM(e){if(e.trim().length===0)return null;try{return JSON.parse(e)}catch{return null}}function TM(e,t){return t?"stopped":e.exit_code===0&&(e.summary?.failed??0)===0&&e.summary?.fail_on_skipped_triggered!==!0?"passed":"failed"}function xM(e,t){return{phase:"finished",message:t?"Background run stopped.":`Background run finished with status=${e.status}.`,heartbeat_at:x(),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 AM(e,t,n){if(t!==null){await le(e.result_path,`${JSON.stringify(t,null,2)}
34
+ `);return}await le(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:Uc(n,ww)},null,2)}
35
+ `)}async function Tw(e,t,n=!1){let r=await En(e,t);if(!r)throw new p(`Background test run ${t} not found`,f.NOT_FOUND);let i={...r,status:"running",started_at:r.started_at??x(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:x()}},s=await Ew(process.cwd()),a=yM(i);await Ze(e,i);let o=wM(i,n),c=hw(process.execPath,[s,...o],{cwd:process.cwd(),env:a,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});i.child_pid=c.pid;let d=vM(e,i),l=d.schedule,u=Promise.resolve(),m=Promise.resolve(),_="",g="",h={stopRequested:!1},y=()=>{bM(i,c,h,l)};process.on("SIGTERM",y),process.on("SIGINT",y);let w=setInterval(()=>{(async()=>(i.resource=await $c(i),i.progress.heartbeat_at=x(),l()))()},Sw("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",rM));w.unref?.(),c.stdout?.on("data",S=>{let A=S.toString("utf8");_+=A,u=pw(u,i.stdout_path,A)}),c.stderr?.on("data",S=>{let A=S.toString("utf8");m=pw(m,i.stderr_path,A),g+=A;let L=g.split(/\r?\n/);g=L.pop();let H=!1;for(let j of L){let C=j.trimEnd();C.length>0&&gw(i,C,h.stopRequested)&&(H=!0)}H&&l()});let b=null,E=null;try{({code:b,signal:E}=await new Promise(S=>{c.on("close",(A,L)=>{S({code:A,signal:L})})}))}finally{clearInterval(w),process.off("SIGTERM",y),process.off("SIGINT",y)}await u,await m;let v=g.trimEnd();v.length>0&&gw(i,v,h.stopRequested)&&l(),g="";let T=SM(_),k=_M(i.kind,T);return i.summary=k.summary,i.exit_code=typeof b=="number"?b:void 0,i.signal=E??void 0,i.finished_at=x(),i.status=TM(i,h.stopRequested),i.progress=xM(i,h.stopRequested),i.resource=await $c(i),await AM(i,T,_),await Ze(e,i),await d.flush(),i}async function Kc(e,t){let n=await lM(e),r=[];for(let c of n){let d=await ne(c);if(!d)continue;let l=await kw(d,c);r.push(l)}let i=[];for(let c of r)i.push(await kr(e,c));let a=(t.status?i.filter(c=>c.status===t.status):i).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)}),o=typeof t.limit=="number"&&t.limit>=0?t.limit:void 0;return o===void 0?a:a.slice(0,o)}async function xw(e,t){let n=await En(e,t);if(!n)throw new p(`Background test run ${t} not found`,f.NOT_FOUND);let r=await kr(e,n),i=kn(r.worker_pid),s=kn(r.child_pid);r.status==="running"&&!s&&!r.finished_at&&!i&&(r.status="failed",r.finished_at=x(),r.error=r.error??"Background run process exited unexpectedly.",await Ze(e,r)),r.status==="running"&&(r.resource=await $c(r),await Ze(e,r));let a=r.progress?.heartbeat_at,o=a?Date.parse(a):Number.NaN,c=Number.isFinite(o)?Math.max(0,vw()-o):void 0,d=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(d)&&d>0?d:sM,u=r.status==="running"?c!==void 0&&c>l?"stale":"healthy":"inactive";return{run:r,health:{state:u,last_heartbeat_at:a,heartbeat_lag_ms:c,worker_alive:i,child_alive:s}}}function CM(e,t){let n=t?"SIGKILL":"SIGTERM";if(!kn(e.worker_pid)||!e.worker_pid)return"none";try{return process.kill(e.worker_pid,n),n}catch{return"none"}}function IM(e,t){return{phase:"stopping",message:t==="none"?"Run marked stopped.":`Stop requested via ${t}.`,heartbeat_at:x(),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 Aw(e,t,n=!1){let r=await En(e,t);if(!r)throw new p(`Background test run ${t} not found`,f.NOT_FOUND);let i=await kr(e,r);if(jc.has(i.status))return{run:i,signal_sent:"none"};let s=CM(i,n);return s==="none"&&(i.status="stopped",i.finished_at=i.finished_at??x()),i.stop_requested_at=x(),i.progress=IM(i,s),await Ze(e,i),{run:i,signal_sent:s}}async function Cw(e,t,n,r=!1){let i=await En(e,t);if(!i)throw new p(`Background test run ${t} not found`,f.NOT_FOUND);let s=await kr(e,i);if(!jc.has(s.status))throw new p(`Background test run ${t} is not terminal and cannot be resumed.`,f.CONFLICT);let a=await Gc({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(!a.started)return a.run;let o=await qc({pmRoot:e,runId:a.run.id,noExtensions:r}),c={...s,resumed_by:o.id};return await Ze(e,c),o}async function Iw(e,t,n,r){let i=await En(e,t);if(!i)throw new p(`Background test run ${t} not found`,f.NOT_FOUND);let s=typeof r=="number"&&Number.isFinite(r)&&r>=0?Math.floor(r):ww,a=n==="stdout"||n==="both"?await ne(i.stdout_path)??"":"",o=n==="stderr"||n==="both"?await ne(i.stderr_path)??"":"";return{run:i,stream:n,tail:s,stdout:n==="stdout"||n==="both"?Uc(a,s):[],stderr:n==="stderr"||n==="both"?Uc(o,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]="1cbb3565-26d8-5657-b724-602658bec852")}catch{}})();var OM=["queued","running","passed","failed","stopped","canceled"],NM=["stdout","stderr","both"];function LM(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(OM.includes(t))return t;throw new p(`Invalid --status value "${e}"`,f.USAGE)}function DM(e){if(e===void 0||e.trim().length===0)return"stderr";let t=e.trim().toLowerCase();if(NM.includes(t))return t;throw new p(`Invalid --stream value "${e}"`,f.USAGE)}function MM(){try{let e=RM.userInfo().username.trim();if(e.length>0)return e}catch{}}function Rw(e,t){let n=[e,Yd(),t,process.env.USER,process.env.LOGNAME,process.env.USERNAME,MM()];for(let r of n){if(typeof r!="string")continue;let i=r.trim();if(i.length>0)return i}return"unknown"}async function qt(e){await F(e)}async function mV(e,t){let n=I(process.cwd(),t.path),r=We(process.cwd());await qt(n);let i=await R(n),s=Rw(e.author,i.author_default),a=await Gc({pmRoot:n,globalPmRoot:r,kind:e.kind,commandArgs:e.commandArgs,requestedBy:s,targetId:e.targetId,statusFilter:e.statusFilter});return a.started?{started:!0,run:await qc({pmRoot:n,runId:a.run.id,noExtensions:e.noExtensions===!0})}:{started:!1,duplicate_of:a.duplicate_of,run:a.run}}async function fV(e,t){let n=I(process.cwd(),t.path);await qt(n);let r=LM(e.status),i=On(e.limit,"limit"),s=await Kc(n,{status:r,limit:i});return{runs:s,count:s.length,filters:{status:r,limit:i}}}async function pV(e,t){let n=I(process.cwd(),t.path);await qt(n);let r=await xw(n,e);return{run:r.run,health:r.health}}async function _V(e,t,n){let r=I(process.cwd(),n.path);await qt(r);let i=DM(t.stream),s=On(t.tail,"tail"),a=await Iw(r,e,i,s);return{run:a.run,stream:a.stream,tail:a.tail,stdout:a.stdout,stderr:a.stderr}}async function gV(e,t,n){let r=I(process.cwd(),n.path);await qt(r);let i=await Aw(r,e,t.force===!0);return{run:i.run,signal_sent:i.signal_sent}}async function hV(e,t,n){let r=I(process.cwd(),n.path);await qt(r);let i=await R(r),s=Rw(t.author,i.author_default),a=await Cw(r,e,s,t.noExtensions===!0);return{resumed_from:e,run:a}}async function yV(e,t){let n=I(process.cwd(),t.path);await qt(n);let r=await Tw(n,e,t.noExtensions===!0);return{id:r.id,status:r.status,exit_code:r.exit_code}}export{N as a,Ie as b,He as c,en as d,Qm as e,ef as f,st as g,$n as h,wv as i,Ia as j,Ra as k,sf as l,nn as m,jn as n,Na as o,$v as p,uf as q,Gn as r,La as s,fi as t,Da as u,ff as v,pf as w,_f as x,qn as y,_i as z,hf as A,yf as B,wf as C,vf as D,wi as E,Sf as F,O as G,te as H,Kv as I,Kn as J,$a as K,oP as L,cP as M,xf as N,dP as O,lP as P,uP as Q,mP as R,fP as S,Ua as T,pP as U,_P as V,Fa as W,gP as X,hP as Y,Af as Z,yP as _,Jv as $,Rf as aa,CP as ba,Bn as ca,IP as da,ib as ea,sb as fa,RP as ga,ab as ha,DP as ia,MP as ja,Pf as ka,yb as la,WP as ma,Vn as na,yi as oa,BP as pa,VP as qa,fp as ra,s$ as sa,_p as ta,hp as ua,dE as va,lE as wa,uE as xa,mE as ya,Jn as za,fE as Aa,ct as Ba,pE as Ca,_E as Da,gE as Ea,oo as Fa,co as Ga,hE as Ha,Si as Ia,Ti as Ja,yp as Ka,U$ as La,kp as Ma,Sp as Na,rU as Oa,iU as Pa,po as Qa,tr as Ra,nr as Sa,nS as Ta,mn as Ua,Lp as Va,vo as Wa,Mp as Xa,Pp as Ya,RS as Za,bj as _a,G_ as $a,sr as ab,qi as bb,Do as cb,H_ as db,Y_ as eb,$j as fb,jT as gb,X_ as hb,J_ as ib,$o as jb,ex as kb,e1 as lb,g1 as mb,nx as nb,Ot as ob,h1 as pb,rx as qb,y1 as rb,cr as sb,w1 as tb,ng as ub,ig as vb,ox as wb,cx as xb,R1 as yb,O1 as zb,M1 as Ab,ux as Bb,og as Cb,jo as Db,cg as Eb,Ax as Fb,dg as Gb,Go as Hb,mg as Ib,Ix as Jb,B1 as Kb,V1 as Lb,fg as Mb,H1 as Nb,Y1 as Ob,fs as Pb,zi as Qb,vg as Rb,fG as Sb,zx as Tb,Tg as Ub,qo as Vb,Mt as Wb,Yi as Xb,Dt as Yb,xg as Zb,dr as _b,lr as $b,Xi as ac,Ji as bc,Pt as cc,Ft as dc,_n as ec,Qi as fc,Zi as gc,es as hc,Cg as ic,aA as jc,Ko as kc,tc as lc,jC as mc,aI as nc,BI as oc,Bq as pc,uh as qc,_K as rc,yK as sc,wK as tc,vK as uc,fR as vc,pR as wc,Es as xc,vh as yc,PK as zc,kR as Ac,fc as Bc,ER as Cc,SR as Dc,TR as Ec,FK as Fc,$K as Gc,GK as Hc,FR as Ic,Ch as Jc,KK as Kc,qR as Lc,pc as Mc,Rh as Nc,Oh as Oc,zR as Pc,BK as Qc,WR as Rc,VK as Sc,HK as Tc,YK as Uc,XK as Vc,BR as Wc,Lh as Xc,QK as Yc,Nh as Zc,Ph as _c,QR as $c,gr as ad,rO as bd,$h as cd,aO as dd,oz as ed,Iz as fd,my as gd,fy as hd,D0 as id,py as jd,Jz as kd,_y as ld,Qz as md,Zz as nd,Cs as od,J0 as pd,aW as qd,vc as rd,oW as sd,bc as td,Q0 as ud,vr as vd,wy as wd,vy as xd,RW as yd,DW as zd,Ey as Ad,BW as Bd,Dc as Cd,OL as Dd,$s as Ed,PL as Fd,Mc as Gd,dw as Hd,WB as Id,mV as Jd,fV as Kd,pV as Ld,_V as Md,gV as Nd,hV as Od,yV as Pd};
36
+ //# sourceMappingURL=chunk-3ENVHX6C.js.map