@unbrained/pm-cli 2026.9.26 → 2026.9.27

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 (130) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +16 -0
  3. package/dist/cli/commander-usage.js +2 -2
  4. package/dist/cli/error-guidance.js +1 -1
  5. package/dist/cli/main.js +2 -2
  6. package/dist/cli/register-setup.js +1 -1
  7. package/dist/cli/runtime/selection.d.ts +3 -1
  8. package/dist/cli/runtime/selection.js +1 -1
  9. package/dist/cli-bundle/bundle-manifest.json +160 -152
  10. package/dist/cli-bundle/chunks/{chunk-IYN4MJ2C.js → chunk-3BTJ66CB.js} +56 -56
  11. package/dist/cli-bundle/chunks/{chunk-FOTXRNY6.js → chunk-4SLLCDFL.js} +39 -39
  12. package/dist/cli-bundle/chunks/{chunk-GRWPZR7F.js → chunk-4UPZLUT2.js} +7 -7
  13. package/dist/cli-bundle/chunks/{chunk-U55RYT3I.js → chunk-6OJVQ7SW.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-TYJXMT3Q.js → chunk-7TAGYNFP.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-QQD3VRMZ.js → chunk-AUS6USO4.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-4ODHIX7N.js → chunk-IEP3VAT5.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-HTHTX6E6.js → chunk-JX6WCCHL.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-LC6WEA5U.js +2 -0
  19. package/dist/cli-bundle/chunks/{chunk-VMO4P5MX.js → chunk-LKGQUZ5M.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-TC74K7SS.js → chunk-OKVDVERQ.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-SZQCHJI4.js → chunk-TSF2LPIH.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-MJWKR7YA.js → chunk-V5UGBYHN.js} +3 -3
  23. package/dist/cli-bundle/chunks/{register-list-query-426QTRET.js → register-list-query-6PAJ4PBU.js} +2 -2
  24. package/dist/cli-bundle/chunks/{register-mutation-FLI3HHMP.js → register-mutation-RZCXZXYS.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-operations-TP7ZG4MK.js → register-operations-GK6VU2H2.js} +2 -2
  26. package/dist/cli-bundle/chunks/register-setup-ASEMNMBF.js +2 -0
  27. package/dist/cli-bundle/focused-chunks/{chunk-H3BI4EDO.js → chunk-6J2YCGSN.js} +3 -3
  28. package/dist/cli-bundle/focused-chunks/{chunk-XKH2FC5D.js → chunk-6UNKK3UH.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-NRHTXBTI.js → chunk-DQ3MB7BO.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-PMPFLA6X.js → chunk-E7LYK7V5.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-25BBHWMH.js → chunk-GZD4ZYIB.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/chunk-KMPKKSA6.js +2 -0
  33. package/dist/cli-bundle/focused-chunks/{chunk-TLF6N56J.js → chunk-LBDWUHQD.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-UIFVIE5F.js → chunk-MILJCOFJ.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-MK5AKKHK.js → chunk-NETVXIH5.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-Q355NPLH.js → chunk-NWRVNHAD.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-XVBWZTU2.js → chunk-NZAG7OKB.js} +12 -12
  38. package/dist/cli-bundle/focused-chunks/{chunk-OY3VHCTX.js → chunk-OJKJFDIG.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/chunk-OJRX6G22.js +2 -0
  40. package/dist/cli-bundle/focused-chunks/{chunk-NVVB2HJC.js → chunk-PDVL7QYU.js} +16 -16
  41. package/dist/cli-bundle/focused-chunks/{chunk-O7MIBEMK.js → chunk-QO4MTAEA.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-ABA3KRPY.js → chunk-SMADBUPL.js} +2 -2
  43. package/dist/cli-bundle/main.js +21 -21
  44. package/dist/cli-bundle/sdk-authoring.js +1 -1
  45. package/dist/cli-bundle/sdk-contracts.js +1 -1
  46. package/dist/cli-bundle/sdk-core.js +2 -2
  47. package/dist/cli-bundle/sdk-governance.js +1 -1
  48. package/dist/cli-bundle/sdk-graph.js +1 -1
  49. package/dist/cli-bundle/sdk-merge.js +23 -23
  50. package/dist/cli-bundle/sdk-query.js +1 -1
  51. package/dist/cli-bundle/sdk-runtime.js +1 -1
  52. package/dist/cli-bundle/sdk-testing.js +1 -1
  53. package/dist/cli-bundle/sdk.js +8 -8
  54. package/dist/sdk/agent-capability-contracts.js +1 -1
  55. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  56. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  57. package/dist/sdk/completion/shared.d.ts +1 -1
  58. package/dist/sdk/completion/shared.js +1 -1
  59. package/dist/sdk/extension/static-inventory.d.ts +54 -0
  60. package/dist/sdk/extension/static-inventory.js +2 -0
  61. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  62. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  63. package/dist/sdk/guide-topics.js +1 -1
  64. package/dist/sdk/index.d.ts +1 -0
  65. package/dist/sdk/index.js +1 -1
  66. package/dist/sdk/public-surface.json +1 -1
  67. package/dist/sdk/query/complete-list.js +1 -1
  68. package/dist/sdk/read-output/provenance.d.ts +20 -0
  69. package/dist/sdk/read-output/provenance.js +2 -0
  70. package/dist/sdk/read-output-contracts.js +1 -1
  71. package/dist/sdk/runtime-input.js +1 -1
  72. package/docs/CLI_GRAMMAR.md +31 -0
  73. package/docs/CODEX_PLUGIN.md +8 -0
  74. package/docs/EXTENSION_LIFECYCLE.md +18 -0
  75. package/docs/RELEASING.md +46 -1
  76. package/docs/agent-task-token-baseline.json +4 -4
  77. package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
  78. package/docs/generated/AGENT_COMMAND_SURFACE.md +5 -1
  79. package/docs/generated/FLAG_LEXICON_BUDGETS.md +4 -0
  80. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +14 -7
  81. package/marketplace.json +2 -2
  82. package/package.json +2 -2
  83. package/packages/pm-beads/package.json +1 -1
  84. package/packages/pm-calendar/package.json +1 -1
  85. package/packages/pm-command-kit/package.json +1 -1
  86. package/packages/pm-digital-twin/package.json +1 -1
  87. package/packages/pm-governance-audit/package.json +1 -1
  88. package/packages/pm-guide-shell/package.json +1 -1
  89. package/packages/pm-kanban/package.json +1 -1
  90. package/packages/pm-lifecycle-hooks/package.json +1 -1
  91. package/packages/pm-linked-test-adapters/package.json +1 -1
  92. package/packages/pm-search-advanced/package.json +1 -1
  93. package/packages/pm-templates/package.json +1 -1
  94. package/packages/pm-todos/package.json +1 -1
  95. package/packages/pm-vcs/package.json +1 -1
  96. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  97. package/plugins/pm-claude/README.md +5 -1
  98. package/plugins/pm-claude/package.json +2 -2
  99. package/plugins/pm-claude/skills/pm-audit/SKILL.md +14 -103
  100. package/plugins/pm-claude/skills/pm-audit/agents/openai.yaml +4 -0
  101. package/plugins/pm-claude/skills/pm-developer/SKILL.md +20 -143
  102. package/plugins/pm-claude/skills/pm-developer/agents/openai.yaml +4 -0
  103. package/plugins/pm-claude/skills/pm-planner/SKILL.md +16 -167
  104. package/plugins/pm-claude/skills/pm-planner/agents/openai.yaml +4 -0
  105. package/plugins/pm-claude/skills/pm-release/SKILL.md +18 -102
  106. package/plugins/pm-claude/skills/pm-release/agents/openai.yaml +4 -0
  107. package/plugins/pm-claude/skills/pm-workflow/SKILL.md +25 -156
  108. package/plugins/pm-claude/skills/pm-workflow/agents/openai.yaml +4 -0
  109. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  110. package/plugins/pm-codex/README.md +10 -2
  111. package/plugins/pm-codex/mcp.json +11 -0
  112. package/plugins/pm-codex/package.json +2 -2
  113. package/plugins/pm-codex/plugin.json +45 -0
  114. package/plugins/pm-codex/skills/pm-audit/SKILL.md +21 -0
  115. package/plugins/pm-codex/skills/pm-audit/agents/openai.yaml +4 -0
  116. package/plugins/pm-codex/skills/pm-auditor/SKILL.md +5 -40
  117. package/plugins/pm-codex/skills/pm-auditor/agents/openai.yaml +3 -5
  118. package/plugins/pm-codex/skills/pm-developer/SKILL.md +26 -0
  119. package/plugins/pm-codex/skills/pm-developer/agents/openai.yaml +4 -0
  120. package/plugins/pm-codex/skills/pm-native/SKILL.md +7 -87
  121. package/plugins/pm-codex/skills/pm-native/agents/openai.yaml +3 -5
  122. package/plugins/pm-codex/skills/pm-planner/SKILL.md +22 -0
  123. package/plugins/pm-codex/skills/pm-planner/agents/openai.yaml +4 -0
  124. package/plugins/pm-codex/skills/pm-release/SKILL.md +17 -38
  125. package/plugins/pm-codex/skills/pm-release/agents/openai.yaml +2 -4
  126. package/plugins/pm-codex/skills/pm-workflow/SKILL.md +39 -0
  127. package/plugins/pm-codex/skills/pm-workflow/agents/openai.yaml +4 -0
  128. package/dist/cli-bundle/chunks/register-setup-574SIVQZ.js +0 -2
  129. package/dist/cli-bundle/focused-chunks/chunk-HNHMK5JI.js +0 -2
  130. package/dist/cli-bundle/focused-chunks/chunk-HQPTDJLF.js +0 -2
@@ -1,9 +1,9 @@
1
- import{a as Ho,c as zr,d as Hr,e as hl,g as _l,h as Go,i as gl,j as sn,k as an,l as yl,m as wl,n as qo,o as kl,p as cn,q as ln,r as Sl,s as El,t as Bo}from"./chunk-MK5AKKHK.js";import{e as Xr,f as Xo,h as Zo}from"./chunk-NRHTXBTI.js";import{B as jl,C as Jr,D as Fl,E as Yo,G as Ul,H as zl,J as Hl,K as Kr,M as Yr,a as cl,g as zo,i as ll}from"./chunk-PMPFLA6X.js";import{K as Zd}from"./chunk-XKH2FC5D.js";import{D as rs,E as di,Ha as Wd,Ia as Gd,Ma as qd,Na as Bd,T as ui,U as wd,V as is,W as Zn,Y as os,aa as $d,ba as Od,ca as Dd,da as Pd,ea as fi,f as dd,g as ud,ga as Nd,h as md,ha as Ld,ia as Md,ja as Ht,k as li,ka as jd,kb as Kd,la as _n,ma as Fd,mb as cs,na as ss,nb as Yd,o as Yn,oa as gn,ob as Xd,p as fd,pa as Ud,q as pd,qa as zd,r as Xn,ra as Hd,s as hd,sa as as,u as ns,v as _d,wb as ls,z as gd}from"./chunk-25BBHWMH.js";import{a as ul,b as on,c as Wo,d as ml,e as fl,f as at,g as Wr,h as pl,i as St}from"./chunk-O7MIBEMK.js";import{$ as Ft,Aa as od,Ab as ct,Bb as zt,C as q,Ca as fn,D as Wl,Da as Kn,Ea as sd,Eb as Td,Fa as ri,Fb as lt,G as Ee,Ga as Ut,H as Qo,Ha as fe,Ia as ii,Ja as ad,Ka as ts,La as oi,Ma as pn,N as Gl,Na as si,O as Zr,Oa as cd,Qa as xe,R as Qr,Ra as ld,S as ei,Sa as T,Ta as ai,Tb as Qn,U as ql,Ua as ci,V as De,Vb as pi,Wa as yd,X as xt,Y as Bl,Z as Vl,_ as Jl,aa as Kl,ac as Vd,bb as vd,cb as bd,dc as Jd,eb as kd,fa as Yl,fb as Sd,ga as es,gb as It,ha as ti,hb as Ed,ia as un,ib as xd,ka as ni,la as Xl,lb as Id,ma as Zl,mb as Ad,oa as Ql,qa as ed,rb as mi,sa as td,tb as Rd,ua as nd,vb as te,wa as mn,wb as Pe,xa as rd,xb as Ne,yb as Cd,za as id,zb as hn}from"./chunk-Q355NPLH.js";import{b as nn,e as de,g as Oe,i as Se,j as Ye,n as _e,o as vl,p as Gr,r as bl}from"./chunk-TLF6N56J.js";import{$ as g,$a as Nt,$d as ce,Aa as $e,Ab as Ke,Ba as Yc,Bc as Dl,Da as ee,Ga as Xc,Jc as H,Ka as Zc,Kb as dl,Mc as X,Oc as He,Pb as qr,Pc as Pl,Qa as Qc,Qb as xl,Qc as Vr,Ra as el,Rb as Vo,S as Wc,Sa as G,Sb as Jo,Sd as C,T as Gc,Tb as Ko,Td as Ml,Ud as dn,V as qc,Vb as Il,Vd as Et,Wb as Al,Wd as jt,X as Bc,Xa as Jn,Xc as Nl,Y as Fr,Ya as N,Yc as Xe,Z as Vc,Za as Ve,Zb as Rl,_a as Ur,_c as Ll,a as Mr,aa as y,bb as tl,cb as Lt,d as jr,eb as nl,ec as Cl,fb as rl,gb as il,ha as Jc,i as Uc,ka as Kc,l as zc,m as Hc,ma as Fo,ob as ol,pb as Mt,qb as R,ra as Vn,rb as sl,sa as $,sb as ke,ta as kt,ua as j,ub as Uo,va as K,vb as al,vc as Tl,w as jo,wa as ne,wb as rn,xc as Br,yb as Je,yc as $l,za as he,zc as Ol}from"./chunk-NVVB2HJC.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00d2200c-d308-51a6-acc4-8da90afaf6d6")}catch{}})();var L=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}},Ze=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 yn(e){try{return await e()}catch(t){throw t instanceof L?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Qd(e){try{return await e()}catch(t){throw t instanceof Ie?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as Mg}from"node:crypto";import jg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var wn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00ad9b34-4feb-5812-8755-801869cce3ad")}catch{}})();var tu=1,Wt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],ds=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Fg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Ug=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,hi=30,_i=5e3,nu=4,zg=50;function dt(e,t){if(!Ug.test(e))throw new L(`${t} must be a stable lowercase id`)}function Hg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function er(e){let t=Fg.filter(i=>e[i]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function ms(e,t){return R(e)===R(t)}function ru(e,t){if(t.polarity==="equals")return ms(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 iu(e){let t=er(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>ru(r.observed,t)===(r.expected==="pass"))}function Wg(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!ms(e.value,t.value)}function Gg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||R(e.scope)!==R(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Wg(er(e),er(t))||n[t.enforcement]<n[e.enforcement]||r}function qg(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new L("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new L("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new L("items source equals/state requires field")}function Bg(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(n=>n!==void 0).length>1)throw new L("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new L("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new L("dependency_kind source source_kind_state must be present or missing")}function Vg(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new L("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new L("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new L("prose_edge_gap exemption selectors must not be empty")}}function fs(e){dt(e.id,"measurement.id"),e.max_cost!==void 0&&Hg(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new L(`measurement.source.kind must be one of ${ds.join(", ")}`);let n=Reflect.get(t,"kind");if(!ds.includes(n))throw new L(`measurement.source.kind must be one of ${ds.join(", ")}`);let r=t;if(r.kind==="items"&&qg(r),r.kind==="dependency_kind"&&Bg(r),r.kind==="prose_edge_gap"&&Vg(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new L(`${r.kind} source requires field`);return r.kind==="provider"&&(dt(r.provider,"provider source provider"),dt(r.key,"provider source key")),e}function ps(e){if(dt(e.id,"assertion.id"),dt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new L("assertion.owner_item_id is required");let t=er(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new L(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new L("retired assertion requires retire_reason");e.scope.kind==="filter"&&dt(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 L("assertion negative control requires pass and fail cases");if(!iu(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function Jg(e){if(!Array.isArray(e.allowed_providers))throw new L("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)dt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Wt.includes(t))throw new L(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new L(`gate provider policy trigger ${t} is invalid`)}}function ou(e){if(dt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new L("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new L("gate requires at least one assertion");for(let t of e.assertion_ids)dt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${Wt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!Wt.includes(t))throw new L(`gate trigger must be one of ${Wt.join(", ")}`);return e.provider_policy&&Jg(e.provider_policy),e}function vn(e){if(e.version!==tu)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(fs(r),t.has(`measurement:${r.id}`))throw new L(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(ps(r),t.has(`assertion:${r.id}`))throw new L(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){ou(r);let i=r.assertion_ids.filter(o=>!e.assertions.some(s=>s.id===o));if(i.length>0)throw new L(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new L(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of su(e))if(!n.has(r))throw new L(`${i.join(", ")} references missing measurement ${r}`);return e}function hs(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)hs(n,t)}function su(e){let t=new Map,n=(r,i)=>{let o=t.get(r)??[];o.push(i),t.set(r,o)};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=[];hs(r.source.expression,i);for(let o of i)n(o,`derived measurement ${r.id}`)}return t}function Kg(e,t){let n=e.assertion_ids.flatMap(o=>{let s=t.assertions.find(a=>a.id===o);return[s.measurement_id,...s.scope.kind==="filter"?[s.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let o=n.pop();if(r.has(o))continue;r.add(o);let s=t.measurements.find(a=>a.id===o);s.source.kind==="provider"?i.add(s.source.provider):s.source.kind==="derived"&&hs(s.source.expression,n)}return i}function tr(){return{version:tu,measurements:[],assertions:[],gates:[]}}function Yg(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 o=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?o:!o}return ms(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Xg(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 Zg(e,t){let n=[],r=Fo(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let o of i.dependencies??[]){let s=Fo(o.kind)??o.kind.trim().toLowerCase(),a=o.source_kind?.trim();s===r&&Xg(e,a)&&n.push(`${i.id}->${o.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Qg(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 o=Reflect.get(i,"text");typeof o=="string"&&t.push(o)}}}return t}function ey(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 us(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function ty(e){let t=new Map,n=new Set,r=[],i=/\b[a-z][a-z0-9]*-[a-z0-9]+\b/giu,o=0;for(let s of e){t.set(s.id.toLowerCase(),s.id);for(let a of s.dependencies??[])n.add(us(s.id,a.id));for(let a of[s.parent,s.blocked_by])typeof a=="string"&&n.add(us(s.id,a));for(let a of Qg(s)){let c=[...a.matchAll(i)].map(l=>l[0]);o+=c.length,r.push({holder_id:s.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:o}}function ny(e,t){let n=ty(t.items),r=new Map;for(let s of n.prose_mentions){let a=s.mentioned_ids.map(l=>n.canonical_ids.get(l.toLowerCase())).filter(l=>l!==void 0&&l!==s.holder_id),c=[...new Set(a)];for(let l of c){let d=us(s.holder_id,l);if(n.linked_pairs.has(d)||ey(e.exemptions??[],s.holder_id,l,s.segment))continue;let u=c.some(m=>m!==l);r.get(d)?.explicit===!0&&!u||r.set(d,{contributor:`${s.holder_id}->${l}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],o=i.map(s=>s.contributor).sort();return{value:o.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:o.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(s=>s.explicit).length,implicit_subject:i.filter(s=>!s.explicit).length}}}function ry(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 iy(e,t){let n=t.items.filter(r=>{let i=r[e.link],o=Array.isArray(i)&&i.length>0;return e.state==="present"?o:!o});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function oy(e,t){let n=e.source;return n.kind==="items"?Yg(n,t):n.kind==="dependency_kind"?Zg(n,t):n.kind==="prose_edge_gap"?ny(n,t):n.kind==="history"?ry(n,t):n.kind==="links"?iy(n,t):null}function au(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 sy(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 cu(e,t,n){let r=new Array(e.length),i=0,o=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let s=i;i+=1,r[s]=await n(e[s],s)}});return await Promise.all(o),r}async function lu(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let s=n.find(l=>l.id===e.measurement);if(!s)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await du(s,t,n,r,i);if(typeof a.value!="number")throw new TypeError(`derived measurement ${s.id} is not numeric`);let c=i.charged.has(s.id)?[]:[a.cost];return i.charged.add(s.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let o=await cu(e.operands,nu,s=>lu(s,t,n,r,i));return{value:sy(e.operator,o.map(s=>s.value)),costs:o.flatMap(s=>s.costs),population_size:Math.max(0,...o.map(s=>s.population_size)),contributors:[...new Set(o.flatMap(s=>s.contributors))]}}async function ay(e,t,n,r,i){fs(e);let o=Date.now(),s,a=[],c=0;if(e.source.kind==="derived"){let u=await lu(e.source.expression,t,n,[...r,e.id],i);s={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=oy(e,t);u!==null?s=u:(s=await t.external(e.source),c=1)}let l={units:s.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()-o},d=au([...a,l],Date.now()-o);if(e.max_cost!==void 0&&d.units>e.max_cost)throw new Ie(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${d.units}`);return{id:e.id,definition_fingerprint:`sha256:${Mg("sha256").update(R(e)).digest("hex")}`,value:s.value,population_size:s.population_size,cost:d,contributors:s.contributors??[],...s.partitions?{partitions:s.partitions}:{}}}function du(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let o=i.cache.get(e.id);if(o)return o;let s=ay(e,t,n,r,i).catch(a=>{if(a instanceof Ze&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},l=new Ze(a.message,c);throw l.cause=a,l}throw a});return i.cache.set(e.id,s),s}async function _s(e,t,n=[e]){return du(e,t,n,[],{cache:new Map,charged:new Set})}function cy(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 ly(e,t,n={}){ps(e);let r=er(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:cy(t.value,r),verdict:i?"retired":ru(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:iu(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function dy(e,t,n,r){let i=Kg(e,t);if(i.size===0)return;let o=e.provider_policy,s=o?.triggers[r];if(!o||!s)throw new Ie(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let a=new Set(o.allowed_providers),c={low:0,medium:1,high:2};for(let l of i){if(!a.has(l))throw new Ie(`assurance gate ${e.id} refuses provider ${l}`);let d=n.provider_capabilities?.[l];if(!d)throw new Ie(`assurance provider ${l} has no declared capabilities`);if(c[d.cost_class]>c[s.max_cost_class])throw new Ie(`assurance gate ${e.id} refuses ${d.cost_class}-cost provider ${l} at trigger ${r}`);if(d.network&&!s.allow_network)throw new Ie(`assurance gate ${e.id} refuses network provider ${l} at trigger ${r}`)}}async function eu(e,t,n,r,i){try{return await _s(n,r,i)}catch(o){if(o instanceof Ze){let s=o.check?` check ${o.check}`:"",a=o.measurement_id??n.id,c=new Ie(`assurance gate ${e} assertion ${t} measurement ${a} source ${o.source_kind}${s} field ${o.field} could not resolve: ${o.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}});throw c.cause=o,c}throw o}}async function uu(e,t,n,r){vn(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}`);dy(i,t,n,r.trigger);let o=await cu(i.assertion_ids,nu,async c=>{let l=t.assertions.find(p=>p.id===c),d=t.measurements.find(p=>p.id===l.measurement_id),u=n;if(l.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(_=>!p.has(_.status))}}else if(l.scope.kind==="filter"){let p=l.scope.measurement_id,_=t.measurements.find(v=>v.id===p),h=await eu(i.id,l.id,_,n,t.measurements),w=new Set(h.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===l.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return ly(l,await eu(i.id,l.id,d,u,t.measurements),{owner_terminal:f})}),s=o.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=o.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:s?"block":a?"warn":"pass",exit_code:s?1:0,assertions:o,assertions_total:o.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:au(o.map(c=>c.cost),Math.max(0,...o.map(c=>c.cost.duration_ms)))}}function gi(e){return jg.join(e,"assurance.json")}async function mu(e){let t=await K(gi(e));return t===null?tr():yi(t)}function yi(e){try{return vn(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function wi(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function uy(e,t){e==="measurement"?fs(t):e==="assertion"?ps(t):ou(t)}async function nr(e,t){let n=structuredClone(wi(await mu(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function gs(e,t,n){let r=wi(await mu(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function vi(e,t,n,r={}){uy(t,n);let i=await T(e),o=q(r.author,i.author_default),s=await pn({pmRoot:e,filePath:gi(e),op:`assurance:${t}:put`,author:o,message:r.message,lockTtlSeconds:hi,lockWaitMs:_i,mutate:a=>{let c=a===null?tr():yi(a),l=wi(c,t),d=l.findIndex(m=>m.id===n.id),u=d<0?"created":"updated";if(t==="assertion"&&d>=0&&Gg(l[d],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new L(`loosening assertion ${n.id} requires a verified authorization_decision`)}return d<0?l.push(structuredClone(n)):l[d]=structuredClone(n),vn(c),{raw:`${JSON.stringify(c,null,2)}
1
+ import{a as Ho,c as zr,d as Hr,e as hl,g as _l,h as Go,i as gl,j as sn,k as an,l as yl,m as wl,n as qo,o as kl,p as cn,q as ln,r as Sl,s as El,t as Bo}from"./chunk-NETVXIH5.js";import{e as Xr,f as Xo,h as Zo}from"./chunk-DQ3MB7BO.js";import{B as jl,C as Jr,D as Fl,E as Yo,G as Ul,H as zl,J as Hl,K as Kr,M as Yr,a as cl,g as zo,i as ll}from"./chunk-E7LYK7V5.js";import{K as Zd}from"./chunk-6UNKK3UH.js";import{D as rs,E as di,Ha as Wd,Ia as Gd,Ma as qd,Na as Bd,T as ui,U as wd,V as is,W as Zn,Y as os,aa as $d,ba as Od,ca as Dd,da as Pd,ea as fi,f as dd,g as ud,ga as Nd,h as md,ha as Ld,ia as Md,ja as Ht,k as li,ka as jd,kb as Kd,la as _n,ma as Fd,mb as cs,na as ss,nb as Yd,o as Yn,oa as gn,ob as Xd,p as fd,pa as Ud,q as pd,qa as zd,r as Xn,ra as Hd,s as hd,sa as as,u as ns,v as _d,wb as ls,z as gd}from"./chunk-GZD4ZYIB.js";import{a as ul,b as on,c as Wo,d as ml,e as fl,f as at,g as Wr,h as pl,i as St}from"./chunk-QO4MTAEA.js";import{$ as Ft,Aa as od,Ab as ct,Bb as zt,C as q,Ca as fn,D as Wl,Da as Kn,Ea as sd,Eb as Td,Fa as ri,Fb as lt,G as Ee,Ga as Ut,H as Qo,Ha as fe,Ia as ii,Ja as ad,Ka as ts,La as oi,Ma as pn,N as Gl,Na as si,O as Zr,Oa as cd,Qa as xe,R as Qr,Ra as ld,S as ei,Sa as T,Ta as ai,Tb as Qn,U as ql,Ua as ci,V as De,Vb as pi,Wa as yd,X as xt,Y as Bl,Z as Vl,_ as Jl,aa as Kl,ac as Vd,bb as vd,cb as bd,dc as Jd,eb as kd,fa as Yl,fb as Sd,ga as es,gb as It,ha as ti,hb as Ed,ia as un,ib as xd,ka as ni,la as Xl,lb as Id,ma as Zl,mb as Ad,oa as Ql,qa as ed,rb as mi,sa as td,tb as Rd,ua as nd,vb as te,wa as mn,wb as Pe,xa as rd,xb as Ne,yb as Cd,za as id,zb as hn}from"./chunk-NWRVNHAD.js";import{b as nn,e as de,g as Oe,i as Se,j as Ye,n as _e,o as vl,p as Gr,r as bl}from"./chunk-LBDWUHQD.js";import{$ as g,$a as Nt,Aa as $e,Ab as Ke,Ba as Yc,Bc as Dl,Da as ee,Ga as Xc,Jc as H,Ka as Zc,Kb as dl,Mc as X,Oc as He,Pb as qr,Pc as Pl,Qa as Qc,Qb as xl,Qc as Vr,Ra as el,Rb as Vo,S as Wc,Sa as G,Sb as Jo,T as Gc,Tb as Ko,Td as C,Ud as Ml,V as qc,Vb as Il,Vd as dn,Wb as Al,Wd as Et,X as Bc,Xa as Jn,Xc as Nl,Xd as jt,Y as Fr,Ya as N,Yc as Xe,Z as Vc,Za as Ve,Zb as Rl,_a as Ur,_c as Ll,a as Mr,aa as y,ae as ce,bb as tl,cb as Lt,d as jr,eb as nl,ec as Cl,fb as rl,gb as il,ha as Jc,i as Uc,ka as Kc,l as zc,m as Hc,ma as Fo,ob as ol,pb as Mt,qb as R,ra as Vn,rb as sl,sa as $,sb as ke,ta as kt,ua as j,ub as Uo,va as K,vb as al,vc as Tl,w as jo,wa as ne,wb as rn,xc as Br,yb as Je,yc as $l,za as he,zc as Ol}from"./chunk-PDVL7QYU.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00d2200c-d308-51a6-acc4-8da90afaf6d6")}catch{}})();var L=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}},Ze=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 yn(e){try{return await e()}catch(t){throw t instanceof L?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Qd(e){try{return await e()}catch(t){throw t instanceof Ie?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as Mg}from"node:crypto";import jg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var wn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00ad9b34-4feb-5812-8755-801869cce3ad")}catch{}})();var tu=1,Wt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],ds=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Fg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Ug=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,hi=30,_i=5e3,nu=4,zg=50;function dt(e,t){if(!Ug.test(e))throw new L(`${t} must be a stable lowercase id`)}function Hg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function er(e){let t=Fg.filter(i=>e[i]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function ms(e,t){return R(e)===R(t)}function ru(e,t){if(t.polarity==="equals")return ms(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 iu(e){let t=er(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>ru(r.observed,t)===(r.expected==="pass"))}function Wg(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!ms(e.value,t.value)}function Gg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||R(e.scope)!==R(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Wg(er(e),er(t))||n[t.enforcement]<n[e.enforcement]||r}function qg(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new L("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new L("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new L("items source equals/state requires field")}function Bg(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(n=>n!==void 0).length>1)throw new L("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new L("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new L("dependency_kind source source_kind_state must be present or missing")}function Vg(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new L("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new L("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new L("prose_edge_gap exemption selectors must not be empty")}}function fs(e){dt(e.id,"measurement.id"),e.max_cost!==void 0&&Hg(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new L(`measurement.source.kind must be one of ${ds.join(", ")}`);let n=Reflect.get(t,"kind");if(!ds.includes(n))throw new L(`measurement.source.kind must be one of ${ds.join(", ")}`);let r=t;if(r.kind==="items"&&qg(r),r.kind==="dependency_kind"&&Bg(r),r.kind==="prose_edge_gap"&&Vg(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new L(`${r.kind} source requires field`);return r.kind==="provider"&&(dt(r.provider,"provider source provider"),dt(r.key,"provider source key")),e}function ps(e){if(dt(e.id,"assertion.id"),dt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new L("assertion.owner_item_id is required");let t=er(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new L(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new L("retired assertion requires retire_reason");e.scope.kind==="filter"&&dt(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 L("assertion negative control requires pass and fail cases");if(!iu(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function Jg(e){if(!Array.isArray(e.allowed_providers))throw new L("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)dt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Wt.includes(t))throw new L(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new L(`gate provider policy trigger ${t} is invalid`)}}function ou(e){if(dt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new L("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new L("gate requires at least one assertion");for(let t of e.assertion_ids)dt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${Wt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!Wt.includes(t))throw new L(`gate trigger must be one of ${Wt.join(", ")}`);return e.provider_policy&&Jg(e.provider_policy),e}function vn(e){if(e.version!==tu)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(fs(r),t.has(`measurement:${r.id}`))throw new L(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(ps(r),t.has(`assertion:${r.id}`))throw new L(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){ou(r);let i=r.assertion_ids.filter(o=>!e.assertions.some(s=>s.id===o));if(i.length>0)throw new L(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new L(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of su(e))if(!n.has(r))throw new L(`${i.join(", ")} references missing measurement ${r}`);return e}function hs(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)hs(n,t)}function su(e){let t=new Map,n=(r,i)=>{let o=t.get(r)??[];o.push(i),t.set(r,o)};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=[];hs(r.source.expression,i);for(let o of i)n(o,`derived measurement ${r.id}`)}return t}function Kg(e,t){let n=e.assertion_ids.flatMap(o=>{let s=t.assertions.find(a=>a.id===o);return[s.measurement_id,...s.scope.kind==="filter"?[s.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let o=n.pop();if(r.has(o))continue;r.add(o);let s=t.measurements.find(a=>a.id===o);s.source.kind==="provider"?i.add(s.source.provider):s.source.kind==="derived"&&hs(s.source.expression,n)}return i}function tr(){return{version:tu,measurements:[],assertions:[],gates:[]}}function Yg(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 o=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?o:!o}return ms(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Xg(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 Zg(e,t){let n=[],r=Fo(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let o of i.dependencies??[]){let s=Fo(o.kind)??o.kind.trim().toLowerCase(),a=o.source_kind?.trim();s===r&&Xg(e,a)&&n.push(`${i.id}->${o.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Qg(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 o=Reflect.get(i,"text");typeof o=="string"&&t.push(o)}}}return t}function ey(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 us(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function ty(e){let t=new Map,n=new Set,r=[],i=/\b[a-z][a-z0-9]*-[a-z0-9]+\b/giu,o=0;for(let s of e){t.set(s.id.toLowerCase(),s.id);for(let a of s.dependencies??[])n.add(us(s.id,a.id));for(let a of[s.parent,s.blocked_by])typeof a=="string"&&n.add(us(s.id,a));for(let a of Qg(s)){let c=[...a.matchAll(i)].map(l=>l[0]);o+=c.length,r.push({holder_id:s.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:o}}function ny(e,t){let n=ty(t.items),r=new Map;for(let s of n.prose_mentions){let a=s.mentioned_ids.map(l=>n.canonical_ids.get(l.toLowerCase())).filter(l=>l!==void 0&&l!==s.holder_id),c=[...new Set(a)];for(let l of c){let d=us(s.holder_id,l);if(n.linked_pairs.has(d)||ey(e.exemptions??[],s.holder_id,l,s.segment))continue;let u=c.some(m=>m!==l);r.get(d)?.explicit===!0&&!u||r.set(d,{contributor:`${s.holder_id}->${l}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],o=i.map(s=>s.contributor).sort();return{value:o.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:o.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(s=>s.explicit).length,implicit_subject:i.filter(s=>!s.explicit).length}}}function ry(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 iy(e,t){let n=t.items.filter(r=>{let i=r[e.link],o=Array.isArray(i)&&i.length>0;return e.state==="present"?o:!o});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function oy(e,t){let n=e.source;return n.kind==="items"?Yg(n,t):n.kind==="dependency_kind"?Zg(n,t):n.kind==="prose_edge_gap"?ny(n,t):n.kind==="history"?ry(n,t):n.kind==="links"?iy(n,t):null}function au(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 sy(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 cu(e,t,n){let r=new Array(e.length),i=0,o=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let s=i;i+=1,r[s]=await n(e[s],s)}});return await Promise.all(o),r}async function lu(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let s=n.find(l=>l.id===e.measurement);if(!s)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await du(s,t,n,r,i);if(typeof a.value!="number")throw new TypeError(`derived measurement ${s.id} is not numeric`);let c=i.charged.has(s.id)?[]:[a.cost];return i.charged.add(s.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let o=await cu(e.operands,nu,s=>lu(s,t,n,r,i));return{value:sy(e.operator,o.map(s=>s.value)),costs:o.flatMap(s=>s.costs),population_size:Math.max(0,...o.map(s=>s.population_size)),contributors:[...new Set(o.flatMap(s=>s.contributors))]}}async function ay(e,t,n,r,i){fs(e);let o=Date.now(),s,a=[],c=0;if(e.source.kind==="derived"){let u=await lu(e.source.expression,t,n,[...r,e.id],i);s={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=oy(e,t);u!==null?s=u:(s=await t.external(e.source),c=1)}let l={units:s.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()-o},d=au([...a,l],Date.now()-o);if(e.max_cost!==void 0&&d.units>e.max_cost)throw new Ie(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${d.units}`);return{id:e.id,definition_fingerprint:`sha256:${Mg("sha256").update(R(e)).digest("hex")}`,value:s.value,population_size:s.population_size,cost:d,contributors:s.contributors??[],...s.partitions?{partitions:s.partitions}:{}}}function du(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let o=i.cache.get(e.id);if(o)return o;let s=ay(e,t,n,r,i).catch(a=>{if(a instanceof Ze&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},l=new Ze(a.message,c);throw l.cause=a,l}throw a});return i.cache.set(e.id,s),s}async function _s(e,t,n=[e]){return du(e,t,n,[],{cache:new Map,charged:new Set})}function cy(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 ly(e,t,n={}){ps(e);let r=er(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:cy(t.value,r),verdict:i?"retired":ru(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:iu(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function dy(e,t,n,r){let i=Kg(e,t);if(i.size===0)return;let o=e.provider_policy,s=o?.triggers[r];if(!o||!s)throw new Ie(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let a=new Set(o.allowed_providers),c={low:0,medium:1,high:2};for(let l of i){if(!a.has(l))throw new Ie(`assurance gate ${e.id} refuses provider ${l}`);let d=n.provider_capabilities?.[l];if(!d)throw new Ie(`assurance provider ${l} has no declared capabilities`);if(c[d.cost_class]>c[s.max_cost_class])throw new Ie(`assurance gate ${e.id} refuses ${d.cost_class}-cost provider ${l} at trigger ${r}`);if(d.network&&!s.allow_network)throw new Ie(`assurance gate ${e.id} refuses network provider ${l} at trigger ${r}`)}}async function eu(e,t,n,r,i){try{return await _s(n,r,i)}catch(o){if(o instanceof Ze){let s=o.check?` check ${o.check}`:"",a=o.measurement_id??n.id,c=new Ie(`assurance gate ${e} assertion ${t} measurement ${a} source ${o.source_kind}${s} field ${o.field} could not resolve: ${o.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}});throw c.cause=o,c}throw o}}async function uu(e,t,n,r){vn(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}`);dy(i,t,n,r.trigger);let o=await cu(i.assertion_ids,nu,async c=>{let l=t.assertions.find(p=>p.id===c),d=t.measurements.find(p=>p.id===l.measurement_id),u=n;if(l.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(_=>!p.has(_.status))}}else if(l.scope.kind==="filter"){let p=l.scope.measurement_id,_=t.measurements.find(v=>v.id===p),h=await eu(i.id,l.id,_,n,t.measurements),w=new Set(h.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===l.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return ly(l,await eu(i.id,l.id,d,u,t.measurements),{owner_terminal:f})}),s=o.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=o.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:s?"block":a?"warn":"pass",exit_code:s?1:0,assertions:o,assertions_total:o.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:au(o.map(c=>c.cost),Math.max(0,...o.map(c=>c.cost.duration_ms)))}}function gi(e){return jg.join(e,"assurance.json")}async function mu(e){let t=await K(gi(e));return t===null?tr():yi(t)}function yi(e){try{return vn(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function wi(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function uy(e,t){e==="measurement"?fs(t):e==="assertion"?ps(t):ou(t)}async function nr(e,t){let n=structuredClone(wi(await mu(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function gs(e,t,n){let r=wi(await mu(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function vi(e,t,n,r={}){uy(t,n);let i=await T(e),o=q(r.author,i.author_default),s=await pn({pmRoot:e,filePath:gi(e),op:`assurance:${t}:put`,author:o,message:r.message,lockTtlSeconds:hi,lockWaitMs:_i,mutate:a=>{let c=a===null?tr():yi(a),l=wi(c,t),d=l.findIndex(m=>m.id===n.id),u=d<0?"created":"updated";if(t==="assertion"&&d>=0&&Gg(l[d],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new L(`loosening assertion ${n.id} requires a verified authorization_decision`)}return d<0?l.push(structuredClone(n)):l[d]=structuredClone(n),vn(c),{raw:`${JSON.stringify(c,null,2)}
2
2
  `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...s.result,changed:s.changed}}async function ys(e,t,n={}){let r=tr();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),vn(r);let i=await T(e),o=q(n.author,i.author_default),s=await pn({pmRoot:e,filePath:gi(e),op:"assurance:bundle:apply",author:o,message:n.message,lockTtlSeconds:hi,lockWaitMs:_i,mutate:a=>{let c=a===null?tr():yi(a),l=[],d=[],u=(m,f,p)=>{for(let _ of f){let h=m.find(w=>w.id===_.id);if(!h){m.push(structuredClone(_)),l.push(`${p}:${_.id}`);continue}if(R(h)!==R(_))throw new L(`assurance bundle refuses to replace divergent ${p} ${_.id}`);d.push(`${p}:${_.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),vn(c),{raw:`${JSON.stringify(c,null,2)}
3
3
  `,result:{changed:l.length>0,created_ids:l,unchanged_ids:d}}}});return{...s.result,changed:s.changed}}async function fu(e,t,n,r={}){let i=await T(e),o=q(r.author,i.author_default),s=await pn({pmRoot:e,filePath:gi(e),op:`assurance:${t}:remove`,author:o,message:r.message,lockTtlSeconds:hi,lockWaitMs:_i,mutate:a=>{let c=a===null?tr():yi(a);if(t==="measurement"){let u=su(c).get(n);if(u&&u.length>0)throw new L(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new L(`assurance assertion ${n} is referenced by gate`);let l=wi(c,t),d=l.findIndex(u=>u.id===n);if(d<0)throw new L(`assurance ${t} ${n} not found`);return l.splice(d,1),vn(c),{raw:`${JSON.stringify(c,null,2)}
4
4
  `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...s.result,changed:s.changed}}async function pu(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await T(e);await oi({pmRoot:e,op:"assurance:gate:verdict",author:q(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:hi,lockWaitMs:_i})}async function hu(e,t={}){let n=t.limit??zg;if(!Number.isInteger(n)||n<1||n>wn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${wn}`);return(await Ft(ii(e),fe)).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]="0daf7c89-abc5-5c35-ba3f-9772a50408c0")}catch{}})();var rr={type:"string",minLength:1,maxLength:128,pattern:"\\S"},bi={type:"array",minItems:1,maxItems:Vo,items:rr},_u={...bi,items:{...rr,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},my={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,bi])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:rr,id:rr}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:_u}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:bi}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:_u,authors:bi}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Vo,items:{type:"array",minItems:2,maxItems:2,items:rr}}}}]}}},UT={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:xl,items:my}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42dee0a5-d003-5e44-8b2d-d74a23d3f2ce")}catch{}})();async function gu(e,t,n,r){let i=await It(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:yu(i,t,n,r)}function fy(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function yu(e,t,n=5,r=!1){let i=[],o=new Map,s=e.policies.filter(h=>h.rule.kind==="require_fields"),a=s.filter(h=>h.subject?.operations===void 0),c=new Set,l=0,d=0,u=0,m=0,f=0,p=Rl(e);for(let h of t){let w=p({operation:"",author:"",before:h,after:h,completeness_only:!0});l+=+(w.decisions.length>0),d+=w.decisions.length,w.decisions.forEach(S=>c.add(S.policy_id));let v=w.decisions.filter(S=>!S.satisfied);if(v.length===0)continue;m+=1;let k=o.get(h.type)??{items:0,violations:0,missing_fields:0};k.items+=1;for(let S of v)u+=1,k.violations+=1,k.missing_fields+=S.missing_fields.length,S.effect==="refuse"&&(f+=1),i.length<n&&i.push({id:h.id,type:h.type,status:h.status,decision:S});o.set(h.type,k)}let _=r||f>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:_,ok:_==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:s.length,state_requirement_count:a.length,applicable_requirement_count:c.size,requirement_application_count:d,governed_items:l,ungoverned_items:t.length-l,contract_status:fy(s.length,t.length,l),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:u,refused_violations:f,missing_by_type:Object.fromEntries(o),violations:i,violations_truncated:i.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}import py 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]="f54fe358-8f4c-5bf4-ae2a-9c92cd08c953")}catch{}})();function hy(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([t,n])=>({id:`completeness-${t.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${t} work reaches completion.`,subject:{types:[t],statuses:["closed"]},rule:{kind:"require_fields",fields:[...n]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function bu(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new y("Policy definition must be valid JSON.",g.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("Policy definition must be an object.",g.USAGE);return t}async function _y(e,t){let n=N(process.cwd(),e.path);await te(n);let r=await T(n);return{pmRoot:n,settings:r,author:q(t,r.author_default)}}function wu(e,t,n,r){if(e==="policy-mode")return Ko({...n,enforcement:t});let i=n.policies.filter(a=>a.id!==t);if(e==="policy-remove")return{...n,policies:i};let o=Jo(r.definition),s=Ko({...n,policies:[...i,o].sort((a,c)=>a.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(s,null,2)}
5
5
  `)>kd)throw new y("Policy registry exceeds its byte ceiling.",g.USAGE);return s}async function vu(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:wu(e,t,await It(r.pmRoot),n)};let i=await pn({pmRoot:r.pmRoot,filePath:py.join(r.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:r.author,message:n.message,lockTtlSeconds:r.settings.locks.ttl_seconds,lockWaitMs:r.settings.locks.wait_ms,mutate(o){let s=wu(e,t,Sd(o),n);return{raw:`${JSON.stringify(s,null,2)}
6
- `,result:s}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function gy(e,t,n){let r,i=await Td({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(o){let a=(await It(n.pmRoot)).policies.find(c=>c.id===t.policy);if(!a||a.rule.kind!=="approval")throw new y("--policy must name an approval rule.",g.USAGE);if(!a.rule.authors.includes(n.author))throw new y("This actor is not a declared approver.",g.CONFLICT);return await Ed(n.pmRoot,o.metadata.id),r={policy_id:a.id,policy_fingerprint:Il(a),content_fingerprint:Al(a,{...o.metadata,body:o.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...r,warnings:i.warnings}}}function yy(e,t){let n=bu(t),r=Jo({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==r.id)throw new y("Policy id operand does not match definition.id.",g.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return r}async function s$(e,t,n={},r={}){if(!qr.includes(e))throw new y("Unknown workflow policy action.",g.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:hy()};let i=await _y(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await It(i.pmRoot)};if(e==="policy-put"){let d=yy(t,n.definition);return vu(e,d.id,{...n,definition:d},i)}if(!t?.trim())throw new y(`schema ${e} requires an operand.`,g.USAGE);if(["policy-remove","policy-mode"].includes(e))return vu(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new y("Use policy-check to preview; policy-approve records an approval.",g.USAGE);return gy(t,n,i)}let o=G(i.settings,H()),s=await Pe(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,o.type_to_folder);if(!s)throw new y(`Item ${t} not found.`,g.NOT_FOUND);let{document:a}=await Ne(s,{schema:i.settings.schema}),c={...a.metadata,body:a.body},l=n.definition===void 0?c:{...c,...bu(n.definition)};if(l.id!==c.id)throw new y("Policy preview cannot change the item id.",g.USAGE);return{policy_result:!0,action:e,changed:!1,result:await xd(i.pmRoot,await It(i.pmRoot),{operation:"update",author:i.author,before:c,after:l,completeness_only:n.definition===void 0})}}import{createHash as Du}from"node:crypto";import ir from"node:fs/promises";import or from"node:path";import{Option as I$}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ffd5046-9154-52e7-94ce-192b07b8ceae")}catch{}})();function wy(e,t){let n=[],r=new Set;for(let i of t.keys){if(!Object.hasOwn(e,i))continue;let o=e[i];if(o!=null){if(typeof o=="string"){n.push(o);continue}if(!Array.isArray(o)||!o.every(s=>typeof s=="string"))return;r.has(o)||(r.add(o),n.push(...o))}}return n.length>0?n.join("; "):void 0}function ki(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function F(e,t){return e[t]===!0?!0:void 0}function ut(e,t){return e[t]===!1?!0:void 0}function ku(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Su(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function Eu(e){let t=i=>zo(e,ki(Xr,i)),n=i=>ll(e,ki(Xo,i)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:wy(e,ki(Xo,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),allowUnresolvedDeps:ku(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:F(e,"replaceDeps"),replaceTests:F(e,"replaceTests"),replaceFiles:F(e,"replaceFiles"),replaceDocs:F(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:F(e,"clearDeps"),clearComments:F(e,"clearComments"),clearNotes:F(e,"clearNotes"),clearLearnings:F(e,"clearLearnings"),clearFiles:F(e,"clearFiles"),clearTests:F(e,"clearTests"),clearDocs:F(e,"clearDocs"),clearReminders:F(e,"clearReminders"),clearEvents:F(e,"clearEvents"),clearTypeOptions:F(e,"clearTypeOptions")};return Su(r,e),r}function re(e,t){let n=ki(cl,t),r=zo(e,n);if(r!==void 0)return r;for(let i of n.keys){let o=e[i];if(Array.isArray(o)){let s=o.filter(a=>typeof a=="string");if(s.length>0)return s.join(",")}if(t==="ids"&&typeof o=="string")return o;if(typeof o=="number"&&Number.isFinite(o))return String(o)}}function vy(e){let t=F(e,"filterFilesMissing"),n=F(e,"filterDocsMissing");return{filterReviewerMissing:F(e,"filterReviewerMissing"),filterRiskMissing:F(e,"filterRiskMissing"),filterConfidenceMissing:F(e,"filterConfidenceMissing"),filterSprintMissing:F(e,"filterSprintMissing"),filterReleaseMissing:F(e,"filterReleaseMissing"),hasNotes:F(e,"hasNotes"),hasLearnings:F(e,"hasLearnings"),hasFiles:F(e,"hasFiles"),hasDocs:F(e,"hasDocs"),hasTests:F(e,"hasTests"),hasComments:F(e,"hasComments"),hasDeps:F(e,"hasDeps"),hasBody:F(e,"hasBody"),hasLinkedCommand:F(e,"hasLinkedCommand"),noNotes:ut(e,"notes"),noLearnings:ut(e,"learnings"),noFiles:ut(e,"files")??t,filterFilesMissing:t,noDocs:ut(e,"docs")??n,filterDocsMissing:n,noTests:ut(e,"tests"),noComments:ut(e,"comments"),noDeps:ut(e,"deps"),emptyBody:F(e,"emptyBody"),noLinkedCommand:ut(e,"linkedCommand")}}function xu(e){let t={status:re(e,"status"),type:re(e,"type"),tag:re(e,"tag"),priority:re(e,"priority"),deadlineBefore:re(e,"deadlineBefore"),deadlineAfter:re(e,"deadlineAfter"),updatedAfter:re(e,"updatedAfter"),updatedBefore:re(e,"updatedBefore"),createdAfter:re(e,"createdAfter"),createdBefore:re(e,"createdBefore"),today:F(e,"today"),recent:F(e,"recent"),ids:re(e,"ids"),assignee:re(e,"assignee"),assigneeFilter:re(e,"assigneeFilter"),parent:re(e,"parent"),sprint:re(e,"sprint"),release:re(e,"release"),limit:re(e,"limit"),offset:re(e,"offset"),noTruncate:ut(e,"truncate"),includeBody:F(e,"includeBody"),strictRead:F(e,"strictRead"),compact:F(e,"compact"),brief:F(e,"brief"),full:F(e,"full"),fields:re(e,"fields"),sort:re(e,"sort"),order:re(e,"order"),tree:F(e,"tree"),treeDepth:re(e,"treeDepth"),filterAcMissing:F(e,"filterAcMissing"),filterEstimatesMissing:ku(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:F(e,"filterResolutionMissing"),filterMetadataMissing:F(e,"filterMetadataMissing"),...vy(e)};return Su(t,e),t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fb87ff0c-88c8-52f9-9dc3-f37fec674425")}catch{}})();var by=Symbol("pm.mcp-mutation-transport"),ky=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function Ei(e){return by in e}function xi(e,t){return Ei(e)?hd(t):ns(e,t)}function j$(e,t,n=[]){let r=ns(e,{...e,...t});for(let i of n)Reflect.deleteProperty(r,i);return r}function O(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function se(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 F$(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function bn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bs(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new y(`${t} must be a finite integer.`,g.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new y(`${t} must be a finite integer.`,g.USAGE);return n}}function U$(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 z$(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:se(e,"outputLimit"),outputBudget:se(e,"outputBudget"),outputSession:O(e,"outputSession"),outputCursor:O(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Sy=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Au=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"]),Ey=new Set([...Au].filter(e=>e!=="file")),xy=new Set(["files","files-discover","docs","test","test-all"]),Ru=new Set(["comments","notes","learnings"]);function Iy(e,t){if(!(!Ru.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new y(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,g.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var Ay=new Set(["claim","release","start-task","pause-task","close-task"]),Ry={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun"],package:["dryRun"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Cy=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Cu(e,t=""){let n={},r=xy.has(t),i=t==="files"||t==="files-discover"||t==="docs",o=Ru.has(t)?Ey:Au;for(let[s,a]of Object.entries(e)){if(Array.isArray(a)&&Sy.has(s)){n[s]=a.join(",");continue}if(s==="note"&&i){n[s]=a;continue}if(typeof a=="string"&&o.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 Ty(e,t,n){let r=O(e,"author");return r!==void 0?r:n!==void 0&&Ay.has(n)?O(e,"assignee")??O(t,"assignee"):void 0}function $y(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function H$(e,t){let n=bn(e.options)?e.options:void 0,r=Zc(e.options),i={},o=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of Ry[t??""]??[])o(c);for(let c of Cy)o(c);t!==void 0&&Ei(e)&&Iy(t,r);let s=Cu({...i,...r},t);if(t==="history-attest"&&Ei(e)&&(s.output!==void 0||typeof s.verify=="string"))throw new y("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",g.USAGE);let a=Ei(e)?e:n??e;return xi(a,$y(s,Ty(e,s,t)))}function W$(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 G$(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 Oy(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 q$(e){return!ky.has(Oy(e))}function B$(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function ks(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function V$(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[o,s]of Object.entries(e))n.has(o)||(r[o]=s);let i={...r,...t};return delete i.args,i}function J$(e,t){let n=xi(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function vs(e){return{type:se(e,"filterType"),tag:se(e,"filterTag"),priority:se(e,"filterPriority"),deadlineBefore:se(e,"filterDeadlineBefore"),deadlineAfter:se(e,"filterDeadlineAfter"),updatedAfter:se(e,"filterUpdatedAfter"),updatedBefore:se(e,"filterUpdatedBefore"),createdAfter:se(e,"filterCreatedAfter"),createdBefore:se(e,"filterCreatedBefore"),ids:rs(e.ids),assignee:se(e,"filterAssignee"),assigneeFilter:se(e,"filterAssigneeFilter")??se(e,"filterAssignee_filter"),parent:se(e,"filterParent"),sprint:se(e,"filterSprint"),release:se(e,"filterRelease"),limit:se(e,"limit"),offset:se(e,"offset")}}function ws(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return ks(e)}function Si(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function K$(e){let t=ws(e.kind),n=ws(e.exemptIsolate),r=ws(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Si(e.maxDepth),limit:Si(e.limit),after:O(e,"after"),direction:O(e,"direction"),maxPaths:Si(e.maxPaths),sample:Si(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 Tu(e){let t=xu(e);return e.ids!==void 0&&(t.ids=rs(e.ids)),t}function Y$(e){return{status:O(e,"filterStatus"),list:bn(e.list)?Tu(e.list):vs(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 Dy=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 Iu(e){let t={};for(let[n,r]of Object.entries(e))Dy.has(n)||(t[n]=r);return $u(t)}function $u(e){let t=Cu(e,"update-many");for(let n of Xr)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return Eu(t)}function X$(e){if(bn(e.list)||bn(e.update)){let t=bn(e.update)?e.update:Iu(e),n=xi(e,$u(t));return{status:se(e,"filterStatus"),list:bn(e.list)?Tu(e.list):vs(e),update:_d(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:O(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:se(e,"filterStatus"),list:vs(e),update:xi(e,Iu(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}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd8c4c35-98bb-5f3b-927d-8696125af703")}catch{}})();function Le(e,t){throw new y(e,g.USAGE,t)}var Py="2026-07-15T06:22:12.276Z",Ny=Date.parse(Py),Ly=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Ou=e=>typeof e=="string"?e:"",Pu=e=>{let t=e??{},n=Ou(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Ou(t.ts))>=Ny);return Ly[r][i]};function Nu(e,t,n=20,r=new Set,i=!1){let o=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}l+=1;let _=Pu(p);if(_!=="attributed"){if(d+=1,_==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}a[_]+=1,i&&_==="actionable_unknown"&&s.push({item_id:e,line:m+1}),o.length<c&&o.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:a.legacy_unknown+a.actionable_unknown>o.length,actionable_events:s}}var aO=(e,t,n=20,r=new Set)=>Nu(e,t,n,r);function Lu(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let o=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof o!="object"||o===null||!Array.isArray(o.events)))for(let s of o.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var sr=async(e,t=20,n=!1)=>{let r=or.join(e,"history"),i;try{i=(await ir.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let o=new Set,s=[],a=[],c=0,l=0,d=0,u=0,m=0,f=0,p="_workspace.jsonl",_=new Set;if(i.includes(p))try{_=Lu(await ir.readFile(or.join(r,p),"utf8"))}catch{_=new Set}for(let w of i){let v;try{v=await ir.readFile(or.join(r,w),"utf8")}catch{continue}let k=w.slice(0,-6),S=Nu(k,v,t-s.length,_,n);c+=1,l+=S.checked_events,d+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,f+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&o.add(k),s.push(...S.samples),n&&a.push(...S.actionable_events)}let h=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...o].sort((w,v)=>w.localeCompare(v)),samples:s,samples_truncated:h>s.length,...n?{actionable_events:a}:{}}};function My(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 jy(e){try{return Lu(await ir.readFile(or.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function Fy(e){return(e.item_id===fe||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function Uy(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Le(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Pu(i)!=="actionable_unknown"&&Le(`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:Du("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Mu(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Le("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Le("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Le("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let o=My(t.all_actionable===!0?(await sr(e,0,!0)).actionable_events:r),s=await jy(e),a=new Map;for(let m of o)if(Fy(m)||Le(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(m.item_id))try{a.set(m.item_id,(await ir.readFile(or.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Le(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=o.map(m=>Uy(m,s,a.get(m.item_id))),l=t.all_actionable===!0?"all_actionable":"events",d=Du("sha256").update(JSON.stringify({version:1,selection:l,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:l},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:d},completeCoordinates:c}}async function cO(e,t,n=50){return(await Mu(e,t,n)).plan}function zy(e,t){let n=e.length>0;return n&&t&&Le("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&&Le("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:Hy(e),all_actionable:t}}function Hy(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),o=r===fe||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!o||!Number.isSafeInteger(i)||i<1)&&Le(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function lO(e,t){let n=zy(ks(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Wy(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 Wy(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",o=await Mu(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:g.SUCCESS,plan:o.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Le("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Le("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()!==o.plan.plan_fingerprint)throw new y("Author acknowledgment selection changed after preview; no history was mutated.",g.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let a=o.completeCoordinates.filter(({disposition:u})=>o.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:m})=>({item_id:u,line:m}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:g.NO_EFFECT,plan:o.plan};let c=await T(e),l=await oi({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:r}},message:i,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),d=o.plan.actionable_count>0&&o.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:g.PARTIAL_EFFECT}:{outcome:"effect",exit_code:g.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...d,plan:o.plan,history_path:l.historyPath}}import{execFile as Gy}from"node:child_process";import ju from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1d4534aa-5a56-5a76-8971-aa3ba6c52e59")}catch{}})();function Fu(e,t){return new Promise((n,r)=>{Gy("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,o)=>{i?r(i):n(o)})})}function Uu(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 pO(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Uu(n),!n)throw new RangeError("Source line range must use start:end.");return n}function qy(e){let t=new Map;for(let n of e.split(`
6
+ `,result:s}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function gy(e,t,n){let r,i=await Td({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(o){let a=(await It(n.pmRoot)).policies.find(c=>c.id===t.policy);if(!a||a.rule.kind!=="approval")throw new y("--policy must name an approval rule.",g.USAGE);if(!a.rule.authors.includes(n.author))throw new y("This actor is not a declared approver.",g.CONFLICT);return await Ed(n.pmRoot,o.metadata.id),r={policy_id:a.id,policy_fingerprint:Il(a),content_fingerprint:Al(a,{...o.metadata,body:o.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...r,warnings:i.warnings}}}function yy(e,t){let n=bu(t),r=Jo({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==r.id)throw new y("Policy id operand does not match definition.id.",g.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return r}async function s$(e,t,n={},r={}){if(!qr.includes(e))throw new y("Unknown workflow policy action.",g.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:hy()};let i=await _y(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await It(i.pmRoot)};if(e==="policy-put"){let d=yy(t,n.definition);return vu(e,d.id,{...n,definition:d},i)}if(!t?.trim())throw new y(`schema ${e} requires an operand.`,g.USAGE);if(["policy-remove","policy-mode"].includes(e))return vu(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new y("Use policy-check to preview; policy-approve records an approval.",g.USAGE);return gy(t,n,i)}let o=G(i.settings,H()),s=await Pe(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,o.type_to_folder);if(!s)throw new y(`Item ${t} not found.`,g.NOT_FOUND);let{document:a}=await Ne(s,{schema:i.settings.schema}),c={...a.metadata,body:a.body},l=n.definition===void 0?c:{...c,...bu(n.definition)};if(l.id!==c.id)throw new y("Policy preview cannot change the item id.",g.USAGE);return{policy_result:!0,action:e,changed:!1,result:await xd(i.pmRoot,await It(i.pmRoot),{operation:"update",author:i.author,before:c,after:l,completeness_only:n.definition===void 0})}}import{createHash as Du}from"node:crypto";import ir from"node:fs/promises";import or from"node:path";import{Option as I$}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ffd5046-9154-52e7-94ce-192b07b8ceae")}catch{}})();function wy(e,t){let n=[],r=new Set;for(let i of t.keys){if(!Object.hasOwn(e,i))continue;let o=e[i];if(o!=null){if(typeof o=="string"){n.push(o);continue}if(!Array.isArray(o)||!o.every(s=>typeof s=="string"))return;r.has(o)||(r.add(o),n.push(...o))}}return n.length>0?n.join("; "):void 0}function ki(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function F(e,t){return e[t]===!0?!0:void 0}function ut(e,t){return e[t]===!1?!0:void 0}function ku(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Su(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function Eu(e){let t=i=>zo(e,ki(Xr,i)),n=i=>ll(e,ki(Xo,i)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:wy(e,ki(Xo,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),allowUnresolvedDeps:ku(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:F(e,"replaceDeps"),replaceTests:F(e,"replaceTests"),replaceFiles:F(e,"replaceFiles"),replaceDocs:F(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:F(e,"clearDeps"),clearComments:F(e,"clearComments"),clearNotes:F(e,"clearNotes"),clearLearnings:F(e,"clearLearnings"),clearFiles:F(e,"clearFiles"),clearTests:F(e,"clearTests"),clearDocs:F(e,"clearDocs"),clearReminders:F(e,"clearReminders"),clearEvents:F(e,"clearEvents"),clearTypeOptions:F(e,"clearTypeOptions")};return Su(r,e),r}function re(e,t){let n=ki(cl,t),r=zo(e,n);if(r!==void 0)return r;for(let i of n.keys){let o=e[i];if(Array.isArray(o)){let s=o.filter(a=>typeof a=="string");if(s.length>0)return s.join(",")}if(t==="ids"&&typeof o=="string")return o;if(typeof o=="number"&&Number.isFinite(o))return String(o)}}function vy(e){let t=F(e,"filterFilesMissing"),n=F(e,"filterDocsMissing");return{filterReviewerMissing:F(e,"filterReviewerMissing"),filterRiskMissing:F(e,"filterRiskMissing"),filterConfidenceMissing:F(e,"filterConfidenceMissing"),filterSprintMissing:F(e,"filterSprintMissing"),filterReleaseMissing:F(e,"filterReleaseMissing"),hasNotes:F(e,"hasNotes"),hasLearnings:F(e,"hasLearnings"),hasFiles:F(e,"hasFiles"),hasDocs:F(e,"hasDocs"),hasTests:F(e,"hasTests"),hasComments:F(e,"hasComments"),hasDeps:F(e,"hasDeps"),hasBody:F(e,"hasBody"),hasLinkedCommand:F(e,"hasLinkedCommand"),noNotes:ut(e,"notes"),noLearnings:ut(e,"learnings"),noFiles:ut(e,"files")??t,filterFilesMissing:t,noDocs:ut(e,"docs")??n,filterDocsMissing:n,noTests:ut(e,"tests"),noComments:ut(e,"comments"),noDeps:ut(e,"deps"),emptyBody:F(e,"emptyBody"),noLinkedCommand:ut(e,"linkedCommand")}}function xu(e){let t={status:re(e,"status"),type:re(e,"type"),tag:re(e,"tag"),priority:re(e,"priority"),deadlineBefore:re(e,"deadlineBefore"),deadlineAfter:re(e,"deadlineAfter"),updatedAfter:re(e,"updatedAfter"),updatedBefore:re(e,"updatedBefore"),createdAfter:re(e,"createdAfter"),createdBefore:re(e,"createdBefore"),today:F(e,"today"),recent:F(e,"recent"),ids:re(e,"ids"),assignee:re(e,"assignee"),assigneeFilter:re(e,"assigneeFilter"),parent:re(e,"parent"),sprint:re(e,"sprint"),release:re(e,"release"),limit:re(e,"limit"),offset:re(e,"offset"),noTruncate:ut(e,"truncate"),includeBody:F(e,"includeBody"),strictRead:F(e,"strictRead"),compact:F(e,"compact"),brief:F(e,"brief"),full:F(e,"full"),fields:re(e,"fields"),sort:re(e,"sort"),order:re(e,"order"),tree:F(e,"tree"),treeDepth:re(e,"treeDepth"),filterAcMissing:F(e,"filterAcMissing"),filterEstimatesMissing:ku(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:F(e,"filterResolutionMissing"),filterMetadataMissing:F(e,"filterMetadataMissing"),...vy(e)};return Su(t,e),t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17883200-00ba-51ef-8a6b-ab0ce2ad2029")}catch{}})();var by=Symbol("pm.mcp-mutation-transport"),ky=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function Ei(e){return by in e}function xi(e,t){return Ei(e)?hd(t):ns(e,t)}function j$(e,t,n=[]){let r=ns(e,{...e,...t});for(let i of n)Reflect.deleteProperty(r,i);return r}function O(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function se(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 F$(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function bn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bs(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new y(`${t} must be a finite integer.`,g.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new y(`${t} must be a finite integer.`,g.USAGE);return n}}function U$(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 z$(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:se(e,"outputLimit"),outputBudget:se(e,"outputBudget"),outputSession:O(e,"outputSession"),outputCursor:O(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Sy=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Au=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"]),Ey=new Set([...Au].filter(e=>e!=="file")),xy=new Set(["files","files-discover","docs","test","test-all"]),Ru=new Set(["comments","notes","learnings"]);function Iy(e,t){if(!(!Ru.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new y(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,g.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var Ay=new Set(["claim","release","start-task","pause-task","close-task"]),Ry={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun"],package:["dryRun"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Cy=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Cu(e,t=""){let n={},r=xy.has(t),i=t==="files"||t==="files-discover"||t==="docs",o=Ru.has(t)?Ey:Au;for(let[s,a]of Object.entries(e)){if(Array.isArray(a)&&Sy.has(s)){n[s]=a.join(",");continue}if(s==="note"&&i){n[s]=a;continue}if(typeof a=="string"&&o.has(s)){n[s]=[a];continue}if(typeof a=="string"&&r&&(s==="add"||s==="remove")){n[s]=[a];continue}n[s]=a}return Object.assign(n,Object.fromEntries(Object.getOwnPropertySymbols(e).map(s=>[s,Reflect.get(e,s)]))),n}function Ty(e,t,n){let r=O(e,"author");return r!==void 0?r:n!==void 0&&Ay.has(n)?O(e,"assignee")??O(t,"assignee"):void 0}function $y(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function H$(e,t){let n=bn(e.options)?e.options:void 0,r=Zc(e.options),i={},o=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of Ry[t??""]??[])o(c);for(let c of Cy)o(c);t!==void 0&&Ei(e)&&Iy(t,r);let s=Cu({...i,...r},t);if(t==="history-attest"&&Ei(e)&&(s.output!==void 0||typeof s.verify=="string"))throw new y("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",g.USAGE);let a=Ei(e)?e:n??e;return xi(a,$y(s,Ty(e,s,t)))}function W$(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 G$(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 Oy(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 q$(e){return!ky.has(Oy(e))}function B$(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function ks(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function V$(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[o,s]of Object.entries(e))n.has(o)||(r[o]=s);let i={...r,...t};return delete i.args,i}function J$(e,t){let n=xi(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function vs(e){return{type:se(e,"filterType"),tag:se(e,"filterTag"),priority:se(e,"filterPriority"),deadlineBefore:se(e,"filterDeadlineBefore"),deadlineAfter:se(e,"filterDeadlineAfter"),updatedAfter:se(e,"filterUpdatedAfter"),updatedBefore:se(e,"filterUpdatedBefore"),createdAfter:se(e,"filterCreatedAfter"),createdBefore:se(e,"filterCreatedBefore"),ids:rs(e.ids),assignee:se(e,"filterAssignee"),assigneeFilter:se(e,"filterAssigneeFilter")??se(e,"filterAssignee_filter"),parent:se(e,"filterParent"),sprint:se(e,"filterSprint"),release:se(e,"filterRelease"),limit:se(e,"limit"),offset:se(e,"offset")}}function ws(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return ks(e)}function Si(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function K$(e){let t=ws(e.kind),n=ws(e.exemptIsolate),r=ws(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Si(e.maxDepth),limit:Si(e.limit),after:O(e,"after"),direction:O(e,"direction"),maxPaths:Si(e.maxPaths),sample:Si(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 Tu(e){let t=xu(e);return e.ids!==void 0&&(t.ids=rs(e.ids)),t}function Y$(e){return{status:O(e,"filterStatus"),list:bn(e.list)?Tu(e.list):vs(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 Dy=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 Iu(e){let t={};for(let[n,r]of Object.entries(e))Dy.has(n)||(t[n]=r);return $u(t)}function $u(e){let t=Cu(e,"update-many");for(let n of Xr)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return Eu(t)}function X$(e){if(bn(e.list)||bn(e.update)){let t=bn(e.update)?e.update:Iu(e),n=xi(e,$u(t));return{status:se(e,"filterStatus"),list:bn(e.list)?Tu(e.list):vs(e),update:_d(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:O(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:se(e,"filterStatus"),list:vs(e),update:xi(e,Iu(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}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd8c4c35-98bb-5f3b-927d-8696125af703")}catch{}})();function Le(e,t){throw new y(e,g.USAGE,t)}var Py="2026-07-15T06:22:12.276Z",Ny=Date.parse(Py),Ly=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Ou=e=>typeof e=="string"?e:"",Pu=e=>{let t=e??{},n=Ou(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Ou(t.ts))>=Ny);return Ly[r][i]};function Nu(e,t,n=20,r=new Set,i=!1){let o=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}l+=1;let _=Pu(p);if(_!=="attributed"){if(d+=1,_==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}a[_]+=1,i&&_==="actionable_unknown"&&s.push({item_id:e,line:m+1}),o.length<c&&o.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:a.legacy_unknown+a.actionable_unknown>o.length,actionable_events:s}}var aO=(e,t,n=20,r=new Set)=>Nu(e,t,n,r);function Lu(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let o=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof o!="object"||o===null||!Array.isArray(o.events)))for(let s of o.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var sr=async(e,t=20,n=!1)=>{let r=or.join(e,"history"),i;try{i=(await ir.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let o=new Set,s=[],a=[],c=0,l=0,d=0,u=0,m=0,f=0,p="_workspace.jsonl",_=new Set;if(i.includes(p))try{_=Lu(await ir.readFile(or.join(r,p),"utf8"))}catch{_=new Set}for(let w of i){let v;try{v=await ir.readFile(or.join(r,w),"utf8")}catch{continue}let k=w.slice(0,-6),S=Nu(k,v,t-s.length,_,n);c+=1,l+=S.checked_events,d+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,f+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&o.add(k),s.push(...S.samples),n&&a.push(...S.actionable_events)}let h=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...o].sort((w,v)=>w.localeCompare(v)),samples:s,samples_truncated:h>s.length,...n?{actionable_events:a}:{}}};function My(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 jy(e){try{return Lu(await ir.readFile(or.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function Fy(e){return(e.item_id===fe||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function Uy(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Le(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Pu(i)!=="actionable_unknown"&&Le(`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:Du("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Mu(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Le("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Le("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Le("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let o=My(t.all_actionable===!0?(await sr(e,0,!0)).actionable_events:r),s=await jy(e),a=new Map;for(let m of o)if(Fy(m)||Le(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(m.item_id))try{a.set(m.item_id,(await ir.readFile(or.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Le(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=o.map(m=>Uy(m,s,a.get(m.item_id))),l=t.all_actionable===!0?"all_actionable":"events",d=Du("sha256").update(JSON.stringify({version:1,selection:l,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:l},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:d},completeCoordinates:c}}async function cO(e,t,n=50){return(await Mu(e,t,n)).plan}function zy(e,t){let n=e.length>0;return n&&t&&Le("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&&Le("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:Hy(e),all_actionable:t}}function Hy(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),o=r===fe||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!o||!Number.isSafeInteger(i)||i<1)&&Le(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function lO(e,t){let n=zy(ks(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Wy(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 Wy(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",o=await Mu(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:g.SUCCESS,plan:o.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Le("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Le("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()!==o.plan.plan_fingerprint)throw new y("Author acknowledgment selection changed after preview; no history was mutated.",g.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let a=o.completeCoordinates.filter(({disposition:u})=>o.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:m})=>({item_id:u,line:m}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:g.NO_EFFECT,plan:o.plan};let c=await T(e),l=await oi({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:r}},message:i,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),d=o.plan.actionable_count>0&&o.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:g.PARTIAL_EFFECT}:{outcome:"effect",exit_code:g.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...d,plan:o.plan,history_path:l.historyPath}}import{execFile as Gy}from"node:child_process";import ju from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1d4534aa-5a56-5a76-8971-aa3ba6c52e59")}catch{}})();function Fu(e,t){return new Promise((n,r)=>{Gy("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,o)=>{i?r(i):n(o)})})}function Uu(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 pO(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Uu(n),!n)throw new RangeError("Source line range must use start:end.");return n}function qy(e){let t=new Map;for(let n of e.split(`
7
7
  `)){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 By(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 o=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((s,a)=>s.localeCompare(a));n.set(i,o)}return n}async function Vy(e){let t=ju.relative(e.workspaceRoot,ju.resolve(e.workspaceRoot,e.sourcePath)),n=await Fu(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Fu(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:qy(n),commitItems:By(r),available:!0}}function Jy(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let o=i.source===t,s=o?i.target:i.source;if((e.visitedDepth.get(s)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(s,n);let a=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,s],kinds:[...e.current.kinds,o?i.kind:a.inverse??i.kind]};e.details.get(s)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function Ky(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let o=t.shift(),s=o.kinds.length;i!==void 0&&s>=i||s>=e.maxDepth||(i=Jy({current:o,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((o,s)=>o.nodes.join("\0").localeCompare(s.nodes.join("\0"))),r}function Yy(e,t,n){let r=Jd(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=Ky({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(a=>[a.id,a]))}),o=i[0];if(!o)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let s=[...new Set(i.map(a=>a.nodes.at(-1)))];return{status:s.length===1?"found":"ambiguous",nodes:o.nodes,kinds:o.kinds,alternative_decision_ids:s.slice(1)}}async function Xy(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await Vy({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function Zy(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 Qy(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function zu(e){Uu(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 Xy(e),r=Qy(n),i=new Map;for(let o of e.candidates){let s=[...n.commitLines.entries()].filter(([d])=>n.commitItems.get(d)?.includes(o.item.id)),a=s.reduce((d,[,u])=>d+u,0),c=Yy(o.item.id,e.corpus,t),l=Zy({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});i.set(o.item.id,{score:a*100+o.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(o.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...o.files.map(d=>({kind:"linked_file",reference:d.path})),...s.map(([d,u])=>({kind:"git_commit",reference:d.slice(0,12),contribution_lines:u}))],rationale:{value:o.item.value?.trim()||null,why_now:o.item.why_now?.trim()||null,outcome:o.item.outcome?.trim()||null,objective:o.item.objective?.trim()||null},decision_path:c,ambiguities:l})}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}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7470da18-4b85-5090-8ede-7de708b1f4ff")}catch{}})();var ar=["software-delivery","research","agent-evaluation","operations"];function Hu(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 Ii(e,t,n,r,i){let o=`preset-${e}`,s=i.map(c=>({id:`${o}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),a=s.map(c=>Hu(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:s,assertions:a,gates:[{id:`${o}-readiness`,description:n,assertion_ids:a.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Ai(e,t){return e==="software-delivery"?Ii(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Ii(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Ii(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Ii(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function Wu(e,t,n,r={}){return ys(e,Ai(t,n).declarations,r)}async function Gu(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(o=>!n.has(o.status))};return await Promise.all(["files","tests","docs"].map(async o=>{let s={id:`derived-active-missing-${o}`,description:`Observed active items missing ${o} evidence.`,source:{kind:"links",link:o,state:"missing"}},c=(await _s(s,r)).value,l=Hu(`${s.id}-ceiling`,s.id,t,c,"observe"),d=`active-missing-${o}`;return{id:d,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[s],assertions:[l],gates:[{id:`derived-${d}`,description:`Observe the accepted ${o} evidence baseline.`,assertion_ids:[l.id],triggers:["ci","scheduled"]}]}}}))}function qu(e,t,n={}){return ys(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 Bu(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 vi(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Ku from"node:fs/promises";import{createRequire as ew}from"node:module";import Ae from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a0014621-9e3d-5620-8f36-081811054843")}catch{}})();function Vu(e,t){let n=Ae.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Ae.sep}`)&&!Ae.isAbsolute(n))return n.split(Ae.sep).join("/");let r=Ae.resolve(e),i=0xcbf29ce484222325n;for(let s=0;s<r.length;s+=1)i^=BigInt(r.charCodeAt(s)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Ae.basename(Ae.dirname(e))}/package.json`}function tw(e){return e.includes(`${Ae.sep}.pnpm${Ae.sep}`)?"pnpm":e.includes(`${Ae.sep}node_modules${Ae.sep}`)?"npm":"other"}async function Ju(e){try{let t=JSON.parse(await Ku.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 Ss(e){try{return await Ku.realpath(e)}catch{return Ae.resolve(e)}}async function Yu(e,t,n=$e(import.meta.url,["../../.."])){let r=await Ss(t),i=await Ss(Ae.join(n,"package.json")),o=await Ju(i),s=new Map;o!==void 0&&s.set(i,{version:o,path:Vu(i,r),layout:"host",consumers:["pm-cli-host"]});for(let l of e)try{let d=ew(l.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await Ss(d),m=await Ju(u);if(m===void 0)continue;let f=u,p=s.get(f);if(p){p.consumers.includes(l.name)||(p.consumers.push(l.name),p.consumers.sort((_,h)=>_.localeCompare(h)));continue}s.set(f,{version:m,path:Vu(u,r),layout:tw(u),consumers:[l.name]})}catch{}let a=[...s.values()].sort((l,d)=>l.path.localeCompare(d.path)),c=o===void 0?[]:a.filter(l=>l.version!==o);return{host_version:o??null,copies:a,mismatches:c,warnings:c.map(l=>`extension_host_pm_cli_version_skew:${o}:${l.version}:${l.consumers.join("+")}`)}}import Es from"node:fs/promises";import xs 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]="86c82880-d6c1-5d03-b786-222421f1146d")}catch{}})();var Xu=8388608,nw=new Set(["resolved","failed"]),rw=[{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 Qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Is(e){return rw.find(t=>t.matches(e))?.kind}function Zu(e){let t=new Map,n=0,r=0;return{entries:e.map(o=>{let s=Qe(o.agent_provenance)?o.agent_provenance:void 0;if(s===void 0||!Xl(o).ok)return o;let a={},c=!1;for(let[d,u]of Object.entries(s)){let m=Qe(u)?Is(u.value):void 0;if(m===void 0){a[d]=u;continue}c=!0,r+=1;let f=o.agent_harness??"unknown",p=`${f}\0${d}\0${m}`,_=t.get(p)??{harness:f,dimension:d,kind:m,count:0};_.count+=1,t.set(p,_)}if(!c)return o;n+=1;let l={...o};return Object.keys(a).length===0?delete l.agent_provenance:l.agent_provenance=a,Zl(o,l,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((o,s)=>o.harness.localeCompare(s.harness)||o.dimension.localeCompare(s.dimension)||o.kind.localeCompare(s.kind))}}}async function Qu(e){let t=[];for(let n of await em(e)??[])try{let r=await Es.readFile(xs.join(e,"history",n),"utf8");for(let i of r.split(`
8
8
  `)){if(i.trim().length===0)continue;let o=tm(i);if(o===null||!Qe(o.agent_provenance))continue;if(Object.values(o.agent_provenance).some(a=>Qe(a)&&Is(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function em(e){try{return(await Es.readdir(xs.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function iw(e,t,n){let r;try{r=await Es.open(xs.join(e,"history",t),"r");let i=(await r.stat()).size,o=Math.min(i,Math.max(0,n)),s=Buffer.alloc(o),{bytesRead:a}=await r.read(s,0,o,0),c=s.subarray(0,a).toString("utf8"),l=a>=i,d=c.lastIndexOf(`
9
9
  `),u=c;return l||(u=d===-1?"":c.slice(0,d+1)),{content:u,bytesRead:a,complete:l}}catch{return null}finally{await r?.close()}}function tm(e){try{let t=JSON.parse(e);return Qe(t)?t:null}catch{return null}}function ow(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=Qe(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([s,a])=>{if(!Qe(a))return;let c=Is(a.value);if(!c)return;let l=`${r}\0${s}\0${c}`,d=n.get(l)??{harness:r,dimension:s,kind:c,count:0};d.count+=1,n.set(l,d)}),!Qe(e.context))return;let o=e.context.agent_provenance_outcomes;Qe(o)&&Object.entries(o).forEach(([s,a])=>{if(!Qe(a)||typeof a.resolver!="string"||!nw.has(String(a.status)))return;let c=`${r}\0${s}\0${a.resolver}`,l=t.get(c)??{harness:r,dimension:s,resolver:a.resolver,attempts:0,successes:0};l.attempts+=1,a.status==="resolved"&&(l.successes+=1),t.set(c,l)})}function sw(e,t,n,r,i,o){let s=i;for(let a of e.split(`
@@ -72,4 +72,4 @@ ${o}`,g.GENERIC_FAILURE)}}function No(e){return typeof e.tag=="string"&&e.tag.tr
72
72
  `);le(e.progressEnabled,"writing keyword artifacts"),await ne(t,`${JSON.stringify(e.manifest,null,2)}
73
73
  `),await ne(n,`${i}
74
74
  `);let o=[];if(e.mode!=="keyword")try{le(e.progressEnabled,"writing vectorization status ledger"),await Ud(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(s){o.push(`search_vectorization_status_ledger_write_failed:${s instanceof Error?s.message:String(s)}`)}return o}async function t2(e,t){let n=oT(e.mode),r=iT(e),i=e.full===!0;le(r,`start mode=${n}`);let o=N(process.cwd(),t.path);await te(o);let s=ui(await T(o)).settings,a=null;try{a=await ce(o,wd,s.locks.ttl_seconds,q(void 0,"pm-reindex"),!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms)}catch(c){throw c instanceof y&&c.exitCode===g.CONFLICT?new y("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",g.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=cT(s),l=lT(s),d=hT({requestedMode:n,pmRoot:o,settings:s,extensionEmbedding:c,extensionVectorAdapter:l}),u=n;le(r,"loading item corpus");let m=await _T({pmRoot:o,settings:s}),f=m.warnings,{documentCandidates:p,metadataDocuments:_}=m;le(r,`loaded_items=${_.length}`);let h=C(),w=pT(u,h,_),v=Lr.join(o,Nc),k=Lr.join(o,Lc),S=u==="keyword"?await jc(o,p,s.schema,f):_,x=[],A={},E=null,b=fT(u);if(u==="keyword"&&await gT({pmRoot:o,settings:s,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let z=await ET({pmRoot:o,settings:s,requestedMode:n,activeEmbeddingProvider:d.activeEmbeddingProvider,activeVectorStore:d.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:p,metadataDocuments:_,documentsForKeywordArtifacts:S,forceFullSemantic:i,reindexWarnings:f,semanticWarnings:x,semanticSummary:b,progressEnabled:r});S=z.documentsForKeywordArtifacts,A=z.vectorizationLedgerEntries,E=z.vectorizationEmbeddingMetadata}let P=await xT({pmRoot:o,mode:u,manifest:w,documentsForKeywordArtifacts:S,settings:s,vectorizationLedgerEntries:A,vectorizationEmbeddingMetadata:E,progressEnabled:r}),U=[...await X({path:v,scope:"project",op:"reindex:manifest"}),...await X({path:k,scope:"project",op:"reindex:embeddings"}),...await Vr({mode:u,total_items:_.length})];return le(r,"done"),{ok:!0,mode:u,total_items:_.length,semantic:b,artifacts:{manifest:Nc,embeddings:Lc},warnings:[...f,...x,...P,...U],generated_at:h}}finally{await a?.()}}export{L as a,Ie as b,Ze as c,yn as d,Qd as e,tu as f,Wt as g,ds as h,Gg as i,fs as j,ps as k,ou as l,vn as m,tr as n,_s as o,ly as p,uu as q,nr as r,gs as s,vi as t,ys as u,fu as v,pu as w,hu as x,Ym as y,xD as z,tv as A,nv as B,tt as C,iP as D,bv as E,my as F,UT as G,yu as H,hy as I,s$ as J,cb as K,cN as L,uN as M,mN as N,fr as O,fN as P,pN as Q,hN as R,_N as S,gN as T,yN as U,wN as V,vN as W,bN as X,kN as Y,SN as Z,pp as _,ba as $,eD as aa,fm as ba,j$ as ca,O as da,se as ea,F$ as fa,bs as ga,U$ as ha,z$ as ia,Cu as ja,H$ as ka,W$ as la,G$ as ma,Oy as na,q$ as oa,B$ as pa,ks as qa,V$ as ra,J$ as sa,vs as ta,K$ as ua,Y$ as va,$u as wa,X$ as xa,Py as ya,Pu as za,aO as Aa,sr as Ba,cO as Ca,zy as Da,Hy as Ea,lO as Fa,Wy as Ga,u_ as Ha,pO as Ia,zu as Ja,f_ as Ka,Rz as La,Cz as Ma,ar as Na,Ai as Oa,Wu as Pa,Gu as Qa,qu as Ra,Bu as Sa,Yu as Ta,Zu as Ua,Qu as Va,nm as Wa,Ot as Xa,zj as Ya,Hj as Za,Wj as _a,Gj as $a,tF as ab,Qp as bb,Ma as cb,bF as db,yt as eb,kF as fb,SF as gb,Yx as hb,eI as ib,fh as jb,lw as kb,im as lb,za as mb,_1 as nb,g1 as ob,Ci as pb,Ti as qb,jh as rb,pU as sb,Fh as tb,zh as ub,Hh as vb,qh as wb,Vh as xb,ER as yb,xR as zb,Dz as Ab,Pz as Bb,Nz as Cb,Lz as Db,AR as Eb,RR as Fb,CR as Gb,Mz as Hb,__ as Ib,$R as Jb,g_ as Kb,ac as Lb,w_ as Mb,OR as Nb,DR as Ob,PR as Pb,uc as Qb,mc as Rb,Vz as Sb,Jz as Tb,Kz as Ub,d0 as Vb,ZH as Wb,sg as Xb,Dr as Yb,lg as Zb,dg as _b,ug as $b,Ac as ac,yC as bc,DW as cc,nG as dc,dG as ec,Sg as fc,Eg as gc,xg as hc,PG as ic,VG as jc,JG as kc,KG as lc,t2 as mc};
75
- //# sourceMappingURL=chunk-H3BI4EDO.js.map
75
+ //# sourceMappingURL=chunk-6J2YCGSN.js.map