@unbrained/pm-cli 2026.9.1 → 2026.9.2

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 (49) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +10 -0
  3. package/dist/cli-bundle/bundle-manifest.json +59 -59
  4. package/dist/cli-bundle/chunks/{chunk-2MC2LCXZ.js → chunk-FZ4Z2J4F.js} +2 -2
  5. package/dist/cli-bundle/chunks/{chunk-6XIIGE7U.js → chunk-T6H5BZCP.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-U45JXJCC.js → chunk-UDW64J2W.js} +2 -2
  7. package/dist/cli-bundle/chunks/chunk-ZLJIFSOE.js +35 -0
  8. package/dist/cli-bundle/chunks/{register-mutation-2MVLRS3J.js → register-mutation-WFQ7MJTX.js} +2 -2
  9. package/dist/cli-bundle/chunks/{register-operations-WCIDXBU3.js → register-operations-JVTI7JPP.js} +2 -2
  10. package/dist/cli-bundle/focused-chunks/{chunk-FWPLDEXF.js → chunk-242AXYB2.js} +2 -2
  11. package/dist/cli-bundle/focused-chunks/{chunk-Y6JJIX6I.js → chunk-O67VDLOT.js} +48 -48
  12. package/dist/cli-bundle/main.js +2 -2
  13. package/dist/cli-bundle/sdk-contracts.js +1 -1
  14. package/dist/cli-bundle/sdk-core.js +1 -1
  15. package/dist/cli-bundle/sdk-governance.js +1 -1
  16. package/dist/cli-bundle/sdk-merge.js +32 -32
  17. package/dist/cli-bundle/sdk-runtime.js +1 -1
  18. package/dist/cli-bundle/sdk-testing.js +1 -1
  19. package/dist/cli-bundle/sdk.js +1 -1
  20. package/dist/core/diagnostics/remediation.js +9 -4
  21. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +14 -2
  22. package/dist/sdk/governance/health.js +77 -11
  23. package/dist/sdk/governance/validate.js +4 -2
  24. package/dist/sdk/merge/index.d.ts +1 -1
  25. package/dist/sdk/merge/index.js +2 -2
  26. package/dist/sdk/merge/receipts.d.ts +24 -0
  27. package/dist/sdk/merge/receipts.js +122 -30
  28. package/docs/CONTEXT_RECOVERY_PRIMITIVES.md +11 -2
  29. package/docs/MERGE_SAFETY.md +16 -2
  30. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
  31. package/marketplace.json +2 -2
  32. package/package.json +1 -1
  33. package/packages/pm-beads/package.json +1 -1
  34. package/packages/pm-calendar/package.json +1 -1
  35. package/packages/pm-command-kit/package.json +1 -1
  36. package/packages/pm-digital-twin/package.json +1 -1
  37. package/packages/pm-governance-audit/package.json +1 -1
  38. package/packages/pm-guide-shell/package.json +1 -1
  39. package/packages/pm-kanban/package.json +1 -1
  40. package/packages/pm-lifecycle-hooks/package.json +1 -1
  41. package/packages/pm-linked-test-adapters/package.json +1 -1
  42. package/packages/pm-search-advanced/package.json +1 -1
  43. package/packages/pm-templates/package.json +1 -1
  44. package/packages/pm-todos/package.json +1 -1
  45. package/packages/pm-vcs/package.json +1 -1
  46. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  47. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  48. package/sdk/public-surface.json +29 -6
  49. package/dist/cli-bundle/chunks/chunk-ALKKAUFN.js +0 -35
@@ -1,51 +1,51 @@
1
- import{a as Bi,c as mr,d as pr,e as Ha,g as Ba,h as Ji,i as Ga,j as Nt,k as Mt,l as Ja,m as Va,n as Vi,o as Xa,p as Lt,q as Ft,r as Za,s as Qa,t as Ki}from"./chunk-4O4CJAR6.js";import{e as yr,f as Yi}from"./chunk-SVXJYD6G.js";import{C as gr,a as La,g as Hi,i as Fa}from"./chunk-BEVHCEWG.js";import{P as nd}from"./chunk-S4U5CN5Q.js";import{$ as Or,B as eo,C as Nc,G as Mc,K as to,L as $r,Na as Kc,Oa as Yc,Sa as Xc,Ta as Zc,Ua as Qc,Wa as oo,aa as Lc,ba as no,ca as Sn,e as Rc,ea as ro,f as Ac,g as Ic,ia as Fc,ja as jc,ka as Uc,la as zc,m as Cc,ma as Dr,n as Tc,o as $c,oa as Wc,pa as qc,qa as Hc,ra as St,sa as Bc,ta as Gt,ua as Gc,v as kn,va as io,w as Oc,wa as Jt,x as Dc,xa as Jc,y as xn,ya as Vc,z as Pc}from"./chunk-MKHG3T76.js";import{a as Ua,b as Pt,c as Gi,d as za,e as Wa,f as Je,g as fr,h as qa,i as lt}from"./chunk-2FEZ5SKM.js";import{$ as Xi,$a as wc,$b as td,Ab as Ht,Bb as ut,Ca as mc,Cb as Bt,Db as Ke,Ea as kr,Eb as kt,Fa as Wt,Ha as pc,Ib as xt,Kb as Tr,Oa as qt,Pb as En,Ra as fc,Rb as Pr,Sa as hc,Ua as xr,Va as Zi,Wa as gc,Xa as _c,Y as V,Ya as yc,Yb as ed,Z as T,Za as pe,_ as cc,_a as Sr,ab as Qi,b as oc,bb as Er,cb as Rr,d as sc,da as fe,db as Ar,eb as vc,fb as De,gb as bc,hb as C,ib as Ir,ja as dc,ka as vr,kb as kc,l as z,na as br,o as ne,oa as lc,pb as xc,q as Ve,qa as uc,qb as Sc,r as ac,ra as jt,s as wr,ta as Ut,vb as Cr,wa as zt,xb as Ec,zb as X}from"./chunk-T2LXXSOD.js";import{$a as nc,A as Sa,Ca as qi,Da as Na,Ea as Ma,F as Ea,Fa as Dt,G as Ra,H as W,Ha as Le,Ja as Fe,La as le,M as bn,Ma as Ae,N as M,O as Me,Oa as be,P as lr,Pa as je,Q as bt,S as Aa,T as ur,Ta as Ie,Ua as Ka,V as Ia,Va as hr,X as Z,Xa as Ya,Za as _r,_ as Ca,_a as tc,a as ga,ca as Ta,d as _a,e as ya,fa as $a,h as Ot,ha as Wi,p as xa,q as vn,r as D,s as ct,t as U,ta as Oa,u as Y,ua as Da,v as de,y as ve,z as Re}from"./chunk-QDFJIRKN.js";import{a as rc,b as Ue,d as ic}from"./chunk-6GCRSLPG.js";import{O as wa,Q as va,S as ba,U as ka,V as dr,Y as y,Z as w,a as ar,aa as Q,ba as Pa,ca as dt,d as cr,fa as ja,oa as ec,t as zi}from"./chunk-Z2USIBR2.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d2d5135a-8110-527e-8530-653b25b792a4")}catch{}})();var P=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},ke=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 Vt(e){try{return await e()}catch(t){throw t instanceof P?new w(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function rd(e){try{return await e()}catch(t){throw t instanceof ke?new w(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as Yf}from"node:crypto";import Xf from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b911b43d-d14d-5e4f-a35e-5020b1a84542")}catch{}})();var Kt=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d4c380ce-031e-5b2d-aaa8-658bb4aa3087")}catch{}})();var od=1,Et=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],so=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Zf=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Qf=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Nr=30,Mr=5e3,sd=4,eh=50;function Ye(e,t){if(!Qf.test(e))throw new P(`${t} must be a stable lowercase id`)}function th(e,t){if(!Number.isFinite(e)||e<0)throw new P(`${t} must be a finite non-negative number`)}function Rn(e){let t=Zf.filter(i=>e[i]!==void 0);if(t.length!==1)throw new P(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function co(e,t){return Q(e)===Q(t)}function ad(e,t){if(t.polarity==="equals")return co(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 cd(e){let t=Rn(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>ad(r.observed,t)===(r.expected==="pass"))}function nh(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!co(e.value,t.value)}function rh(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||Q(e.scope)!==Q(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return nh(Rn(e),Rn(t))||n[t.enforcement]<n[e.enforcement]||r}function ih(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new P("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 P("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new P("items source equals/state requires field")}function oh(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new P("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 P("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 P("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 P("dependency_kind source source_kind_state must be present or missing")}function sh(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new P("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 P("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 P("prose_edge_gap exemption selectors must not be empty")}}function lo(e){Ye(e.id,"measurement.id"),e.max_cost!==void 0&&th(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new P(`measurement.source.kind must be one of ${so.join(", ")}`);let n=Reflect.get(t,"kind");if(!so.includes(n))throw new P(`measurement.source.kind must be one of ${so.join(", ")}`);let r=t;if(r.kind==="items"&&ih(r),r.kind==="dependency_kind"&&oh(r),r.kind==="prose_edge_gap"&&sh(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new P(`${r.kind} source requires field`);return r.kind==="provider"&&(Ye(r.provider,"provider source provider"),Ye(r.key,"provider source key")),e}function uo(e){if(Ye(e.id,"assertion.id"),Ye(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new P("assertion.owner_item_id is required");let t=Rn(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new P(`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 P("retired assertion requires retire_reason");e.scope.kind==="filter"&&Ye(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 P("assertion negative control requires pass and fail cases");if(!cd(e))throw new P(`assertion ${e.id} negative control does not prove its bound`);return e}function ah(e){if(!Array.isArray(e.allowed_providers))throw new P("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)Ye(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new P("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Et.includes(t))throw new P(`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 P(`gate provider policy trigger ${t} is invalid`)}}function dd(e){if(Ye(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new P("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new P("gate requires at least one assertion");for(let t of e.assertion_ids)Ye(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new P(`gate.triggers is required and must be an array of ${Et.join(", ")}`);if(e.triggers.length===0)throw new P("gate requires at least one trigger");for(let t of e.triggers)if(!Et.includes(t))throw new P(`gate trigger must be one of ${Et.join(", ")}`);return e.provider_policy&&ah(e.provider_policy),e}function Yt(e){if(e.version!==od)throw new P(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(lo(r),t.has(`measurement:${r.id}`))throw new P(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(uo(r),t.has(`assertion:${r.id}`))throw new P(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){dd(r);let i=r.assertion_ids.filter(o=>!e.assertions.some(s=>s.id===o));if(i.length>0)throw new P(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new P(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of ld(e))if(!n.has(r))throw new P(`${i.join(", ")} references missing measurement ${r}`);return e}function mo(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)mo(n,t)}function ld(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=[];mo(r.source.expression,i);for(let o of i)n(o,`derived measurement ${r.id}`)}return t}function ch(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"&&mo(s.source.expression,n)}return i}function An(){return{version:od,measurements:[],assertions:[],gates:[]}}function dh(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 co(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function lh(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 uh(e,t){let n=[],r=Wi(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let o of i.dependencies??[]){let s=Wi(o.kind)??o.kind.trim().toLowerCase(),a=o.source_kind?.trim();s===r&&lh(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 mh(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 ph(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 ao(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function fh(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(ao(s.id,a.id));for(let a of[s.parent,s.blocked_by])typeof a=="string"&&n.add(ao(s.id,a));for(let a of mh(s)){let c=[...a.matchAll(i)].map(d=>d[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 hh(e,t){let n=fh(t.items),r=new Map;for(let s of n.prose_mentions){let a=s.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==s.holder_id),c=[...new Set(a)];for(let d of c){let l=ao(s.holder_id,d);if(n.linked_pairs.has(l)||ph(e.exemptions??[],s.holder_id,d,s.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${s.holder_id}->${d}|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 gh(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 _h(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 yh(e,t){let n=e.source;return n.kind==="items"?dh(n,t):n.kind==="dependency_kind"?uh(n,t):n.kind==="prose_edge_gap"?hh(n,t):n.kind==="history"?gh(n,t):n.kind==="links"?_h(n,t):null}function ud(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 wh(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 md(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 pd(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(d=>d.id===e.measurement);if(!s)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await fd(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 md(e.operands,sd,s=>pd(s,t,n,r,i));return{value:wh(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 vh(e,t,n,r,i){lo(e);let o=Date.now(),s,a=[],c=0;if(e.source.kind==="derived"){let u=await pd(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=yh(e,t);u!==null?s=u:(s=await t.external(e.source),c=1)}let d={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},l=ud([...a,d],Date.now()-o);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new ke(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${Yf("sha256").update(Q(e)).digest("hex")}`,value:s.value,population_size:s.population_size,cost:l,contributors:s.contributors??[],...s.partitions?{partitions:s.partitions}:{}}}function fd(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=vh(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}:{}},d=new ze(a.message,c);throw d.cause=a,d}throw a});return i.cache.set(e.id,s),s}async function po(e,t,n=[e]){return fd(e,t,n,[],{cache:new Map,charged:new Set})}function bh(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 kh(e,t,n={}){uo(e);let r=Rn(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:bh(t.value,r),verdict:i?"retired":ad(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:cd(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function xh(e,t,n,r){let i=ch(e,t);if(i.size===0)return;let o=e.provider_policy,s=o?.triggers[r];if(!o||!s)throw new ke(`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 d of i){if(!a.has(d))throw new ke(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new ke(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[s.max_cost_class])throw new ke(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!s.allow_network)throw new ke(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function id(e,t,n,r,i){try{return await po(n,r,i)}catch(o){if(o instanceof ze){let s=o.check?` check ${o.check}`:"",a=o.measurement_id??n.id,c=new ke(`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 hd(e,t,n,r){Yt(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new ke(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new ke(`assurance gate ${e} does not declare trigger ${r.trigger}`);xh(i,t,n,r.trigger);let o=await md(i.assertion_ids,sd,async c=>{let d=t.assertions.find(f=>f.id===c),l=t.measurements.find(f=>f.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let f=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!f.has(h.status))}}else if(d.scope.kind==="filter"){let f=d.scope.measurement_id,h=t.measurements.find(v=>v.id===f),g=await id(i.id,d.id,h,n,t.measurements),_=new Set(g.contributors);u={...n,items:n.items.filter(v=>_.has(v.id))}}let m=n.items.find(f=>f.id===d.owner_item_id),p=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return kh(d,await id(i.id,d.id,l,u,t.measurements),{owner_terminal:p})}),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:ud(o.map(c=>c.cost),Math.max(0,...o.map(c=>c.cost.duration_ms)))}}function Lr(e){return Xf.join(e,"assurance.json")}async function gd(e){let t=await Y(Lr(e));return t===null?An():Fr(t)}function Fr(e){try{return Yt(JSON.parse(e))}catch(t){throw new w("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",y.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 jr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Sh(e,t){e==="measurement"?lo(t):e==="assertion"?uo(t):dd(t)}async function In(e,t){let n=structuredClone(jr(await gd(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function fo(e,t,n){let r=jr(await gd(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Ur(e,t,n,r={}){Sh(t,n);let i=await C(e),o=V(r.author,i.author_default),s=await Rr({pmRoot:e,filePath:Lr(e),op:`assurance:${t}:put`,author:o,message:r.message,lockTtlSeconds:Nr,lockWaitMs:Mr,mutate:a=>{let c=a===null?An():Fr(a),d=jr(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&rh(d[l],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new P(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),Yt(c),{raw:`${JSON.stringify(c,null,2)}
2
- `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...s.result,changed:s.changed}}async function ho(e,t,n={}){let r=An();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),Yt(r);let i=await C(e),o=V(n.author,i.author_default),s=await Rr({pmRoot:e,filePath:Lr(e),op:"assurance:bundle:apply",author:o,message:n.message,lockTtlSeconds:Nr,lockWaitMs:Mr,mutate:a=>{let c=a===null?An():Fr(a),d=[],l=[],u=(m,p,f)=>{for(let h of p){let g=m.find(_=>_.id===h.id);if(!g){m.push(structuredClone(h)),d.push(`${f}:${h.id}`);continue}if(Q(g)!==Q(h))throw new P(`assurance bundle refuses to replace divergent ${f} ${h.id}`);l.push(`${f}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),Yt(c),{raw:`${JSON.stringify(c,null,2)}
3
- `,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...s.result,changed:s.changed}}async function _d(e,t,n,r={}){let i=await C(e),o=V(r.author,i.author_default),s=await Rr({pmRoot:e,filePath:Lr(e),op:`assurance:${t}:remove`,author:o,message:r.message,lockTtlSeconds:Nr,lockWaitMs:Mr,mutate:a=>{let c=a===null?An():Fr(a);if(t==="measurement"){let u=ld(c).get(n);if(u&&u.length>0)throw new P(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new P(`assurance assertion ${n} is referenced by gate`);let d=jr(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new P(`assurance ${t} ${n} not found`);return d.splice(l,1),Yt(c),{raw:`${JSON.stringify(c,null,2)}
4
- `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...s.result,changed:s.changed}}async function yd(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await C(e);await Er({pmRoot:e,op:"assurance:gate:verdict",author:V(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Nr,lockWaitMs:Mr})}async function wd(e,t={}){let n=t.limit??eh;if(!Number.isInteger(n)||n<1||n>Kt)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${Kt}`);return(await zt(Sr(e),pe)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="05c29627-6763-5aee-8579-71e563a98780")}catch{}})();var Cn=["software-delivery","research","agent-evaluation","operations"];function vd(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 zr(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=>vd(`${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 Wr(e,t){return e==="software-delivery"?zr(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?zr(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?zr(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):zr(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function bd(e,t,n,r={}){return ho(e,Wr(t,n).declarations,r)}async function kd(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 po(s,r)).value,d=vd(`${s.id}-ceiling`,s.id,t,c,"observe"),l=`active-missing-${o}`;return{id:l,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[s],assertions:[d],gates:[{id:`derived-${l}`,description:`Observe the accepted ${o} evidence baseline.`,assertion_ids:[d.id],triggers:["ci","scheduled"]}]}}}))}function xd(e,t,n={}){return ho(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 Sd(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 Ur(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Ad from"node:fs/promises";import{createRequire as Eh}from"node:module";import xe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c21b1a94-1d80-57c0-b090-c4831fc505a2")}catch{}})();function Ed(e,t){let n=xe.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${xe.sep}`)&&!xe.isAbsolute(n))return n.split(xe.sep).join("/");let r=xe.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")}/${xe.basename(xe.dirname(e))}/package.json`}function Rh(e){return e.includes(`${xe.sep}.pnpm${xe.sep}`)?"pnpm":e.includes(`${xe.sep}node_modules${xe.sep}`)?"npm":"other"}async function Rd(e){try{let t=JSON.parse(await Ad.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 go(e){try{return await Ad.realpath(e)}catch{return xe.resolve(e)}}async function Id(e,t,n=Re(import.meta.url,["../../.."])){let r=await go(t),i=await go(xe.join(n,"package.json")),o=await Rd(i),s=new Map;o!==void 0&&s.set(i,{version:o,path:Ed(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=Eh(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await go(l),m=await Rd(u);if(m===void 0)continue;let p=u,f=s.get(p);if(f){f.consumers.includes(d.name)||(f.consumers.push(d.name),f.consumers.sort((h,g)=>h.localeCompare(g)));continue}s.set(p,{version:m,path:Ed(u,r),layout:Rh(u),consumers:[d.name]})}catch{}let a=[...s.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=o===void 0?[]:a.filter(d=>d.version!==o);return{host_version:o??null,copies:a,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${o}:${d.version}:${d.consumers.join("+")}`)}}import{createHash as Ud}from"node:crypto";import Tn from"node:fs/promises";import $n from"node:path";import{Option as VA}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]="01742f33-d1e8-5684-a585-2add88ddb73c")}catch{}})();function Ah(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 qr(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function L(e,t){return e[t]===!0?!0:void 0}function Xe(e,t){return e[t]===!1?!0:void 0}function Cd(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Td(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function $d(e){let t=i=>Hi(e,qr(yr,i)),n=i=>Fa(e,qr(Yi,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:Ah(e,qr(Yi,"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:Cd(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:L(e,"replaceDeps"),replaceTests:L(e,"replaceTests"),replaceFiles:L(e,"replaceFiles"),replaceDocs:L(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:L(e,"clearDeps"),clearComments:L(e,"clearComments"),clearNotes:L(e,"clearNotes"),clearLearnings:L(e,"clearLearnings"),clearFiles:L(e,"clearFiles"),clearTests:L(e,"clearTests"),clearDocs:L(e,"clearDocs"),clearReminders:L(e,"clearReminders"),clearEvents:L(e,"clearEvents"),clearTypeOptions:L(e,"clearTypeOptions")};return Td(r,e),r}function ee(e,t){let n=qr(La,t),r=Hi(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 Ih(e){let t=L(e,"filterFilesMissing"),n=L(e,"filterDocsMissing");return{filterReviewerMissing:L(e,"filterReviewerMissing"),filterRiskMissing:L(e,"filterRiskMissing"),filterConfidenceMissing:L(e,"filterConfidenceMissing"),filterSprintMissing:L(e,"filterSprintMissing"),filterReleaseMissing:L(e,"filterReleaseMissing"),hasNotes:L(e,"hasNotes"),hasLearnings:L(e,"hasLearnings"),hasFiles:L(e,"hasFiles"),hasDocs:L(e,"hasDocs"),hasTests:L(e,"hasTests"),hasComments:L(e,"hasComments"),hasDeps:L(e,"hasDeps"),hasBody:L(e,"hasBody"),hasLinkedCommand:L(e,"hasLinkedCommand"),noNotes:Xe(e,"notes"),noLearnings:Xe(e,"learnings"),noFiles:Xe(e,"files")??t,filterFilesMissing:t,noDocs:Xe(e,"docs")??n,filterDocsMissing:n,noTests:Xe(e,"tests"),noComments:Xe(e,"comments"),noDeps:Xe(e,"deps"),emptyBody:L(e,"emptyBody"),noLinkedCommand:Xe(e,"linkedCommand")}}function Od(e){let t={status:ee(e,"status"),type:ee(e,"type"),tag:ee(e,"tag"),priority:ee(e,"priority"),deadlineBefore:ee(e,"deadlineBefore"),deadlineAfter:ee(e,"deadlineAfter"),updatedAfter:ee(e,"updatedAfter"),updatedBefore:ee(e,"updatedBefore"),createdAfter:ee(e,"createdAfter"),createdBefore:ee(e,"createdBefore"),today:L(e,"today"),recent:L(e,"recent"),ids:ee(e,"ids"),assignee:ee(e,"assignee"),assigneeFilter:ee(e,"assigneeFilter"),parent:ee(e,"parent"),sprint:ee(e,"sprint"),release:ee(e,"release"),limit:ee(e,"limit"),offset:ee(e,"offset"),noTruncate:Xe(e,"truncate"),includeBody:L(e,"includeBody"),strictRead:L(e,"strictRead"),compact:L(e,"compact"),brief:L(e,"brief"),full:L(e,"full"),fields:ee(e,"fields"),sort:ee(e,"sort"),order:ee(e,"order"),tree:L(e,"tree"),treeDepth:ee(e,"treeDepth"),filterAcMissing:L(e,"filterAcMissing"),filterEstimatesMissing:Cd(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:L(e,"filterResolutionMissing"),filterMetadataMissing:L(e,"filterMetadataMissing"),...Ih(e)};return Td(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]="fde4fea5-94d6-53e2-bfbc-bff71d828c01")}catch{}})();var Ch=Symbol("pm.mcp-mutation-transport");function yo(e){return Ch in e}function Br(e,t){return yo(e)?Pc(t):eo(e,t)}function oI(e,t,n=[]){let r=eo(e,{...e,...t});for(let i of n)Reflect.deleteProperty(r,i);return r}function $(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function re(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function sI(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Xt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vo(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new w(`${t} must be a finite integer.`,y.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new w(`${t} must be a finite integer.`,y.USAGE);return n}}function aI(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:$(e,"limit")??$(t,"limit")}function cI(e){let t=$(e,"outputFormat");return{json:!0,quiet:!0,author:$(e,"author"),path:$(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:$(e,"outputInclude"),outputLimit:re(e,"outputLimit"),outputBudget:re(e,"outputBudget"),outputSession:$(e,"outputSession"),outputCursor:$(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Th=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Pd=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"]),$h=new Set([...Pd].filter(e=>e!=="file")),Oh=new Set(["files","files-discover","docs","test","test-all"]),Nd=new Set(["comments","notes","learnings"]);function Dh(e,t){if(!(!Nd.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new w(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,y.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var Ph=new Set(["claim","release","start-task","pause-task","close-task"]),Nh={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"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Mh=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Md(e,t=""){let n={},r=Oh.has(t),i=t==="files"||t==="files-discover"||t==="docs",o=Nd.has(t)?$h:Pd;for(let[s,a]of Object.entries(e)){if(Array.isArray(a)&&Th.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 Lh(e,t,n){let r=$(e,"author");return r!==void 0?r:n!==void 0&&Ph.has(n)?$(e,"assignee")??$(t,"assignee"):void 0}function Fh(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function dI(e,t){let n=Xt(e.options)?e.options:void 0,r=Ta(e.options),i={},o=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of Nh[t??""]??[])o(c);for(let c of Mh)o(c);t!==void 0&&yo(e)&&Dh(t,r);let s=Md({...i,...r},t),a=yo(e)?e:n??e;return Br(a,Fh(s,Lh(e,s,t)))}function lI(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 uI(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 mI(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 pI(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function bo(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function fI(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 hI(e,t){let n=Br(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function wo(e){return{type:re(e,"filterType"),tag:re(e,"filterTag"),priority:re(e,"filterPriority"),deadlineBefore:re(e,"filterDeadlineBefore"),deadlineAfter:re(e,"filterDeadlineAfter"),updatedAfter:re(e,"filterUpdatedAfter"),updatedBefore:re(e,"filterUpdatedBefore"),createdAfter:re(e,"filterCreatedAfter"),createdBefore:re(e,"filterCreatedBefore"),ids:to(e.ids),assignee:re(e,"filterAssignee"),assigneeFilter:re(e,"filterAssigneeFilter")??re(e,"filterAssignee_filter"),parent:re(e,"filterParent"),sprint:re(e,"filterSprint"),release:re(e,"filterRelease"),limit:re(e,"limit"),offset:re(e,"offset")}}function _o(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return bo(e)}function Hr(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function gI(e){let t=_o(e.kind),n=_o(e.exemptIsolate),r=_o(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Hr(e.maxDepth),limit:Hr(e.limit),after:$(e,"after"),direction:$(e,"direction"),maxPaths:Hr(e.maxPaths),sample:Hr(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 Ld(e){let t=Od(e);return e.ids!==void 0&&(t.ids=to(e.ids)),t}function _I(e){return{status:$(e,"filterStatus"),list:Xt(e.list)?Ld(e.list):wo(e),reason:$(e,"reason"),resolution:$(e,"resolution"),expectedResult:$(e,"expectedResult")??$(e,"expected_result")??$(e,"expected"),actualResult:$(e,"actualResult")??$(e,"actual_result")??$(e,"actual"),validateClose:$(e,"validateClose")??$(e,"validate_close"),author:$(e,"author"),message:$(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:$(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var jh=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 Dd(e){let t={};for(let[n,r]of Object.entries(e))jh.has(n)||(t[n]=r);return Fd(t)}function Fd(e){let t=Md(e,"update-many");for(let n of yr)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return $d(t)}function yI(e){if(Xt(e.list)||Xt(e.update)){let t=Xt(e.update)?e.update:Dd(e),n=Br(e,Fd(t));return{status:re(e,"filterStatus"),list:Xt(e.list)?Ld(e.list):wo(e),update:Nc(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:$(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:re(e,"filterStatus"),list:wo(e),update:Br(e,Dd(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:$(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]="b389e521-f689-5895-a5f4-08c3866b3ea3")}catch{}})();function Ce(e,t){throw new w(e,y.USAGE,t)}var Uh="2026-07-15T06:22:12.276Z",zh=Date.parse(Uh),Wh=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],jd=e=>typeof e=="string"?e:"",zd=e=>{let t=e??{},n=jd(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(jd(t.ts))>=zh);return Wh[r][i]};function Wd(e,t,n=20,r=new Set,i=!1){let o=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,p]of t.split(/\r?\n/).entries()){let f;try{f=JSON.parse(p)}catch{continue}d+=1;let h=zd(f);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}a[h]+=1,i&&h==="actionable_unknown"&&s.push({item_id:e,line:m+1}),o.length<c&&o.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:a.legacy_unknown+a.actionable_unknown>o.length,actionable_events:s}}var II=(e,t,n=20,r=new Set)=>Wd(e,t,n,r);function qd(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 On=async(e,t=20,n=!1)=>{let r=$n.join(e,"history"),i;try{i=(await Tn.readdir(r)).filter(_=>_.endsWith(".jsonl")).sort((_,v)=>_.localeCompare(v))}catch{i=[]}let o=new Set,s=[],a=[],c=0,d=0,l=0,u=0,m=0,p=0,f="_workspace.jsonl",h=new Set;if(i.includes(f))try{h=qd(await Tn.readFile($n.join(r,f),"utf8"))}catch{h=new Set}for(let _ of i){let v;try{v=await Tn.readFile($n.join(r,_),"utf8")}catch{continue}let k=_.slice(0,-6),x=Wd(k,v,t-s.length,h,n);c+=1,d+=x.checked_events,l+=x.unknown_event_count,u+=x.legacy_unknown_event_count,m+=x.actionable_unknown_event_count,p+=x.acknowledged_actionable_event_count,x.unknown_event_count>0&&o.add(k),s.push(...x.samples),n&&a.push(...x.actionable_events)}let g=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:p,affected_item_ids:[...o].sort((_,v)=>_.localeCompare(v)),samples:s,samples_truncated:g>s.length,...n?{actionable_events:a}:{}}};function qh(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 Hh(e){try{return qd(await Tn.readFile($n.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function Bh(e){return(e.item_id===pe||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function Gh(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Ce(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return zd(i)!=="actionable_unknown"&&Ce(`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:Ud("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Hd(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Ce("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Ce("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Ce("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let o=qh(t.all_actionable===!0?(await On(e,0,!0)).actionable_events:r),s=await Hh(e),a=new Map;for(let m of o)if(Bh(m)||Ce(`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 Tn.readFile($n.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Ce(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=o.map(m=>Gh(m,s,a.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Ud("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function CI(e,t,n=50){return(await Hd(e,t,n)).plan}function Jh(e,t){let n=e.length>0;return n&&t&&Ce("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&&Ce("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:Vh(e),all_actionable:t}}function Vh(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),o=r===pe||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!o||!Number.isSafeInteger(i)||i<1)&&Ce(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function TI(e,t){let n=Jh(bo(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Kh(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:$(t,"planFingerprint")??$(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:$(t,"attributedAuthor")??$(t,"attributed_author")??void 0,reviewer:$(t,"reviewer"),reason:$(t,"reason")})}async function Kh(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",o=await Hd(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:y.SUCCESS,plan:o.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Ce("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Ce("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 w("Author acknowledgment selection changed after preview; no history was mutated.",y.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:y.NO_EFFECT,plan:o.plan};let c=await C(e),d=await Er({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}),l=o.plan.actionable_count>0&&o.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:y.PARTIAL_EFFECT}:{outcome:"effect",exit_code:y.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...l,plan:o.plan,history_path:d.historyPath}}import ko from"node:fs/promises";import xo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6efed404-acd2-5c3a-a008-856df67c8b77")}catch{}})();var Yh=8388608,Xh=new Set(["resolved","failed"]),Zh=[{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 We(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function So(e){return Zh.find(t=>t.matches(e))?.kind}function Bd(e){let t=new Map,n=0,r=0;return{entries:e.map(o=>{let s=We(o.agent_provenance)?o.agent_provenance:void 0;if(s===void 0)return o;let a={},c=!1;for(let[l,u]of Object.entries(s)){let m=We(u)?So(u.value):void 0;if(m===void 0){a[l]=u;continue}c=!0,r+=1;let p=o.agent_harness??"unknown",f=`${p}\0${l}\0${m}`,h=t.get(f)??{harness:p,dimension:l,kind:m,count:0};h.count+=1,t.set(f,h)}if(!c)return o;n+=1;let d={...o};return Object.keys(a).length===0?delete d.agent_provenance:d.agent_provenance=a,d}),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 Gd(e){let t=[];for(let n of await Jd(e))try{let r=await ko.readFile(xo.join(e,"history",n),"utf8");for(let i of r.split(`
5
- `)){if(i.trim().length===0)continue;let o=Vd(i);if(o===null||!We(o.agent_provenance))continue;if(Object.values(o.agent_provenance).some(a=>We(a)&&So(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Jd(e){try{return(await ko.readdir(xo.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function Qh(e,t,n){let r;try{r=await ko.open(xo.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"),d=a>=i,l=c.lastIndexOf(`
6
- `),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:a,complete:d}}catch{return null}finally{await r?.close()}}function Vd(e){try{let t=JSON.parse(e);return We(t)?t:null}catch{return null}}function eg(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=We(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([s,a])=>{if(!We(a))return;let c=So(a.value);if(!c)return;let d=`${r}\0${s}\0${c}`,l=n.get(d)??{harness:r,dimension:s,kind:c,count:0};l.count+=1,n.set(d,l)}),!We(e.context))return;let o=e.context.agent_provenance_outcomes;We(o)&&Object.entries(o).forEach(([s,a])=>{if(!We(a)||typeof a.resolver!="string"||!Xh.has(String(a.status)))return;let c=`${r}\0${s}\0${a.resolver}`,d=t.get(c)??{harness:r,dimension:s,resolver:a.resolver,attempts:0,successes:0};d.attempts+=1,a.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function tg(e,t,n,r,i){let o=i;for(let s of e.split(`
7
- `)){if(s.trim().length===0)continue;if(o>=r)return{eventsRead:o,truncated:!0};o+=1;let a=Vd(s);a&&eg(a,t,n)}return{eventsRead:o,truncated:!1}}async function Kd(e,t=1e4){let n=new Map,r=new Map,i=0,o=0,s=!1;for(let d of await Jd(e)){let l=await Qh(e,d,Math.max(0,Yh-o));if(l===null)continue;o+=l.bytesRead;let u=tg(l.content,n,r,t,i);if(i=u.eventsRead,u.truncated){s=!0;break}if(!l.complete){s=!0;break}}let a=[...n.values()].sort((d,l)=>d.harness.localeCompare(l.harness)||d.dimension.localeCompare(l.dimension)||d.resolver.localeCompare(l.resolver)),c=[...r.values()].sort((d,l)=>d.harness.localeCompare(l.harness)||d.dimension.localeCompare(l.dimension)||d.kind.localeCompare(l.kind));return{outcomes:a,invalid_values:c,warnings:s?[]:[...a.filter(d=>d.attempts>0&&d.successes===0).map(d=>`provenance_resolver_zero_success:${d.harness}:${d.dimension}:${d.resolver}:${String(d.attempts)}`),...c.map(d=>`provenance_value_domain_invalid:${d.harness}:${d.dimension}:${d.kind}:${String(d.count)}`)],events_read:i,truncated:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd7acf28-cb93-516e-9058-54c32625ec26")}catch{}})();function Gr(e,t,n=25){let r=e.definitions.filter(s=>s.roles.length===0).map(s=>s.id).sort((s,a)=>s.localeCompare(a)),i=new Set(r),o=t.filter(s=>{let a=Ka(s.status,e);return a!==void 0&&i.has(a)}).map(s=>s.id).sort((s,a)=>s.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:o.length,affected_item_ids:o.slice(0,n),affected_item_ids_truncated:o.length>n}}function Jr(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}import it from"node:fs/promises";import _e from"node:path";import Dn from"node:fs/promises";import{createHash as ng}from"node:crypto";import Xd 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]="1c6c65ef-115b-50e2-815e-84f6e91158cd")}catch{}})();var Zd=9,rg="history-drift-cache.json";function Qd(e){return Xd.join(e,"runtime",rg)}async function ig(e){try{let t=await Dn.readFile(Qd(e),"utf8"),n=JSON.parse(t);return n.version!==Zd||n.history_item_hash_version!==kr||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!Wt.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&Wt.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}async function og(e,t,n,r,i){let o=Sr(e),s;try{s=await Dn.stat(o)}catch(d){return U(d)||i.unreadableStreams.push(pe),!1}let a=i.missingStreams.length,c=await el({itemId:pe,historyPath:o,stat:s,cached:t[pe],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(pe),c.verification.chainOk||i.chainMismatches.push(pe),n[pe]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(i.missingStreams.splice(a),c.cacheDirty)}function sg(e){return ng("sha256").update(e).digest("hex")}async function ag(e){let t=await Dn.readFile(e,"utf8"),n=sg(t);if(t.trim().length===0)return null;let r=[],i=null;for(let u of t.split(/\r?\n/)){let m=u.trim();if(m.length===0)continue;let p=JSON.parse(m);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(p),i=p.after_hash}if(!i)return null;let o=xr(r),s=r.some(u=>u.item_hash_version!==void 0&&!Wt.includes(u.item_hash_version)),c=r[r.length-1].item_hash_version,d=c!==void 0&&Wt.includes(c),l=d?c:o.item_hash_version;return{latestAfterHash:i,chainOk:o.ok,versionSkew:s,latestHashComparable:l!==void 0&&(!s||d||c===void 0),contentHash:n,itemHashVersion:l??kr}}function cg(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Yd(e,t,n){try{let r=await ag(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function el(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(cg(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Yd(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let r=await Yd(e.itemId,e.historyPath,e.accumulator);return{verification:r,cacheDirty:r===null||r.contentHash!==t||r.latestAfterHash!==e.cached.latest_after_hash||r.chainOk!==e.cached.chain_ok||r.versionSkew!==(e.cached.version_skew===!0)||r.latestHashComparable!==e.cached.latest_hash_comparable||r.itemHashVersion!==e.cached.item_hash_version}}return{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&Wt.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version},cacheDirty:!1}}async function dg(e,t,n,r){let i=ur(e,t.id),o;try{o=await Dn.stat(i)}catch(l){return(U(l)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await el({itemId:t.id,historyPath:i,stat:o,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!s.verification)return s.cacheDirty;s.verification.versionSkew&&r.versionSkews.push(t.id),s.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:s.verification.contentHash,latest_after_hash:s.verification.latestAfterHash,chain_ok:s.verification.chainOk,version_skew:s.verification.versionSkew,latest_hash_comparable:s.verification.latestHashComparable,item_hash_version:s.verification.itemHashVersion};let{body:a,...c}=t;return s.verification.latestHashComparable&&(pc({metadata:c,body:a},s.verification.itemHashVersion).includes(s.verification.latestAfterHash)||r.hashMismatches.push(t.id)),s.cacheDirty}async function lg(e,t){if(!(t.unreadableStreams.includes(pe)||t.chainMismatches.includes(pe)||t.versionSkews.includes(pe)))try{let n=await wc(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(pe)}}async function Rt(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},o=(await ig(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",d={previousEntries:o,nextEntries:s,verifyCacheHitByContent:c};for(let m of t)await dg(e,m,d,r)&&(a=!0);let l=await og(e,o,s,c,r);if(a||=l,await lg(e,r),a||Object.keys(o).length!==Object.keys(s).length){let m=Qd(e);try{await Dn.mkdir(Xd.dirname(m),{recursive:!0}),await de(m,JSON.stringify({version:Zd,history_item_hash_version:kr,entries:s}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.versionSkews,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[pe]:[]])].sort((m,p)=>m.localeCompare(p));return{...r,driftedItems:u}}import Pn from"node:fs/promises";import Vr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="79f9ccbd-48d1-5eb3-82ae-3dd62427041c")}catch{}})();function ug(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:o,ttl_seconds:s}=n;return typeof r!="string"||typeof i!="string"||typeof o!="string"||typeof s!="number"||!Number.isFinite(s)?null:{id:r,owner:i,created_at:o,ttl_seconds:s}}function tl(e,t,n){let r=ug(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let o=n-i,s=Math.floor(o/1e3),a=o>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:s,stale:a,reason:a?"expired":"active"}}}async function nl(e,t){let n=t??Date.now(),r=Vr.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await Pn.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(s){if(U(s))return i;throw s}for(let s of o){let a;try{a=await Pn.readFile(Vr.join(r,s),"utf8")}catch(d){if(U(d))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=tl(s,a,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function rl(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Vr.join(e,"locks"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},a;try{a=(await Pn.readdir(o)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if(U(c))return s;throw c}for(let c of a){s.scanned+=1;let d=Vr.join(o,c),l=`locks/${c}`;if(r?.onRead){let p=await r.onRead(d);s.warnings.push(...p)}let u;try{u=await Pn.readFile(d,"utf8")}catch(p){if(U(p)){s.scanned-=1;continue}s.warnings.push(`lock_unreadable:${c}`),s.retained.push(l),s.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=tl(c,u,i);if(m.detail==="unparseable_json"){s.warnings.push(`lock_unparseable:${c}`),s.retained.push(l),s.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){s.warnings.push(`lock_invalid_timestamp:${c}`),s.retained.push(l),s.entries.push(m.entry);continue}if(m.detail==="active"){s.retained.push(l),s.entries.push(m.entry);continue}if(!n){try{await Pn.unlink(d)}catch(p){if(!U(p)){s.warnings.push(`lock_remove_failed:${c}`),s.retained.push(l),s.entries.push(m.entry);continue}}if(r?.onWrite){let p=await r.onWrite(d);s.warnings.push(...p)}}s.removed.push(l),s.entries.push(m.entry)}return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bb094b44-42b2-5a1c-9fc2-7a0eeaf9fbfd")}catch{}})();var mg=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm health --check-only --full",summary:"One or more receipt files failed bounded-file, schema, or identity validation; use the full health count to inspect the clone-local and durable receipt directories, then repair or remove only confirmed invalid evidence."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Eo(e){if(typeof e!="string")return;let t=e.trim();for(let n of mg)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Ro(e){let t={};for(let n of e){let r=Eo(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function il(e){return Object.values(Ro(e))}import gt from"node:fs/promises";import Te 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]="2c514907-377f-59f9-bfdd-a184abf7ffb7")}catch{}})();var pg=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Zt(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(_r(t.extensionName));for(let g of t.extensionNames??[])n.add(_r(g));let r=g=>n.size===0||n.has(_r(g)),i=(g,_)=>ol(g.filter(v=>r(v.name)).map(_)),o=(g,_)=>ol(g.filter(v=>r(v.name)).flatMap(_)),{registrations:s,commands:a,parsers:c,preflight:d,services:l,renderers:u,hooks:m}=e,p=o(s.relationship_kinds??[],g=>g.definitions.map(_=>_.kind)),f=u.overrides.filter(g=>r(g.name)&&((g.commands?.length??0)>0||g.resultDiscriminator!==void 0)).map(g=>({format:g.format,commands:[...g.commands??[]],result_discriminator:g.resultDiscriminator!==void 0})).sort((g,_)=>g.format.localeCompare(_.format)),h=i(s.assurance_providers??[],g=>g.definition.id);return{capabilities:tc(e,t),commands:i(s.commands,g=>g.command),command_overrides:i(a.overrides,g=>g.command),command_handlers:i(a.handlers,g=>g.command),hooks:pg.filter(([g])=>m[g].some(_=>r(_.name))).map(([,g])=>g),flag_commands:i(s.flags,g=>g.target_command),item_types:o(s.item_types,g=>g.types.map(_=>_.name)),item_fields:o(s.item_fields,g=>g.fields.map(_=>_.name)),...p.length>0?{relationship_kinds:p}:{},migrations:o(s.migrations,g=>typeof g.definition.id=="string"?[g.definition.id]:[]),profiles:i(s.profiles,g=>g.profile.name),importers:i(s.importers,g=>g.importer),exporters:i(s.exporters,g=>g.exporter),search_providers:i(s.search_providers,g=>g.definition.name),vector_store_adapters:i(s.vector_store_adapters,g=>g.definition.name),...h.length>0?{assurance_providers:h}:{},parser_overrides:i(c.overrides,g=>g.command),service_overrides:i(l.overrides,g=>g.service),renderer_overrides:i(u.overrides,g=>g.format),...f.length>0?{renderer_ownership:f}:{},preflight_overrides:d.overrides.filter(g=>r(g.name)).length,preflight_ownership:d.overrides.filter(g=>r(g.name)).map(g=>({commands:[...g.commands??[]]}))}}function ol(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import f_ from"node:path";import{mkdir as h_}from"node:fs/promises";import{readFile as Yr,realpath as To,writeFile as vg}from"node:fs/promises";import{execFile as bg}from"node:child_process";import ie from"node:path";import{promisify as kg}from"node:util";import{readFile as fg,writeFile as hg}from"node:fs/promises";import Nn 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]="89261a49-97e5-5ffc-a81c-2409f0b529cf")}catch{}})();var al="# pm-cli:runtime-cache:start",Ao="# pm-cli:runtime-cache:end",cl=".agents/pm",Io=["runtime/","search/","locks/","transactions/","checkpoints/"],gg=["search/eval-queries.json"];async function sl(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new w("The workspace .gitignore is not writable.",y.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function dl(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function Co(e){let t=e.replaceAll("\\","/");return Nn.isAbsolute(e)||t===".."||t.startsWith("../")}function _g(e=cl){let t=dl(e);return[al,...Io.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...gg.map(n=>`!${t}/${n}`),Ao].join(`
8
- `)}async function iC(e,t={}){let n=Nn.join(e,".gitignore"),r=cl;if(t.pmRoot!==void 0){let l=dl(Nn.relative(Nn.resolve(e),Nn.resolve(t.pmRoot)));if(Co(l))return{path:n,changed:!1};l.length>0&&(r=l)}let i="";try{i=await sl(()=>fg(n,"utf8"))}catch(l){if(!(l instanceof Error&&"code"in l&&U(l)))throw l}let o=i.indexOf(al),s=i.indexOf(Ao),c=(o>=0&&s>=o?`${i.slice(0,o)}${i.slice(s+Ao.length)}`:i).trimEnd(),d=`${c.length>0?`${c}
1
+ import{a as Ji,c as mr,d as pr,e as Ga,g as Ja,h as Ki,i as Va,j as Mt,k as Lt,l as Ka,m as Ya,n as Yi,o as Qa,p as Ft,q as jt,r as ec,s as tc,t as Xi}from"./chunk-4O4CJAR6.js";import{e as yr,f as Zi}from"./chunk-SVXJYD6G.js";import{C as _r,a as ja,g as Gi,i as Ua}from"./chunk-BEVHCEWG.js";import{P as id}from"./chunk-S4U5CN5Q.js";import{$ as Or,B as no,C as Lc,G as Fc,K as ro,L as $r,Na as Xc,Oa as Zc,Sa as Qc,Ta as ed,Ua as td,Wa as ao,aa as jc,ba as io,ca as En,e as Ic,ea as oo,f as Cc,g as Tc,ia as Uc,ja as zc,ka as Wc,la as Hc,m as $c,ma as Dr,n as Oc,o as Dc,oa as qc,pa as Bc,qa as Gc,ra as St,sa as Jc,ta as Jt,ua as Vc,v as xn,va as so,w as Pc,wa as Vt,x as Nc,xa as Kc,y as Sn,ya as Yc,z as Mc}from"./chunk-MKHG3T76.js";import{a as Wa,b as Nt,c as Vi,d as Ha,e as qa,f as Ve,g as fr,h as Ba,i as lt}from"./chunk-2FEZ5SKM.js";import{$ as Qi,$a as bc,$b as rd,Ab as Bt,Bb as ut,Ca as fc,Cb as Gt,Db as Ye,Ea as kr,Eb as kt,Fa as Ht,Ha as hc,Ib as xt,Kb as Tr,Oa as qt,Pb as Rn,Ra as _c,Rb as Pr,Sa as gc,Ua as xr,Va as eo,Wa as yc,Xa as wc,Y as V,Ya as vc,Yb as nd,Z as T,Za as pe,_ as lc,_a as Sr,ab as to,b as ac,bb as Er,cb as Rr,d as cc,da as fe,db as Ar,eb as kc,fb as Pe,gb as xc,hb as C,ib as Ir,ja as uc,ka as vr,kb as Sc,l as z,na as br,o as ne,oa as mc,pb as Ec,q as Ke,qa as pc,qb as Rc,r as dc,ra as Ut,s as wr,ta as zt,vb as Cr,wa as Wt,xb as Ac,zb as X}from"./chunk-T2LXXSOD.js";import{$a as ic,A as Ra,Ca as Bi,Da as La,Ea as Fa,F as Aa,Fa as Pt,G as Ia,H as W,Ha as Fe,Ja as je,La as ue,M as kn,Ma as Ae,N as M,O as Le,Oa as be,P as lr,Pa as Ue,Q as bt,S as Ca,T as ur,Ta as Ie,Ua as Xa,V as Ta,Va as hr,X as Z,Xa as Za,Za as gr,_ as $a,_a as rc,a as ya,ca as Oa,d as wa,e as va,fa as Da,h as Dt,ha as qi,p as Ea,q as bn,r as D,s as dt,t as U,ta as Pa,u as Y,ua as Na,v as le,y as ve,z as Re}from"./chunk-QDFJIRKN.js";import{a as oc,b as ze,d as sc}from"./chunk-6GCRSLPG.js";import{O as ba,Q as ka,S as xa,U as Sa,V as dr,Y as y,Z as w,a as ar,aa as Q,ba as Ma,ca as De,d as cr,fa as za,oa as nc,t as Hi}from"./chunk-Z2USIBR2.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d2d5135a-8110-527e-8530-653b25b792a4")}catch{}})();var P=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},ke=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},We=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 Kt(e){try{return await e()}catch(t){throw t instanceof P?new w(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function od(e){try{return await e()}catch(t){throw t instanceof ke?new w(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as Zf}from"node:crypto";import Qf from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b911b43d-d14d-5e4f-a35e-5020b1a84542")}catch{}})();var Yt=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d4c380ce-031e-5b2d-aaa8-658bb4aa3087")}catch{}})();var ad=1,Et=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],co=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],eh=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],th=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Nr=30,Mr=5e3,cd=4,nh=50;function Xe(e,t){if(!th.test(e))throw new P(`${t} must be a stable lowercase id`)}function rh(e,t){if(!Number.isFinite(e)||e<0)throw new P(`${t} must be a finite non-negative number`)}function An(e){let t=eh.filter(i=>e[i]!==void 0);if(t.length!==1)throw new P(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function uo(e,t){return Q(e)===Q(t)}function dd(e,t){if(t.polarity==="equals")return uo(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 ld(e){let t=An(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>dd(r.observed,t)===(r.expected==="pass"))}function ih(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!uo(e.value,t.value)}function oh(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||Q(e.scope)!==Q(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return ih(An(e),An(t))||n[t.enforcement]<n[e.enforcement]||r}function sh(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new P("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 P("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new P("items source equals/state requires field")}function ah(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new P("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 P("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 P("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 P("dependency_kind source source_kind_state must be present or missing")}function ch(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new P("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 P("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 P("prose_edge_gap exemption selectors must not be empty")}}function mo(e){Xe(e.id,"measurement.id"),e.max_cost!==void 0&&rh(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new P(`measurement.source.kind must be one of ${co.join(", ")}`);let n=Reflect.get(t,"kind");if(!co.includes(n))throw new P(`measurement.source.kind must be one of ${co.join(", ")}`);let r=t;if(r.kind==="items"&&sh(r),r.kind==="dependency_kind"&&ah(r),r.kind==="prose_edge_gap"&&ch(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new P(`${r.kind} source requires field`);return r.kind==="provider"&&(Xe(r.provider,"provider source provider"),Xe(r.key,"provider source key")),e}function po(e){if(Xe(e.id,"assertion.id"),Xe(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new P("assertion.owner_item_id is required");let t=An(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new P(`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 P("retired assertion requires retire_reason");e.scope.kind==="filter"&&Xe(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 P("assertion negative control requires pass and fail cases");if(!ld(e))throw new P(`assertion ${e.id} negative control does not prove its bound`);return e}function dh(e){if(!Array.isArray(e.allowed_providers))throw new P("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)Xe(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new P("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Et.includes(t))throw new P(`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 P(`gate provider policy trigger ${t} is invalid`)}}function ud(e){if(Xe(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new P("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new P("gate requires at least one assertion");for(let t of e.assertion_ids)Xe(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new P(`gate.triggers is required and must be an array of ${Et.join(", ")}`);if(e.triggers.length===0)throw new P("gate requires at least one trigger");for(let t of e.triggers)if(!Et.includes(t))throw new P(`gate trigger must be one of ${Et.join(", ")}`);return e.provider_policy&&dh(e.provider_policy),e}function Xt(e){if(e.version!==ad)throw new P(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(mo(r),t.has(`measurement:${r.id}`))throw new P(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(po(r),t.has(`assertion:${r.id}`))throw new P(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){ud(r);let i=r.assertion_ids.filter(o=>!e.assertions.some(s=>s.id===o));if(i.length>0)throw new P(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new P(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of md(e))if(!n.has(r))throw new P(`${i.join(", ")} references missing measurement ${r}`);return e}function fo(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)fo(n,t)}function md(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=[];fo(r.source.expression,i);for(let o of i)n(o,`derived measurement ${r.id}`)}return t}function lh(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"&&fo(s.source.expression,n)}return i}function In(){return{version:ad,measurements:[],assertions:[],gates:[]}}function uh(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 uo(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function mh(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 ph(e,t){let n=[],r=qi(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let o of i.dependencies??[]){let s=qi(o.kind)??o.kind.trim().toLowerCase(),a=o.source_kind?.trim();s===r&&mh(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 fh(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 hh(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 lo(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function _h(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(lo(s.id,a.id));for(let a of[s.parent,s.blocked_by])typeof a=="string"&&n.add(lo(s.id,a));for(let a of fh(s)){let c=[...a.matchAll(i)].map(d=>d[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 gh(e,t){let n=_h(t.items),r=new Map;for(let s of n.prose_mentions){let a=s.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==s.holder_id),c=[...new Set(a)];for(let d of c){let l=lo(s.holder_id,d);if(n.linked_pairs.has(l)||hh(e.exemptions??[],s.holder_id,d,s.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${s.holder_id}->${d}|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 yh(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 wh(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 vh(e,t){let n=e.source;return n.kind==="items"?uh(n,t):n.kind==="dependency_kind"?ph(n,t):n.kind==="prose_edge_gap"?gh(n,t):n.kind==="history"?yh(n,t):n.kind==="links"?wh(n,t):null}function pd(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 bh(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 fd(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 hd(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(d=>d.id===e.measurement);if(!s)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await _d(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 fd(e.operands,cd,s=>hd(s,t,n,r,i));return{value:bh(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 kh(e,t,n,r,i){mo(e);let o=Date.now(),s,a=[],c=0;if(e.source.kind==="derived"){let u=await hd(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=vh(e,t);u!==null?s=u:(s=await t.external(e.source),c=1)}let d={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},l=pd([...a,d],Date.now()-o);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new ke(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${Zf("sha256").update(Q(e)).digest("hex")}`,value:s.value,population_size:s.population_size,cost:l,contributors:s.contributors??[],...s.partitions?{partitions:s.partitions}:{}}}function _d(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=kh(e,t,n,r,i).catch(a=>{if(a instanceof We&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},d=new We(a.message,c);throw d.cause=a,d}throw a});return i.cache.set(e.id,s),s}async function ho(e,t,n=[e]){return _d(e,t,n,[],{cache:new Map,charged:new Set})}function xh(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 Sh(e,t,n={}){po(e);let r=An(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:xh(t.value,r),verdict:i?"retired":dd(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:ld(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Eh(e,t,n,r){let i=lh(e,t);if(i.size===0)return;let o=e.provider_policy,s=o?.triggers[r];if(!o||!s)throw new ke(`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 d of i){if(!a.has(d))throw new ke(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new ke(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[s.max_cost_class])throw new ke(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!s.allow_network)throw new ke(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function sd(e,t,n,r,i){try{return await ho(n,r,i)}catch(o){if(o instanceof We){let s=o.check?` check ${o.check}`:"",a=o.measurement_id??n.id,c=new ke(`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 gd(e,t,n,r){Xt(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new ke(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new ke(`assurance gate ${e} does not declare trigger ${r.trigger}`);Eh(i,t,n,r.trigger);let o=await fd(i.assertion_ids,cd,async c=>{let d=t.assertions.find(f=>f.id===c),l=t.measurements.find(f=>f.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let f=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!f.has(h.status))}}else if(d.scope.kind==="filter"){let f=d.scope.measurement_id,h=t.measurements.find(v=>v.id===f),_=await sd(i.id,d.id,h,n,t.measurements),g=new Set(_.contributors);u={...n,items:n.items.filter(v=>g.has(v.id))}}let m=n.items.find(f=>f.id===d.owner_item_id),p=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return Sh(d,await sd(i.id,d.id,l,u,t.measurements),{owner_terminal:p})}),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:pd(o.map(c=>c.cost),Math.max(0,...o.map(c=>c.cost.duration_ms)))}}function Lr(e){return Qf.join(e,"assurance.json")}async function yd(e){let t=await Y(Lr(e));return t===null?In():Fr(t)}function Fr(e){try{return Xt(JSON.parse(e))}catch(t){throw new w("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",y.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 jr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Rh(e,t){e==="measurement"?mo(t):e==="assertion"?po(t):ud(t)}async function Cn(e,t){let n=structuredClone(jr(await yd(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function _o(e,t,n){let r=jr(await yd(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Ur(e,t,n,r={}){Rh(t,n);let i=await C(e),o=V(r.author,i.author_default),s=await Rr({pmRoot:e,filePath:Lr(e),op:`assurance:${t}:put`,author:o,message:r.message,lockTtlSeconds:Nr,lockWaitMs:Mr,mutate:a=>{let c=a===null?In():Fr(a),d=jr(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&oh(d[l],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new P(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),Xt(c),{raw:`${JSON.stringify(c,null,2)}
2
+ `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...s.result,changed:s.changed}}async function go(e,t,n={}){let r=In();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),Xt(r);let i=await C(e),o=V(n.author,i.author_default),s=await Rr({pmRoot:e,filePath:Lr(e),op:"assurance:bundle:apply",author:o,message:n.message,lockTtlSeconds:Nr,lockWaitMs:Mr,mutate:a=>{let c=a===null?In():Fr(a),d=[],l=[],u=(m,p,f)=>{for(let h of p){let _=m.find(g=>g.id===h.id);if(!_){m.push(structuredClone(h)),d.push(`${f}:${h.id}`);continue}if(Q(_)!==Q(h))throw new P(`assurance bundle refuses to replace divergent ${f} ${h.id}`);l.push(`${f}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),Xt(c),{raw:`${JSON.stringify(c,null,2)}
3
+ `,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...s.result,changed:s.changed}}async function wd(e,t,n,r={}){let i=await C(e),o=V(r.author,i.author_default),s=await Rr({pmRoot:e,filePath:Lr(e),op:`assurance:${t}:remove`,author:o,message:r.message,lockTtlSeconds:Nr,lockWaitMs:Mr,mutate:a=>{let c=a===null?In():Fr(a);if(t==="measurement"){let u=md(c).get(n);if(u&&u.length>0)throw new P(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new P(`assurance assertion ${n} is referenced by gate`);let d=jr(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new P(`assurance ${t} ${n} not found`);return d.splice(l,1),Xt(c),{raw:`${JSON.stringify(c,null,2)}
4
+ `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...s.result,changed:s.changed}}async function vd(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await C(e);await Er({pmRoot:e,op:"assurance:gate:verdict",author:V(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Nr,lockWaitMs:Mr})}async function bd(e,t={}){let n=t.limit??nh;if(!Number.isInteger(n)||n<1||n>Yt)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${Yt}`);return(await Wt(Sr(e),pe)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="05c29627-6763-5aee-8579-71e563a98780")}catch{}})();var Tn=["software-delivery","research","agent-evaluation","operations"];function kd(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 zr(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=>kd(`${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 Wr(e,t){return e==="software-delivery"?zr(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?zr(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?zr(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):zr(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function xd(e,t,n,r={}){return go(e,Wr(t,n).declarations,r)}async function Sd(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 ho(s,r)).value,d=kd(`${s.id}-ceiling`,s.id,t,c,"observe"),l=`active-missing-${o}`;return{id:l,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[s],assertions:[d],gates:[{id:`derived-${l}`,description:`Observe the accepted ${o} evidence baseline.`,assertion_ids:[d.id],triggers:["ci","scheduled"]}]}}}))}function Ed(e,t,n={}){return go(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 Rd(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 Ur(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Cd from"node:fs/promises";import{createRequire as Ah}from"node:module";import xe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c21b1a94-1d80-57c0-b090-c4831fc505a2")}catch{}})();function Ad(e,t){let n=xe.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${xe.sep}`)&&!xe.isAbsolute(n))return n.split(xe.sep).join("/");let r=xe.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")}/${xe.basename(xe.dirname(e))}/package.json`}function Ih(e){return e.includes(`${xe.sep}.pnpm${xe.sep}`)?"pnpm":e.includes(`${xe.sep}node_modules${xe.sep}`)?"npm":"other"}async function Id(e){try{let t=JSON.parse(await Cd.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 yo(e){try{return await Cd.realpath(e)}catch{return xe.resolve(e)}}async function Td(e,t,n=Re(import.meta.url,["../../.."])){let r=await yo(t),i=await yo(xe.join(n,"package.json")),o=await Id(i),s=new Map;o!==void 0&&s.set(i,{version:o,path:Ad(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=Ah(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await yo(l),m=await Id(u);if(m===void 0)continue;let p=u,f=s.get(p);if(f){f.consumers.includes(d.name)||(f.consumers.push(d.name),f.consumers.sort((h,_)=>h.localeCompare(_)));continue}s.set(p,{version:m,path:Ad(u,r),layout:Ih(u),consumers:[d.name]})}catch{}let a=[...s.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=o===void 0?[]:a.filter(d=>d.version!==o);return{host_version:o??null,copies:a,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${o}:${d.version}:${d.consumers.join("+")}`)}}import{createHash as Wd}from"node:crypto";import $n from"node:fs/promises";import On from"node:path";import{Option as eI}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]="01742f33-d1e8-5684-a585-2add88ddb73c")}catch{}})();function Ch(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 Hr(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function L(e,t){return e[t]===!0?!0:void 0}function Ze(e,t){return e[t]===!1?!0:void 0}function $d(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Od(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function Dd(e){let t=i=>Gi(e,Hr(yr,i)),n=i=>Ua(e,Hr(Zi,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:Ch(e,Hr(Zi,"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:$d(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:L(e,"replaceDeps"),replaceTests:L(e,"replaceTests"),replaceFiles:L(e,"replaceFiles"),replaceDocs:L(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:L(e,"clearDeps"),clearComments:L(e,"clearComments"),clearNotes:L(e,"clearNotes"),clearLearnings:L(e,"clearLearnings"),clearFiles:L(e,"clearFiles"),clearTests:L(e,"clearTests"),clearDocs:L(e,"clearDocs"),clearReminders:L(e,"clearReminders"),clearEvents:L(e,"clearEvents"),clearTypeOptions:L(e,"clearTypeOptions")};return Od(r,e),r}function ee(e,t){let n=Hr(ja,t),r=Gi(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 Th(e){let t=L(e,"filterFilesMissing"),n=L(e,"filterDocsMissing");return{filterReviewerMissing:L(e,"filterReviewerMissing"),filterRiskMissing:L(e,"filterRiskMissing"),filterConfidenceMissing:L(e,"filterConfidenceMissing"),filterSprintMissing:L(e,"filterSprintMissing"),filterReleaseMissing:L(e,"filterReleaseMissing"),hasNotes:L(e,"hasNotes"),hasLearnings:L(e,"hasLearnings"),hasFiles:L(e,"hasFiles"),hasDocs:L(e,"hasDocs"),hasTests:L(e,"hasTests"),hasComments:L(e,"hasComments"),hasDeps:L(e,"hasDeps"),hasBody:L(e,"hasBody"),hasLinkedCommand:L(e,"hasLinkedCommand"),noNotes:Ze(e,"notes"),noLearnings:Ze(e,"learnings"),noFiles:Ze(e,"files")??t,filterFilesMissing:t,noDocs:Ze(e,"docs")??n,filterDocsMissing:n,noTests:Ze(e,"tests"),noComments:Ze(e,"comments"),noDeps:Ze(e,"deps"),emptyBody:L(e,"emptyBody"),noLinkedCommand:Ze(e,"linkedCommand")}}function Pd(e){let t={status:ee(e,"status"),type:ee(e,"type"),tag:ee(e,"tag"),priority:ee(e,"priority"),deadlineBefore:ee(e,"deadlineBefore"),deadlineAfter:ee(e,"deadlineAfter"),updatedAfter:ee(e,"updatedAfter"),updatedBefore:ee(e,"updatedBefore"),createdAfter:ee(e,"createdAfter"),createdBefore:ee(e,"createdBefore"),today:L(e,"today"),recent:L(e,"recent"),ids:ee(e,"ids"),assignee:ee(e,"assignee"),assigneeFilter:ee(e,"assigneeFilter"),parent:ee(e,"parent"),sprint:ee(e,"sprint"),release:ee(e,"release"),limit:ee(e,"limit"),offset:ee(e,"offset"),noTruncate:Ze(e,"truncate"),includeBody:L(e,"includeBody"),strictRead:L(e,"strictRead"),compact:L(e,"compact"),brief:L(e,"brief"),full:L(e,"full"),fields:ee(e,"fields"),sort:ee(e,"sort"),order:ee(e,"order"),tree:L(e,"tree"),treeDepth:ee(e,"treeDepth"),filterAcMissing:L(e,"filterAcMissing"),filterEstimatesMissing:$d(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:L(e,"filterResolutionMissing"),filterMetadataMissing:L(e,"filterMetadataMissing"),...Th(e)};return Od(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]="fde4fea5-94d6-53e2-bfbc-bff71d828c01")}catch{}})();var $h=Symbol("pm.mcp-mutation-transport");function vo(e){return $h in e}function Br(e,t){return vo(e)?Mc(t):no(e,t)}function uI(e,t,n=[]){let r=no(e,{...e,...t});for(let i of n)Reflect.deleteProperty(r,i);return r}function $(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function re(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function mI(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Zt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ko(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new w(`${t} must be a finite integer.`,y.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new w(`${t} must be a finite integer.`,y.USAGE);return n}}function pI(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:$(e,"limit")??$(t,"limit")}function fI(e){let t=$(e,"outputFormat");return{json:!0,quiet:!0,author:$(e,"author"),path:$(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:$(e,"outputInclude"),outputLimit:re(e,"outputLimit"),outputBudget:re(e,"outputBudget"),outputSession:$(e,"outputSession"),outputCursor:$(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Oh=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Md=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"]),Dh=new Set([...Md].filter(e=>e!=="file")),Ph=new Set(["files","files-discover","docs","test","test-all"]),Ld=new Set(["comments","notes","learnings"]);function Nh(e,t){if(!(!Ld.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new w(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,y.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var Mh=new Set(["claim","release","start-task","pause-task","close-task"]),Lh={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"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Fh=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Fd(e,t=""){let n={},r=Ph.has(t),i=t==="files"||t==="files-discover"||t==="docs",o=Ld.has(t)?Dh:Md;for(let[s,a]of Object.entries(e)){if(Array.isArray(a)&&Oh.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 jh(e,t,n){let r=$(e,"author");return r!==void 0?r:n!==void 0&&Mh.has(n)?$(e,"assignee")??$(t,"assignee"):void 0}function Uh(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function hI(e,t){let n=Zt(e.options)?e.options:void 0,r=Oa(e.options),i={},o=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of Lh[t??""]??[])o(c);for(let c of Fh)o(c);t!==void 0&&vo(e)&&Nh(t,r);let s=Fd({...i,...r},t),a=vo(e)?e:n??e;return Br(a,Uh(s,jh(e,s,t)))}function _I(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 gI(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 yI(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 wI(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function xo(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function vI(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 bI(e,t){let n=Br(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function bo(e){return{type:re(e,"filterType"),tag:re(e,"filterTag"),priority:re(e,"filterPriority"),deadlineBefore:re(e,"filterDeadlineBefore"),deadlineAfter:re(e,"filterDeadlineAfter"),updatedAfter:re(e,"filterUpdatedAfter"),updatedBefore:re(e,"filterUpdatedBefore"),createdAfter:re(e,"filterCreatedAfter"),createdBefore:re(e,"filterCreatedBefore"),ids:ro(e.ids),assignee:re(e,"filterAssignee"),assigneeFilter:re(e,"filterAssigneeFilter")??re(e,"filterAssignee_filter"),parent:re(e,"filterParent"),sprint:re(e,"filterSprint"),release:re(e,"filterRelease"),limit:re(e,"limit"),offset:re(e,"offset")}}function wo(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return xo(e)}function qr(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function kI(e){let t=wo(e.kind),n=wo(e.exemptIsolate),r=wo(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:qr(e.maxDepth),limit:qr(e.limit),after:$(e,"after"),direction:$(e,"direction"),maxPaths:qr(e.maxPaths),sample:qr(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 jd(e){let t=Pd(e);return e.ids!==void 0&&(t.ids=ro(e.ids)),t}function xI(e){return{status:$(e,"filterStatus"),list:Zt(e.list)?jd(e.list):bo(e),reason:$(e,"reason"),resolution:$(e,"resolution"),expectedResult:$(e,"expectedResult")??$(e,"expected_result")??$(e,"expected"),actualResult:$(e,"actualResult")??$(e,"actual_result")??$(e,"actual"),validateClose:$(e,"validateClose")??$(e,"validate_close"),author:$(e,"author"),message:$(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:$(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var zh=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 Nd(e){let t={};for(let[n,r]of Object.entries(e))zh.has(n)||(t[n]=r);return Ud(t)}function Ud(e){let t=Fd(e,"update-many");for(let n of yr)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return Dd(t)}function SI(e){if(Zt(e.list)||Zt(e.update)){let t=Zt(e.update)?e.update:Nd(e),n=Br(e,Ud(t));return{status:re(e,"filterStatus"),list:Zt(e.list)?jd(e.list):bo(e),update:Lc(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:$(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:re(e,"filterStatus"),list:bo(e),update:Br(e,Nd(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:$(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]="b389e521-f689-5895-a5f4-08c3866b3ea3")}catch{}})();function Ce(e,t){throw new w(e,y.USAGE,t)}var Wh="2026-07-15T06:22:12.276Z",Hh=Date.parse(Wh),qh=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],zd=e=>typeof e=="string"?e:"",Hd=e=>{let t=e??{},n=zd(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(zd(t.ts))>=Hh);return qh[r][i]};function qd(e,t,n=20,r=new Set,i=!1){let o=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,p]of t.split(/\r?\n/).entries()){let f;try{f=JSON.parse(p)}catch{continue}d+=1;let h=Hd(f);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}a[h]+=1,i&&h==="actionable_unknown"&&s.push({item_id:e,line:m+1}),o.length<c&&o.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:a.legacy_unknown+a.actionable_unknown>o.length,actionable_events:s}}var PI=(e,t,n=20,r=new Set)=>qd(e,t,n,r);function Bd(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 Dn=async(e,t=20,n=!1)=>{let r=On.join(e,"history"),i;try{i=(await $n.readdir(r)).filter(g=>g.endsWith(".jsonl")).sort((g,v)=>g.localeCompare(v))}catch{i=[]}let o=new Set,s=[],a=[],c=0,d=0,l=0,u=0,m=0,p=0,f="_workspace.jsonl",h=new Set;if(i.includes(f))try{h=Bd(await $n.readFile(On.join(r,f),"utf8"))}catch{h=new Set}for(let g of i){let v;try{v=await $n.readFile(On.join(r,g),"utf8")}catch{continue}let k=g.slice(0,-6),x=qd(k,v,t-s.length,h,n);c+=1,d+=x.checked_events,l+=x.unknown_event_count,u+=x.legacy_unknown_event_count,m+=x.actionable_unknown_event_count,p+=x.acknowledged_actionable_event_count,x.unknown_event_count>0&&o.add(k),s.push(...x.samples),n&&a.push(...x.actionable_events)}let _=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:p,affected_item_ids:[...o].sort((g,v)=>g.localeCompare(v)),samples:s,samples_truncated:_>s.length,...n?{actionable_events:a}:{}}};function Bh(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 Gh(e){try{return Bd(await $n.readFile(On.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function Jh(e){return(e.item_id===pe||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function Vh(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Ce(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Hd(i)!=="actionable_unknown"&&Ce(`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:Wd("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Gd(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Ce("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Ce("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Ce("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let o=Bh(t.all_actionable===!0?(await Dn(e,0,!0)).actionable_events:r),s=await Gh(e),a=new Map;for(let m of o)if(Jh(m)||Ce(`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 $n.readFile(On.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Ce(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=o.map(m=>Vh(m,s,a.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Wd("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function NI(e,t,n=50){return(await Gd(e,t,n)).plan}function Kh(e,t){let n=e.length>0;return n&&t&&Ce("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&&Ce("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:Yh(e),all_actionable:t}}function Yh(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),o=r===pe||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!o||!Number.isSafeInteger(i)||i<1)&&Ce(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function MI(e,t){let n=Kh(xo(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Xh(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:$(t,"planFingerprint")??$(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:$(t,"attributedAuthor")??$(t,"attributed_author")??void 0,reviewer:$(t,"reviewer"),reason:$(t,"reason")})}async function Xh(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",o=await Gd(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:y.SUCCESS,plan:o.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Ce("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Ce("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 w("Author acknowledgment selection changed after preview; no history was mutated.",y.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:y.NO_EFFECT,plan:o.plan};let c=await C(e),d=await Er({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}),l=o.plan.actionable_count>0&&o.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:y.PARTIAL_EFFECT}:{outcome:"effect",exit_code:y.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...l,plan:o.plan,history_path:d.historyPath}}import So from"node:fs/promises";import Eo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6efed404-acd2-5c3a-a008-856df67c8b77")}catch{}})();var Zh=8388608,Qh=new Set(["resolved","failed"]),e_=[{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 He(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ro(e){return e_.find(t=>t.matches(e))?.kind}function Jd(e){let t=new Map,n=0,r=0;return{entries:e.map(o=>{let s=He(o.agent_provenance)?o.agent_provenance:void 0;if(s===void 0)return o;let a={},c=!1;for(let[l,u]of Object.entries(s)){let m=He(u)?Ro(u.value):void 0;if(m===void 0){a[l]=u;continue}c=!0,r+=1;let p=o.agent_harness??"unknown",f=`${p}\0${l}\0${m}`,h=t.get(f)??{harness:p,dimension:l,kind:m,count:0};h.count+=1,t.set(f,h)}if(!c)return o;n+=1;let d={...o};return Object.keys(a).length===0?delete d.agent_provenance:d.agent_provenance=a,d}),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 Vd(e){let t=[];for(let n of await Kd(e))try{let r=await So.readFile(Eo.join(e,"history",n),"utf8");for(let i of r.split(`
5
+ `)){if(i.trim().length===0)continue;let o=Yd(i);if(o===null||!He(o.agent_provenance))continue;if(Object.values(o.agent_provenance).some(a=>He(a)&&Ro(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Kd(e){try{return(await So.readdir(Eo.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function t_(e,t,n){let r;try{r=await So.open(Eo.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"),d=a>=i,l=c.lastIndexOf(`
6
+ `),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:a,complete:d}}catch{return null}finally{await r?.close()}}function Yd(e){try{let t=JSON.parse(e);return He(t)?t:null}catch{return null}}function n_(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=He(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([s,a])=>{if(!He(a))return;let c=Ro(a.value);if(!c)return;let d=`${r}\0${s}\0${c}`,l=n.get(d)??{harness:r,dimension:s,kind:c,count:0};l.count+=1,n.set(d,l)}),!He(e.context))return;let o=e.context.agent_provenance_outcomes;He(o)&&Object.entries(o).forEach(([s,a])=>{if(!He(a)||typeof a.resolver!="string"||!Qh.has(String(a.status)))return;let c=`${r}\0${s}\0${a.resolver}`,d=t.get(c)??{harness:r,dimension:s,resolver:a.resolver,attempts:0,successes:0};d.attempts+=1,a.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function r_(e,t,n,r,i){let o=i;for(let s of e.split(`
7
+ `)){if(s.trim().length===0)continue;if(o>=r)return{eventsRead:o,truncated:!0};o+=1;let a=Yd(s);a&&n_(a,t,n)}return{eventsRead:o,truncated:!1}}async function Xd(e,t=1e4){let n=new Map,r=new Map,i=0,o=0,s=!1;for(let d of await Kd(e)){let l=await t_(e,d,Math.max(0,Zh-o));if(l===null)continue;o+=l.bytesRead;let u=r_(l.content,n,r,t,i);if(i=u.eventsRead,u.truncated){s=!0;break}if(!l.complete){s=!0;break}}let a=[...n.values()].sort((d,l)=>d.harness.localeCompare(l.harness)||d.dimension.localeCompare(l.dimension)||d.resolver.localeCompare(l.resolver)),c=[...r.values()].sort((d,l)=>d.harness.localeCompare(l.harness)||d.dimension.localeCompare(l.dimension)||d.kind.localeCompare(l.kind));return{outcomes:a,invalid_values:c,warnings:s?[]:[...a.filter(d=>d.attempts>0&&d.successes===0).map(d=>`provenance_resolver_zero_success:${d.harness}:${d.dimension}:${d.resolver}:${String(d.attempts)}`),...c.map(d=>`provenance_value_domain_invalid:${d.harness}:${d.dimension}:${d.kind}:${String(d.count)}`)],events_read:i,truncated:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd7acf28-cb93-516e-9058-54c32625ec26")}catch{}})();function Gr(e,t,n=25){let r=e.definitions.filter(s=>s.roles.length===0).map(s=>s.id).sort((s,a)=>s.localeCompare(a)),i=new Set(r),o=t.filter(s=>{let a=Xa(s.status,e);return a!==void 0&&i.has(a)}).map(s=>s.id).sort((s,a)=>s.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:o.length,affected_item_ids:o.slice(0,n),affected_item_ids_truncated:o.length>n}}function Jr(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}import ot from"node:fs/promises";import ge from"node:path";import Pn from"node:fs/promises";import{createHash as i_}from"node:crypto";import Qd 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]="1c6c65ef-115b-50e2-815e-84f6e91158cd")}catch{}})();var el=9,o_="history-drift-cache.json";function tl(e){return Qd.join(e,"runtime",o_)}async function s_(e){try{let t=await Pn.readFile(tl(e),"utf8"),n=JSON.parse(t);return n.version!==el||n.history_item_hash_version!==kr||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!Ht.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&Ht.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}async function a_(e,t,n,r,i){let o=Sr(e),s;try{s=await Pn.stat(o)}catch(d){return U(d)||i.unreadableStreams.push(pe),!1}let a=i.missingStreams.length,c=await nl({itemId:pe,historyPath:o,stat:s,cached:t[pe],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(pe),c.verification.chainOk||i.chainMismatches.push(pe),n[pe]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(i.missingStreams.splice(a),c.cacheDirty)}function c_(e){return i_("sha256").update(e).digest("hex")}async function d_(e){let t=await Pn.readFile(e,"utf8"),n=c_(t);if(t.trim().length===0)return null;let r=[],i=null;for(let u of t.split(/\r?\n/)){let m=u.trim();if(m.length===0)continue;let p=JSON.parse(m);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(p),i=p.after_hash}if(!i)return null;let o=xr(r),s=r.some(u=>u.item_hash_version!==void 0&&!Ht.includes(u.item_hash_version)),c=r[r.length-1].item_hash_version,d=c!==void 0&&Ht.includes(c),l=d?c:o.item_hash_version;return{latestAfterHash:i,chainOk:o.ok,versionSkew:s,latestHashComparable:l!==void 0&&(!s||d||c===void 0),contentHash:n,itemHashVersion:l??kr}}function l_(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Zd(e,t,n){try{let r=await d_(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function nl(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(l_(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Zd(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let r=await Zd(e.itemId,e.historyPath,e.accumulator);return{verification:r,cacheDirty:r===null||r.contentHash!==t||r.latestAfterHash!==e.cached.latest_after_hash||r.chainOk!==e.cached.chain_ok||r.versionSkew!==(e.cached.version_skew===!0)||r.latestHashComparable!==e.cached.latest_hash_comparable||r.itemHashVersion!==e.cached.item_hash_version}}return{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&Ht.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version},cacheDirty:!1}}async function u_(e,t,n,r){let i=ur(e,t.id),o;try{o=await Pn.stat(i)}catch(l){return(U(l)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await nl({itemId:t.id,historyPath:i,stat:o,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!s.verification)return s.cacheDirty;s.verification.versionSkew&&r.versionSkews.push(t.id),s.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:s.verification.contentHash,latest_after_hash:s.verification.latestAfterHash,chain_ok:s.verification.chainOk,version_skew:s.verification.versionSkew,latest_hash_comparable:s.verification.latestHashComparable,item_hash_version:s.verification.itemHashVersion};let{body:a,...c}=t;return s.verification.latestHashComparable&&(hc({metadata:c,body:a},s.verification.itemHashVersion).includes(s.verification.latestAfterHash)||r.hashMismatches.push(t.id)),s.cacheDirty}async function m_(e,t){if(!(t.unreadableStreams.includes(pe)||t.chainMismatches.includes(pe)||t.versionSkews.includes(pe)))try{let n=await bc(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(pe)}}async function Rt(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},o=(await s_(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",d={previousEntries:o,nextEntries:s,verifyCacheHitByContent:c};for(let m of t)await u_(e,m,d,r)&&(a=!0);let l=await a_(e,o,s,c,r);if(a||=l,await m_(e,r),a||Object.keys(o).length!==Object.keys(s).length){let m=tl(e);try{await Pn.mkdir(Qd.dirname(m),{recursive:!0}),await le(m,JSON.stringify({version:el,history_item_hash_version:kr,entries:s}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.versionSkews,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[pe]:[]])].sort((m,p)=>m.localeCompare(p));return{...r,driftedItems:u}}import Nn from"node:fs/promises";import Vr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="79f9ccbd-48d1-5eb3-82ae-3dd62427041c")}catch{}})();function p_(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:o,ttl_seconds:s}=n;return typeof r!="string"||typeof i!="string"||typeof o!="string"||typeof s!="number"||!Number.isFinite(s)?null:{id:r,owner:i,created_at:o,ttl_seconds:s}}function rl(e,t,n){let r=p_(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let o=n-i,s=Math.floor(o/1e3),a=o>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:s,stale:a,reason:a?"expired":"active"}}}async function il(e,t){let n=t??Date.now(),r=Vr.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await Nn.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(s){if(U(s))return i;throw s}for(let s of o){let a;try{a=await Nn.readFile(Vr.join(r,s),"utf8")}catch(d){if(U(d))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=rl(s,a,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function ol(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Vr.join(e,"locks"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},a;try{a=(await Nn.readdir(o)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if(U(c))return s;throw c}for(let c of a){s.scanned+=1;let d=Vr.join(o,c),l=`locks/${c}`;if(r?.onRead){let p=await r.onRead(d);s.warnings.push(...p)}let u;try{u=await Nn.readFile(d,"utf8")}catch(p){if(U(p)){s.scanned-=1;continue}s.warnings.push(`lock_unreadable:${c}`),s.retained.push(l),s.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=rl(c,u,i);if(m.detail==="unparseable_json"){s.warnings.push(`lock_unparseable:${c}`),s.retained.push(l),s.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){s.warnings.push(`lock_invalid_timestamp:${c}`),s.retained.push(l),s.entries.push(m.entry);continue}if(m.detail==="active"){s.retained.push(l),s.entries.push(m.entry);continue}if(!n){try{await Nn.unlink(d)}catch(p){if(!U(p)){s.warnings.push(`lock_remove_failed:${c}`),s.retained.push(l),s.entries.push(m.entry);continue}}if(r?.onWrite){let p=await r.onWrite(d);s.warnings.push(...p)}}s.removed.push(l),s.entries.push(m.entry)}return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="24a69725-363a-59e1-96c6-1e1ca079a311")}catch{}})();var f_=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm health --check-only --full --json",summary:"One or more append-only history coordinates reference receipt evidence that is no longer present; inspect the bounded item, line, and privacy-safe receipt locator, then recover the named evidence from an authoritative clone or backup without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Ao(e){if(typeof e!="string")return;let t=e.trim();for(let n of f_)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Io(e){let t={};for(let n of e){let r=Ao(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function sl(e){return Object.values(Io(e))}import _t from"node:fs/promises";import Te 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]="2c514907-377f-59f9-bfdd-a184abf7ffb7")}catch{}})();var h_=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Qt(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(gr(t.extensionName));for(let _ of t.extensionNames??[])n.add(gr(_));let r=_=>n.size===0||n.has(gr(_)),i=(_,g)=>al(_.filter(v=>r(v.name)).map(g)),o=(_,g)=>al(_.filter(v=>r(v.name)).flatMap(g)),{registrations:s,commands:a,parsers:c,preflight:d,services:l,renderers:u,hooks:m}=e,p=o(s.relationship_kinds??[],_=>_.definitions.map(g=>g.kind)),f=u.overrides.filter(_=>r(_.name)&&((_.commands?.length??0)>0||_.resultDiscriminator!==void 0)).map(_=>({format:_.format,commands:[..._.commands??[]],result_discriminator:_.resultDiscriminator!==void 0})).sort((_,g)=>_.format.localeCompare(g.format)),h=i(s.assurance_providers??[],_=>_.definition.id);return{capabilities:rc(e,t),commands:i(s.commands,_=>_.command),command_overrides:i(a.overrides,_=>_.command),command_handlers:i(a.handlers,_=>_.command),hooks:h_.filter(([_])=>m[_].some(g=>r(g.name))).map(([,_])=>_),flag_commands:i(s.flags,_=>_.target_command),item_types:o(s.item_types,_=>_.types.map(g=>g.name)),item_fields:o(s.item_fields,_=>_.fields.map(g=>g.name)),...p.length>0?{relationship_kinds:p}:{},migrations:o(s.migrations,_=>typeof _.definition.id=="string"?[_.definition.id]:[]),profiles:i(s.profiles,_=>_.profile.name),importers:i(s.importers,_=>_.importer),exporters:i(s.exporters,_=>_.exporter),search_providers:i(s.search_providers,_=>_.definition.name),vector_store_adapters:i(s.vector_store_adapters,_=>_.definition.name),...h.length>0?{assurance_providers:h}:{},parser_overrides:i(c.overrides,_=>_.command),service_overrides:i(l.overrides,_=>_.service),renderer_overrides:i(u.overrides,_=>_.format),...f.length>0?{renderer_ownership:f}:{},preflight_overrides:d.overrides.filter(_=>r(_.name)).length,preflight_ownership:d.overrides.filter(_=>r(_.name)).map(_=>({commands:[..._.commands??[]]}))}}function al(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import _g from"node:path";import{mkdir as gg}from"node:fs/promises";import{readFile as Yr,realpath as Oo,writeFile as k_}from"node:fs/promises";import{execFile as x_}from"node:child_process";import ie from"node:path";import{promisify as S_}from"node:util";import{readFile as __,writeFile as g_}from"node:fs/promises";import Mn 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]="89261a49-97e5-5ffc-a81c-2409f0b529cf")}catch{}})();var dl="# pm-cli:runtime-cache:start",Co="# pm-cli:runtime-cache:end",ll=".agents/pm",To=["runtime/","search/","locks/","transactions/","checkpoints/"],y_=["search/eval-queries.json"];async function cl(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new w("The workspace .gitignore is not writable.",y.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function ul(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function $o(e){let t=e.replaceAll("\\","/");return Mn.isAbsolute(e)||t===".."||t.startsWith("../")}function w_(e=ll){let t=ul(e);return[dl,...To.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...y_.map(n=>`!${t}/${n}`),Co].join(`
8
+ `)}async function lC(e,t={}){let n=Mn.join(e,".gitignore"),r=ll;if(t.pmRoot!==void 0){let l=ul(Mn.relative(Mn.resolve(e),Mn.resolve(t.pmRoot)));if($o(l))return{path:n,changed:!1};l.length>0&&(r=l)}let i="";try{i=await cl(()=>__(n,"utf8"))}catch(l){if(!(l instanceof Error&&"code"in l&&U(l)))throw l}let o=i.indexOf(dl),s=i.indexOf(Co),c=(o>=0&&s>=o?`${i.slice(0,o)}${i.slice(s+Co.length)}`:i).trimEnd(),d=`${c.length>0?`${c}
9
9
 
10
- `:""}${_g(r)}
11
- `;return d===i?{path:n,changed:!1}:(await sl(()=>hg(n,d,"utf8")),{path:n,changed:!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]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var yg="PM_SOURCE_CONTEXT_ACCESS",wg="PM_ALLOW_SOURCE_CONTEXT_WRITES";function ll(e){let t=e[yg],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[wg]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dea4137f-adbd-5dca-bfc7-b56c99c7aa79")}catch{}})();var Oo=kg(bg),Kr="# pm-cli:merge-drivers:start",fl="# pm-cli:merge-drivers:end",Qt="# pm-cli:merge-drivers:v2:start",$o="# pm-cli:merge-drivers:v2:end",xg="merge-fence";function ul(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function hl(){let e=Re(import.meta.url,["../../.."]);return`${ul(process.execPath)} ${ul(ie.join(e,"dist","cli.js"))}`}var gl=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function Sg(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=ll(e.environment),o=!!(n&&r),s=t===void 0&&o&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let a=M(e.cwd,t);return{pm_root:a,workspace_start:a,source_coordinates_available:o,source_context_selected:!1,source_policy:i}}return s?{pm_root:ie.resolve(r),workspace_start:ie.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:o?M(e.cwd,".agents/pm"):M(e.cwd),workspace_start:e.cwd,source_coordinates_available:o,source_context_selected:!1,source_policy:i}}async function Ze(e){try{let{stdout:t}=await Oo("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await To(t.trim())}catch{return null}}async function _l(e){let t=await Ze(e);if(t===null)throw new w("pm merge install requires a git repository (merge drivers are git configuration).",y.USAGE);return t}function Do(e,t){return ie.relative(e,t).replaceAll("\\","/")}function qe(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function ml(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function Eg(e,t){let n=ml(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=ml(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(ie.basename(n.value))||ie.basename(r.value)!=="cli.js"||ie.basename(ie.dirname(r.value))!=="dist"||!await D(n.value)||!await D(r.value))return!1;try{let i=ie.dirname(ie.dirname(r.value)),o=JSON.parse(await Yr(ie.join(i,"package.json"),"utf8")),s=typeof o.bin=="object"&&o.bin!==null&&"pm"in o.bin?o.bin.pm:void 0;return o.name==="@unbrained/pm-cli"&&(o.bin==="dist/cli.js"||s==="dist/cli.js")}catch{return!1}}function Po(e,t){let n=e.length>0?`${e}/`:"",r=[`${qe(`${n}**/*.toon`)} merge=pm-item-toon`,`${qe(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${qe(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${qe(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${qe(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${qe(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${qe(`${n}settings.json`)} merge=pm-json`),r.push(`${qe(`${n}**/*.json`)} merge=pm-json`),r.push(`${qe(`${n}extensions/**`)} -merge`),r.push(`${qe(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function pl(e,t,n){let r=e.indexOf(t),i=e.indexOf(n);return r>=0&&i>r?`${e.slice(0,r)}${e.slice(i+n.length)}`:e.replace(t,"").replace(n,"")}async function yl(e,t,n){let r=ie.join(e,".gitattributes"),i="";try{i=await Yr(r,"utf8")}catch(d){if(!(d instanceof Error&&"code"in d&&U(d)))throw d}let o=[Qt,...t,$o].join(`
12
- `),a=pl(pl(i,Qt,$o),Kr,fl).trimEnd(),c=`${a.length>0?`${a}
10
+ `:""}${w_(r)}
11
+ `;return d===i?{path:n,changed:!1}:(await cl(()=>g_(n,d,"utf8")),{path:n,changed:!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]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var v_="PM_SOURCE_CONTEXT_ACCESS",b_="PM_ALLOW_SOURCE_CONTEXT_WRITES";function ml(e){let t=e[v_],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[b_]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dea4137f-adbd-5dca-bfc7-b56c99c7aa79")}catch{}})();var Po=S_(x_),Kr="# pm-cli:merge-drivers:start",_l="# pm-cli:merge-drivers:end",en="# pm-cli:merge-drivers:v2:start",Do="# pm-cli:merge-drivers:v2:end",E_="merge-fence";function pl(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function gl(){let e=Re(import.meta.url,["../../.."]);return`${pl(process.execPath)} ${pl(ie.join(e,"dist","cli.js"))}`}var yl=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function R_(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=ml(e.environment),o=!!(n&&r),s=t===void 0&&o&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let a=M(e.cwd,t);return{pm_root:a,workspace_start:a,source_coordinates_available:o,source_context_selected:!1,source_policy:i}}return s?{pm_root:ie.resolve(r),workspace_start:ie.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:o?M(e.cwd,".agents/pm"):M(e.cwd),workspace_start:e.cwd,source_coordinates_available:o,source_context_selected:!1,source_policy:i}}async function Qe(e){try{let{stdout:t}=await Po("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await Oo(t.trim())}catch{return null}}async function wl(e){let t=await Qe(e);if(t===null)throw new w("pm merge install requires a git repository (merge drivers are git configuration).",y.USAGE);return t}function No(e,t){return ie.relative(e,t).replaceAll("\\","/")}function qe(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function fl(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function A_(e,t){let n=fl(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=fl(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(ie.basename(n.value))||ie.basename(r.value)!=="cli.js"||ie.basename(ie.dirname(r.value))!=="dist"||!await D(n.value)||!await D(r.value))return!1;try{let i=ie.dirname(ie.dirname(r.value)),o=JSON.parse(await Yr(ie.join(i,"package.json"),"utf8")),s=typeof o.bin=="object"&&o.bin!==null&&"pm"in o.bin?o.bin.pm:void 0;return o.name==="@unbrained/pm-cli"&&(o.bin==="dist/cli.js"||s==="dist/cli.js")}catch{return!1}}function Mo(e,t){let n=e.length>0?`${e}/`:"",r=[`${qe(`${n}**/*.toon`)} merge=pm-item-toon`,`${qe(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${qe(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${qe(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${qe(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${qe(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${qe(`${n}settings.json`)} merge=pm-json`),r.push(`${qe(`${n}**/*.json`)} merge=pm-json`),r.push(`${qe(`${n}extensions/**`)} -merge`),r.push(`${qe(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function hl(e,t,n){let r=e.indexOf(t),i=e.indexOf(n);return r>=0&&i>r?`${e.slice(0,r)}${e.slice(i+n.length)}`:e.replace(t,"").replace(n,"")}async function vl(e,t,n){let r=ie.join(e,".gitattributes"),i="";try{i=await Yr(r,"utf8")}catch(d){if(!(d instanceof Error&&"code"in d&&U(d)))throw d}let o=[en,...t,Do].join(`
12
+ `),a=hl(hl(i,en,Do),Kr,_l).trimEnd(),c=`${a.length>0?`${a}
13
13
 
14
14
  `:""}${o}
15
- `;return c===i?{path:r,changed:!1}:(n||await vg(r,c,"utf8"),{path:r,changed:!0})}function en(e){let t=W(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function Xr(e,t){let n=ie.resolve(e),r=null,i="",o=n;for(let v=0;v<8;v+=1){let k=ie.join(o,".gitattributes");try{let b=await Yr(k,"utf8");if(b.includes(Qt)||b.includes(Kr)){r=o,i=b;break}}catch{}let x=ie.dirname(o);if(x===o)break;o=x}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=ie.join(r,".gitattributes"),a=i.includes(Qt),c=a?Qt:Kr,d=a?$o:fl,l=i.indexOf(c),u=i.indexOf(d),m=u>l?i.slice(l+c.length,u).split(`
16
- `).map(v=>v.trim()).filter(v=>v.length>0):[],p=Po(Do(r,n),t),f=new Set(m),h=new Set(p),g=p.filter(v=>!f.has(v)),_=m.filter(v=>!h.has(v));return{status:g.length>0||_.length>0?"drift":"ok",path:s,missing_patterns:g,stale_patterns:_,schema_scope:"project"}}async function tn(e){let t=hl(),n=[],r=[];for(let i of gl){let o=`merge.${i.key}.driver`,s=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`,a=`${t}${s}`;try{let{stdout:c}=await Oo("git",["config","--local","--get",o],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),d=c.trim();d!==a&&!await Eg(d,s)&&r.push(o)}catch{n.push(o)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function wl(e){let t;try{t=await _l(ie.resolve(e))}catch{return{status:"no_git"}}let n=Do(t,ie.resolve(e)),r=await C(e),i=V(void 0,r.author_default),o=await fe(e,xg,r.locks.ttl_seconds,i,!1,De(r).force_required_for_stale_lock,r.locks.wait_ms);try{let s=ie.join(t,".gitattributes"),a;try{a=await Yr(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&U(u))return{status:"not_installed",path:s};throw u}if(!a.includes(Qt)&&!a.includes(Kr))return{status:"not_installed",path:s};let c=await C(e),d=en(c),l=await yl(t,Po(n,d),!1);return{status:l.changed?"refreshed":"unchanged",path:l.path}}finally{await o()}}async function EC(e,t){let n=Sg({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await X(r);let i=await _l(n.workspace_start);return Rg({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function Rg(e){let t=ie.resolve(e.pmRoot),n=ie.resolve(e.workspaceRoot),r=e.dryRun===!0,i,o;try{[i,o]=await Promise.all([To(t),To(n)])}catch(p){throw new w(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(p)}`,y.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let s=Do(o,i);if(Co(s))throw new w(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,y.USAGE);let a=await C(i),c=en(a),d=Po(s,c),l=[],u=hl();for(let p of gl)l.push({key:`merge.${p.key}.name`,value:p.name}),l.push({key:`merge.${p.key}.driver`,value:`${u} merge driver ${p.artifact} "%O" "%A" "%B"${p.itemPath===void 0?"":` --item-path ${p.itemPath}`}`});if(!r)try{for(let p of l)await Oo("git",["config","--local",p.key,p.value],{cwd:o,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new w(`Cannot install repository-local merge drivers in ${o}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,y.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await yl(o,d,r);return{ok:!0,dry_run:r,workspace_root:o,pm_root:i,gitattributes:{path:m.path,changed:m.changed,patterns:d,schema_scope:"project"},git_config:l,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();var Ag=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Ig(e){let t=Ag.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Cg(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function vl(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let s of e){let a=typeof s=="string"?s.trim():"";if(a.length===0)continue;let c=Ig(a);if(c===void 0)continue;let d=i.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(a),i.set(c,d)}let o=[];for(let[s,a]of i.entries()){if(a.count<n)continue;let c=Cg(s);o.push({name:c,prefix:s,count:a.count,examples:a.examples,shadows_builtin:Ua(c)!==void 0})}return o.sort((s,a)=>a.count-s.count||s.name.localeCompare(a.name)),o}import{createHash as Ol}from"node:crypto";import It from"node:fs/promises";import rn from"node:path";import{mkdir as Tg,readFile as $g}from"node:fs/promises";import Rl 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]="6ed4a26f-2ae2-556a-87db-56844108757f")}catch{}})();var No=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Og="sdk-workspace-transaction",Dg=/^[a-zA-Z0-9._-]+$/,Pg=30,Ng=3e3;function bl(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Dg.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function kl(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function xl(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function Al(e,t){return Rl.join(e,"transactions","sdk",`${t}.json`)}async function mt(e,t){t.updatedAt=T();let n=Al(e,t.transactionId);await Tg(Rl.dirname(n),{recursive:!0}),await de(n,`${JSON.stringify(t,null,2)}
17
- `)}function Mg(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function At(e){return Object.assign(Object.create(null),e)}function Lg(e,t){try{let n=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function Mo(e,t){return e===void 0?void 0:Lg(e,t)}function Lo(e,t,n,r){let i=Mo(n,r);i===void 0?delete e[t]:e[t]=i}function Sl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function El(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Fg(e,t){if(!El(e.startedStepIds,t)||!El(e.completedStepIds,t)||!Sl(e.results)||!Sl(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,o=new Set(i);return Object.keys(e.compensationData).some(s=>!r.has(s))||Object.keys(e.results).some(s=>!o.has(s))?!1:e.status==="committed"?t.every(s=>o.has(s)):e.status!=="compensated"||o.size===0&&r.size===0}function jg(e,t,n){let r;try{r=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let i=r,o=i.schemaVersion===1&&i.transactionId===t,s=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((l,u)=>l===n[u]),a=Fg(i,n),c=Mg(i),d=["applying","compensating","compensated","committed"].includes(String(i.status));if(!o||!s||!a||!c||!d)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...i,results:At(i.results),compensationData:At(i.compensationData)}}async function Ug(e,t,n,r,i){let o=i,s=o!==void 0;if(o?.status==="compensating"&&await Il(e,o),o===void 0||o.status==="compensated"){let a=T();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??a,updatedAt:a,stepIds:r,startedStepIds:[],completedStepIds:[],results:At(),compensationData:At()},await mt(e.pmRoot,o),await Qe(e,o,"prepared")}return{journal:o,recovered:s}}async function zg(e,t,n){try{await qg(t,e.steps),await mt(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let o of e.steps){if(r.has(o.id))continue;let s=await o.inspect(),a=Mo(s.result,`Step ${o.id} result`);if(s.state!=="applied"){let c=await o.prepareCompensation?.();Lo(t.compensationData,o.id,c,`Step ${o.id} compensation data`),i.add(o.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await mt(e.pmRoot,t);let d=await o.apply();a=Mo(d,`Step ${o.id} result`)}await Qe(e,t,"step_applied",o.id),r.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),Lo(t.results,o.id,a,`Step ${o.id} result`),await mt(e.pmRoot,t),await Qe(e,t,"step_recorded",o.id)}return await Qe(e,t,"committing"),t.status="committed",await mt(e.pmRoot,t),await Qe(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:At(t.results)}}catch(r){if(r instanceof No||t.status==="committed")throw r;try{await Il(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function Wg(e,t,n){try{return jg(await $g(Al(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&U(r))return;throw r}}async function Qe(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function qg(e,t){let n=new Set,r=At();for(let i of t){let o=await i.inspect();o.state==="applied"&&(n.add(i.id),Lo(r,i.id,o.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function Il(e,t){t.status="compensating",await mt(e.pmRoot,t),await Qe(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!r.has(i.id)&&!n.has(i.id))continue;let o;try{o=r.has(i.id)&&(await i.inspect()).state==="applied"}catch{o=r.has(i.id)}o&&(await Qe(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),r.delete(i.id),t.completedStepIds=e.steps.map(s=>s.id).filter(s=>n.has(s)),t.startedStepIds=e.steps.map(s=>s.id).filter(s=>r.has(s)),delete t.results[i.id],delete t.compensationData[i.id],await mt(e.pmRoot,t),await Qe(e,t,"step_compensated",i.id)}t.status="compensated",await mt(e.pmRoot,t),await Qe(e,t,"compensated")}async function Cl(e){let t=kl(e.pmRoot,"Transaction pmRoot"),n=bl(e.transactionId,"Transaction id"),r=kl(e.author,"Transaction author"),i=xl(e.lockTtlSeconds,Pg,"Transaction lock TTL"),o=xl(e.lockWaitMs,Ng,"Transaction lock wait"),s=[...e.steps];if(s.length===0)throw new TypeError("Workspace transaction requires at least one step");let a=s.map(l=>{let u=bl(l.id,"Transaction step id");if(u!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return u});if(new Set(a).size!==a.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:s,lockTtlSeconds:i,lockWaitMs:o},d=await fe(t,Og,i,r,!1,!1,o);try{let l=await Wg(t,n,a),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:At(l.results)};let m=await Ug(c,n,r,a,l);return await zg(c,m.journal,u||m.recovered)}finally{await d()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60738c1f-3b44-5f8a-82c9-99d2b2de1e51")}catch{}})();function et(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Dl(e){let t=et(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Pl(e,t){let n=jo(e),r=et(t,"migrationScope");return`auto-${Ol("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function jo(e){let t=e.kind==="rename-type"?{kind:e.kind,from:et(e.from,"source"),to:et(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:le(et(e.from,"source")),to:le(et(e.to,"target")),...e.type===void 0?{}:{type:et(e.type,"type")}}:{kind:e.kind,from:le(et(e.from,"source")),to:le(et(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Hg(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Bg(e,t,n){let r=be(t.schema),i=Hg(n);return je(e,r.files[i],Ae[i])}function Nl(e,t){return rn.join(e,"transactions","schema",`${t}-plan.json`)}function Zr(e){return e.length===0?null:JSON.parse(e)}async function nn(e){let t=await Y(e);return{exists:t!==null,raw:t??""}}async function Ml(e,t){t.exists?await de(e,t.raw):await It.rm(e,{force:!0})}function Gg(e,t,n){let r=Je(e),i=r.definitions.findIndex(s=>s.name.trim().toLowerCase()===t.from.toLowerCase()),o=r.definitions.findIndex(s=>s.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return lt(r);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[i],name:t.to})}else i>=0&&r.definitions.splice(i,1);return lt(r)}function Jg(e,t,n){let r=Nt(e),i=r.fields.findIndex(s=>s.key===t.from),o=r.fields.findIndex(s=>s.key===t.to);if(n==="stage"){if(o>=0)return Mt(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let s=r.fields[i];r.fields.push({...s,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&r.fields.splice(i,1);return Mt(r)}function Vg(e,t,n){let r=Lt(e),i=r.statuses.findIndex(s=>s.id===t.from),o=r.statuses.findIndex(s=>s.id===t.to);if(n==="stage"){if(o>=0)return Ft(r);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[i],id:t.to})}else i>=0&&r.statuses.splice(i,1);return Ft(r)}function Kg(e,t,n){return t.kind==="rename-type"?Gg(e,t,n):t.kind==="rename-field"?Jg(e,t,n):Vg(e,t,n)}function pt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Uo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function on(e){return Array.isArray(e)?e.map(t=>Uo(t)).filter(t=>t!==void 0):[]}function Yg(e,t){for(let n of on(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>pt(r,t)));for(let n of on(e.type_workflows))n.type=pt(n.type,t)}function Xg(e,t){for(let r of on(e.definitions))r.default_status=pt(r.default_status,t);let n=Uo(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=pt(i,t);for(let r of on(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(o=>pt(o,t)):i))}function Zg(e,t){for(let n of on(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>pt(i,t)));for(let r of["options","command_option_policies"])for(let i of on(n[r])){let o=r==="options"?"key":"option";i[o]=pt(i[o],t)}}}function Qg(e,t){let n=Uo(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=pt(n[r],t)}function Fo(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?Yg(r,t):t.kind==="rename-field"?Zg(r,t):Xg(r,t),Qg(r,t),`${JSON.stringify(r,null,2)}
18
- `}function Ll(e,t){if(t.kind==="rename-type"){let r=Je(e).definitions;return{source:r.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=Nt(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=Lt(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function e_(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function t_(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function Fl(e,t){let n=jo(t.request),r=t.migrationId===void 0?Pl(n,t.migrationScope??"plan"):Dl(t.migrationId),i=e.map(c=>t_(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),o=Ol("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),s=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),a=i.filter(c=>!s.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:o,affected_item_count:i.length,pending_item_count:a.length,skipped_completed_count:i.length-a.length,items:Object.freeze(a)})}async function n_(e){let t=W(e.settings,z()),n=[...new Set(Object.values(t.type_to_folder))],r=await Cr(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},o=r?await xc({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:i}):null;return o?{items:o.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Ke(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function r_(e,t){let n=await Y(Nl(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new w(`Stored schema migration plan "${t}" is invalid: ${Ca(r)}`,y.GENERIC_FAILURE)}}async function i_(e,t){let n=Nl(e,t.migration_id);await It.mkdir(rn.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await de(n,`${JSON.stringify(r,null,2)}
19
- `)}function o_(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function s_(e){let t=await Ht(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new w(`Schema migration item "${e.id}" no longer exists.`,y.NOT_FOUND);return(await ut(t,{schema:e.settings.schema})).document.metadata}function Tl(e,t,n){let r=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let o=e.metadata;if(Object.prototype.hasOwnProperty.call(o,i)&&!Object.prototype.hasOwnProperty.call(o,r))return[];if(!Object.prototype.hasOwnProperty.call(o,r)||Object.prototype.hasOwnProperty.call(o,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return o[i]=o[r],delete o[r],[r,i]}function $l(e){return{id:e.id,inspect:async()=>{let t=await nn(e.filePath),n=Ll(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await nn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await nn(e.filePath);return await de(e.filePath,Kg(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await Ml(e.filePath,{exists:t.exists,raw:t.raw})}}}function a_(e){return{id:e.stepId,inspect:async()=>{let t=await nn(e.filePath);return{state:Fo(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await nn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await nn(e.filePath);return await de(e.filePath,Fo(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await Ml(e.filePath,{exists:t.exists,raw:t.raw})}}}function c_(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await C(e.pmRoot),n=W(t,z()).type_to_folder,r=await s_({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=e_(r,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await C(e.pmRoot),n=W(t,z()).type_to_folder,r=await xt({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:Tl(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await C(e.pmRoot),n=W(t,z()).type_to_folder;await xt({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:Tl(r,e.request,"reverse")}}})}}}async function d_(e){let t=await r_(e.pmRoot,e.migrationId);if(t){if(!o_(t.request,e.request))throw new w(`Schema migration id "${e.migrationId}" already belongs to a different request.`,y.CONFLICT);return{plan:t,stored:!0}}let n=await n_({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Fl(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function l_(e){let t=Ll(await Y(e.schemaPath)??"",e.request);if(!t.source)throw new w(`Schema migration source "${e.request.from}" is not a custom definition.`,y.NOT_FOUND);if(t.target)throw new w(`Schema migration target "${e.request.to}" already exists.`,y.CONFLICT);await i_(e.pmRoot,e.plan)}async function u_(e){let t=be(e.settings.schema),n=[...new Set([["types",Ae.types],["fields",Ae.fields],["workflows",Ae.workflows]].map(([i,o])=>je(e.pmRoot,t.files[i],o)).filter(i=>i!==e.schemaPath))];try{let i=rn.join(e.pmRoot,"templates"),o=await It.readdir(i,{withFileTypes:!0});n.push(...o.filter(s=>s.isFile()&&s.name.toLowerCase().endsWith(".json")).map(s=>rn.join(i,s.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!U(i))throw i}n.sort((i,o)=>i.localeCompare(o));let r=[];for(let i of n){let o=await Y(i);o!==null&&Fo(o,e.request)!==o&&r.push({filePath:i,beforeRaw:o})}return{paths:n,snapshots:r}}async function m_(e){for(let t of e.snapshots){let n=await It.readFile(t.filePath,"utf8"),r=rn.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await Qi({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Zr(t.beforeRaw),after:Zr(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function p_(e,t,n){let r=jo(e),i=M(process.cwd(),n.path);await X(i);let o=t.migrationId===void 0?Pl(r,await It.realpath(i)):Dl(t.migrationId),s=await C(i),a=V(t.author,s.author_default),c=await d_({pmRoot:i,settings:s,migrationId:o,request:r}),d=c.plan;if(t.dryRun===!0)return{...d,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Bg(i,s,r),u=await It.readFile(l,"utf8");c.stored||await l_({pmRoot:i,schemaPath:l,request:r,plan:d});let m=await u_({pmRoot:i,schemaPath:l,settings:s,request:r}),p=[$l({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...m.paths.map((_,v)=>a_({filePath:_,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(_=>c_({pmRoot:i,id:_.id,request:r,author:a,force:t.force===!0})),$l({id:"retire-source",filePath:l,request:r,phase:"retire"})],f=await Cl({pmRoot:i,transactionId:`schema-${o}`,author:a,steps:p,lockTtlSeconds:Math.max(s.locks.ttl_seconds,300),lockWaitMs:s.locks.wait_ms}),h=await It.readFile(l,"utf8"),{historyPath:g}=await Qi({pmRoot:i,author:a,documentPath:rn.relative(i,l).replaceAll("\\","/"),before:Zr(u),after:Zr(h),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms});return await m_({pmRoot:i,author:a,settings:s,request:r,plan:d,snapshots:m.snapshots}),{...d,action:r.kind,applied:!0,recovered:f.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:g}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="264088a5-09d1-52ed-8b12-af00392e1a5f")}catch{}})();var CT=["add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Qr="schema-types",jl="schema-statuses",Ul="schema-fields";function ft(e){return Ar({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function TT(e,t,n){let r=M(process.cwd(),n.path);await tt(r);let i;try{i=Gi({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(p){throw new w(p instanceof Error?p.message:String(p),y.USAGE)}let o=await C(r),s=be(o.schema),a=je(r,s.files.types,Ae.types),c=[],d=V(t.author,o.author_default),l=De(o),u=await fe(r,Qr,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms),m;try{let p=await Y(a),f;try{f=Je(p)}catch(h){throw new w(h instanceof Error?h.message:String(h),y.GENERIC_FAILURE)}try{za(i,f);let h=new Map,g=W(o,z());for(let[_,v]of Object.entries(g.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!h.has(k)&&h.set(k,_)}Wa(i,f,h)}catch(h){throw new w(h instanceof Error?h.message:String(h),y.USAGE)}m=fr(f,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await ft({pmRoot:r,filePath:a,raw:lt(m.file),op:"schema:add-type",author:d,settings:o}),await Mn(r,[m.definition],c,"schema:add-type-folder"),c.push(...await ne({path:a,scope:"project",op:"schema:add-type"}))}finally{await u()}return await zl(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:a,definitions:m.file.definitions.length},warnings:ht(c),generated_at:T()}}async function tt(e){await X(e)}async function zl(e,t){try{let n=await wl(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function ht(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function g_(e,t,n,r){let i=W(t,z()),o=r.trim().toLowerCase();return(await Ke(e,t.item_format,i.type_to_folder,[],n)).filter(a=>typeof a.type=="string"&&a.type.toLowerCase()===o).length}async function __(e,t,n,r){let i=W(t,z()),o=Ie(n),s=le(r);return(await Ke(e,t.item_format,i.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(o.alias_to_id.get(le(d))??le(d))===s}).length}async function y_(e,t,n,r,i){if(i.length===0||Vi.has(i))return;let o=await __(t,n,r,i);o>0&&e.push(`items_using_status:${o}`);let s=w_(r.workflow,i);s.length>0&&e.push(`status_referenced_by_workflow:${s.join(",")}`)}function w_(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,r])=>r!==void 0&&le(r)===t).map(([r])=>r)}async function $T(e,t,n){let r=M(process.cwd(),n.path);await tt(r);let i=await C(r),o=be(i.schema),s=je(r,o.files.types,Ae.types),a=[],c=V(t.author,i.author_default),d=De(i),l=await fe(r,Qr,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(s),p;try{p=Je(m)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.GENERIC_FAILURE)}try{u=qa(p,e)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.USAGE)}if(u.removed){let f=(u.definition?.name??e??"").trim();if(f.length>0){let h=await g_(r,i,o,f);h>0&&a.push(`items_using_type:${h}`)}await ft({pmRoot:r,filePath:s,raw:lt(u.file),op:"schema:remove-type",author:c,settings:i}),a.push(...await ne({path:s,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await zl(r,a),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:s,definitions:u.file.definitions.length},warnings:ht(a),generated_at:T()}}function zo(e,t){return je(e,t.files.statuses,Ae.statuses)}function ei(e,t){return je(e,t.files.fields,Ae.fields)}function Wl(e,t){return je(e,t.files.types,Ae.types)}async function Mn(e,t,n,r){for(let i of t){let o=Ra(i.folder??Ea(i.name)),s=f_.join(e,o);await D(s)||(await h_(s,{recursive:!0}),n.push(...await ne({path:s,scope:"project",op:r})))}}function Wo(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function v_(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function b_(e){let t=new Map;for(let n of e){let r=le(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let o=le(i);o.length>0&&!t.has(o)&&t.set(o,r)}}}return t}async function OT(e,t,n){let r=M(process.cwd(),n.path);await tt(r);let i;try{i=Xa({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(g){throw new w(g instanceof Error?g.message:String(g),y.USAGE)}let o=await C(r),s=be(o.schema),a=zo(r,s),c=Ie(s);try{Ki(i,c.alias_to_id)}catch(g){throw new w(g instanceof Error?g.message:String(g),y.USAGE)}let d=v_(c.by_id.get(i.id));if((i.roles??d?.roles??[]).length===0)throw new w(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,y.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Pt(i.id)}" --role active`,`pm schema add-status "${Pt(i.id)}" --role blocked`]});let u=[],m=V(t.author,o.author_default),p=De(o),f=await fe(r,jl,o.locks.ttl_seconds,m,!!t.force,p.force_required_for_stale_lock,o.locks.wait_ms),h;try{let g=await Y(a),_;try{_=Lt(g)}catch(k){throw new w(k instanceof Error?k.message:String(k),y.GENERIC_FAILURE)}let v=b_(_.statuses);try{Ki(i,v)}catch(k){throw new w(k instanceof Error?k.message:String(k),y.USAGE)}h=Za(_,i,d),await ft({pmRoot:r,filePath:a,raw:Ft(h.file),op:"schema:add-status",author:m,settings:o}),u.push(...await ne({path:a,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:h.replaced,status:h.definition,file:{path:a,statuses:h.file.statuses.length},warnings:ht(u),generated_at:T()}}async function DT(e,t,n){let r=M(process.cwd(),n.path);await tt(r);let i=await C(r),o=be(i.schema),s=zo(r,o),a=[],c=V(t.author,i.author_default),d=De(i),l=await fe(r,jl,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(s),p;try{p=Lt(m)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.GENERIC_FAILURE)}try{u=Qa(p,e)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.USAGE)}if(u.removed){let f=le(u.definition?.id??e);await y_(a,r,i,o,f),await ft({pmRoot:r,filePath:s,raw:Ft(u.file),op:"schema:remove-status",author:c,settings:i}),a.push(...await ne({path:s,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:s,statuses:u.file.statuses.length},warnings:ht(a),generated_at:T()}}function ql(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function k_(e,t,n){return{...ql(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function Hl(e){return{id:e.id,source:Vi.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Bl(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function x_(){let e=new Map,t=z();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let i of r){if(typeof i!="object"||i===null||Array.isArray(i))continue;let o=i.name;typeof o=="string"&&o.trim().length>0&&e.set(o.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function S_(e){let t=Ie(e),n=[],r=[];for(let i of t.definitions){let o=Hl(i);o.source==="builtin"?n.push(o):r.push(o)}return{builtin:n,custom:r}}async function Ln(e){let t=M(process.cwd(),e.path);await tt(t);let n=await C(t),r=be(n.schema),i=je(t,r.files.types,Ae.types),o=zo(t,r),s=W(n,z()),a=x_(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!a.has(d)));return{pmRoot:t,typesPath:i,statusesPath:o,byType:s.by_type,customNames:c,extensionProvenance:a,schema:r}}async function PT(e){let t=await Ln(e),n=[],r=[],i=[];for(let a of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Bl(a.name,t.customNames,new Set(t.extensionProvenance.keys())),d=ql(a);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let o=S_(t.schema),s=hr(t.schema).definitions.map(Wo);return{action:"list",builtin:n,custom:r,extension:i,counts:{builtin:n.length,custom:r.length,extension:i.length,total:n.length+r.length+i.length},statuses:{builtin:o.builtin,custom:o.custom,counts:{builtin:o.builtin.length,custom:o.custom.length,total:o.builtin.length+o.custom.length}},fields:{custom:s,counts:{total:s.length}},file:{path:t.typesPath},generated_at:T()}}async function NT(e,t){let n=(e??"").trim();if(n.length===0)throw new w("Type name must not be empty.",y.USAGE);let r=await Ln(t),i=Object.values(r.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(s=>s.toLowerCase()===n.toLowerCase()));if(!i)throw new w(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Pt(n)}" to register it.`,y.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:k_(i,Bl(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:T()}}async function MT(e,t){let n=le(e);if(n.length===0)throw new w("Status id must not be empty.",y.USAGE);let r=await Ln(t),i=Ie(r.schema),o=i.alias_to_id.get(n)??n,s=i.by_id.get(o);if(!s)throw new w(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Pt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Hl(s),file:{path:r.statusesPath},generated_at:T()}}async function LT(e,t,n){let r=M(process.cwd(),n.path);await tt(r);let i;try{i=Ga({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(f){throw new w(f instanceof Error?f.message:String(f),y.USAGE)}let o=await C(r),s=be(o.schema),a=ei(r,s),c=[],d=gr(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=V(t.author,o.author_default),u=De(o),m=await fe(r,Ul,o.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,o.locks.wait_ms),p;try{let f=await Y(a),h;try{h=Nt(f)}catch(g){throw new w(g instanceof Error?g.message:String(g),y.GENERIC_FAILURE)}p=Ja(h,i),await ft({pmRoot:r,filePath:a,raw:Mt(p.file),op:"schema:add-field",author:l,settings:o}),c.push(...await ne({path:a,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:p.replaced,field:p.definition,file:{path:a,fields:p.file.fields.length},warnings:ht(c),generated_at:T()}}async function E_(e,t,n,r){let i=W(t,z());return(await Ke(e,t.item_format,i.type_to_folder,[],n)).filter(s=>{let a=s[r];return a==null?!1:Array.isArray(a)?a.length>0:typeof a=="string"?a.trim().length>0:!0}).length}async function FT(e,t,n){let r=M(process.cwd(),n.path);await tt(r);let i=await C(r),o=be(i.schema),s=ei(r,o),a=[],c=V(t.author,i.author_default),d=De(i),l=await fe(r,Ul,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(s),p;try{p=Nt(m)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.GENERIC_FAILURE)}try{u=Va(p,e)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.USAGE)}if(u.removed){let f=le(u.definition?.key??e),h=le(u.definition?.metadata_key??u.definition?.front_matter_key??f);if(h.length>0){let g=await E_(r,i,o,h);g>0&&a.push(`items_using_field:${g}`)}await ft({pmRoot:r,filePath:s,raw:Mt(u.file),op:"schema:remove-field",author:c,settings:i}),a.push(...await ne({path:s,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:s,fields:u.file.fields.length},warnings:ht(a),generated_at:T()}}async function jT(e){let t=await Ln(e),n=hr(t.schema).definitions.map(Wo);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:ei(t.pmRoot,t.schema)},generated_at:T()}}async function UT(e,t){let n=le(e);if(n.length===0)throw new w("Field key must not be empty.",y.USAGE);let r=await Ln(t),i=hr(r.schema).by_key.get(n);if(!i)throw new w(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Pt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Wo(i),file:{path:ei(r.pmRoot,r.schema)},generated_at:T()}}async function zT(e,t,n){let r=M(process.cwd(),n.path);await tt(r);let i;try{let h=Ba(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${Ha.join(", ")}.`);i=h}catch(h){throw new w(h instanceof Error?h.message:String(h),y.USAGE)}let o=await C(r),s=be(o.schema),a=Wl(r,s),c=[],d=V(t.author,o.author_default),l=De(o),u=[],m=[],p,f=await fe(r,Qr,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms);try{let h=await Y(a),g;try{g=Je(h)}catch(v){throw new w(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let _=g;for(let v of Ji(i)){let k=fr(_,v);_=k.file,(k.replaced?m:u).push(k.definition.name)}p=_.definitions.length,await ft({pmRoot:r,filePath:a,raw:lt(_),op:"schema:apply-preset",author:d,settings:o}),await Mn(r,Ji(i),c,"schema:apply-preset-folder"),c.push(...await ne({path:a,scope:"project",op:"schema:apply-preset"}))}finally{await f()}return{action:"apply-preset",preset:i,registered:u,replaced:m,file:{path:a,definitions:p},warnings:ht(c),generated_at:T()}}function R_(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new w("--min-count must be a positive integer (>= 1).",y.USAGE);return e}async function WT(e,t){let n=M(process.cwd(),t.path);await tt(n);let r=await C(n),i=be(r.schema),o=Wl(n,i),s=R_(e.minCount),a=W(r,z()),d=(await Ke(n,r.item_format,a.type_to_folder,[],i)).map(k=>typeof k.title=="string"?k.title:""),l=vl(d,{minCount:s}),u=[],m=[],p=[],f=[],h;if(!e.apply){let k;try{k=Je(await Y(o))}catch(x){throw new w(x instanceof Error?x.message:String(x),y.GENERIC_FAILURE)}return h=k.definitions.length,{action:"infer-types",applied:!1,min_count:s,candidates:l,registered:m,replaced:p,skipped:f,file:{path:o,definitions:h},warnings:u,generated_at:T()}}let g=V(e.author,r.author_default),_=De(r),v=await fe(n,Qr,r.locks.ttl_seconds,g,!!e.force,_.force_required_for_stale_lock,r.locks.wait_ms);try{let k=await Y(o),x;try{x=Je(k)}catch(I){throw new w(I instanceof Error?I.message:String(I),y.GENERIC_FAILURE)}let b=x;for(let I of l){if(I.shadows_builtin){f.push({name:I.name,reason:"shadows_builtin"});continue}let S;try{S=Gi({name:I.name})}catch{f.push({name:I.name,reason:"invalid_type_token"});continue}let E=fr(b,S);b=E.file,(E.replaced?p:m).push(E.definition.name)}h=b.definitions.length,await ft({pmRoot:n,filePath:o,raw:lt(b),op:"schema:infer-types",author:g,settings:r}),await Mn(n,b.definitions.filter(I=>m.includes(I.name)||p.includes(I.name)),u,"schema:infer-types-folder"),u.push(...await ne({path:o,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:s,candidates:l,registered:m,replaced:p,skipped:f,file:{path:o,definitions:h},warnings:ht(u),generated_at:T()}}import Gl from"node:fs/promises";import qo 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]="af718efb-d1cf-5adc-9518-c858627e1b54")}catch{}})();function Se(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function R(e){return e.trim().toLowerCase()}function ti(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let i=t.slice(n,r);if(i.length===0)throw new w("Extension manifest name must resolve to a non-empty directory name.",y.USAGE);if(i==="."||i==="..")throw new w('Extension manifest name must not resolve to "." or "..".',y.USAGE);return i}function Ho(e){return Na(e)}async function A_(e){try{let t=JSON.parse(await Gl.readFile(qo.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(r=>typeof t.scripts?.[r]=="string")}}catch{return{has_build_script:!1}}}async function I_(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new w(`Extension entry file is missing at "${t}".`,y.USAGE);let r=await A_(n.source_root),i=r.package_name?`pm install npm:${r.package_name}`:void 0,o=n.source_input??n.source_root;return new w(`Extension entry "${e.entry}" is absent from GitHub source "${o}". pm install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,y.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${o}`,normalized_args:["install",o],...i?{next_best_command:i}:{}}})}async function sn(e,t={}){let n=qo.join(e,"manifest.json");if(!await D(n))throw new w(`Extension manifest is missing at "${n}".`,y.USAGE);let r;try{r=JSON.parse(await Gl.readFile(n,"utf8"))}catch(s){throw new w(`Failed to parse extension manifest at "${n}": ${C_(s)}`,y.USAGE)}let i=Ho(r);if(!i)throw new w(`Extension manifest at "${n}" is invalid.`,y.USAGE);let o=qo.resolve(e,i.entry);if(!ve(e,o))throw new w(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,y.USAGE);if(!await D(o))throw await I_(i,o,t);if(!await Ma(e,o))throw new w(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,y.USAGE);return{directory:e,manifest_path:n,entry_path:o,manifest:i}}function C_(e){return e instanceof Error?e.message:String(e)}import Bo from"node:fs/promises";import T_ 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]="159d7bbd-1d2a-503d-b3ce-f32dcc6f6547")}catch{}})();var $_=".managed-extensions.json",ni=1;function Fn(e){return T_.join(e,$_)}function O_(){return{version:ni,updated_at:T(),entries:[]}}function jn(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function Jl(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function Ee(e){return typeof e=="string"?e:void 0}function D_(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function P_(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:Ee(t.name),package:Ee(t.package),version:Ee(t.version),repository:Ee(t.repository),owner:Ee(t.owner),repo:Ee(t.repo),ref:Ee(t.ref),subpath:Ee(t.subpath),commit:Ee(t.commit)}}function N_(e){if(typeof e!="object"||e===null)return null;let t=e;if(!D_(t))return null;let n=P_(t.source);if(!n)return null;let r=Oa(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Se(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Ee(t.last_update_check_at),last_update_remote_commit:Ee(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Ee(t.update_error)}}function M_(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==ni||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=N_(r);i&&n.push(i)}return{version:ni,updated_at:Ee(t.updated_at)??T(),entries:jn(n)}}async function ge(e){let t=Fn(e),n=O_();try{let r=await Bo.readFile(t,"utf8"),i=JSON.parse(r),o=M_(i);if(!o)throw new w(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE);return{path:t,state:o,warnings:[]}}catch(r){if(r instanceof w)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&U(r))return{path:t,state:n,warnings:[]};throw new w(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE)}}async function Ct(e,t){let n=Fn(e),r={version:ni,updated_at:T(),entries:jn(t.entries)};await Bo.mkdir(e,{recursive:!0}),await Bo.writeFile(n,`${JSON.stringify(r,null,2)}
20
- `,"utf8")}function Un(e,t){let n=e.entries.filter(r=>R(r.name)!==R(t.name)&&R(r.directory)!==R(t.directory));return n.push(t),{...e,updated_at:T(),entries:jn(n)}}async function Vl(e,t,n,r){let i=t.entries.find(s=>R(s.name)===R(n));if(!i)return t;let o=Un(t,{...i,contributions:r});return await Ct(e,o),o}import{execFile as J_}from"node:child_process";import J from"node:fs/promises";import Xo from"node:os";import N from"node:path";import{fileURLToPath as V_}from"node:url";import{promisify as K_}from"node:util";import Y_ from"npm-package-arg";import{extract as X_,list as Z_}from"tar";import L_ from"node:fs/promises";import Pe 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]="259656b0-09b7-52c5-8f54-52ac29eec607")}catch{}})();var F_="PM_CLI_PACKAGE_ROOT",Kl={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},j_=new Set(["*","all"]);function Go(){let e=[],t=process.env[F_];return typeof t=="string"&&t.trim().length>0&&e.push(Pe.resolve(t.trim())),e.push(Re(import.meta.url,["../../.."])),[...new Set(e)]}async function zn(e){let t=e.trim().toLowerCase(),n=await Xl(t);if(n)return n;let r=Kl[t];if(!r)return null;for(let i of Go()){let o=Pe.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await D(Pe.join(o,"manifest.json")))return o}return null}function Yl(e){return j_.has(e.trim().toLowerCase())}function U_(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function z_(e,t){let n=await L_.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=Pe.join(e,r.name);if(!await D(Pe.join(i,"package.json")))continue;let o=await mr(i),s=o.aliases&&o.aliases.length>0?o.aliases:[U_(r.name)];for(let a of s){let c=a.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:i,package_name:o.package_name??null})}}}async function Jo(){let e=new Map;for(let t of Go()){let n=Pe.join(t,"packages");await D(n)&&await z_(n,e)}for(let[t,n]of Object.entries(Kl))if(!e.has(t))for(let r of Go()){let i=Pe.join(r,"packages",n.package_directory);if(await D(Pe.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function ri(){return(await Jo()).map(e=>e.alias)}async function Xl(e){let t=e.trim().toLowerCase();return(await Jo()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function Zl(e){let t=await Xl(e);return t?(await mr(t)).package_name??null:null}async function Ql(e){let t=await zn(e);if(!t)return null;try{let n=await pr(t);return n.length!==1?null:(await sn(n[0])).manifest.name}catch{return null}}function W_(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function q_(e,t,n,r,i,o){let s=r==="global"?"--global":"--project",a=Object.fromEntries(Bi.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||o.has(Pe.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${s}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:a,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:W_(e),media:e.catalog?.media}}}async function eu(e,t,n={}){let r=Dt(M(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,o=await ge(i),s=new Set(o.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>Pe.resolve(m.source.location))),a=new Set(o.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),c=[],d=new Map;for(let m of await Jo()){let p=Pe.resolve(m.package_root),f=d.get(p)??[];f.push(m),d.set(p,f)}for(let m of d.values()){let p=m[0],f=m.map(g=>g.alias).sort((g,_)=>g.localeCompare(_)),h=await mr(p.package_root);c.push(q_(h,p,f,e,a,s))}let l=B_(n.fields),u=l?c.map(m=>G_(m,l)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Bi.filter(m=>m!=="extensions"),packages:u}}var H_=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function B_(e){if(e===void 0)return;let t=Yc(e);if(t.length===0)throw new w("Package catalog --fields requires a comma-separated list of field names",y.USAGE);let n=t.filter(r=>!H_.has(r));if(n.length>0)throw new w(`Unknown package catalog --fields value(s): ${n.join(", ")}`,y.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function G_(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="05f56edb-c08d-570c-b8b5-641fc694331e")}catch{}})();var nu=K_(J_),oi="@unbrained/pm-cli",Q_={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},Vo;async function ru(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=N.resolve(t);for(;;){let i=N.join(r,"node_modules",...n.split("/")),o=N.join(i,"package.json");if(await D(o))try{let a=JSON.parse(await J.readFile(o,"utf8"));if(a.name===n)return{package:n,...typeof a.version=="string"?{version:a.version}:{},directory:i}}catch{return null}let s=N.dirname(r);if(s===r)return null;r=s}}function Ko(e,t,n){let r=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(r.length<2)return null;let i=r[0],o=r[1].replace(/\.git$/i,"");if(i.length===0||o.length===0)return null;let s=r.slice(2),a,c;return s[0]==="tree"&&s.length>=2?(a=s[1],c=s.slice(2).join("/")):s.length>0&&(c=s.join("/")),typeof n=="string"&&n.trim().length>0&&(a=n.trim()),{kind:"github",input:t,owner:i,repo:o,repository:`https://github.com/${i}/${o}.git`,ref:a,subpath:c&&c.length>0?c:void 0}}function ey(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new w('npm package source must include a package spec after "npm:".',y.USAGE);if(t)throw new w('Options "--gh/--github" cannot be combined with npm: package sources.',y.USAGE);if(n)throw new w('Option "--ref" cannot be combined with npm: package sources.',y.USAGE);return{kind:"npm",input:e,spec:r}}function si(e,t={}){let n=e.trim();if(n.length===0)throw new w("Extension source is required for --install.",y.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return ey(n,t.forceGithub===!0,r);let i=(()=>{try{let s=new URL(n);if(s.hostname!=="github.com")return null;let a=s.pathname.replace(/^\/+/,"");return Ko(a,n,r)}catch{return null}})();if(i)return i;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let s=Ko(o,n,r);if(!s)throw new w(`Invalid GitHub source "${n}".`,y.USAGE);return s}if(t.forceGithub){let s=Ko(n,n,r);if(!s)throw new w(`Invalid GitHub shorthand "${n}".`,y.USAGE);return s}if(/^https?:\/\//i.test(n))throw new w(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,y.USAGE);return{kind:"local",input:n,absolute_path:N.resolve(process.cwd(),n)}}async function ii(e,t=nu,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new w(`Git command failed: git ${e.join(" ")}
21
- ${o}`,y.GENERIC_FAILURE)}}function ty(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function ny(e=process.platform){return e==="win32"}async function iu(e,t,n=nu,r=process.platform,i=process.env){let o=ty(r),s=Object.fromEntries(Object.entries(i).filter(([a])=>a.toLowerCase()!=="npm_config_allow_scripts"));s.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(o,e,{cwd:t,encoding:"utf8",env:s,shell:ny(r)})).stdout??"").trim()}catch(a){let c=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr):"",d=c.trim().length>0?c.trim():a instanceof Error?a.message:String(a);throw new w(`npm command failed: ${o} ${e.join(" ")}
22
- ${d}`,y.GENERIC_FAILURE)}}function ou(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function su(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function ry(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("npm err! code e404")||n.includes("404 not found")||n.includes("is not in this registry")}function iy(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return ry(e)||n.includes("not found")}function oy(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function sy(e){let t=ou(e),n=oy(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,o=i?`pm install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:o?[o,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:o?[`Try ${o} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&o?{fallback_candidates:[{source:i,command:o,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:o}:{}}}}}function ay(e,t){if(!iy(t))return null;let n=sy(e);return new w(n.message,y.NOT_FOUND,n.context)}async function au(e){if(N.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=N.resolve(process.cwd(),e);return await D(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=V_(t);return await D(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=N.resolve(process.cwd(),e);if(await D(t))return t}return null}async function cy(e){let t=await au(e);if(t)return t;let n=dy(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function dy(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!su(e))return e;let i=e.slice(0,r),o=e.slice(r+n.length);if(o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${i}@${N.resolve(t,o)}`;let s;try{s=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let a=/^\/[A-Za-z]:/.test(s)?s.slice(1):s;return`${i}@${a}`}function tu(e,t){let n=N.resolve(e,t),r=N.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${N.sep}`)||N.isAbsolute(r))throw new w("npm pack reported a package archive outside its isolated destination.",y.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function ly(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function uy(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]).flatMap(({key:n,value:r})=>{let i=ly(r,n);return i?[i]:[]})}function my(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(s=>{let a=s.name?.trim().toLowerCase();return a!==void 0?a===n:s.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let i=e[0],o=i.name??i.key;return n&&o!==void 0&&o.trim().toLowerCase()!==n?void 0:i}function py(e,t,n){let r;try{r=JSON.parse(e)}catch{let s=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0).at(-1);if(!s)throw new w("npm pack did not report a tarball filename.",y.GENERIC_FAILURE);return{tarball:tu(t,s)}}let i=uy(r),o=my(i,n);if(!o)throw new w("npm pack --json returned an unsupported or ambiguous package receipt.",y.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:tu(t,o.filename),package:o.name??o.key,version:o.version}}async function fy(e){return hy(e,iu)}async function hy(e,t){let n=await au(e.spec);if(n){if((await J.stat(n)).isFile()&&cu(n))return Yo(n);let s=N.join(n,"package.json"),a=await D(s)?JSON.parse(await J.readFile(s,"utf8")):{};return{directory:await ai(n,e.input),package:typeof a.name=="string"?a.name:void 0,version:typeof a.version=="string"?a.version:void 0,cleanup:async()=>{}}}let r=await J.mkdtemp(N.join(Xo.tmpdir(),"pm-npm-package-source-")),i=N.join(r,"pack");await J.mkdir(i,{recursive:!0});try{let o=await cy(e.spec),s=await t(["pack",o,"--json","--pack-destination",i]),a=py(s,i,su(e.spec)?void 0:ou(e.spec));if(!await D(a.tarball))throw new w("npm pack did not create its reported package archive.",y.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await Yo(a.tarball);return{directory:c.directory,package:a.package??c.package,version:a.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await J.rm(r,{recursive:!0,force:!0})}}}}catch(o){await J.rm(r,{recursive:!0,force:!0});let s=ay(e.spec,o);throw s||o}}function cu(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function nt(e){throw new w(e,y.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function gy(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&nt(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,i=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||i.some(o=>o===".."))&&nt(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&nt(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&nt(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&nt(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&nt(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&nt(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function Yo(e,t=Q_){(await J.stat(e)).size>t.maxArchiveBytes&&nt(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await J.mkdtemp(N.join(Xo.tmpdir(),"pm-local-package-archive-")),i=N.join(r,"extract");await J.mkdir(i,{recursive:!0});let o={entries:0,expandedBytes:0,packageJsonEntries:0},s;try{if(await Z_({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(s===void 0)try{gy(l,t,o)}catch(u){s=u}}}),s!==void 0)throw s;o.packageJsonEntries!==1&&nt(`Local package archive must contain exactly one package/package.json entry; found ${o.packageJsonEntries}.`),await X_({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let a=N.join(i,"package"),c=N.join(a,"package.json"),d=JSON.parse(await J.readFile(c,"utf8"));return await _y(a),{directory:await ai(a,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await J.rm(r,{recursive:!0,force:!0})}}}catch(a){throw await J.rm(r,{recursive:!0,force:!0}),a}}async function _y(e,t=iu){let n=N.join(e,"package.json");if(!await D(n))return;let r;try{r=JSON.parse(await J.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,o=xy(i),s=yy(i);if(o.length===0&&!s)return;let a={...r};delete a.devDependencies;let c={...a};wy(c),await J.writeFile(n,`${JSON.stringify(c,null,2)}
23
- `,"utf8");try{await Promise.all([J.rm(N.join(e,"package-lock.json"),{force:!0}),J.rm(N.join(e,"npm-shrinkwrap.json"),{force:!0})]),o.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),s&&await vy(e)}finally{await J.writeFile(n,`${JSON.stringify(a,null,2)}
24
- `,"utf8")}}function yy(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&oi in t)return!0;return!1}function wy(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[oi],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function vy(e){let t=Re(import.meta.url,["../../.."]),[n,r]=oi.split("/"),i=N.join(e,"node_modules",n),o=N.join(i,r);await J.mkdir(i,{recursive:!0}),await J.rm(o,{recursive:!0,force:!0}),await J.symlink(t,o,by(process.platform))}function by(e){return e==="win32"?"junction":"dir"}function ky(e,t){if(e.startsWith("-"))throw new w(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,y.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(r=>{let i=r.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(r)}))throw new w(`Extension runtime dependency "${e}" has an unsafe version specifier.`,y.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Y_.resolve(e,t)}catch{throw new w(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,y.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function xy(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===oi||typeof i!="string"||i.trim().length===0||t.has(r))continue;let o=i.trim();t.set(r,ky(r,o))}return[...t.values()]}async function ai(e,t){let n=await pr(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>N.relative(e,i).replaceAll(N.sep,"/")).sort((i,o)=>i.localeCompare(o));throw new w(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,y.USAGE)}throw new w(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,y.USAGE)}async function Sy(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(N.posix.join(".agents/pm/extensions",t.subpath)),n.push(N.posix.join(".custom/pm-extensions",t.subpath)),n.push(N.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let o=N.resolve(e,i);if(ve(e,o)&&await D(N.join(o,"manifest.json")))return{directory:o,resolved_subpath:i}}if(await D(N.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await ai(e,t.input);return{directory:r,resolved_subpath:N.relative(e,r).replaceAll(N.sep,"/")}}function Ey(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function Ry(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Ey(n))return new w(t,y.NOT_FOUND);let r=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,s=typeof o=="string"&&o.trim().length>0?N.resolve(o.trim()):"";Vo?.key!==s&&(Vo={key:s,aliases:await ri()}),r=Vo.aliases}catch{}let i=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${r.join(", ")}`];return new w(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,y.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function du(e){if(e.kind==="local"){let r;try{r=await J.stat(e.absolute_path)}catch{throw await Ry(e)}if(r.isFile()&&cu(e.absolute_path)){let o=await Yo(e.absolute_path);return{source:e,directory:o.directory,source_root:N.dirname(o.directory),resolved_subpath:N.relative(N.dirname(o.directory),o.directory).replaceAll(N.sep,"/"),npm_package:o.package,npm_version:o.version,cleanup:o.cleanup}}if(!r.isDirectory())throw new w(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,y.USAGE);let i=await ai(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await fy(e);return{source:e,directory:r.directory,source_root:N.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:N.relative(N.dirname(r.directory),r.directory).replaceAll(N.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await J.mkdtemp(N.join(Xo.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await ii(n);let r=await ii(["-C",t,"rev-parse","HEAD"]),i=await Sy(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await J.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await J.rm(t,{recursive:!0,force:!0}),r}}async function lu(e,t){if(!await D(e)||!await D(t))return!1;let[n,r]=await Promise.all([J.realpath(e),J.realpath(t)]);return n===r}import Wn from"node:fs/promises";import qn 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]="5321d574-4de4-5f94-99db-0c49639673fc")}catch{}})();var Zo=1,Tt="2026.6.24",Ay=">=22.18.0",Iy={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},uu=new Set([...ec.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(ja).map(e=>e.toLowerCase()),"scaffold"]),Cy="^6.0.0",Ty="^22.0.0",fu=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],He=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function mu(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function hu(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function gu(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var $y={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},pu=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],_u={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},Oy={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},Dy={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},Py={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},yu="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Ny={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},My={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},Ly={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},Fy={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function wu(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function vu(e,t){return e==="schema"?Ly[t]:e==="profile"?Fy[t]:My[t]}function jy(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),o=r>0&&(r===t.length||i!==void 0&&uu.has(i));return`${(uu.has(n)||o?["starter",...t]:t).join(" ")} ping`}function bu(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],o=`${e.replace(/-/g,"_")}_owner`,s="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(s)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(o)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(s)}],`,` [${JSON.stringify(s)}, "in_progress"],`,` [${JSON.stringify(s)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function Uy(e,t,n){let r=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return s;if(n==="search")return[...s,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let a=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===a?[]:[d],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...s,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(a)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...s,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...bu(e).map(a=>` ${a}`)," });"]:n==="importers"?[...s,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(o)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(o)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...s,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...s,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...s,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...s,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function zy(e,t,n){let r=n==="hooks",i=n==="search",o=n==="importers",s=n==="schema",a=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",m=Oy[n],p=e,f=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,g=`${e}-0001-init`,_=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...He,"});",""]:[],k=i?Qo(e,t,"search",m):[],x=o?Qo(e,t,"importers",m):[],b=s?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...mu(hu({extensionName:e,itemTypeName:p,itemTypeFolder:f,fieldName:h,migrationId:g,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...He,"});",""]:[],I=a?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...mu(gu(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...He,"});",""]:[],S=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...He,"});",""]:[],E=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...He,"});",""]:[],A=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...He,"});",""]:[],F=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...He,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",..._,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...fu,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...He,"});","",...v,...k,...x,...b,...I,...S,...E,...A,...F,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
25
- `)}function Wy(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var qy={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},Hy={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function By(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function Gy(e,t,n){let r=[],i=[...By(e,t,n)],o=[" commands: [pingCommand],"],s=`${e}-search`,a=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),m=u===d?[]:[u],p=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),o.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(s)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(a)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),o.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),o.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(f)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),o.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...bu(e),"});"),o.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),o.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),o.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),o.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),o.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:o}}function Jy(e,t,n){let r=Gy(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((o,s)=>o.localeCompare(s)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
26
- `)}function Qo(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,o=`${e}-vector`,s=`${e.replace(/-/g," ")} items`,a=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],m=p=>[...u," let deactivated = false;"," try {",...p.map(f=>f===""?f:` ${f}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...He];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(o)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(s)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(s)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(s)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(s)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(hu({extensionName:e,itemTypeName:a,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(gu(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function Vy(e,t,n){let r=n==="parser",i=JSON.stringify([..._u[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...fu,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(Tt)},`," },",` target: { pmVersion: ${JSON.stringify(Tt)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...He,"});","",...Qo(e,t,n,i)].join(`
27
- `)}function Ky(e,t,n){let r=wu(n,"package"),i=vu(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${qy[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",yu,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${Hy[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Zo}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Tt}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
28
- `)}function Yy(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function Xy(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function Zy(e,t,n,r){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function Qy(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function ew(e,t,n,r="commands",i=!1){let o=`pm-${e}`,s=_u[r],a=Wy(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Zo,pm_min_version:Tt,trusted:!0,sandbox_profile:"strict",permissions:{...Iy},capabilities:s,...a.length>0?{activation:{commands:a}}:{}},null,2)}
29
- `,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Uy(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
30
- `),l=`${JSON.stringify($y,null,2)}
31
- `,u=Dy[r],m=wu(r,"package"),p=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Ay},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Tt}`},devDependencies:{"@types/node":Ty,typescript:Cy},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
32
- `,f=zy(e,t,r),h=Py[r],g=["node_modules/","*.log","*.tsbuildinfo",""].join(`
33
- `),_=Yy(e),k=["```ts",`import { ${Xy(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Zy(e,t,r,_),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Qy(t,r,_),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],x=[`# ${o}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,h,yu,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...k,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Ny[r],...vu(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Tt}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Zo}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Tt}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
34
- `);return{"package.json":p,"manifest.json":c,"index.ts":i?Jy(e,t,r):d,"index.test.ts":i?Vy(e,t,r):f,"tsconfig.json":l,".gitignore":g,"README.md":i?Ky(o,t,r):x}}async function ku(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!pu.includes(i))throw new w(`Unknown scaffold capability "${n}". Supported capabilities: ${pu.join(", ")}.`,y.USAGE);let o=i;if(r&&t!=="package")throw new w("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",y.USAGE);let s=r?"declarative":"imperative",a=e.trim(),c=qn.resolve(process.cwd(),a),d=ti(qn.basename(c)).replace(/^(?:pm-)+/u,""),l=jy(d),u=ew(d,l,t,o,r),m=!1;if(await D(c)){if(!(await Wn.stat(c)).isDirectory())throw new w(`Scaffold target "${c}" exists and is not a directory.`,y.CONFLICT)}else await Wn.mkdir(c,{recursive:!0}),m=!0;for(let[f,h]of Object.entries(u)){let g=qn.join(c,f);if(!await D(g))continue;if(await Wn.readFile(g,"utf8")!==h)throw new w(`Scaffold file "${f}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,y.CONFLICT)}let p=[];for(let[f,h]of Object.entries(u)){let g=qn.join(c,f);if(await D(g)){p.push({path:f,status:"unchanged"});continue}await Wn.mkdir(qn.dirname(g),{recursive:!0}),await Wn.writeFile(g,h,"utf8"),p.push({path:f,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:o,style:s,target_path:c,created_directory:m,files:p}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="536ed530-7726-50ab-bb2d-ace030818f1d")}catch{}})();function xu(e,t){return`${e}:${R(t)}`}function tw(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let s of i){let a=o.get(s.command)??[];o.set(s.command,[...a,s])}for(let[s,a]of o){if(t!==null&&!a.some(d=>t.has(R(d.name))))continue;let c=a.at(-1);n.push({command:s,surface:r,policy:"last_activated_wins",collision:a.length>1,claimants:a.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function Su(e,t,n){let r=new Set(n.failed.map(d=>xu(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(xu(d.layer,d.name))?"failed":"ok",surfaces:Zt(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:Zt(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),o=typeof e=="string"?R(e):null,s=o===null?null:new Set(t.loaded.filter(d=>R(d.name)===o||typeof d.source_package=="string"&&R(d.source_package)===o||(d.source_aliases??[]).some(l=>R(l)===o)).map(d=>R(d.name)).concat(o)),a=s===null?i:i.filter(d=>s.has(R(d.name))),c=s===null?{}:{extensionNames:[...s]};return{target:typeof e=="string"?e.trim():null,total:a.length,extensions:a,union:Zt(n,c),command_ownership:tw(n,s)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function es(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function ci(e,t,n){let r=R(t),i=n.trim();if(r.length===0||i.length===0)return;let o=e.get(r)??new Set;o.add(i),e.set(r,o)}function nw(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)ci(t,r.name,r.command),ci(n,r.name,r.action);for(let r of e.commands.handlers)ci(t,r.name,r.command);for(let r of e.commands.overrides)ci(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Eu(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function rw(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:o}=e;return t?i.has(n)||o.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function di(e,t,n){let r=new Set(t.loaded.map(c=>R(c.name))),i=new Set(t.failed.map(c=>R(c.name))),o=new Set(n.failed.map(c=>R(c.name))),{commandPathsByExtension:s,actionPathsByExtension:a}=nw(n);return e.map(c=>{let d=R(c.name),l=Eu(s.get(d)),u=Eu(a.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},p=rw({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:i,activationFailedNames:o});return{...c,...p,...m}})}function iw(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function ue(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Iu=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function ow(e){return Iu.has(Pu(e))}function Ru(e){return e==="project"||e==="global"}function Cu(e){let t=e.split(":"),n=t[0];if(!n||!Iu.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),o=t.at(-2),s=t.at(-1)?.trim();return!Ru(r)||!Ru(o)||!i||!s?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:o,name:s}}}function sw(e){let t=new Set;for(let n of e){let r=Cu(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function ts(e,t){let n=e.filter(ow);if(n.length===0)return null;let r=sw(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function aw(e,t,n,r){let i=t.map(u=>Cu(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let o=e==="global"?"--global":"--project",s=ue(r,"deactivate"),a=`${ue(r,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(u=>[R(u.name),u])),d=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let p=R(m);d.set(p,(d.get(p)??0)+1)}let l=[...d.entries()].map(([u,m])=>{let p=c.get(u),f=p?.name??u,h=p?.command_paths??[],g=p?.action_paths??[];return{action:"deactivate",extension:f,command:`${s} ${f} ${o}`,affected_collisions:m,feature_loss:{command_paths:[...h].sort((_,v)=>_.localeCompare(v)),action_paths:[...g].sort((_,v)=>_.localeCompare(v))}}}).sort((u,m)=>{let p=m.affected_collisions-u.affected_collisions;if(p!==0)return p;let f=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,h=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return f!==h?f-h:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:d.size,next_best_command:a,collisions:i,remediation_candidates:l}}function Tu(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function $u(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function Ou(e,t){let n=[];for(let r of nc(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var cw=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${ue(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${ar.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${ue(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${ue(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${ue(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${ue(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${ue(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${ue(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function dw(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:s,updateHealthPartial:a,skippedUnmanagedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=[],m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:s};if(t.length>0){let p=ts(t,{deactivate:`${ue(n,"deactivate")} <name> ${i}`,doctor:`${ue(n,"doctor")} ${i} --detail deep --trace`});p&&u.push(p);for(let f of cw)f.matches(t,m)&&u.push(f.build(m))}return a?u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${ue(n,"manage")} ${i} --fix-managed-state (or ${ue(n,"adopt-all")} ${i}, ${ue(n,"adopt")} <name> ${i}, or reinstall via ${ue(n,"install")} ${i} <source>).`):c>0&&u.push(`Loaded unmanaged extensions are currently treated as informational. Use ${ue(n,"manage")} ${i} --fix-managed-state to adopt them for update checks.`),d>0&&u.push("Non-GitHub managed extensions are skipped by update checks. Use doctor output for non-update diagnostics."),l>0&&u.push(`Update available managed extensions via ${ue(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${ue(n,"manage")} ${i} after extension changes.`),u}function li(e,t,n,r={}){let i=[...new Set(t)].sort((A,F)=>A.localeCompare(F)),o=n.filter(A=>A.managed).length,s=n.filter(A=>A.enabled).length,a=n.filter(A=>A.active).length,c=n.filter(A=>A.update_available===!0).length,d=n.filter(A=>A.managed===!1),l=d.filter(A=>Au(A)).map(A=>A.name).sort((A,F)=>A.localeCompare(F)),u=d.filter(A=>!Au(A)).map(A=>A.name).sort((A,F)=>A.localeCompare(F)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let A of n)m[A.update_check_status]+=1;let p=m.failed,f=m.skipped_unmanaged,h=m.skipped_non_github,g=u.length>0,_=g?"partial":"full",v=g?[`extension_update_health_partial_coverage:skipped_unmanaged:${u.length}`]:[],k=[...new Set([...i,...v])].sort((A,F)=>A.localeCompare(F)),x=[...new Set(k.map(A=>Pu(A)))].sort((A,F)=>A.localeCompare(F)),b=iw(k),I=e==="global"?"--global":"--project",S=aw(e,i,n,r),E=dw({normalizedWarnings:i,options:r,scope:e,scopeFlag:I,updateCheckFailedTotal:p,policyWarningCount:b.warning_count,updateHealthPartial:g,skippedUnmanagedTotal:f,skippedNonGithubTotal:h,updateAvailableTotal:c});return{status:k.length===0?"ok":"warn",warning_count:k.length,warning_codes:x,warnings:k,policy_warning_count:b.warning_count,policy_violation_count:b.violation_count,policy_blocked_count:b.blocked_count,total_extensions:n.length,managed_total:o,enabled_total:s,active_total:a,update_available_total:c,update_health_coverage:_,update_health_partial:g,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(A=>A.name).sort((A,F)=>A.localeCompare(F)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:p,top_warnings:k.slice(0,8),remediation:E,...S?{collision_plan:S}:{}}}function Du(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new w(`Invalid --detail value "${e}". Expected summary or deep.`,y.USAGE)}function Pu(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Hn(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let o=_a(r);return o?[o]:ya(r)})();for(let o of i){let s=`${o.layer}:${o.name}:${o.capability}`;t.has(s)||(t.add(s),n.push(o))}}return n}function Bn(){return{version:cr.version,capabilities:[...cr.capabilities],legacy_aliases:{...cr.legacy_aliases}}}function Au(e){let t=R(e.name),n=R(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Nu(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let o=[...new Set(t.filter(l=>l.active).map(l=>R(l.name)))].sort((l,u)=>l.localeCompare(u)),s=[...new Set(n.filter(l=>l.layer==="project").map(l=>R(l.name)))].sort((l,u)=>l.localeCompare(u)),a=new Set(r.map(l=>R(l.name))),c=o.filter(l=>!s.includes(l)&&!a.has(l)).sort((l,u)=>l.localeCompare(u));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:o.length,loaded_project_count:s.length,active_project_names:o,loaded_project_names:s,missing_active_project_names:c}}}import{randomUUID as lw}from"node:crypto";import oe from"node:fs/promises";import uw from"node:os";import K 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]="263602a2-c000-5df7-80d2-6f095985496f")}catch{}})();var Mu=3,mw=120,Lu=250,pw=12e4,fw=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Fu=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,ju=e=>fw.has(String(Fu(e))),ui=(e,t)=>Fu(e)===t,Uu=e=>new Promise(t=>{setTimeout(t,e)}),zu=async e=>{let t=K.join(e,"package.json");await D(t)||await oe.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
35
- `,"utf8")},Wu=async e=>{let t=Re(import.meta.url,["../../.."]),n=K.join(e,"node_modules","@unbrained"),r=K.join(n,"pm-cli");await oe.mkdir(n,{recursive:!0}),await oe.rm(r,{recursive:!0,force:!0}),await oe.symlink(t,r,process.platform==="win32"?"junction":"dir")},ns=async e=>{let t=K.resolve(e),n=K.dirname(t),r=K.parse(n).root,i=await oe.realpath(r).catch(()=>r),o=K.relative(r,n),s=o===""?[]:o.split(K.sep);for(let[a,c]of s.entries()){let d=K.join(i,c);try{i=await oe.realpath(d)}catch{i=K.join(i,...s.slice(a));break}}return K.join(i,K.basename(t))},qu=async(e,t,n,r=uw.tmpdir())=>{let i=K.resolve(e),o=await oe.realpath(i).catch(()=>i),s=await ns(t);if(o===s)return;if(!ve(o,s)){await n(e,t,{recursive:!0,force:!0});return}let a=m=>{let p=K.resolve(m);if(p!==i&&!ve(i,p))return!1;let f=K.resolve(o,K.relative(i,p));if(f===s||ve(s,f))return!1;let g=K.relative(o,f).split(K.sep);return g.some(_=>_==="node_modules"||_.startsWith(".pm-extension-install-backup-"))?!1:g[0]!==".agents"},c=await oe.realpath(K.resolve(r)).catch(()=>ns(r)),d=ve(o,c)?K.dirname(o):c;if(ve(o,d))throw new w(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,y.USAGE,{code:"extension_install_source_contains_destination"});let l=await oe.mkdtemp(K.join(d,"pm-extension-copy-")),u=K.join(l,"extension");try{await n(e,u,{recursive:!0,force:!0,filter:a}),await n(u,t,{recursive:!0,force:!0})}finally{await oe.rm(l,{recursive:!0,force:!0})}},Hu=async(e,t,n=oe.cp)=>{for(let r=1;r<=Mu;r+=1)try{await oe.rm(t,{recursive:!0,force:!0}),await qu(e,t,n);return}catch(i){if(!ju(i)||r===Mu)throw i;await Uu(Lu)}},rs=async e=>{let t;try{t=await oe.readFile(K.join(e,"owner.json"),"utf8")}catch(i){if(!ct(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},Bu=async(e,t)=>await rs(e)!==t?!1:(await oe.rm(e,{recursive:!0,force:!0}),!0),hw=async(e,t)=>{let n;try{n=await oe.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await rs(e);return r===null?(await oe.rm(e,{recursive:!0,force:!0}),!0):Bu(e,r)},gw=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await rs(e)!==t)return;let o=new Date;await oe.utimes(e,o,o)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},_w=async(e,t)=>{await oe.mkdir(e);try{await oe.writeFile(K.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
36
- `,"utf8")}catch(n){throw await oe.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},yw=async(e,t,n,r,i)=>{for(let o=1;o<=n;o+=1)try{return await _w(e,t),!0}catch(s){if(!ui(s,"EEXIST"))throw s;await hw(e,i)?o-=1:await Uu(r)}return!1},is=async(e,t,n,r)=>{let i=K.join(e,"runtime","extension-install-locks"),o=K.join(i,"scope.lock");await oe.mkdir(i,{recursive:!0});let{attempts:s=mw,delay_ms:a=Lu,stale_ms:c=pw,heartbeat_ms:d}=r??{};if(![s,a,c,d].filter(_=>_!==void 0).every(Number.isFinite))throw new w("Extension install lock timings must be finite numbers.",y.USAGE);let l=Math.max(1,Math.floor(s)),u=Math.max(0,Math.floor(a)),m=Math.floor(c),p=Math.floor(d??m/3);if(m<=0||p<=0||p>=m)throw new w("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",y.USAGE);let f={pid:process.pid,token:lw(),created_at:T(),destination:t};if(!await yw(o,f,l,u,m))throw new w(`Timed out waiting for extension install lock for "${t}".`,y.CONFLICT);let g=gw(o,f.token,p);try{return await n()}finally{await g(),await Bu(o,f.token).catch(()=>!1)}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d3c62e9-9116-5cdc-bbda-48bbd2e39476")}catch{}})();var Gu=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");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])}});return await Promise.all(o),r};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b17dfc10-9e07-5912-b294-c5663133f192")}catch{}})();function Ju(e,t){let n=R(e),r=t.find(i=>R(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,o)=>i.localeCompare(o)),action_paths:[...r?.action_paths??[]].sort((i,o)=>i.localeCompare(o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5a4cea9-ac5d-5bda-9f7c-6cf8cf9e9998")}catch{}})();function Vu(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${R(o.name)}`]:[])),r=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>o.passThrough!==!0).filter(o=>!n.has(`${o.layer}:${R(o.name)}`)).map(o=>`extension_output_service_override_global:${o.service}:${o.layer}:${o.name}`),i=e.renderers.overrides.filter(o=>(o.commands?.length??0)===0&&o.resultDiscriminator===void 0).map(o=>`extension_output_renderer_override_global:${o.format}:${o.layer}:${o.name}`);return[...new Set([...r,...i])].sort((o,s)=>o.localeCompare(s))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var Ku=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=gr(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(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]="ccb857a5-045d-57a7-91d2-b761225fe53a")}catch{}})();var ww=1e4,vw=(e,t,n)=>{let r=e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).map(s=>{let[a,c=""]=s.split(/\s+/);return{commit:a,ref:c}}),i=r.find(s=>s.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let o=t?.trim();return o?{checked_at:n,remote_commit:i.commit,available:i.commit!==o}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},Yu=async(e,t=ii)=>{let n=T();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let r=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,ww);return vw(i,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import bw from"node:fs/promises";import kw 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]="56290db9-933c-590d-8b9f-df62ff45e515")}catch{}})();function os(e){return kw.join(e,"extension-migrations.json")}function Xu(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Zu(e,t){return`${e.layer}:${e.name}:${t}`}async function xw(e){let t=os(e);if(!await D(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await bw.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function ss(e,t){let n=await xw(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let s=Xu(i,o),a=r.get(Zu(i,s));a&&(i.definition.status=a.status,a.status==="failed"?i.definition.reason=a.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function Sw(e){let t=await ss(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),r=[],i=!1,o=e.migrations.map((l,u)=>({migration:l,index:u})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:u}of o){let m=Xu(l,u),p=Zu(l,m),f=n.get(p),h=String(l.definition.status??"pending").toLowerCase(),g=f?.status??(h==="applied"||h==="failed"?h:"pending");if(g==="applied"){r.push({key:p,layer:l.layer,extension:l.name,id:m,before:g,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:p,layer:l.layer,extension:l.name,id:m,before:g,outcome:"pending"});continue}let _=l.runtime_definition?.run??l.definition.run;if(typeof _!="function"){r.push({key:p,layer:l.layer,extension:l.name,id:m,before:g,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(_({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:g}));let k={key:p,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(p,k),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:p,layer:l.layer,extension:l.name,id:m,before:g,outcome:"applied"}),i=!0}catch(k){let x=k instanceof Error?k.message:String(k),b={key:p,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:x};n.set(p,b),l.definition.status="failed",l.definition.reason=x,r.push({key:p,layer:l.layer,extension:l.name,id:m,before:g,outcome:"failed",error:x}),i=!0}}if(i){let l=await C(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,p)=>m.key.localeCompare(p.key))};await Ar({pmRoot:e.pmRoot,filePath:os(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
37
- `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let s=r.filter(l=>l.outcome==="pending").length,a=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:os(e.pmRoot),total:r.length,pending_count:s,applied_count:a,skipped_count:c,failed_count:d,migrations:r}}async function Qu(e){let t=await C(e.resolvedRoots.settings_root),n=await Le({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Fe(n);e.warnings.push(...n.warnings,...r.warnings);let i=await Sw({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}import Ew from"node:fs/promises";import Rw 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]="5755dee7-d2df-5ced-8a94-aeb51762edb7")}catch{}})();function Aw(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Iw(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function as(e){let t=Rw.join(e,"manifest.json"),n;try{n=await Ew.readFile(t,"utf8")}catch(a){if(ct(a))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw a}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=r,o=xa(i),s=Aw(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:o.findings,warnings:o.findings.map(a=>Iw(s,a)),remediation:o.findings.map(a=>a.message)}}function em(e){return as(Me(e))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39bc7f14-2d32-5b58-97ab-647f9f238273")}catch{}})();async function tm(e,t,n){let r=typeof t=="string"?null:await zn(e),i=r===null?null:e.trim().toLowerCase(),o=i===null?null:await Zl(i),s=si(r??e,{forceGithub:typeof t=="string",ref:n}),a=i===null?null:await ru(e);return{bundledAliasName:i,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:i===null?s.kind:"builtin",input:i??s.input,...o===null?{}:{package:o}},ambiguous:a!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...o===null?{}:{package:o},command:`pm install ${i}`}],...a===null?[]:[{kind:"npm",input:`npm:${a.package}`,package:a.package,...a.version===void 0?{}:{version:a.version},directory:a.directory,command:`pm install npm:${a.package}`}]]}}}import $t from"node:fs/promises";import Cw 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]="98b47a2f-d48a-5c90-8b88-3f33bdd1c826")}catch{}})();var cs=async e=>$t.readFile(e).catch(t=>{if(ui(t,"ENOENT"))return null;throw t}),nm=async(e,t,n,r,i)=>{let o=Fn(e),s=bt(t),[a,c]=await Promise.all([cs(o),cs(s)]);return r&&await $t.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:o,managedStateContents:a,settingsPath:s,settingsContents:c}},rm=async e=>{await $t.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await $t.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await $t.rm(t,{force:!0}):(await $t.mkdir(Cw.dirname(t),{recursive:!0}),await $t.writeFile(t,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]="8d5ed026-8d61-5083-956c-9281caa0168b")}catch{}})();var Tw=4,am=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],$w=am.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Ow={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},Dw="__pm_native_output",Pw=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],cm=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Nw=["disabled","require_trusted","require_provenance"],dm={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},Mw=e=>{let t=e??dm,n={};for(let r of Pw)n[r]=Se(t[r]??[]);return n},Lw=(e,t)=>{for(let n of cm)t[n].length>0&&(e[n]=t[n]);return e},Fw=(e,t)=>{for(let n of Nw)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},jw=e=>{let t={};for(let n of cm)t[n]=Se(e[n]??[]);return t},Uw=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Lw(Fw({name:t},e),jw(e))},zw=e=>(e??[]).map(t=>Uw(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Ww=e=>{let t=Object.assign({},dm,e??{}),n=Mw(e),r=zw(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},lm=async(e,t)=>{let n=[t],r=await Ql(t);r&&n.push(r);let i=[...new Set(n.map(o=>R(o)).filter(o=>o.length>0))];for(let o of i){let s=e.find(c=>R(c.name)===o);if(s)return s;let a=e.find(c=>R(c.directory)===o);if(a)return a}},um=(e,t)=>{let n=t.trim(),r=new Set(Se(e.extensions.enabled));return new Set(Se(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},mm=(e,t)=>{let n=t.trim(),r=new Set(Se(e.extensions.enabled)),i=new Set(Se(e.extensions.disabled)),o=[...r],s=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},qw=(e,t)=>{let n=t.trim(),r=new Set(Se(e.extensions.enabled)),i=new Set(Se(e.extensions.disabled)),o=[...r],s=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},Hw=(e,t)=>{let n=t.trim(),r=new Set(Se(e.extensions.enabled)),i=new Set(Se(e.extensions.disabled)),o=[...r],s=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},Bw=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=am.map(([i,o,s])=>({action:o,flag:s,distance:ga(t,i,n)})).filter(i=>i.distance!==null).sort((i,o)=>i.distance-o.distance)[0];return r?{action:r.action,flag:r.flag}:null},Gw=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=Bw(e);if(!r)return new w(`One action flag is required. Use one of: ${$w}. Bare \`pm package\` and \`pm extension\` default to --explore.`,y.USAGE);let i=`pm ${n} ${r.flag}`;return Tr({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(pm),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},Jw=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],pm={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Vw=e=>pm[e]??null,Kw=(e,t)=>{let n=[...new Set(Jw.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=Vw(e.trim().toLowerCase());if(r)return r;throw Gw(e,t)}if(n.length>1)throw new w("Extension action flags are mutually exclusive.",y.USAGE);return n[0]},Yw=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new w('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"},Xw=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&e.source.kind!=="github"?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],fm=e=>{for(let t of Xw){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},hm=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,update_error:i.update_error,update_check_status:r.status,update_check_reason:r.reason}},Zw=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),o=r?um(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:hm({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:o},t,r,fm(r))}},Qw=async(e,t,n,r,i,o)=>{let s=Te.join(e,t),a=Te.join(s,"manifest.json"),c=o.get(R(t));if(!await D(a))return Zw(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await gt.readFile(a,"utf8").then(p=>JSON.parse(p)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=Ho(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(R(u.name))??o.get(R(t));return{summary:hm({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:um(r,u.name)},n,m,fm(m))}},Be=async(e,t,n,r)=>{if(!await D(e))return{extensions:[],warnings:[]};let o=(await gt.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),s=new Map(r.entries.map(l=>[R(l.name),l])),a=new Map(r.entries.map(l=>[R(l.directory),l])),c=[],d=[];for(let l of o){let u=await Qw(e,l,t,n,s,a);u.warning&&c.push(u.warning),u.summary&&d.push(u.summary)}return{extensions:d.sort((l,u)=>l.name.localeCompare(u.name)),warnings:c.sort((l,u)=>l.localeCompare(u))}},ev=oc(),tv=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,nv=(e,t,n,r)=>{let i=n.command_paths.map(a=>`pm ${a} --help`),o=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,s=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&s.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:tv(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:s,...o?{sdk_dependency_status:"missing"}:{}}},rv=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},gm=e=>e.map(t=>rv(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),_m=(e,t,n)=>{let r=R(e);return t.find(i=>(n===void 0||i.layer===n)&&R(i.name)===r)},iv=(e,t,n,r)=>n.find(o=>o.scope===t&&R(o.name)===R(e))?.activation_status??(r?"failed":"unknown"),ym=(e,t,n,r,i)=>ev.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,s=await gt.mkdtemp(Te.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Re(import.meta.url,["../.."]);try{let a=await Le({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:qi(),cache_bust:!0,module_graph_snapshot_root:s}),c=await Fe({...a}),d=[...a.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...gm(c.failed)],l=Object.fromEntries(a.loaded.map(u=>[R(u.name),Da(Zt(c,{extensionName:u.name}))]));return{installed:di(r,a,c),warnings:[...a.warnings,...c.warnings],activation_failures:d,extensions_disabled:a.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await gt.rm(s,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),ls=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),o=[...i].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),s=r,a=[];for(let c of o){let d=Te.join(e,c.directory),l=await sn(d),u=T(),m={kind:"local",input:c.name,location:d};s=Un(s,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:u,updated_at:u,source:m}),a.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return a.length>0&&await Ct(e,s),{state:s,adopted_entries:a,unmanaged_candidates:o,already_managed_count:n.length-i.length}},ov=(e,t)=>{let n=M(process.cwd(),t.path),r=Dt(n,process.cwd()),i=e==="global"?lr(process.cwd()):n,o=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:o,roots:r}},mi=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new w('Options "--gh" and "--github" must match when both are provided.',y.USAGE);return n[0]},sv=e=>Ow[e],av=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,o=sv(e),s=`<${r}>`,a=`pm ${n} ${o} ${s}`;throw new w(`Action "${e}" requires ${i} input.`,y.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${s}`,a,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:a,fallback_candidates:[{source:"lifecycle_action",command:a,reason:`flag-form ${e} command with required ${r} target`}]}})},pi=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new w('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',y.USAGE);return av(t,n)},cv=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${R(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${R(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,i,o)=>o.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},dv=(e,t)=>{let r=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate",message:"--dry-run is only valid with --migrate."}].find(i=>i.triggered&&!i.allowed);if(r)throw new w(r.message,y.USAGE)},lv=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},uv=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},mv=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:uv(e),warnings:[...new Set(e.warnings)].sort((i,o)=>i.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(r,Dw,{value:!0,enumerable:!1,configurable:!1}),r},us=async(e,t,n)=>{let r=Kw(e,t);dv(r,t);let i=lv(e,r,t),o=Yw(t),s=ov(o,n),c={action:r,normalizedTarget:i,scope:o,resolvedRoots:s,warnings:[],options:t,global:n},l={...c,withResult:(u,m=!0)=>mv(c,u,m)};return await Bv(l)},pv=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=rc(r),o={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},s={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},a=[];return[n==="package",t.declarative===!0].every(Boolean)&&a.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[o[n],...a,`Install the scaffold: ${Ue(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,s[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},fv=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([mi(r),r.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new w('Action "init" does not accept --gh/--github/--ref options.',y.USAGE);let a=pi(n,t,r),c=await ku(a,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:c.created_directory||c.files.some(d=>d.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:pv(c,r)})},hv=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:o,withResult:s}=e;if(t!==void 0)throw new w('Action "reload" does not accept a target argument.',y.USAGE);let a=await C(n.settings_root),c=qi(),d=await Le({pmRoot:n.settings_root,settings:a,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await Fe(d);r.push(...l.warnings);let u={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),s(u)},gv=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:o}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new w('Action "catalog" does not accept a package target.',y.USAGE);return o(await eu(n,i,r))},_v=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),yv=e=>({kind:"local",input:e.input,location:e.absolute_path}),wv=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),vv=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),bv=(e,t,n,r)=>e?_v(e,t):n.kind==="local"?yv(n):n.kind==="npm"?wv(n,r):vv(n,r),kv=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:Jl(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},xv=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:o,destinationDirectoryName:s}=t,a=await C(r.settings_root),c=await ge(r.selected_root);i.push(...c.warnings);let d=Te.join(r.selected_root,s),l=await D(d),u=await lu(o.directory,d);await gt.mkdir(r.selected_root,{recursive:!0});let m=await gt.mkdtemp(Te.join(r.selected_root,".pm-extension-install-backup-")),p=Te.join(m,"destination");try{let f=await nm(r.selected_root,r.settings_root,d,l,p),h=bv(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),g=c.state.entries.find(x=>R(x.name)===R(o.manifest.name)),_=kv(g,o.manifest.version,h,T()),v=Un(c.state,{name:o.manifest.name,directory:s,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,..._,source:h}),k=mm(a,o.manifest.name);try{u||await Hu(o.directory,d),await zu(d),await Wu(d),await Ct(r.selected_root,v),k&&await Ir(r.settings_root,a,"settings:write")}catch(x){try{await rm(f)}catch(b){throw new AggregateError([x,b],`Extension install failed: ${String(x)}; rollback failed: ${String(b)}`,{cause:b})}throw x}return{settings:a,managedState:v,sourceRecord:h,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:k}}finally{await gt.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},Sv=async(e,t,n)=>{let r=n.filter(i=>R(i.name)===R(t)).flatMap(i=>i.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&r.length>0&&await Mn(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},Ev=(e,t,n,r,i)=>{let o=_m(t,n.activation_failures,e.scope),s=iv(t,e.scope,n.installed,o),a=[!n.extensions_disabled,s==="ok"].every(Boolean);a||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${s}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:a,status:s,failure:o,verification:{status:c[String(a)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:s,activated:a,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(a)]}}},Rv=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:o,withResult:s}=e,{validated:a,destinationDirectoryName:c}=t,d=await xv(e,t),l=await Be(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let u=await ym(r.pm_root,Te.dirname(r.selected_root),d.settings,l.extensions,o);i.push(...u.warnings);let m=await Sv(e,a.manifest.name,u.item_type_registrations),p=Ju(a.manifest.name,u.installed),f=Ev(e,a.manifest.name,u,p,m),h=u.contribution_inventories[R(a.manifest.name)];return h&&(d.managedState=await Vl(r.selected_root,d.managedState,a.manifest.name,h)),s({extension:{name:a.manifest.name,version:a.manifest.version,entry:a.manifest.entry,capabilities:a.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:f.activated,settings_changed:d.activationChanged,runtime_activation_status:f.status,command_paths:p.command_paths,action_paths:p.action_paths,contributions:h,command_discovery:nv(a.manifest.name,d.sourceRecord,p,f.failure),verification:f.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:f.failure??null}},f.activated)},Av=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new w('Action "install all" does not accept --ref.',y.USAGE);let o=[],s=new Map;for(let c of await ri()){let d=await zn(c),l=Te.resolve(d),u=s.get(l);u===void 0&&(u=await us(c,{...t,install:!0},n),s.set(l,u)),o.push({alias:c,result:u})}r.push(...o.flatMap(c=>c.result.warnings));let a=o.every(c=>c.result.ok);return i({installed_all:a,installed_count:o.filter(c=>c.result.ok).length,failed_count:o.filter(c=>!c.result.ok).length,packages:o.map(c=>{let d=c.result.details;return{alias:c.alias,ok:c.result.ok,extension:d.extension,source:d.source,source_resolution:d.source_resolution,destination_path:d.destination_path,activated:d.activated,settings_changed:d.settings_changed,command_paths:d.command_paths,action_paths:d.action_paths,command_discovery:d.command_discovery,verification:d.verification,runtime_activation_status:d.runtime_activation_status,activation_diagnostics:d.activation_diagnostics,warnings:c.result.warnings}})},a)},Iv=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:o,installSource:s,sourceResolution:a}=await tm(t,n,e.options.ref);if(a.ambiguous){let d=a.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${d.package}`)}let c=await du(s);try{let d=await sn(c.directory,{source_kind:s.kind,source_input:s.input,source_root:c.source_root}),l=ti(d.manifest.name);return await is(r.settings_root,l,()=>Rv(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:o,sourceResolution:a,installSource:s,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},Cv=async e=>{let t=mi(e.options),n=t??pi(e.normalizedTarget,e.action,e.options);return[t===void 0,Yl(n)].every(Boolean)?Av(e):Iv(e,n,t)},Tv=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:s}=e;if(t!==void 0)throw new w('Action "adopt-all" does not accept a target argument.',y.USAGE);if(mi(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new w('Action "adopt-all" does not accept --gh/--github/--ref options.',y.USAGE);let c=await C(r.settings_root),d=await ge(r.selected_root);i.push(...d.warnings);let l=await Be(r.selected_root,n,c,d.state);i.push(...l.warnings);let u=await ls(r.selected_root,n,l.extensions,d.state),m=await Be(r.selected_root,n,c,u.state);i.push(...m.warnings);let p=li(n,i,m.extensions,o);i.push(...p.warnings);let f=new Map(m.extensions.map(_=>[`${R(_.name)}:${R(_.directory)}`,_])),h=new Map(m.extensions.map(_=>[R(_.directory),_])),g=u.adopted_entries.map(_=>{let v=R(_.directory),k=f.get(`${R(_.name)}:${v}`)??h.get(v);return{..._,...wm(k)}});return s({adopted_all:g.length>0,adopted_count:g.length,already_managed_count:u.already_managed_count,extensions:g,triage:p,warning_codes:p.warning_codes,update_health_partial:p.update_health_partial,update_health_coverage:p.update_health_coverage})},wm=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),$v=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=si(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new w(`Invalid GitHub shorthand "${e}".`,y.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},Ov=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:s,withResult:a}=e,c=pi(n,t,s),d=mi(s),l=await C(i.settings_root),u=await ge(i.selected_root);o.push(...u.warnings);let m=await Be(i.selected_root,r,l,u.state);o.push(...m.warnings);let p=await lm(m.extensions,c);if(!p)throw new w(`Installed extension "${c}" was not found in ${r} scope.`,y.NOT_FOUND);if(p.managed)return a({adopted:!1,already_managed:!0,extension:{name:p.name,directory:p.directory}});let f=Te.join(i.selected_root,p.directory),h=await sn(f),g=T(),_=$v(d,c,f,s.ref),v=Un(u.state,{name:h.manifest.name,directory:p.directory,scope:r,manifest_version:h.manifest.version,manifest_entry:h.manifest.entry,capabilities:[...h.manifest.capabilities],contributions:h.manifest.contributions,installed_at:g,updated_at:g,source:_});await Ct(i.selected_root,v);let k=await Be(i.selected_root,r,l,v);o.push(...k.warnings);let x=k.extensions.find(b=>R(b.name)===R(h.manifest.name))??k.extensions.find(b=>R(b.directory)===R(p.directory));return a({adopted:!0,extension:{name:h.manifest.name,directory:p.directory,version:h.manifest.version,entry:h.manifest.entry},source:_,...wm(x)})},vm=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:s}=e,a=pi(n,t,s),c=await C(i.settings_root),d=await ge(i.selected_root);o.push(...d.warnings);let l=await Be(i.selected_root,r,c,d.state);o.push(...l.warnings);let u=await lm(l.extensions,a);if(!u)throw new w(`Installed extension "${a}" was not found in ${r} scope.`,y.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},Dv=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:o}=await vm(e),s=Te.join(t.selected_root,o.directory);await gt.rm(s,{recursive:!0,force:!0});let a={...i.state,updated_at:T(),entries:i.state.entries.filter(d=>R(d.name)!==R(o.name)&&R(d.directory)!==R(o.directory))};await Ct(t.selected_root,a);let c=Hw(r,o.name);return c&&await Ir(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:s,settings_changed:c})},im=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:o}=e,{settings:s,candidate:a}=await vm(e),c=t==="activate"?mm(s,a.name):qw(s,a.name);c&&await Ir(n.settings_root,s,"settings:write");let d=t==="activate"?await ym(n.pm_root,Te.dirname(n.selected_root),s,[a],i).then(l=>(r.push(...l.warnings),_m(a.name,l.activation_failures,e.scope))):void 0;return d&&r.push(`extension_activate_failed:${e.scope}:${a.name}`),o({extension:{name:a.name,directory:a.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...s.extensions.enabled],disabled:[...s.extensions.disabled]}},d===void 0)},Pv=(e,t,n,r,i,o)=>{let s=r==="package"?"package":"extension",a={package:"doctor",extension:"--doctor"}[s],c=i?.adopted_entries.length??0,d=[[o!==null,o??""],[t>0,`Run pm ${s} explore --project and pm ${s} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${s} ${a} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},ds=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Nv=(e,t,n,r)=>{if(e!=="project"||t||!ds(r))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Mv=(e,t,n)=>{if(String(e??"").trim().length>0)throw new w('Action "doctor" does not accept a target argument.',y.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new w("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",y.USAGE);let i=Du(n.detail),o=n.trace===!0;if([o,i!=="deep"].every(Boolean))throw new w("--trace requires --detail deep with --doctor.",y.USAGE);return{isolated:r,detailMode:i,includeTrace:o}},Lv=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await ls(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},Fv=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:ds(r),rerun_command:null,pm_global_path_recipe:null};let o=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:ds(r),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},jv=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:s,withResult:a}=e,{isolated:c,detailMode:d,includeTrace:l}=Mv(t,n,o),u=await C(r.settings_root),m=await ge(r.selected_root);i.push(...m.warnings);let p=await Be(r.selected_root,n,u,m.state);i.push(...p.warnings);let{state:f,fix:h}=await Lv(e,p.extensions,m.state),g=await Be(r.selected_root,n,u,f);i.push(...g.warnings);let _=await Le({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:s.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Fe({..._,loaded:_.loaded}),k=await em(r.pm_root);i.push(...k.warnings,..._.warnings),i.push(...Tu(_.failed)),i.push(...v.warnings),i.push(...$u(v.failed)),i.push(...Ou(_,v)),i.push(...Vu(v,_)),i.push(...cv(_,v)),i.push(...Ku(v));let x=di(g.extensions,_,v),b=Nu(n,x,_.loaded.map(j=>({layer:j.layer,name:j.name})),_.failed.map(j=>({name:j.name})),_.disabled_by_flag);i.push(...b.warnings);let I=x.filter(j=>j.update_check_status==="failed").map(j=>`extension_update_check_failed:${j.name}`);i.push(...I);let S=li(n,i,x,o);i.push(...S.warnings);let E=[...S.warnings],A={mode:_.policy.mode,trust_mode:_.policy.trust_mode,require_provenance:_.policy.require_provenance,default_sandbox_profile:_.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:_.policy.trusted_extensions.length,allowed_extensions_count:_.policy.allowed_extensions.length,blocked_extensions_count:_.policy.blocked_extensions.length,allowed_capabilities_count:_.policy.allowed_capabilities.length,blocked_capabilities_count:_.policy.blocked_capabilities.length,allowed_surfaces_count:_.policy.allowed_surfaces.length,blocked_surfaces_count:_.policy.blocked_surfaces.length,allowed_commands_count:_.policy.allowed_commands.length,blocked_commands_count:_.policy.blocked_commands.length,allowed_actions_count:_.policy.allowed_actions.length,blocked_actions_count:_.policy.blocked_actions.length,allowed_services_count:_.policy.allowed_services.length,blocked_services_count:_.policy.blocked_services.length,extension_override_count:_.policy.extension_overrides.length},F=Hn(E),H=Bn(),O=S.warning_codes,B=Nv(n,c,o.vocabulary,_),se=Pv(S.remediation,_.failed.length,v.failed.length,o.vocabulary,h,B),ae=Fv(n,c,o.vocabulary,_),he={status:S.status,scope:n,warning_count:S.warning_count,warning_codes:O,total_extensions:x.length,managed_total:x.filter(j=>j.managed).length,enabled_total:x.filter(j=>j.enabled).length,active_total:x.filter(j=>j.active).length,unmanaged_loaded_extension_count:S.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:S.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:S.unmanaged_expected_extension_count,runtime_active_total:x.filter(j=>j.runtime_active===!0).length,activation_status_totals:{ok:x.filter(j=>j.activation_status==="ok").length,failed:x.filter(j=>j.activation_status==="failed").length,not_loaded:x.filter(j=>j.activation_status==="not_loaded").length,unknown:x.filter(j=>j.activation_status==="unknown").length},unknown_capability_count:F.length,capability_contract_version:H.version,update_available_total:x.filter(j=>j.update_available===!0).length,update_health_coverage:S.update_health_coverage,update_health_partial:S.update_health_partial,update_check_failed_total:x.filter(j=>j.update_check_status==="failed").length,load_failure_count:_.failed.length,activation_failure_count:v.failed.length,load_failures:es(_.failed),activation_failures:es(v.failed),blocking_failure_count:_.failed.length+v.failed.length,has_blocking_failures:_.failed.length+v.failed.length>0,consistency_warning_count:b.warnings.length,trace_enabled:l,isolation:ae,policy:A,remediation:se},vt=h?{requested:!0,applied:h.adopted_entries.length>0,adopted_count:h.adopted_entries.length,already_managed_count:h.already_managed_count,adopted_extensions:h.adopted_entries.map(j=>j.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:g.extensions.filter(j=>j.managed).length,adopted_extensions:[]},wn={mode:d,summary:he,triage:S,trace_enabled:l,capability_contract:H,capability_guidance:F,managed_state_fix:vt,author_manifest:k,isolation:ae,policy:_.policy};if(d==="deep"){let j=l?v.failed:v.failed.map(G=>{let{trace:or,...sr}=G;return sr});wn.deep={warnings:E,warning_codes:O,capability_contract:H,capability_guidance:F,trace_enabled:l,managed_state:{path:m.path,count:f.entries.length,entries:f.entries},installed_extensions:x,load:{roots:_.roots,policy:_.policy,warnings:_.warnings,failed:_.failed,loaded:_.loaded.map(G=>({layer:G.layer,directory:G.directory,name:G.name,version:G.version,entry:G.entry,priority:G.priority}))},activation:{failed:j,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:b.summary},l&&(wn.deep.trace={activation_failures:v.failed.filter(G=>G.trace!==void 0).map(G=>({layer:G.layer,name:G.name,entry_path:G.entry_path,error:G.error,method:G.trace.method,command:G.trace.command,capability:G.trace.capability,missing_capability:G.trace.missing_capability,registration_index:G.trace.registration_index,expected_schema:G.trace.expected_schema,hint:G.trace.hint,received:G.trace.received}))})}return a(wn)},Uv=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:s,withResult:a}=e,c=await C(r.settings_root),d=await Le({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:s.noExtensions===!0}),l=await Fe(d);i.push(...d.warnings),i.push(...l.warnings);let u=Su(t,d,l);if(t!==void 0&&u.extensions.length===0){let m=o.vocabulary==="package"?"package":"extension",p=[...new Set(d.loaded.map(h=>o.vocabulary==="package"&&typeof h.source_package=="string"&&h.source_package.trim().length>0?h.source_package.trim():h.name))].sort((h,g)=>h.localeCompare(g)),f=p.length>0?` Loaded ${m} names: ${p.join(", ")}.`:"";throw new w(`No loaded ${m} named "${t}" was found in ${n} scope.${f} Run pm ${m} explore to list discovered ${m}s.`,y.NOT_FOUND)}return a({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},zv=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await ls(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let o=await Gu(r.entries,Tw,async s=>{if(s.source.kind!=="github")return s;let a=await Yu(s.source);return{...s,last_update_check_at:a.checked_at,last_update_remote_commit:a.remote_commit,update_available:a.available,update_error:a.error}});r={...r,updated_at:T(),entries:jn(o)},await Ct(e.resolvedRoots.selected_root,r)}return{state:r,fix:i}},Wv=async(e,t,n)=>{let r=await Le({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Fe({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:di(n,r,i),failures:gm(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...r.warnings,...i.warnings])].length,policy:r.policy}}},qv=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},om=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:s}=e,a=await C(r.settings_root),c=Ww(a.extensions.policy),d=await ge(r.selected_root);i.push(...d.warnings);let l=await Be(r.selected_root,n,a,d.state);i.push(...l.warnings);let{state:u,fix:m}=await zv(e,l.extensions,d.state),p=await Be(r.selected_root,n,a,u);if(i.push(...p.warnings),t==="manage"){let v=p.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);i.push(...v)}let f=await Wv(e,a,p.extensions),h=f.installed,g=li(n,i,h,o);i.push(...g.warnings);let _={total:h.length,managed_total:h.filter(v=>v.managed).length,enabled_total:h.filter(v=>v.enabled).length,active_total:h.filter(v=>v.active).length,extensions:h,triage:g,policy:c};return f.failures!==void 0&&(_.activation_diagnostics={failed_count:f.failures.length,failed:f.failures}),t==="explore"&&(_.runtime_probe=f.summary),t==="manage"&&(_.runtime_probe=f.summary,_.managed_state_fix=qv(m,h)),s(_)},sm={init:fv,install:Cv,uninstall:Dv,explore:om,manage:om,describe:Uv,reload:hv,doctor:jv,catalog:gv,adopt:Ov,"adopt-all":Tv,activate:im,deactivate:im,migrate:Qu},Hv=e=>[e.action==="uninstall",e.action==="manage",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[e.action==="doctor",e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Bv=e=>Hv(e)?is(e.resolvedRoots.settings_root,`${e.action}-state`,()=>sm[e.action](e)):sm[e.action](e);import{execFile as Gv}from"node:child_process";import{realpath as Jv}from"node:fs/promises";import bm from"node:path";import{promisify as Vv}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var Kv=Vv(Gv),Yv=32*1024*1024,Xv=1e4,Zv=["search/eval-queries.json"];function ms(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Qv(e){return`'${e.replaceAll("'","'\\''")}'`}async function eb(e,t=Jv){return t(e).catch(()=>bm.resolve(e))}async function fi(e){let t=await Ze(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await eb(e),r=ms(bm.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=Io.map(o=>`${r}/${ms(o)}`);try{let{stdout:o}=await Kv("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:Yv,windowsHide:!0,timeout:Xv}),s=new Set(Zv.map(d=>`${r}/${d}`)),a=[...new Set(o.split("\0").filter(d=>d.length>0&&!s.has(ms(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>Qv(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import{execFile as ob}from"node:child_process";import{randomUUID as sb}from"node:crypto";import{readdir as ab}from"node:fs/promises";import me from"node:path";import{promisify as cb}from"node:util";import{constants as km}from"node:fs";import{lstat as tb,open as nb}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ece0e15-aff5-5e2d-b18a-16ffaa0fe2ea")}catch{}})();var rb={lstat:tb,open:nb};function ib(e){return e.O_NOFOLLOW??0}async function xm(e,t,n=rb){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let i=await n.open(e,km.O_RDONLY|ib(km));try{let o=await i.stat();if(!o.isFile()||o.size>t)return null;let s=Buffer.alloc(o.size),a=0;for(;a<s.length;){let{bytesRead:d}=await i.read(s,a,s.length-a,a);if(d===0)break;a+=d}return(await i.stat()).size===o.size&&a===o.size?s.toString("utf8",0,a):null}finally{await i.close()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="624fc190-4c46-5a55-b757-72e621aec35d")}catch{}})();var db=cb(ob),lb=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,ub=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,fs=2048,mb=16*1024*1024,pb=64,fb=1e5,hb=new Set(["version","id","item_path","item_id","requested_preference","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","evidence_source"]),gb=new Set(["field","base","ours","theirs","retained","discarded"]);async function hs(e){try{let{stdout:t}=await db("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Im(e,t){let n=me.dirname(me.resolve(e,t));for(let r=0;r<12;r+=1){if(await D(me.join(n,"settings.json")))return n;let i=me.dirname(n);if(i===n)break;n=i}return null}function gs(e){return me.join(e,"merge-receipts")}function an(e){return`${e}.json`}function Jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cm(e,t){return Object.keys(e).every(n=>t.has(n))}function Sm(e){return Array.isArray(e)&&e.length<=fs&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Gn(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>fb||r.depth>pb)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(Jn(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function _b(e){return Jn(e)&&Cm(e,gb)&&typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&Object.hasOwn(e,"base")&&Object.hasOwn(e,"ours")&&Object.hasOwn(e,"theirs")&&Object.hasOwn(e,"retained")&&Object.hasOwn(e,"discarded")&&Gn(e.base)&&Gn(e.ours)&&Gn(e.theirs)&&Gn(e.retained)&&Gn(e.discarded)}function yb(e){if(!Jn(e))return!1;let t=Object.entries(e);return t.length<=fs&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function wb(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||me.posix.isAbsolute(e))return!1;let n=me.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&me.posix.basename(n,me.posix.extname(n))===t}function vb(e){return!Cm(e,hb)||e.version!==1?!1:typeof e.id=="string"&&lb.test(e.id)&&typeof e.item_id=="string"&&ub.test(e.item_id)&&wb(e.item_path,e.item_id)}function bb(e){return!Sm(e.fields_from_theirs)||!Sm(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>fs||!e.decisions.every(_b)?!1:e.merged_field_hashes===void 0||yb(e.merged_field_hashes)}function kb(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order"],r=[void 0,"clone_local","hash_only"],i=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&i.includes(e.evidence_source)}function xb(e){return typeof e.created_at=="string"&&Xi(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&Xi(e.reconciled_at))}function Sb(e){return e.value_availability==="hash_only"&&e.decisions.every(t=>t.base===null&&t.ours===null&&t.theirs===null&&Rm(t.retained)&&Rm(t.discarded))}function _s(e,t){return!Jn(e)||!vb(e)||!bb(e)||!kb(e)||!xb(e)?!1:t!=="durable"||Sb(e)}async function Tm(e){return xm(e,mb)}async function Em(e){let t;try{t=await(e.readReceipt??Tm)(e.receiptPath)}catch(o){if(ct(o))return null;throw o}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=JSON.parse(t)}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!_s(n,e.evidenceSource)||n.id!==e.receiptId||me.basename(e.receiptPath)!==an(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprint:hi(n),content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt},null,2)}
38
- `}}function hi(e){return dt(Q({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,decisions:gi(e).decisions}))}function Eb(e,t){if(e.state==="reconciled"&&t.state==="reconciled")return e;let{reconciled_at:n,...r}=e;return{...r,state:"pending"}}function gi(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:ps(t.retained)??dt(Q(t.retained)),discarded_hash:ps(t.discarded)??dt(Q(t.discarded))}))}}function ps(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function Rm(e){return Jn(e)&&Object.keys(e).length===1&&ps(e)!==void 0}async function GO(e){let t=await hs(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,i=me.basename(r,me.extname(r)),o={version:1,id:sb(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions),state:"pending",created_at:T(),value_availability:"clone_local"};await vn(t),await de(me.join(t,an(o.id)),`${JSON.stringify(o,null,2)}
39
- `);let s=await Im(e.cwd,o.item_path);if(s!==null){let a=gs(s),c=gi(o),d={...o,decisions:c.decisions.map(l=>({field:l.field,base:null,ours:null,theirs:null,retained:{pm_value_hash:l.retained_hash},discarded:{pm_value_hash:l.discarded_hash}})),value_availability:"hash_only"};await vn(a),await de(me.join(a,an(o.id)),`${JSON.stringify(d,null,2)}
40
- `)}return o}async function Am(e,t){let n;try{n=await ab(e)}catch(o){return{receipts:[],invalid_evidence_count:U(o)?0:1}}let r=[],i=0;for(let o of n.sort((s,a)=>s.localeCompare(a)))if(o.endsWith(".json"))try{let s=me.join(e,o),a=await Tm(s);if(a===null){i+=1;continue}let c=JSON.parse(a);if(!_s(c,t)||o!==an(c.id)){i+=1;continue}let{preferred:d,evidence_source:l,...u}=c,m={...u,requested_preference:c.requested_preference??d??"ours",conflict_resolution:c.conflict_resolution??"preferred_side",evidence_source:t};r.push(m)}catch{i+=1}return{receipts:r,invalid_evidence_count:i}}async function rt(e,t={}){let n=await hs(e),r=n===null?{receipts:[],invalid_evidence_count:0}:await Am(n,"clone_local"),i=t.pmRoot??me.join(e,".agents","pm"),o=await Am(gs(i),"durable"),s=new Map(o.receipts.map(c=>[c.id,c])),a=0;for(let c of r.receipts){let d=s.get(c.id);if(d!==void 0&&hi(d)!==hi(c)){s.delete(c.id),a+=1;continue}s.set(c.id,d===void 0?c:Eb(c,d))}return{receipts:[...s.values()].filter(c=>(t.includeReconciled||c.state==="pending")&&(t.includeLossless!==!1||c.decisions.length>0)).sort((c,d)=>c.created_at.localeCompare(d.created_at)),invalid_evidence_count:r.invalid_evidence_count+o.invalid_evidence_count+a,clone_local_evidence_resolved:n!==null}}function cn(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function JO(e,t,n={}){let r=await hs(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!_s(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let o=T(),s=me.join(r,an(t.id)),a=await Im(e,t.item_path),c=a===null?null:me.join(gs(a),an(t.id)),l=(await Promise.all([Em({receiptPath:s,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:o}),...c===null?[]:[Em({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:o})]])).filter(m=>m!==null);if(l.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let u=hi(t);if(new Set([u,...l.map(m=>m.fingerprint)]).size!==1)throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let m of l)await de(m.path,m.content)}async function VO(e){let t=await rt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:T()}}import{realpath as Dm}from"node:fs/promises";import Rb from"node:path";import Pm from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="151e5d26-d6f5-5fcf-84ab-ce89e2b7664e")}catch{}})();function $m(e,t){return t==="body"?e.body:e.metadata[t]}function ys(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(i=>{let o=t.findIndex((s,a)=>!r.has(a)&&ys(i,s));return o<0?!1:(r.add(o),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,i])=>Object.hasOwn(n,r)&&ys(i,n[r]))}function Om(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let o=e[i],s=new Set;for(let c of hc(o.patch))s.add($r(c.path)),c.from&&s.add($r(c.from));let a=[...n].filter(c=>s.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:i+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function Ab(e,t,n){let r=Pm.compare(t,n);if(r.length===0)return;let i=new Set;for(let f of r)i.add($r(f.path));let o=new Set([...i].filter(f=>ys($m(t,f),$m(n,f)))),s=new Set([...i].filter(f=>!o.has(f))),a=Om(e,s),c=Om(e,o),d=[...i].sort((f,h)=>f.localeCompare(h)),l=[...s].sort((f,h)=>f.localeCompare(h)),u=[...o].sort((f,h)=>f.localeCompare(h)),m=[...new Set(a.map(f=>f.author))].sort((f,h)=>f.localeCompare(h)),p=[...new Set(c.map(f=>f.author))].sort((f,h)=>f.localeCompare(h));return{reconciled_field_count:i.size,reconciled_fields:d,reverted_field_count:s.size,reverted_fields:l,discarded_events:a,discarded_authors:m,preserved_field_count:o.size,preserved_fields:u,preserved_events:c,preserved_authors:p,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function Ib(e){try{return await Dm(e)}catch{return null}}async function Cb(e){if(await Ib(Rb.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let n=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let i=Object.keys(r).sort();if(n.length!==i.length||n.some((a,c)=>a!==i[c]))return null;let o=e.currentItemReplay.metadata;return n.every(a=>{let c=a==="body"?e.currentItemReplay.body:o[a];return r[a]===dt(Q(c))})?{receipt:e.receipt,declaredFields:n}:null}async function Tb(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(s=>s.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Dm(e.itemPath),r=[];for(let s of t){let a=await Cb({receipt:s,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});a&&r.push(a)}let i=new Set(r.flatMap(({declaredFields:s})=>s)),o=e.reconciliation?.reconciled_fields;return r.length>0&&(o===void 0||o.length>0&&o.every(s=>i.has(s)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:s})=>s.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function $b(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(s=>s.item_id===e.subjectId).map(s=>s.id)??[]),r=(e.options.mergeReceiptProof?await rt(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(s=>s.item_id===e.subjectId&&t.has(s.id))??[],i=e.options.mergeReceiptProof?await Tb({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(i&&!i.trusted&&e.options.dryRun!==!0&&e.options.force!==!0)throw new w(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${i.reason}).`,y.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let o=i?.trusted?r.filter(s=>i.receipt_ids.includes(s.id)):[];return{mergeReceiptProof:i,effectiveAuditContext:o.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:o.map(gi)}}:e.options.auditContext}}async function Ob(e,t,n,r){let i=e.located?.itemPath??null,o=e.located?await ut(e.located,{schema:t.schema}):null;if(!o)return{currentItemReplay:null,currentItemPath:i,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=fc(o.document),a=n[n.length-1].after_hash;return{currentItemReplay:s,currentItemPath:i,matchedChainBefore:qt(s,r).includes(a),currentItemRawBeforeLock:o.raw,loadedItem:o}}function Db(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function Pb(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=qt(e.finalReplay,e.itemHashVersion),i=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=r.indexOf(i),s=qt(n,e.itemHashVersion);return t.push({ts:T(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Pm.compare(e.finalReplay,e.currentItemReplay):[],before_hash:r[o],after_hash:s[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function Nb(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function Mb(e){return Ac({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Rc({historyPath:e.historyPath,nextHistoryRaw:yc(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>ne({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function ws(e,t,n){let r=M(process.cwd(),n.path);await X(r);let i=await C(r),o=W(i,z()),s=await Ic(r,e,i,o.type_to_folder);if(!await D(s.historyPath))throw new w(`No history stream exists for ${s.id}.`,y.NOT_FOUND);let a=await Y(s.historyPath),c=await zt(s.historyPath,s.id);if(c.length===0)throw new w(`No history entries exist for ${s.id}; nothing to repair.`,y.USAGE);let d=Zi(c),l=xr(c),u=t.normalizeProvenance?Bd(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},m=gc(u.entries),p=new Set(u.entries.map(se=>se.item_hash_version).filter(se=>se!==void 0)),f=_c(u.entries,m),h=await Ob(s,i,c,m),g=f.finalDocument,_=qt(g,m),v=!1;if(h.currentItemReplay!==null){let se=qt(h.currentItemReplay,m);v=!_.some((ae,he)=>ae===se[he])}let k=v&&h.currentItemReplay?Ab(f.entries,g,h.currentItemReplay):void 0,{mergeReceiptProof:x,effectiveAuditContext:b}=await $b({options:t,pmRoot:r,subjectId:s.id,itemReplayContext:h,reconciliation:k}),I=[f.entriesRehashed>0,f.entriesPatchRepaired>0,v,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),S=V(t.author,i.author_default),E=!!t.dryRun,A=Db({message:t.message,entriesRehashed:f.entriesRehashed,entriesPatchRepaired:f.entriesPatchRepaired,reconcileNeeded:v}),{rewrittenEntries:F,auditEntryAdded:H}=Pb({reanchorEntries:f.entries,changed:I,reconcileNeeded:v,currentItemReplay:h.currentItemReplay,finalReplay:g,author:S,message:A,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...b,provenance_normalization:u.receipt}:b,itemHashVersion:m,explicitItemHashVersion:f.explicitItemHashVersion}),O=Zi(F);if(!O.ok)throw new w(`history-repair produced an invalid rewritten chain (${O.errors.join(", ")}).`,y.GENERIC_FAILURE);let B=Nb(I,f.skippedOps,k);return I&&!E&&B.push(...await Mb({pmRoot:r,subject:s,settings:i,typeRegistry:o,historyRawBeforeLock:a,currentItemRawBeforeLock:h.currentItemRawBeforeLock,author:S,force:t.force,loadedItem:h.loadedItem,historyPath:s.historyPath,rewrittenEntries:F})),{id:s.id,dry_run:E,changed:I,history:{path:s.historyPath,entries_scanned:c.length,chain_drift_before:!d.ok,entries_rehashed:f.entriesRehashed,entries_patch_repaired:f.entriesPatchRepaired,converted_replace_to_add:f.convertedReplaceToAdd,skipped_ops:f.skippedOps,reconciled_with_item:v,audit_entry_added:H,verify_ok:O.ok,verify_errors:O.errors,item_hash_version_before:l.item_hash_version??null,item_hash_version_after:m,version_disposition:p.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:h.currentItemPath!==null,path:h.currentItemPath,matched_chain_before:h.matchedChainBefore},provenance_normalization:{requested:t.normalizeProvenance===!0,...u.receipt},...k?{reconciliation:k}:{},...x?{merge_receipt_proof:x}:{},warnings:[...new Set(B)].sort((se,ae)=>se.localeCompare(ae)),generated_at:T()}}function vD(e,t){if(t&&e!==void 0)throw new w("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",y.USAGE);if(!t&&e===void 0)throw new w("history-repair: provide an item <id> or pass --all to repair every drifted stream.",y.USAGE)}async function bD(e,t){let n=M(process.cwd(),t.path);await X(n);let r=await C(n),i=W(r,z()),o=[],s=await kt(n,r.item_format,i.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await Rt(n,s),c=e.normalizeProvenance?await Gd(n):[],d=[...new Set([...a.driftedItems,...c])].sort((p,f)=>p.localeCompare(f)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let p of d)try{let f=await ws(p,{...e,auditContext:e.auditContextById?.[p],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[p]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=f.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...f.warnings.map(g=>`${p}:${g}`)),l.push({id:p,outcome:h,entries_rehashed:f.history.entries_rehashed,entries_patch_repaired:f.history.entries_patch_repaired,reconciled_with_item:f.history.reconciled_with_item,...f.reconciliation?{reconciliation:f.reconciliation}:{},...f.merge_receipt_proof?{merge_receipt_proof:f.merge_receipt_proof}:{},warnings:f.warnings})}catch(f){m.failed+=1,l.push({id:p,outcome:"failed",error:f instanceof Error?f.message:String(f)})}return e.dryRun||await mc(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:s.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...o,...u])].sort((p,f)=>p.localeCompare(f)),generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="76693c03-9395-5bbf-bcc8-fa15e408f30f")}catch{}})();var Lb=new Set(Qc),Mm=25,ln=8,Vn=100,Fb=_e.join("runtime","telemetry","events.jsonl"),jb=_e.join("runtime","telemetry","state.json"),Ub=2500,zb=500,Lm=Zc-3,Wb=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Es(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Rs(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function un(e){return e.trim().toLowerCase()}function ks(e,t){let n=un(e),r=un(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function As(e){try{return(await it.stat(e)).isDirectory()}catch{return!1}}async function qb(e){let t=(await it.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>it.readdir(_e.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>bn.some(o=>i.name.endsWith(o))).map(i=>_e.parse(i.name).name)))}async function Hb(e,t,n,r){let i=await Ve({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:i,overThreshold:!1,classification:"live"};let s;try{s=await it.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(o){let d=s.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?s.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function Bb(e,t,n){let r=_e.join(e,"history");if(!await As(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await it.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),s=t.enabled?t.max_entries:null,a=[],c=[],d=[],l=[];for(let u of i){let m=_e.join(r,u),p=u.slice(0,-6),f=await Hb(m,p,t,n);a.push(...f.warnings),f.classification==="tombstone"&&d.push(p),f.classification==="orphaned"&&l.push(p),f.overThreshold&&c.push(p)}return{count:i.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:s,tombstones:d,orphaned:l}}function xs(e,t){return _e.relative(e,t).replaceAll("\\","/")}async function Fm(e,t){let n=[...new Set(Object.values(t))].sort((i,o)=>i.localeCompare(o)),r=[];for(let i of n){let o=_e.join(e,i),s=[];try{s=await it.readdir(o)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&U(a))continue;continue}for(let a of s)bn.some(c=>a.toLowerCase().endsWith(c))&&r.push(_e.join(o,a))}return r.sort((i,o)=>xs(e,i).localeCompare(xs(e,o))),r}function Gb(e){return!(typeof e=="object"&&e!==null&&"code"in e&&U(e))}async function Jb(e,t,n){let r=await Fm(e,t),i=[],o=[],s=[],a=[],c=Ot(z());for(let d of r){let l=xs(e,d),u;try{u=await it.readFile(d,"utf8")}catch{i.push(l);continue}let m=jt(u);if(m){o.push({path:l,...m});continue}try{let p=Ut(u,{format:Aa(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:vr(p.metadata)})}catch{s.push(l)}}return{paths:r,unreadable:i,conflictMarkers:o,parseFailures:s,formatVersions:a}}async function Vb(e){let t=_e.join(e,"history"),n=[],r=[],i=[],o=[];try{o=(await it.readdir(t)).filter(s=>s.endsWith(".jsonl")).sort((s,a)=>s.localeCompare(a))}catch(s){Gb(s)&&n.push("history")}for(let s of o){let a=s.slice(0,-6),c;try{c=await it.readFile(_e.join(t,s),"utf8")}catch{n.push(a);continue}let d=jt(c);if(d){r.push({id:a,...d});continue}c.split(/\r?\n/).forEach((l,u)=>{if(l.trim())try{JSON.parse(l)}catch{i.push({id:a,line:u+1})}})}return{files:o,unreadable:n,conflictMarkers:r,invalidJson:i}}function jm(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}function Kb(e){return e===0?[]:[`merge_receipt_evidence_invalid:${e}`]}async function Yb(e,t,n,r,i){let o=await Jb(e,t,n),s=await Vb(e),a=br(o.formatVersions),c=Ie(n),d=Pr(i,b=>uc(b,c),En()),l=await fi(e),u=await Ze(e),m=u===null?null:await tn(u),p=await rt(u??e,{includeLossless:!0,pmRoot:e}),f=p.receipts,{pendingDecisions:h,lossless:g}=cn(f),_=m?.status==="missing"&&m.missing_keys.length===5&&m.drifted_keys.length===0,v=[...o.unreadable.map(b=>`integrity_item_unreadable:${b}`),...o.conflictMarkers.map(b=>`integrity_item_conflict_marker:${b.path}:L${b.line}`),...o.parseFailures.map(b=>`integrity_item_parse_failed:${b}`),...s.unreadable.map(b=>`integrity_history_unreadable:${b}`),...s.conflictMarkers.map(b=>`integrity_history_conflict_marker:${b.id}:L${b.line}`),...s.invalidJson.map(b=>`integrity_history_invalid_json:${b.id}:L${b.line}`),...a.outdated.map(b=>`integrity_item_outdated_format_version:${b}`),...a.ahead.map(b=>`integrity_item_ahead_format_version:${b}`),...jm(d),...l.tracked_path_count>0?[`tracked_runtime_cache_files:${l.tracked_path_count}`]:[],...m!==null&&m.status!=="ok"?[`merge_driver_configuration_${_?"missing":"drift"}:${m.missing_keys.length+m.drifted_keys.length}`]:[],...h.length>0?[`merge_decisions_unreviewed:${h.length}`]:[],...g.length>0?[`merge_receipts_pending:${g.length}`]:[],...Kb(p.invalid_evidence_count)],k=[...new Set(v)].sort((b,I)=>b.localeCompare(I)),x=k.filter(b=>!b.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:x.length===0?"ok":"warn",ok:x.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:s.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:s.unreadable.length,history_conflict_markers:s.conflictMarkers.length,history_invalid_json:s.invalidJson.length,item_outdated_format_version:a.outdated.length,item_ahead_format_version:a.ahead.length,hierarchy_cycles:d.cycles.length,hierarchy_cardinality_violations:d.cardinality_violations.length,hierarchy_parent_divergences:d.divergences.length,tracked_runtime_cache_files:l.tracked_path_count,merge_driver_configuration:m===null||m.status==="ok"?0:m.missing_keys.length+m.drifted_keys.length,pending_merge_decisions:h.length,lossless_merge_receipts:g.length,invalid_merge_receipt_evidence:p.invalid_evidence_count},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:a.outdated,item_ahead_format_version:a.ahead,hierarchy_integrity:{...d,relations:Ge(d.relations,ln)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.invalidJson,tracked_runtime_cache:{tracker_relative_root:l.tracker_relative_root,tracked_paths:l.tracked_paths,tracked_path_count:l.tracked_path_count,remediation_command:l.remediation_command},merge_driver_configuration:m===null?null:{...m,required:r},pending_merge_decision_items:[...new Set(h.map(b=>b.item_id))].sort((b,I)=>b.localeCompare(I)),lossless_merge_receipt_items:[...new Set(g.map(b=>b.item_id))].sort((b,I)=>b.localeCompare(I))}},warnings:k,gitWorkspaceRoot:u,pendingMergeReceipts:f}}function Xb(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function Zb(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:Xb(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Qb(e,t){let n=Z(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function ek(e){let n=Z(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function tk(e){return Z(e.reason)??Z(e.error)??Z(e.message)}function vs(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function nk(e){let t=[],n=[],r=[];e.forEach((o,s)=>{let a=Qb(o.definition,s),c=ek(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:a,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:a,status:c,reason:tk(o.definition)});return}n.push({layer:o.layer,name:o.name,id:a,status:c})}),t.sort(vs),n.sort(vs),r.sort(vs);let i=[...r.map(o=>`extension_migration_failed:${o.layer}:${o.name}:${o.id}`),...n.map(o=>`extension_migration_pending:${o.layer}:${o.name}:${o.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function Um(e,t,n,r,i,o,s,a,c){let d=[...new Set(e)].sort((g,_)=>g.localeCompare(_)),l=[...new Set(d.map(g=>Rs(g)))].sort((g,_)=>g.localeCompare(_)),u=d.filter(g=>g.startsWith("extension_capability_unknown:")).length,m=c.length>0,p=m?"partial":"full",f=[],h=ts(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&f.push(h),t>0&&f.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&f.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&f.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&f.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&f.push(`Unknown extension capabilities detected. Allowed capabilities: ${ar.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(g=>g.startsWith("extension_capability_legacy_alias:"))&&f.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(g=>g.startsWith("extension_command_definition_legacy_handler_alias:"))&&f.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?f.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):s.length>0&&f.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),f.length===0&&f.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:o,unmanaged_loaded_extension_count:s.length,unmanaged_loaded_extensions:s,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:p,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:f}}async function rk(e,t,n){let r=await as(Me(e)),i=await Le({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),o=i.loaded.map(S=>Zb(S)),s=await Id(i.loaded,Me(e)),a=await Fe({...i,loaded:i.loaded}),[c,d]=await Promise.all([ge(i.roots.project),ge(i.roots.global)]);await ss(e,a.registrations.migrations);let l=nk(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},m=new Set(c.state.entries.map(S=>un(S.name))),p=new Set(d.state.entries.map(S=>un(S.name))),f=[...new Map(i.loaded.filter(S=>!(S.layer==="project"?m:p).has(un(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,E)=>{let A=`${S.layer}:${S.name}`,F=`${E.layer}:${E.name}`;return A.localeCompare(F)}),h=f.map(S=>`${S.layer}:${S.name}`).sort((S,E)=>S.localeCompare(E)),g=f.filter(S=>ks(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,E)=>S.localeCompare(E)),_=f.filter(S=>!ks(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,E)=>S.localeCompare(E)),v=_.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${_.length}`]:[],k=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...s.warnings],x=Hn(k),b=Bn(),I=Um(k,i.failed.length,a.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,g,_);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...i,loaded:o,warnings:k,activation:u,author_manifest:r,triage:I,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:b,capability_guidance:x,host_version_census:s}},warnings:k}}function ik(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Ge(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function ok(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function _i(e,t){let n=Ge(e,t);return{...n,sample:n.sample.map(r=>ok(r))}}function q(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function sk(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var ak={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:q(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:q(e.missing_required,t),missing_optional:q(e.missing_optional,t),missing:q(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:q(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:_i(e.discovered,t),effective:_i(e.effective,t),loaded:_i(e.loaded,t),failed:Ge(e.failed,t),warnings:q(e.warnings,t),activation:{failed:Ge(n.failed,t),warnings:q(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:sk(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Ge(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:q(n.affected_item_ids,t),samples:Ge(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:q(e.item_unreadable,t),item_conflict_markers:Ge(e.item_conflict_markers,t),item_parse_failures:q(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:q(n.tracked_paths,t)},history_unreadable:q(e.history_unreadable,t),history_conflict_markers:Ge(e.history_conflict_markers,t),history_invalid_json:Ge(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:q(n.candidate_items,t),confirmed_items:q(n.confirmed_items,t),resolved_false_positive_items:q(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:q(e.drifted_items,t),merge_receipt_attributed_items:q(e.merge_receipt_attributed_items,t),missing_streams:q(e.missing_streams,t),unreadable_streams:q(e.unreadable_streams,t),hash_mismatches:q(e.hash_mismatches,t),chain_mismatches:q(e.chain_mismatches,t),version_skews:q(e.version_skews,t),workspace_state_mismatches:q(e.workspace_state_mismatches,t),workspace_state_missing:q(e.workspace_state_missing,t),workspace_state_unreadable:q(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:q(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:q(e.stale_items_after,t),skipped:e.skipped})};function zm(e,t){let n=ak[e.name];return n?n(e.details,t):e.details}function ck(e){let t=q(e.warnings,ln);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:zm(n,ln)})),warnings:t.sample,findings:e.findings.filter(n=>t.sample.includes(n.warning)||e.failed_because.includes(n.warning)),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:ln},generated_at:e.generated_at}}function Nm(e){return e.details.skipped===!0}function dk(e){let t=q(e.warnings,ln),n=e.checks.filter(Nm).map(r=>r.name);return{ok:e.ok,checks:e.checks.filter(r=>!Nm(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:e.findings.filter(r=>t.sample.includes(r.warning)||e.failed_because.includes(r.warning)),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:ln,omitted_checks:n},generated_at:e.generated_at}}function Ss(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ik(e,Mm);return{values:n.values,truncated:n.truncated,total:e.length}}function dn(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function lk(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return Lb.has(e)?e:null}function yi(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function Wm(e){let t=0,n=0,r=0,i=0,o=0;for(let s of e.split(`
41
- `)){let a=s.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,o=Math.max(o,d),d>=Lm&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:o}}function uk(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function mk(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function pk(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await qm(n)}}function fk(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,o=n.last_failed_flush_at,s=o&&(!i||o>i),a=!i,c=t.validEntries>=zb;return(s||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function hk(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function gk(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Xc?[`telemetry_schema_version_behind:${t}`]:[]}function _k(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function yk(){return{telemetry_disabled:dn("PM_TELEMETRY_DISABLED")||dn("PM_NO_TELEMETRY"),pm_no_telemetry:dn("PM_NO_TELEMETRY"),telemetry_otel_disabled:dn("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:dn("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:lk()}}function wk(e,t){return e.telemetry.enabled&&t.validEntries>0}function vk(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function qm(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(Ub)});return{probe_url:yi(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of Wb){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:yi(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function bk(e,t){let n=lr(process.cwd()),r=_e.join(n,Fb),i=_e.join(n,jb),o=await Y(r),s=o!==null,a=o?Buffer.byteLength(o,"utf8"):0,c=o?Wm(o):uk(),d=await Y(i),{runtimeState:l,stateParseFailed:u}=mk(d),m=e.telemetry.endpoint.trim(),p=yi(m),f=await pk(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...fk(e,c,l),...hk(f),...gk(f),..._k(e,l));let g=wk(e,c),_=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:p,global_pm_root:n,queue_path:r,queue_exists:s,queue_entries:c.validEntries,queue_draining:vk(g,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:a,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Lm,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:_,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:f??{attempted:!1},env_overrides:yk()}},warnings:h}}async function kk(e){let t;try{t=await nl(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function xk(e){let t="metadata",n=e.items,r=await Rt(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((_,v)=>_.localeCompare(v)),o=[],s=[];if(i.length>0){n=await kt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Rt(e.pmRoot,n),o=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,k)=>v.localeCompare(k));let _=new Set(o);s=i.filter(v=>!_.has(v))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:p,workspaceStateMissing:f,workspaceStateUnreadable:h}=r,g=[...a.map(_=>`history_drift_missing_stream:${_}`),...c.map(_=>`history_drift_unreadable_stream:${_}`),...d.map(_=>`history_drift_hash_mismatch:${_}`),...l.map(_=>`history_drift_chain_mismatch:${_}`),...u.map(_=>`history_drift_version_skew:${_}`),...p.map(_=>`history_drift_workspace_state_mismatch:${_}`),...f.map(_=>`history_drift_workspace_state_missing:${_}`),...h.map(_=>`history_drift_workspace_state_unreadable:${_}`)];return{check:{name:"history_drift",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:o,resolved_false_positive_items:s,authoritative_item_source:i.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:p.length,workspace_state_missing:f.length,workspace_state_unreadable:h.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:p,workspace_state_missing:f,workspace_state_unreadable:h}},warnings:g}}function Sk(e,t){let n=Or(e),r=Sn(n.settings),i=Dr(n.settings,t),o=r.active?St(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(r.active&&i.active)}}function Ek(){return{refreshed:[],skipped:[],warnings:[]}}async function Rk(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?Ek():Vc(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function Ak(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Gt(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function Ik(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function Ck(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Hm(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:no(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:no(r,e.vector_store?.adapter??null)}}function Tk(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function $k(e,t,n){return e.enabled&&n.length>0&&t}async function Ok(e,t,n,r,i){let o=Sk(t,e),s=await Jt(e),a=o.semanticRuntimeAvailable?oo(n,s.entries):[],c=await Rk({pmRoot:e,snapshot:o,refreshPolicy:r,staleBefore:a}),d=await Jt(e),l=o.semanticRuntimeAvailable?oo(n,d.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,m=Ak({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:s,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),p=Ik({ledgerBefore:s,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),f=Ss(a,i),h=Ss(l,i),g=$k(r,o.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:p.length===0?"ok":"warn",ok:p.length===0,details:{semantic_runtime_available:o.semanticRuntimeAvailable,compatibility_mode_auto_defaults:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:o.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:o.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:Tk(r),...Hm(t,o),embedding_identity_changed:m,embedding_identity_before:s.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(s.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Mm,stale_items_before_total:f.total,stale_items_before:f.values,stale_items_before_truncated:f.truncated,refresh_attempted:g,refresh_skipped_reason:Ck(r,o.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:p}}function Dk(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function Bm(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new w("--check-only cannot be combined with --refresh-vectors",y.USAGE);if(n&&e.noRefresh===!0)throw new w("--no-refresh cannot be combined with --refresh-vectors",y.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var Pk=new Set(["extensions","locks","search"]);function Nk(e){let t=new Set(va.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(ba));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of Pk)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,o)=>i.localeCompare(o)),optionalDirs:[...n].sort((i,o)=>i.localeCompare(o)),optionalDirSet:n}}async function Mk(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:o}=Nk(t),s=[],a=[],c=[];for(let d of[...r,...i]){let l=_e.join(e,d);c.push(...await Ve({path:l,scope:"project"})),!await As(l)&&(o.has(d)?a.push(d):s.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:s,missingOptionalDirs:a,missingDirs:n?[...s,...a]:[...s],hookWarnings:c}}function Gm(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function Lk(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Ke(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):kt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function bs(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function Fk(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function jk(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function Uk(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var Is=e=>e.unknown_event_count??0,Cs=e=>e.actionable_unknown_event_count??Is(e);function zk(e,t,n,r,i,o,s){let a=Is(r),c=Cs(r),d=a>0,l=c>0,u=i.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...d?{author_attribution:r}:{},...u?{stale_in_progress:i}:{},...o.length>0?{provenance_resolver_outcomes:o}:{},...s.length>0?{provenance_invalid_values:s}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Jm(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function Wk(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function qk(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function Hk(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.over_threshold.map(t=>`history_stream_over_compact_threshold:${t}`),...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function Vm(e){let t=new Map;for(let[i,o]of Object.entries(e.remediationSources))for(let s of o)t.has(s)||t.set(s,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let o=t.get(i)??"integrity",s=Eo(i)?.code??Rs(i),a=n.get(o)?.details,d=(typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{})[s],l=Es(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:s,check:o,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function Bk(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function Gk(e){for(let t of e.checks){let n=Ro(e.remediationSources[t.name]);Bk({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function Jk(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(s=>typeof s=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(s=>Array.isArray(s)?s:[])),i=new Map;for(let s of e.pendingMergeReceipts){if(s.evidence_source!=="clone_local")continue;let a=i.get(s.item_id)??[];a.push(s),i.set(s.item_id,a)}let o=[];for(let s of n){if(r.has(s))continue;let a=i.get(s);if(!(!a||a.length===0))try{(await ws(s,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global)).merge_receipt_proof?.trusted&&o.push(s)}catch{}}return[...new Set(o)].sort((s,a)=>s.localeCompare(a))}function Vk(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}function Km(e,t,n){let r=e.warning_count??e.warnings.length,i={...e,warning_count:r,warning_limit:Vn,warnings_truncated:r>Vn,warnings:e.warnings.slice(0,Vn),findings:(e.findings??[]).filter(s=>e.warnings.slice(0,Vn).includes(s.warning)||e.failed_because.includes(s.warning))},o=n?dk(i):t.brief===!0?ck(i):i;return{...o,warning_count:r,warning_limit:Vn,warnings_truncated:r>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:r,warnings_truncated:r>o.warnings.length}}:{}}}async function Ym(e,t={}){let n=M(process.cwd(),e.path);await X(n);let r=bt(n),{settings:i,warnings:o}=await bc(n),s=[...new Set(o)],a=W(i,z()),c=t.strictDirectories===!0,d=Bm(t),l=await Mk(n,a,c),u=Dk(i),m=await bk(i,{checkTelemetry:t.checkTelemetry===!0}),p=await rk(n,i,!!e.noExtensions),f=Gm(t),h=[],g=await Lk({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:f,itemReadWarnings:h}),_=g,v=Gr(Ie(i.schema),g),k=[...u,...Jr(v)],x=f.skipDrift?{warnings:[]}:await kc({pmRoot:n,settings:i,itemIds:g.map(Ui=>Ui.id),commandLabel:"health"}),b=await Bb(n,i.history.compact_policy,await qb(n)),I=await On(n,20,t.verboseAuthorEvents===!0),S=Cs(I),E=S>0?[`history_unknown_author_events:${S}`]:[],A=Jm(await Kc(n,g,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),F=await Kd(n),H=F.outcomes,O=F.invalid_values,B=F.warnings,se=await kk(n),ae=f.skipIntegrity?{...bs("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await Yb(n,a.type_to_folder,i.schema,t.requireMergeDrivers===!0,g),he=f.skipDrift?bs("history_drift"):await xk({pmRoot:n,items:_,settings:i,typeRegistry:a,itemReadWarnings:h}),vt=[...new Set(h)],wn=await Jk({gitWorkspaceRoot:ae.gitWorkspaceRoot,pendingMergeReceipts:ae.pendingMergeReceipts,historyDriftCheck:he,global:e});Vk(he,wn);let j=f.skipVectors?bs("vectorization"):await Ok(n,i,_,d,t.verboseStaleItems===!0),G=[Fk(r,i,s),jk(l,c),Uk(k,v),m.check,p.check,zk(g,i,b,I,A.scan,H,O),se.check,ae.check,he.check,j.check],or=Wk({directoryState:l,normalizedSettingsReadWarnings:s,settingWarnings:k,normalizedItemReadWarnings:vt,telemetryCheck:m,extensionCheck:p,historyPolicyWarnings:x.warnings,historySummary:b,authorAttributionWarnings:E,staleInProgressWarnings:A.warnings,provenanceWarnings:B,locksCheck:se,integrityCheck:ae,historyDriftCheck:he,vectorizationCheck:j}),sr=Hk({directoryState:l,normalizedSettingsReadWarnings:s,settingWarnings:k,normalizedItemReadWarnings:vt,telemetryCheck:m,extensionCheck:p,historyPolicyWarnings:x.warnings,historySummary:b,authorAttributionWarnings:E,staleInProgressWarnings:A.warnings,provenanceWarnings:B,locksCheck:se,integrityCheck:ae,historyDriftCheck:he,vectorizationCheck:j});Gk({checks:G,remediationSources:sr,historyDriftedCount:qk(he),overThresholdCount:b.over_threshold.length});let ha=or.filter(Ui=>!Es(Ui,t.requireMergeDrivers===!0)),Vf=Vm({warnings:or,checks:G,remediationSources:sr,requireMergeDrivers:t.requireMergeDrivers===!0}),Kf={ok:ha.length===0,checks:G,warnings:or,findings:Vf,failed_because:ha,generated_at:T()};return Km(Kf,t,f.summaryMode)}var hP={buildHierarchyIntegrityWarnings:jm,buildExtensionHealthTriageSummary:Um,buildHealthFindings:Vm,buildCapabilityContractMetadata:Bn,buildStaleInProgressHealthSummary:Jm,buildVectorizationProviderDetails:Hm,collectUnknownCapabilityGuidance:Hn,isAdvisoryHealthWarning:Es,isDirectory:As,isExpectedUnmanagedExtension:ks,listItemDocumentPaths:Fm,normalizeEndpointForDisplay:yi,normalizeExtensionNameForMatch:un,parseTelemetryQueue:Wm,probeTelemetryEndpointHealth:qm,projectHealthResult:Km,resolveActionableUnknownAuthorEventCount:Cs,resolveHealthSkipPolicy:Gm,resolveUnknownAuthorEventCount:Is,resolveVectorRefreshPolicy:Bm,selectStaleItemDetail:Ss,summarizeHealthCheckDetails:zm,summarizeExtensionList:_i,summarizeRecordList:Ge,summarizeStringList:q,telemetryEnvFlagEnabled:dn,warningCode:Rs};import mn from"node:fs/promises";import pn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function Kk(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let o;try{o=await mn.readdir(pn.join(e,i))}catch{return}for(let s of o)for(let a of bn)if(s.toLowerCase().endsWith(a)){r.push({relativePath:`${i}/${s}`,id:s.slice(0,-a.length)});break}})),r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath))}function Yk(e,t){let{id:n,relativePath:r,liveItemIds:i,out:o}=e,s=jt(t);if(s){o.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=null,c=t.split(/\r?\n/).map((d,l)=>({content:d.trim(),number:l+1})).filter(d=>d.content.length>0);for(let d of c)try{let l=JSON.parse(d.content);if(typeof l!="object"||l===null||Array.isArray(l))throw new TypeError("history entry must be an object");a=l}catch{o.unparseable.push({id:n,path:r,line:d.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&i.has(n)&&o.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(o.repairReconciliations+=1))}function Ts(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function Xk(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await mn.readdir(pn.join(e,"history"))}catch{return n}for(let i of r.sort((o,s)=>o.localeCompare(s))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await mn.readFile(pn.join(e,"history",i),"utf8")}catch(s){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Ts("history stream",s)});continue}Yk({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},o)}return n}function Xm(e){let t=jt(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function Zk(e){let t=[],n=0,r=null;try{r=await Y(bt(e))}catch(o){n+=1,t.push({path:"settings.json",detail:Ts("configuration file",o)})}if(r!==null){n+=1;let o=Xm(r);o!==null&&t.push({path:"settings.json",detail:o})}let i;try{i=await mn.readdir(pn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of i.sort((s,a)=>s.localeCompare(a))){if(!o.endsWith(".json"))continue;n+=1;let s;try{s=await mn.readFile(pn.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:Ts("configuration file",c)});continue}let a=Xm(s);a!==null&&t.push({path:`schema/${o}`,detail:a})}return{scanned:n,unparseable:t}}async function Zm(e,t,n,r={}){let i=await Kk(e,n),o=new Set(i.map(u=>u.id)),s=new Map;for(let u of i){let m=s.get(u.id);m===void 0?s.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((p,f)=>p.localeCompare(f))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=pn.join(e,u.relativePath);return Ut(await mn.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await Xk(e,o),l=await Zk(e);return{item_files_on_disk:i.length,item_ids_on_disk:o.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import{execFile as Qk}from"node:child_process";import Qm from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b8b3f729-be32-5a77-b08f-f616ee068e0f")}catch{}})();function ep(e,t){return new Promise((n,r)=>{Qk("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,o)=>{i?r(i):n(o)})})}function tp(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 AP(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(tp(n),!n)throw new RangeError("Source line range must use start:end.");return n}function ex(e){let t=new Map;for(let n of e.split(`
42
- `)){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 tx(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 nx(e){let t=Qm.relative(e.workspaceRoot,Qm.resolve(e.workspaceRoot,e.sourcePath)),n=await ep(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await ep(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:ex(n),commitItems:tx(r),available:!0}}function rx(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 ix(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=rx({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 ox(e,t,n){let r=td(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=ix({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 sx(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await nx({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function ax(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 cx(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function np(e){tp(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 sx(e),r=cx(n),i=new Map;for(let o of e.candidates){let s=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(o.item.id)),a=s.reduce((l,[,u])=>l+u,0),c=ox(o.item.id,e.corpus,t),d=ax({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(l=>({kind:"linked_file",reference:l.path})),...s.map(([l,u])=>({kind:"git_commit",reference:l.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:d})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}import Qs from"node:fs/promises";import{realpathSync as bS}from"node:fs";import{execFile as kS}from"node:child_process";import ye from"node:path";import{promisify as xS}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var dx=["metadata","resolution"],$s=["metadata","resolution","estimates","lifecycle"],lx="completed";function Os(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function rp(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function ip(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=rp(n.close_reason)??lx;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Os(r)}`,gate:"resolution"})}return t}function op(e){let t=[];for(let n of e){let r=rp(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${Os(r)}`,gate:"metadata"})}return t}function sp(e,t){return e.map(n=>{let r=vc(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function ap(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function cp(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${Os(n.path)}`})}return t}function dp(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new w(`--fix-scope values must not be empty. Supported values: ${$s.join(", ")}.`,y.USAGE);return new Set(dx)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if($s.includes(i)){n.add(i);continue}throw new w(`Unknown --fix-scope value "${r}". Supported values: ${$s.join(", ")}.`,y.USAGE)}return n}function lp(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function Kn(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a7fbaf1-917f-5067-b9b6-a9f27c80e291")}catch{}})();var ux=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function mx(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=ux.exec(n);if(!r)return null;let i=r[1],o=i.toUpperCase(),s=i.slice(0,i.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(m=>m.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${o}`)||d.includes(`ISSUE CODE \`${o}\``)||d.includes(`\`${o}\``)||d.includes(`[${o}]`);return s===s.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(s.toUpperCase())||l?o:null}function up(e){return typeof e=="string"&&e.trim().length>0}function mp(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||up(i.duplicate_of))continue;let o=mx(i.title,{...t,evidenceText:i.body});if(o===null)continue;let s=n.get(o);s||(s=[],n.set(o,s)),s.some(a=>a.id===i.id)||s.push({id:i.id,title:i.title,parent:up(i.parent)?i.parent.trim():null})}let r=[];for(let[i,o]of n){if(o.length<2)continue;let s=new Set(o.map(d=>d.id.toLowerCase())),a=o.filter(d=>d.parent===null||!s.has(d.parent.toLowerCase()));if(a.length<2)continue;let c=[...a].sort((d,l)=>d.id.localeCompare(l.id));r.push({code:i,count:c.length,ids:c.map(d=>d.id),titles:c.map(d=>d.title)})}return r.sort((i,o)=>i.code.localeCompare(o.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function pp(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,o)=>i.localeCompare(o))){let i=t.get(r),o={};for(let s of[...i.keys()].sort((a,c)=>a.localeCompare(c)))o[s]=i.get(s);n[r]=o}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var fp=3;function hp(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function gp(e,t,n=fp){let r=Number.isFinite(n)&&n>=1?Math.floor(n):fp,i=new Map;for(let o of t){let s=hp(o);if(s.length===0)continue;let a=i.get(s);a?a.push(o):i.set(s,[o])}return e.map(o=>{let s=(i.get(hp(o))??[]).filter(a=>a!==o).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:o,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:o,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function _p(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var px=/^[a-z][a-z0-9+.-]+:\/\//i;function Yn(e){return px.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function fx(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function yp(e){return`${e.item_id} ${e.link_kind}`}function wp(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=fx(i.classification,r.classification),i.owners.set(yp(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[yp(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(o=>{let s=t(o.item_id);return{id:o.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:o.link_kind}}).sort((o,s)=>{let a=o.id.localeCompare(s.id);return a!==0?a:o.field.localeCompare(s.field)})}))}function hx(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function vp(e){let t=[];for(let n of e)for(let r of n.items)t.push(`${n.path}:${n.classification} owner=${r.id} status=${r.status} field=${r.field} title="${hx(r.title)}"`);return t}import gx from"node:fs/promises";import $e from"node:path";import _x from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accd0229-6974-5950-8cea-74f517706878")}catch{}})();var yx=["path","scope","note"],wx=["pattern","glob","path","scope","note"],vx=["path"],bx=["from","to"],kx=new Set(["note","scope"]);function kp(e){let t=e??"project";if(!zi.includes(t))throw new w(`Invalid scope "${e}". Valid scopes: ${zi.join(", ")} (default: project).`,y.USAGE);return t}function Ds(e){if(e.startsWith("```")||e.includes(`
43
- `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||Oc(e)}function xx(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function Sx(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Ds(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let o=e.slice(t+2,-1).trim();if(o.length>0&&xx(o))return{path:o,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function Ex(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let o=Sx(r);if(o!==void 0)return[o]}Dc(r,"--add",`${t} path`,Ds(r));let i=Ds(r)?kn(n,"--add"):{path:r};if(xn(i,"--add",yx),!i.path)throw new w(`--add requires path=<value> or a bare ${t} path`,y.USAGE);return[{path:i.path,scope:kp(i.scope),note:i.note?.trim()||void 0}]}):[]}function Rx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new w("--add-glob requires a glob pattern value",y.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=kn(n,"--add-glob");xn(r,"--add-glob",wx);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new w("--add-glob key/value form requires pattern=<glob>",y.USAGE);return{pattern:i,scope:kp(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Ax(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new w("--remove requires a path value",y.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=kn(n,"--remove"),i=Object.keys(r).filter(o=>kx.has(o.toLowerCase()));if(i.length>0)throw new w(`--remove identifies a linked artifact by path only and does not accept ${i.map(o=>`"${o}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,y.USAGE);if(xn(r,"--remove",vx),!r.path)throw new w("--remove key/value form requires path=<value>",y.USAGE);return r.path}return n}):[]}function Ix(e){return e?e.map(t=>{let n=kn(t,"--migrate");xn(n,"--migrate",bx);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new w("--migrate requires from=<value> and to=<value>",y.USAGE);return{from:r,to:i}}):[]}function Xn(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function Cx(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(o=>Xn(o.path,n))),i=[...new Set(t.map(o=>Xn(o,n)).filter(o=>r.has(o)))].sort((o,s)=>o.localeCompare(s));if(i.length!==0)throw new w(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,y.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function ot(e){return e.split($e.sep).join("/")}function Ps(e,t,n=process.cwd()){let r=e.trim();if(Yn(r))return r;if($e.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return ot(r.replaceAll("\\",$e.sep));let i=$e.relative(t,n);return i.startsWith(`..${$e.sep}`)||i===".."||$e.isAbsolute(i)?ot($e.normalize(r)):ot($e.relative(t,$e.resolve(n,r)))}async function Tx(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){let o=$e.isAbsolute(i.pattern),s=await _x(i.pattern,{cwd:n,absolute:o,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>Ps(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of a)r.push({path:c,scope:i.scope,note:i.note})}return r}function $x(e,t,n){if(t===void 0)return e;if(!n)throw new w("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",y.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function Ox(e){return`${e.path}::${e.scope}`}function Ns(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function Ms(e){return[...new Map(e.map(t=>[Ox(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function Dx(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],i=[],o=[],s=[];for(let a of n){if(Yn(a)){s.push(a.trim());continue}let c=$e.isAbsolute(a)?a:$e.resolve(t,a);try{(await gx.stat(c)).isFile()?r.push(a):o.push(a)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&ct(d)){i.push(a);continue}o.push(a)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:o,remote_references:s}}function Px(e,t,n,r){let i=0;for(let s=0;s<e.length;s+=1){let a=Xn(e[s].path,r);a!==e[s].path&&(e[s]={...e[s],path:a},i+=1)}return{adds:t.map(s=>{let a=Xn(s.path,r);return a!==s.path&&(i+=1),{...s,path:a}}),removes:n.map(s=>Xn(s,r)),count:i}}function Nx(e,t,n,r){for(let o of t)e.some(s=>s.path===o.path&&s.scope===o.scope)||e.push(o);if(n.length>0)for(let o=e.length-1;o>=0;o-=1)n.includes(e[o].path)&&e.splice(o,1);let i=Ms(e);return r?i:Ns(i)}async function bp(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await Dx(t,e.workspaceRoot):void 0}}async function wi(e,t,n,r){let{metadataKey:i}=r,o=Mc(),s=M(process.cwd(),n.path),a=Me(s),c=process.cwd();await X(s);let d=await C(s),l=W(d,z()),u=await o.resolveList(t.add,"--add"),m=await o.resolveList(t.addGlob,"--add-glob"),p=await o.resolveList(t.remove,"--remove"),f=await o.resolveList(t.migrate,"--migrate"),h=Ex(u,r.bareNoun).map(H=>({...H,path:Ps(H.path,a,c)})),g=Rx(m),_=await Tx(g,a,c),v=$x([...h,..._],t.note,h.length>0||g.length>0),k=Ax(p).map(H=>Ps(H,a,c)),x=Ix(f);if(Cx(v,k,x),!(v.length>0||k.length>0||x.length>0)){let H=await Ht(s,e,d.id_prefix,d.item_format,l.type_to_folder);if(!H)throw new w(`Item ${e} not found`,y.NOT_FOUND);let B=(await ut(H,{schema:d.schema})).document.metadata[i]??[];return bp({id:H.id,artifacts:B,changed:!1,options:t,workspaceRoot:a})}let I=V(t.author,d.author_default),S=await xt({pmRoot:s,settings:d,id:e,op:r.op,author:I,message:t.message,force:t.force,skipNoop:!0,mutate(H){let O=H.metadata,B=O[i]??[],se=[...B],ae=Px(se,v,k,x),he=Nx(se,ae.adds,ae.removes,r.supportsAppendStable&&t.appendStable===!0);he.length>0?O[i]=he:delete O[i];let vt=!Pa(B,he);return{changedFields:vt?[i]:[],warnings:vt&&ae.count>0?[`path_migrations_applied:${ae.count}`]:[]}}}),E=S.item[i]??[],A=S.warnings.find(H=>H.startsWith("path_migrations_applied:")),F=A?Number(A.slice(24)):0;return bp({id:S.item.id,artifacts:E,changed:S.changedFields.includes(i),migrationsApplied:F,options:t,workspaceRoot:a})}function vi(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function xp(e,t,n){let r=await wi(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return vi(r,"docs")}import Sp from"node:fs/promises";import Oe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed504f2b-8b78-5fca-a4a7-7b0709a65533")}catch{}})();var Mx=32768;function Ls(e){return ot(Oe.normalize(e))}async function bi(e){try{return await Sp.realpath(e)}catch{return Oe.resolve(e)}}function fn(e,t){let n=Oe.isAbsolute(e.path)?Oe.resolve(e.path):Oe.resolve(t,e.path);return`${Ls(n)}::${e.scope}`}function ki(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>ki(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))ki(i,t?`${t}.${r}`:r,n)}function Lx(e){let t=[];return ki(e.metadata,"metadata",t),ki(e.body,"body",t),t}function Fx(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function jx(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let o=new Set,s=i.value.slice(0,Mx);for(let[a,c]of[[n,i.value],[r,s]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=Fx(d[0]);!l||o.has(l)||(o.add(l),t.push({field:i.field,value:l}))}}}return t}async function Ux(e,t,n=t){let r=Oe.isAbsolute(e)?Oe.resolve(e):Oe.resolve(n,e),i;try{i=await Sp.stat(r)}catch{return}if(!i.isFile())return;let[o,s]=await Promise.all([bi(t),bi(r)]);if(ve(o,s)){let a=Oe.relative(o,s);return!a||a.startsWith("..")||Oe.isAbsolute(a)?void 0:{path:Ls(a),scope:"project"}}return{path:Ls(r),scope:"global"}}async function zx(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>fn(c,t))),i=new Map,o=jx(Lx(e)),s=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{s.set(c,await Ux(c,t,n))}));let a=o.map(c=>({reference:c,resolved:s.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=fn(d,t),u=i.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function Ep(e,t,n){let r=await wi(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return vi(r,"files")}async function Wx(e,t){let n=await bi(t),r=await Promise.all(e.map(async o=>{let s=o.trim();if(!s)throw new w("Files lookup paths must not be empty.",y.USAGE);if(!Oe.isAbsolute(s))return ot(s);let a=await bi(s);return ve(n,a)?ot(Oe.relative(n,a)):ot(a)})),i=[...new Set(r)].sort((o,s)=>o.localeCompare(s));if(i.length===0)throw new w("Files lookup requires at least one path.",y.USAGE);return i}function qx(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new w(`Files lookup ${r} must be a non-negative integer.`,y.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function Rp(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Ap(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function Hx(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(ot(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(Ap)}async function Bx(e){if(e.explain)return np({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function Gx(e){if([e.strictRead,e.noTruncate,e.explain,ac()].includes(!0))return null;let t=await Cr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Sc({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function Jx(e){let t=[],n=await Bt(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=Hx({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&i.length>0)throw new w(`Files lookup could not read every item: ${i.join("; ")}`,y.GENERIC_FAILURE);let o=await Bx({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(o?[...r].sort((c,d)=>{let l=o.explanations.get(d.item.id).score-o.explanations.get(c.item.id).score;return l!==0?l:Ap(c,d)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<r.length,truncated:e.offset+a.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:Rp(c.item),files:c.files,...o?{traceability:o.explanations.get(c.item.id)}:{}})),...o?{traceability_receipt:o.receipt}:{}}}async function vN(e,t){let n=M(process.cwd(),t.path),r=Me(n);await X(n);let i=await Wx(e.paths,r);if(e.lineRange&&i.length!==1)throw new w("Files lookup line attribution requires exactly one source path.",y.USAGE);let o=await C(n),s=W(o,z()),{offset:a,limit:c}=qx(e),d=await Gx({pmRoot:n,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:a,limit:c,has_more:a+d.matches.length<d.total,truncated:a+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:Rp(l.item),files:l.files}))}:Jx({pmRoot:n,settings:o,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function bN(e,t,n){let r=M(process.cwd(),n.path),i=Me(r);await X(r);let o=await C(r),s=W(o,z()),a=await Ht(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!a)throw new w(`Item ${e} not found`,y.NOT_FOUND);let c=await ut(a,{schema:o.schema}),d=await zx(c.document,i,process.cwd()),l=d.filter(E=>E.status==="addable"),u=d.filter(E=>E.status==="already_linked"),m=t.apply===!0,p=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let E=c.document.metadata.files??[];return{id:a.id,files:E,changed:!1,apply:m,count:E.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let f=V(t.author,o.author_default),h=l.map(E=>({path:E.path,scope:E.scope,note:p})),g=[],_=new Set,v=await xt({pmRoot:r,settings:o,id:e,op:"files_discover",author:f,message:t.message??"Discover referenced file links",force:t.force,mutate(E){let A=[...E.metadata.files??[]],F=new Set(A.map(B=>fn(B,i)));g=[],_.clear();for(let[B,se]of h.entries()){let ae=fn(se,i);F.has(ae)||(A.push(se),F.add(ae),g.push(se),_.add(B))}let H=Ms(A),O=t.appendStable?H:Ns(H);return O.length>0?E.metadata.files=O:delete E.metadata.files,{changedFields:g.length>0?["files"]:[],warnings:g.length!==h.length?[`files_discover_skipped_existing:${h.length-g.length}`]:[]}}}),k=v.item.files??[],x=new Set(g.map(E=>fn(E,i))),b=k.filter(E=>x.has(fn(E,i))),I=l.filter((E,A)=>!_.has(A)),S=[...u,...I];return{id:v.item.id,files:k,changed:b.length>0,apply:!0,count:k.length,candidate_count:d.length,addable_count:l.length,added_count:b.length,skipped_existing_count:S.length,candidates:d,added:b,skipped_existing:S}}import{readFileSync as Vx}from"node:fs";import xi from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var Kx=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Fs=new Set(["--pm-path","--path","--author"]),Yx={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},Xx=new Set(["-p","--package"]),Zx=new Set(["-c","--call"]),Qx=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),eS=new Set(["-C","--prefix","--userconfig","--cache"]),EN=new Set(["--cwd"]),RN=new Set(["--cwd"]),tS=new Set(["exec","x"]),AN=new Set(["run","run-script"]),IN=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function nS(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function rS(e,t=process.cwd()){let n=iS(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...i]=n;if(Ip(r)||Cp(r,t))return i;if(r==="node"&&i[0]&&Cp(i[0],t))return i.slice(1);let o=r==="npx"||r==="bunx"?js(i):r==="pnpm"?aS(i):r==="npm"?cS(i):null;return o&&(Ip(o.command)||sS(o.command))?o.args:null}var Tp=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let o=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of nS(o)){let c=rS(a),d=c?dS(c):null,l=d&&Kx.has(d.subcommand)?lS(d.remaining,Yx[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&s.add(l)}return[...s].sort((a,c)=>a.localeCompare(c))};function iS(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function CN(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Fs.has(n)){t+=2;continue}t+=1;continue}return n}}function Ip(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function oS(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function sS(e){let t=oS(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Cp(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=xi.resolve(t,e);try{return JSON.parse(Vx(xi.join(xi.dirname(xi.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function js(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let o=i[1];return o?{command:o,args:e.slice(t+1)}:null}if(Zx.has(r)){t+=1;break}t+=Xx.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function $p(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function aS(e){let t=$p(e,Qx);return t?.subcommand!=="dlx"?null:js(t.args)}function cS(e){let t=$p(e,eS);return!t||!tS.has(t.subcommand)?null:js(t.args)}function dS(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Fs.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function lS(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Fs.has(r)||t.has(r))&&(n+=1)}}import{execFile as uS}from"node:child_process";import{readFile as mS}from"node:fs/promises";import Dp from"node:path";import{promisify as pS}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="30a61f26-5db8-50ba-af37-1990a4742ce8")}catch{}})();var fS=pS(uS),Us=1,hS="linked-test-trust.json";function zs(e){return Dp.join(Ia(e),hS)}function Op(){return{version:Us,acknowledged:{}}}async function Ws(e){try{let t=JSON.parse(await mS(zs(e),"utf8"));return t.version!==Us||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Op():{version:Us,acknowledged:t.acknowledged}}catch{return Op()}}async function qs(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await fS("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function Hs(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function gS(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&cc(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Zn(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function _S(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function jN(e,t,n){if(!e||e.length===0)return e;let r=Hs();return _S(e,t,n,await qs(r))}function Pp(e){return dt(Q({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function UN(e,t,n){let r=await Ws(e);return Np(t,n,r)}function Np(e,t,n){let r=Pp(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let o=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!gS(e.provenance)?o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Zn(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...Zn(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...Zn(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Zn(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...Zn(i,t)}}async function Mp(e,t,n){let r=await Ws(e);return t.map(i=>Np(i,n,r))}async function zN(e,t,n){let r=await Ws(e),i=t.filter(o=>typeof o.command=="string"&&o.command.length>0).map(Pp);for(let o of i)r.acknowledged[o]={acknowledged_at:n};return await vn(Dp.dirname(zs(e))),await de(zs(e),`${JSON.stringify(r,null,2)}
44
- `),{acknowledged:i.length,fingerprints:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function Si(e){return e.includeBody?kt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Bt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8bec3c39-b871-5c7c-907c-6da66274d9be")}catch{}})();var yS=5;async function Ei(e,t,n){let r=await Rt(e,t),o=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),s=n?Number.POSITIVE_INFINITY:yS,a=r.driftedItems.slice(0,s);return{check:{name:"history_drift",status:o.length===0?"ok":"warn",ok:o.length===0,details:{checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,s)}},warnings:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77a3c404-bbcd-5a5e-80bf-cb61c45af55d")}catch{}})();function Ri(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],o=new Set([n]),s=a=>{for(let c of(t.get(a)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!o.has(c)){if(o.add(c),i.push(c),s(c))return!0;i.pop(),o.delete(c)}}return!1};return s(n)?[...i]:[...e,n]}function wS(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function vS(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let o=r.resolve(i.kind);if(!o?.hierarchy)continue;let s=n.get(i.id.toLowerCase());s&&(o.hierarchyDirection==="source_parent"?t.get(s).push(e.id):t.get(e.id).push(s))}}function Bs(e,t=En()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((o,s)=>o.id.localeCompare(s.id))){let o=r.get(i.id),s=wS(i.parent,n);s&&o.push(s),vS(i,r,n,t)}for(let[i,o]of r)r.set(i,[...new Set(o)].sort());return r}function Gs(e,t,n=En()){let r=Pr(e,s=>t?Ya(s,t):s==="closed"||s==="canceled",n),i=Bs(e,n),o=r.cycles.map(s=>s.item_ids);return{cycle_count:o.length,active_cycle_count:r.cycles.filter(s=>!s.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(s=>s.legacy_terminal).length,cycle_item_ids:[...new Set(o.flat())].sort(),cycle_sample_paths:o.map(s=>Ri(s,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(s=>!s.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(s=>s.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(s=>`${s.child_id}:${s.parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(s=>!s.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(s=>s.legacy_terminal).length,parent_divergence_rows:r.divergences.map(s=>`${s.child_id}:scalar=${s.scalar_parent_id}:dependencies=${s.dependency_parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de2cc648-965a-59c9-b688-0fe12edeec82")}catch{}})();function _t(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Js(e){return _t(e).replace(/\/+$/,"")}function Ne(e){let t=Z(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cde10e58-cfeb-5718-a471-3e4acf46cfe7")}catch{}})();var SS=["src","tests","docs"],ES=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],RS=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),AS=["resolution","expected_result","actual_result"],IS=["default","tracked-all","tracked-all-strict"],Lp=["core","strict","custom"],Ci=["off","warn","error"],Ys=["author","acceptance_criteria","estimated_minutes","close_reason"],Up=[...Ys,"reviewer","risk","confidence","sprint","release"],ea=Array.from(new Set(Up)),CS={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},TS={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},$S={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},OS={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},DS={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},PS=32*1024*1024,NS=1e4,zp=40,at=5,MS=4096,LS=255,FS=xS(kS);function Wp(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?Wp(r):r);return t}function jS(e){return{...e,checks:e.checks.map(t=>({...t,details:Wp(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function $i(e,t){return lc(e,t)??e}function Qn(e,t){return t.terminal_statuses.has($i(e,t))}function yt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ai(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function US(e){let t=yt(ka),n={blocked_reason:yt(dr.blocked_reason),resolution:yt(dr.resolution),actual_result:yt(dr.actual_result)},r=yt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:yt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:yt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:yt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Ai(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Ai(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Ai(i.resolution,n.resolution)?"default":"settings",actual_result:Ai(i.actual_result,n.actual_result)?"default":"settings"}}}function qp(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Lp.includes(t))return t;throw new w(`Unknown --metadata-profile value "${e}". Supported values: ${Lp.join(", ")}.`,y.USAGE)}function Hp(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ci.includes(t))return t;throw new w(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Ci.join(", ")}.`,y.USAGE)}function Bp(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ci.includes(t))return t;throw new w(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Ci.join(", ")}.`,y.USAGE)}function zS(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>CS[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function WS(e,t,n){let r=zS(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Ys],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Up],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Ys],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var qS=new Set(["acceptance_criteria","estimated_minutes"]);function Gp(e,t,n,r){return!r&&qS.has(t)&&Qn(e.status,n)?!1:t==="author"?!Z(e.author):t==="acceptance_criteria"?!Z(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?$i(e.status,n)===n.close_status&&!Z(e.close_reason):t==="reviewer"?!Z(e.reviewer):t==="risk"?!Z(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!Z(e.confidence):t==="sprint"?!Z(e.sprint):!Z(e.release)}function Jp(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new w(`Unknown --scan-mode value "${e}". Supported values: ${IS.join(", ")}.`,y.USAGE)}function Vp(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return ye.resolve(t);let n=ye.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return ye.dirname(ye.dirname(n));let i=ye.resolve(process.cwd()),o=Fp(n),s=Fp(i),a=ye.relative(o,s);return a.length===0||!a.startsWith("..")&&!ye.isAbsolute(a)?n:i}function Fp(e){try{return bS.native(e)}catch{return ye.resolve(e)}}function HS(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function ta(e,t,n){let r=t.length>0?ye.join(e,t):e,i;try{i=await Qs.readdir(r,{withFileTypes:!0})}catch(o){if(U(o))return;throw o}for(let o of i){if(o.name.startsWith("."))continue;let s=t.length>0?ye.join(t,o.name):o.name;if(o.isDirectory()){if(RS.has(o.name))continue;await ta(e,s,n);continue}o.isFile()&&n.push(_t(s))}}async function Xs(e){let t=[];for(let n of SS)await ta(e,n,t);for(let n of ES){let r=ye.join(e,n);try{(await Qs.stat(r)).isFile()&&t.push(_t(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function Kp(e){try{let{stdout:t}=await FS("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:PS,windowsHide:!0,timeout:NS}),n=t.split("\0").map(r=>_t(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function BS(e,t){let n=new Set,r=Js(wa);r.length>0&&n.add(r);let i=Js(ye.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((o,s)=>o.localeCompare(s))}function jp(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function GS(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await Kp(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Xs(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Xs(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function te(e,t=at){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function wt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=te(e,zp);return{values:n.values,truncated:n.truncated,total:e.length}}var JS={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},VS={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function KS(e){let t=e.missing_fields.map(n=>`${JS[n]} "${VS[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Yp(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(s=>typeof s=="string"):il(t);if(i.length===0)return;let o=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...o?{fix_hints_truncated:!0}:{}}}function Xp(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var YS="validate_metadata_duplicate_issue_codes";function Zp(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:at,r=e.slice(0,n);return{rows:r.map(o=>({code:o.code,count:o.count,ids:o.ids,titles:o.titles,remediation_hint:`Items ${o.ids.join(", ")} share issue code "${o.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${YS}:${e.length}`]}}function XS(){return Object.fromEntries(ea.map(e=>[e,[]]))}function ZS(e,t,n){let r=XS();for(let i of e)for(let o of ea)Gp(i,o,t,n)&&r[o].push(i.id);return r}function QS(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let o=t[i];o.length>0&&r.push(`${TS[i]}:${o.length}`)}return r.push(...n),r}function Qp(e,t){let n={};for(let r of e.required_fields){let i=t[r],o=i?i.length:0,s=$S[r];n[s]=o}return n}function ef(e,t,n){let r=[];for(let i of e.required_fields){let o=t[i];if(o)for(let s of o){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:i})}}return r}function eE(e,t,n,r){for(let i of t.required_fields){let o=n[i];if(!o||o.length===0)continue;let s=OS[i],a=DS[i];if(!s||!a)continue;let c=te(o,r?o.length:at);e[s]=c.values,e[a]=c.truncated}}function tf(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:Z(n.get(i)?.resolution)})):[]}function nf(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:Z(n.get(i)?.type)})):[]}function tE(e,t,n,r,i){let o=new Map(e.map(_=>[_.id,_])),s=t.profile==="strict",a=ZS(e,n,s),c=mp(e,{configuredPrefixes:i}),d=Zp(c,r),l=QS(t,a,d.warnings),u=Qp(t,a),m=ef(t,a,o),p=pp(m),f={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...ea],counts:u,missing_by_type:p,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),eE(f,t,a,r);let h=tf(t,a,o),g=nf(t,a,o);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:f},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:g}}function nE(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has($i(m.status,t))),o=[],s=[];for(let m of i){let p=AS.filter(f=>!Z(m[f]));p.length!==0&&(o.push({id:m.id,missing_fields:p}),s.push({id:m.id,missing_fields:p,close_reason:Z(m.close_reason)}))}let a=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:at,d=te(o.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=o.map(m=>KS(m)),u=te(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:i.length,missing_resolution_items:o.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:s}}function rf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function of(e,t="pm",n=$a()){let r=new Set(e.map(o=>o.id)),i=[...e].sort((o,s)=>o.id.localeCompare(s.id));return new Map(i.map(o=>{let s=new Set,a=Ne(o.blocked_by);a&&r.has(a)&&s.add(a),(o.dependencies??[]).filter(d=>{let l=Ne(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ne(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>s.add(d));let c=Ne(o.definition_of_ready);return af(c??"",t).filter(d=>r.has(d)).forEach(d=>s.add(d)),[o.id,[...s].sort((d,l)=>d.localeCompare(l))]}))}function sf(e,t,n){let r=ed(e,n?l=>Qn(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),o=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),s=t?Number.POSITIVE_INFINITY:at,a=te(i,s),c=te(o,s),d=te(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),s);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+o.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:o.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function af(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${rf(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,o)=>i.localeCompare(o))}function cf(e){let t=0,n=new Map,r=new Map,i=[],o=new Set,s=[],a=l=>{n.set(l,t),r.set(l,t),t+=1,i.push(l),o.add(l);for(let m of e.get(l)??[])n.has(m)?o.has(m)&&r.set(l,Math.min(r.get(l),n.get(m))):(a(m),r.set(l,Math.min(r.get(l),r.get(m))));if(r.get(l)!==n.get(l))return;let u=[];for(;i.length>0;){let m=i.pop();if(o.delete(m),u.push(m),m===l)break}u.sort((m,p)=>m.localeCompare(p)),s.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return s.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function df(e,t="pm"){let n=of(e,t),r=cf(n),i=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),o=r.map(s=>Ri(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:o}}function lf(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function Ti(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function uf(e,t){let n=Ti(e).split("/").filter(Boolean),r=Ti(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function rE(e,t){let n=Ti(t),r=Ti(e),i=t.endsWith("/")?t:`${t}/`,o=e.startsWith(i),s=n.length>0&&n===r,a=uf(e,t);return!o&&!s&&a===0?null:o?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function iE(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function oE(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(o=>(r==="docs"?o.docs??[]:o.files??[]).map(s=>({item:o,link:s}))).forEach(({item:o,link:s})=>{if(s.scope!=="project")return;let a=_t(s.path);if(a.length===0||a===e)return;let c=rE(e,a);c!==null&&iE(i,o,c.score)&&(i={item:o,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function mf(e,t){return e.map(n=>{let r=lf(n),i=r==="docs_unowned"?"docs":"files",o=oE(n,r,t),s=o?.id??"<id>";return{path:n,classification:r,owner_candidate:o,remediation_hint:`pm ${i} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function pf(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function sE(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Ne(e[n]);return i?r.some(o=>i.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function aE(e,t,n,r,i){let o=Ne(t.parent),s=o?n.get(r.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!Qn(s.status,i)}}function cE(e,t,n,r){let i=Ne(e.blocked_by),o=Ne(e.blocked_reason),s=o?.toLowerCase(),a=$i(e.status,n),c=[];return t.has(a)?(!i&&!o&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(d=>s.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function dE(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!Qn(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=sE(c,r);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=Ne(c.parent),u=l?i.get(o.get(l.toLowerCase())??l):void 0;if(u&&Qn(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(aE(c,u,i,o,n))),t){let m=cE(c,s,n,r);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((p,f)=>p.localeCompare(f))})}}return a}function lE(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function Ii(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Vs(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function uE(e,t,n,r,i){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=Ii("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),a=Ii("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=Ii("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=Ii("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=Vs("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=Vs("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=Vs("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...o,...s?[s]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function ff(e){let t=_t(e);return t.length>MS||t.split(/[\\/]/).some(n=>n.length>LS)}async function mE(e,t){let n=ye.isAbsolute(t)?t:ye.resolve(e,t);if(ff(n))return!1;try{let r=await Qs.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return HS(r,["ENOENT","ENOTDIR"])}}async function pE(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(o=>({item:i,artifact:o,link_kind:"files"})),...(i.docs??[]).map(o=>({item:i,artifact:o,link_kind:"docs"}))]);for(let{item:i,artifact:o,link_kind:s}of r){if(o.scope!=="project")continue;if(Yn(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let a=_t(o.path);a.length!==0&&(n.linkedProjectPaths.add(a),await mE(t,o.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:s})))}return n}function fE(e,t,n,r,i,o){let s=r==="tracked-all-strict",a=s&&!i,c=i||s,d=c?[]:BS(t,n),l=d.length===0?[]:e.candidateFiles.filter(p=>jp(p,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(p=>!jp(p,d)),m={};if(l.length>0){let p=wt(l,o);m.pm_internals={count:l.length,paths:p.values,paths_truncated:p.truncated,paths_total:p.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function hf(e,t,n,r,i,o,s,a="pm"){let c=dE(e,t,i,o);lE(c);let d=df(c.activeItems,a),l=Gs(e,i),u=Gr(i,e,s?Number.POSITIVE_INFINITY:at),m=[...uE(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...Jr(u)],p=s?Number.POSITIVE_INFINITY:at,f=te(c.closureLikeRows.map(E=>`${E.id}:${E.fields.join(",")}`),p),h=te(c.terminalParentRows.map(E=>`${E.id}:${E.parent_id}:${E.parent_status}`),p),g=te(c.staleBlockerRows.map(E=>`${E.id}:${E.status}:${E.reasons.join(",")}`),p),_=te(d.cycle_item_ids,p),v=te(d.cycle_sample_paths,p),k=te(l.cycle_item_ids,p),x=te(l.cycle_sample_paths,p),b=te(l.cardinality_violation_rows,p),I=te(l.parent_divergence_rows,p),S=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:S?"error":m.length===0?"ok":"warn",ok:!S&&m.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:g.values,stale_blocker_rows_truncated:g.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:_.values,dependency_cycle_item_ids_truncated:_.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:x.values,parent_cycle_sample_paths_truncated:x.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:b.values,hierarchy_cardinality_violation_rows_truncated:b.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:I.values,hierarchy_parent_divergence_rows_truncated:I.truncated,stale_blocker_reason_patterns:[...o.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:o.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...o.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:o.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...o.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:o.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...o.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:o.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function gf(e,t,n,r,i,o){let s=await pE(e,t),a=new Map(e.map(O=>[O.id,O])),c=[...new Set(s.missingLinkedPaths)].sort((O,B)=>O.localeCompare(B)),d=await GS(t,r),l=fE(d,n,t,r,i,o),u=l.candidateFiles.filter(O=>!s.linkedProjectPaths.has(O)),m=mf(u,e),p=gp(c,l.candidateFiles),f=new Map(p.map(O=>[O.path,O.classification])),h=p.filter(O=>O.classification==="moved").length,g=s.staleLinkRows.map(O=>({...O,classification:f.get(O.path)??"deleted"})).sort((O,B)=>O.item_id.localeCompare(B.item_id)||O.path.localeCompare(B.path)||O.link_kind.localeCompare(B.link_kind)),_=[];l.strictModeForcesPmInternals&&_.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&_.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&_.push(`validate_files_orphaned_paths:${u.length}`);let v=[...s.remoteLinkedPaths].sort((O,B)=>O.localeCompare(B)),k=wt(v,o),x=wt(c,o),b=wt(u,o),I=wt(m.map(O=>`${O.path}:${O.classification}:owner_candidate=${O.owner_candidate?.id??"unowned"}`),o),S=o?m:wt(pf(m),!1).values,E=wt(_p(p),o),A=g.map(O=>({item_id:O.item_id,path:O.path,link_kind:O.link_kind,classification:O.classification})),F=wp(A,O=>{let B=a.get(O);return B?{type:B.type,title:B.title,status:B.status}:void 0}),H=o?F:wt(vp(F),!1).values;return{check:{name:"files",status:_.length===0?"ok":"warn",ok:_.length===0,details:{workspace_root:t,scan_mode_requested:d.requestedMode,scan_mode_applied:d.appliedMode,strict_tracked_all_mode:l.strictTrackedAllMode,strict_mode_forces_pm_internals:l.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:l.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:o?"full":"summary",file_list_summary_limit:zp,candidate_scan_source:d.source,include_pm_internals:l.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:l.pmInternalCandidatePrefixes,pm_internal_excluded_count:l.excludedPmInternalPaths.length,excluded_total:l.excludedPmInternalPaths.length,excluded_by_reason:l.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:k.total,remote_linked_paths:k.values,remote_linked_paths_truncated:k.truncated,candidate_total_raw:d.candidateTotal,candidate_scanned_raw:d.candidateScanned,candidate_total:l.candidateFiles.length,candidate_scanned:l.candidateFiles.length,scanned_candidate_files:l.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:x.total,missing_linked_paths:x.values,missing_linked_paths_truncated:x.truncated,missing_linked_paths_moved_count:h,missing_linked_paths_deleted_count:c.length-h,missing_linked_path_classifications:E.values,missing_linked_path_classifications_truncated:E.truncated,missing_linked_path_rows_count:F.length,missing_linked_path_rows:H,orphaned_paths_count:u.length,orphaned_paths_total:b.total,orphaned_paths:b.values,orphaned_paths_truncated:b.truncated,orphaned_path_classifications:I.values,orphaned_path_classifications_truncated:I.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:S}},warnings:_,staleLinkPruneRows:g}}function _f(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function hE(e,t,n){return`${e}:${t}:${_f(n)}`}function gE(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},o)=>{let s=t[o];if(s.trusted)return;let a=_f(i.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function yf(e,t,n,r){let i=new Set(e.map(b=>b.id.toLowerCase())),o=0,s=0,a=new Set,c=[],d=e.flatMap(b=>(b.tests??[]).map(I=>({item:b,linkedTest:I}))),l=await qs(Hs()),u=await Mp(r,d.map(({linkedTest:b})=>b),l),m=gE(d,u);for(let{item:b,linkedTest:I}of d){if(typeof I.command!="string"||I.command.trim().length===0)continue;o+=1;let S=Tp(I.command,t);if(S.length!==0){s+=S.length;for(let E of S)a.add(E),i.has(E.toLowerCase())||c.push(hE(b.id,E,I.command))}}let p=[...new Set(c)].sort((b,I)=>b.localeCompare(I)),f=[...new Set(p.map(b=>b.split(":")[1]??""))].filter(b=>b.length>0).sort((b,I)=>b.localeCompare(I)),h=[];p.length>0&&h.push(`validate_command_references_stale_pm_ids:${p.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let g=n?Number.POSITIVE_INFINITY:at,_=te(p,g),v=te(f,g),k=te([...a].sort((b,I)=>b.localeCompare(I)),g),x=te(m,g);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:o,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:x.values,untrusted_linked_tests_truncated:x.truncated,stale_pm_id_references_count:p.length,stale_pm_ids_count:f.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:_.values,stale_pm_id_reference_rows_truncated:_.truncated}},warnings:h}}function _E(e,t){let n=br(e.map(c=>({ref:c.id,version:vr(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:at,o=te(n.outdated,i),s=te(n.ahead,i),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:dc,outdated_items_count:n.outdated.length,outdated_items:o.values,outdated_items_truncated:o.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var Zs="pm validate auto-fix";async function wf(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Zs};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new w("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",y.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Ks(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function vf(e,t,n){let r=[],i=[],o=new Map;for(let s of e.filter(a=>Ks(a)===null))try{await wf(s,t,n),r.push(s)}catch(a){i.push({fix:s,error:a})}for(let s of e.filter(a=>Ks(a)!==null)){let a=Ks(s),c=o.get(a);c?c.push(s):o.set(a,[s])}for(let s of o.values()){let a=s[0];if(!a)continue;let c=s.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await Ep(a.item_id,{remove:c,message:Zs},t):await xp(a.item_id,{remove:c,message:Zs},t),r.push(...s)}catch(d){i.push(...s.map(l=>({fix:l,error:d})))}}return{applied:r,failed:i}}var WM={applyValidateFix:wf,applyValidateFixes:vf,attachValidateFixHints:Yp,buildCommandReferencesCheck:yf,buildDependencyReferencesCheck:sf,buildCloseReasonBackfillRows:tf,buildFilesCheck:gf,buildLifecycleCheck:hf,buildLifecycleDependencyGraph:of,buildLifecycleParentGraph:Bs,buildEstimateBackfillRows:nf,buildMetadataCounts:Qp,buildMissingFieldOccurrences:ef,buildOrphanedPathRows:mf,classifyOrphanedPath:lf,collectDefaultProjectFileCandidates:Xs,collectTrackedGitFileCandidates:Kp,detectLifecycleDependencyCycles:df,detectLifecycleParentCycles:Gs,escapeRegExp:rf,extractItemIds:af,findLifecycleDependencyCycleComponents:cf,isMetadataFieldMissing:Gp,linkedArtifactPathExceedsFilesystemLimits:ff,listFilesRecursive:ta,resolveDependencyCycleSeverity:Hp,resolveParentCycleSeverity:Bp,resolveFileScanMode:Jp,resolveLifecycleDependencyCycleSamplePath:Ri,resolveRequestedChecks:Xp,resolveValidateMetadataProfile:qp,resolveWorkspaceRoot:Vp,sharedDirectoryPrefixLength:uf,summarizeOrphanedPathRows:pf,summarizeDuplicateIssueCodes:Zp,toMeaningfulString:Ne};function yE(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function wE(e,t,n,r){let i=await Zm(e,new Set(t.map(g=>g.id)),n,{schema:r.schema,extensionFieldNames:Ot(z())}),o=[];i.unreadable_item_files.length>0&&o.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&o.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&o.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&o.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&o.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&o.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let s=o.length,a=await fi(e);a.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Xr(e,en(r));c.status==="drift"&&o.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Ze(e),l=d===null?null:await tn(d);l!==null&&l.status!=="ok"&&o.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await rt(d??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:p,lossless:f}=cn(m);p.length>0&&o.push(`validate_merge_decisions_unreviewed:${p.length}`),yE(o,u.invalid_evidence_count);let h=s>0?"error":o.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...i,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:p.length,pending_merge_decision_items:[...new Set(p.map(g=>g.item_id))].sort((g,_)=>g.localeCompare(_)),lossless_merge_receipt_count:f.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,lossless_merge_receipt_items:[...new Set(f.map(g=>g.item_id))].sort((g,_)=>g.localeCompare(_)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:o}}function st(e,t,n){n&&Yp(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function vE(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let i=tE(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,st(t,i,n)}if(e.requestedChecks.has("resolution")){let i=nE(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,st(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=hf(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,st(t,i,n),st(t,sf(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await gf(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=i.staleLinkPruneRows,st(t,i,n)}return e.requestedChecks.has("command_references")&&st(t,await yf(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&st(t,await Ei(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&st(t,_E(e.items,r),n),e.requestedChecks.has("storage_integrity")&&st(t,await wE(e.pmRoot,e.items,W(e.settings,z()).type_to_folder,e.settings),n),t}function bE(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...op(t.closeReasonBackfillRows)),r.push(...ip(t.resolutionBackfillRows)),r.push(...sp(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...ap(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...cp(t.staleLinkPruneRows)),r}async function kE(e,t,n,r,i,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=bE(e,t,n),{applicable:a,gated:c}=lp(s,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await vf(a,i,o);l.push(...m.applied.map(Kn)),u.push(...m.failed.map(({fix:p,error:f})=>({...Kn(p),error:f instanceof Error?f.message:String(f)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,p)=>m.localeCompare(p)),planned_count:s.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(Kn),applied_fixes:l,gated_fixes:c.map(m=>({...Kn(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function bf(e,t,n={}){ic(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new w("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",y.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new w("--fix-scope requires --auto-fix.",y.USAGE);let i=dp(e.fixScope),o=M(process.cwd(),t.path);await X(o);let s=await C(o),a=Ie(s.schema),c=W(s,z()),d=Xp(e),l=[],u=await Si({includeBody:d.has("history_drift")||d.has("metadata"),pmRoot:o,settings:s,typeToFolder:c.type_to_folder,warnings:l});if(d.has("history_drift")){let A=await On(o);A.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${A.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",p=qp(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),f=WS(p,m,s.validation.metadata_required_fields),h=US(s),g=Hp(e.dependencyCycleSeverity),_=Bp(e.parentCycleSeverity),v=Jp(e.scanMode),k=Vp(o),x=await vE({requestedChecks:d,options:e,global:t,pmRoot:o,workspaceRoot:k,settings:s,items:u,statusRegistry:a,metadataPolicy:f,lifecyclePatternPolicy:h,dependencyCycleSeverity:g,parentCycleSeverity:_,fileScanMode:v,initialWarnings:[...new Set(l)]}),b=r?await kE(e,x,s,i,t,n):void 0,I=[...new Set(x.warnings)].sort((A,F)=>A.localeCompare(F)),E={ok:!x.checks.some(A=>A.status==="error"),has_warnings:I.length>0,checks:x.checks,warnings:I,...b!==void 0?{fixes:b}:{},generated_at:T(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?E:{...jS(E),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as xE}from"node:child_process";import{promisify as SE}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f9c26dab-b2fb-5ca0-b575-682b4b0bb830")}catch{}})();var EE=SE(xE),RE=16,AE=3e4;function IE(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(o=>typeof o=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function CE(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let o of Object.entries(i).filter(([,s])=>s.required===!0).map(([s])=>s))if(!Object.hasOwn(r,o))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${o}`);for(let[o,s]of Object.entries(r)){let a=i[o];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${o}`);if(s===null||typeof s!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${o} must be ${a.type}`)}return{...r}}async function TE(e,t,n,r){let i=CE(e,t),o=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...sc(n)}));o.catch(()=>{});let s;try{let a=await Promise.race([o,new Promise((c,d)=>{s=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??AE),s.unref?.()})]);return IE(e,t.key,a)}finally{clearTimeout(s)}}function xf(e,t,n,r){let i=e;for(let o of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new ze(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[o]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(o=>typeof o=="string"))return i;throw new ze(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function kf(e,t,n,r){let i=e.checks.find(s=>s.name===t);if(!i)throw new ze(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:xf(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function $E(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await EE("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function OE(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(RE,t.length)},async()=>{for(;r<t.length;){let o=r;r+=1;let s=t[o],a=await zt(ur(e,s.id),s.id);n[o]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function er(e,t={}){let n=await C(e),r=W(n),i=Ie(n.schema),s=(await Bt(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(p=>({...p,id:p.id,status:p.status,type:p.type})),a={path:e},c=z(),d=Object.fromEntries((c?.assurance_providers??[]).map(p=>[p.definition.id,{cost_class:p.runtime_definition.cost_class,network:p.runtime_definition.network}])),l=new Map,u,m;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await $E(e,t.tree_id),items:s,history:t.include_history===!1?[]:await OE(e,s),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async p=>{if(p.kind==="graph"){let g=Q({operation:p.operation,parameters:p.parameters??{}}),_=l.get(g);_===void 0&&(_=nd(p.operation,void 0,void 0,{...p.parameters,full:!0},a),l.set(g,_));let v=await _;return{value:xf(v,p.field,p.kind),population_size:s.length,cost:s.length}}if(p.kind==="validate"){u??=bf({counts:!0},a);let g=await u;return kf(g,p.check,p.field,p.kind)}if(p.kind==="health"){m??=Ym(a,{checkOnly:!0,full:!0});let g=await m;return kf(g,p.check,p.field,p.kind)}let f=t.providers?.[p.provider];if(f)return f(p);let h=Cc(c,p.provider);if(!h)throw new TypeError(`assurance provider ${p.provider} is not registered`);return TE(h.runtime_definition,p,e,t.trigger??"sdk")}}}import{createHash as DE}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e78c3363-1741-52b9-8bd5-729e3ccada50")}catch{}})();function Oi(e){return{files:(Array.isArray(e.files)?e.files:[]).flatMap(t=>{if(typeof t!="object"||t===null||Array.isArray(t))return[];let n=t.path;return typeof n=="string"?[n]:[]}),package_names:Array.isArray(e.package_names)?e.package_names.filter(t=>typeof t=="string"):[],item_ids:[e.id],tags:Array.isArray(e.tags)?e.tags.filter(t=>typeof t=="string"):[],error_codes:Array.isArray(e.error_codes)?e.error_codes.filter(t=>typeof t=="string"):[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59f5918f-108e-5cad-905b-7f690c3c4794")}catch{}})();var Pi=["production_defect","nightly_regression","scanner_finding","review_caught_late"],ra=["gate_added","gate_strengthened","explicit_waiver"],Sf=256,PE=1024,tr=new Map,NE=["files","package_names","item_ids","tags","error_codes"];function we(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t<n?-1:1)}function Ef(e){return DE("sha256").update(Q(e)).digest("hex")}function na(e,t){if(typeof e!="string"||!e.trim())throw new TypeError(`${t} must be a non-empty string`)}function nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hn(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function Af(e,t){if(!nr(e))throw new TypeError(`${t} must be an object`);for(let n of NE)if(e[n]!==void 0&&!hn(e[n]))throw new TypeError(`${t}.${n} must be an array of strings`);return e}function ME(e,t){if(!nr(e))throw new TypeError(`defect recurrence family ${t} triggers must be an object`);for(let r of["package_names","item_ids","tags","error_codes"])if(e[r]!==void 0&&!hn(e[r]))throw new TypeError(`defect recurrence family ${t} triggers.${r} must be an array of strings`);let n=e.file_patterns;if(n!==void 0&&!hn(n))throw new TypeError(`defect recurrence family ${t} triggers.file_patterns must be an array of strings`);for(let r of n??[])if(r.length>Sf)throw new TypeError(`defect recurrence family ${t} file pattern exceeds ${Sf} characters`)}function LE(e,t){if(na(e.id,"defect recurrence family id"),t.has(e.id))throw new TypeError(`Duplicate defect recurrence family ${e.id}`);if(t.add(e.id),!Number.isInteger(e.version)||e.version<1)throw new TypeError(`defect recurrence family ${e.id} version must be a positive integer`);if(!Pi.includes(e.escape_class))throw new TypeError(`defect recurrence family ${e.id} has an invalid escape class`);na(e.title,`defect recurrence family ${e.id} title`),na(e.owner_item_id,`defect recurrence family ${e.id} owner_item_id`)}function FE(e){if(!hn(e.historical_item_ids)||e.historical_item_ids.length===0||e.historical_item_ids.some(t=>!t.trim()))throw new TypeError(`defect recurrence family ${e.id} requires historical_item_ids`);if(ME(e.triggers,e.id),!nr(e.checks)||!hn(e.checks.local)||!hn(e.checks.hosted)||e.checks.local.length===0||e.checks.hosted.length===0||e.checks.local.some(t=>!t.trim())||e.checks.hosted.some(t=>!t.trim()))throw new TypeError(`defect recurrence family ${e.id} checks must contain nonempty local and hosted string arrays`)}function jE(e){if(!nr(e.budget)||typeof e.budget.max_escape_rate!="number"||!Number.isFinite(e.budget.max_escape_rate)||typeof e.budget.max_false_positive_rate!="number"||!Number.isFinite(e.budget.max_false_positive_rate))throw new TypeError(`defect recurrence family ${e.id} requires numeric budgets`);if(e.budget.max_escape_rate<0||e.budget.max_escape_rate>1||e.budget.max_false_positive_rate<0||e.budget.max_false_positive_rate>1)throw new TypeError(`defect recurrence family ${e.id} budgets must be between 0 and 1`)}function UE(e){let t=Af(e.negative_control,`defect recurrence family ${e.id} negative_control`);if(oa(e,t,{}).length===0)throw new TypeError(`defect recurrence family ${e.id} negative_control must select its own family`)}function ia(e){if(e.version!==1)throw new TypeError(`Unsupported defect recurrence policy version ${e.version}`);if(typeof e.evidence_epoch!="string"||!Number.isFinite(Date.parse(e.evidence_epoch)))throw new TypeError("defect recurrence evidence_epoch must be an ISO timestamp");let t=new Set;for(let n of e.families){if(!nr(n))throw new TypeError("defect recurrence family must be an object");LE(n,t),FE(n),jE(n),UE(n)}}function zE(e,t){let n=tr.get(e);if(n===void 0){if(tr.size>=PE){let i=tr.keys().next().value;tr.delete(i)}let r=e.replaceAll("**","\0").replaceAll(/[|\\{}()[\]^$+?./]/gu,"\\$&").replaceAll("*","[^/]*").replaceAll("\0",".*");n=new RegExp(`^${r}$`,"u"),tr.set(e,n)}return n.test(t)}function WE(e,t){let n=[],r=we(e.triggers.file_patterns??[]);for(let i of we(t.files??[]))for(let o of r)zE(o,i)&&n.push({signal:"file",value:i,matched:o});return n}function qE(e,t){let n=[{signal:"package",values:we(t.package_names??[]),triggers:we(e.triggers.package_names??[])},{signal:"tag",values:we(t.tags??[]),triggers:we(e.triggers.tags??[])},{signal:"error_code",values:we(t.error_codes??[]),triggers:we(e.triggers.error_codes??[])}],r=[];for(let i of n){let o=new Set(i.triggers);for(let s of i.values)o.has(s)&&r.push({signal:i.signal,value:s,matched:s})}return r}function HE(e,t,n){let r=new Set(e.triggers.item_ids??[]);return we(t.item_ids??[]).flatMap(i=>r.has(i)||n[i]?.includes(e.id)?[{signal:"item",value:i,matched:e.id}]:[])}function oa(e,t,n){return[...WE(e,t),...qE(e,t),...HE(e,t,n)].sort((i,o)=>i.signal!==o.signal?i.signal.localeCompare(o.signal):i.value!==o.value?i.value.localeCompare(o.value):i.matched.localeCompare(o.matched))}function BE(e,t){if(!e)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("defect change-risk cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n)||n.index_fingerprint!==t||!Number.isInteger(n.offset)||n.offset<0)throw new TypeError("defect change-risk cursor does not match this index");return n.offset}function GE(e){return[e.files,e.package_names,e.item_ids,e.tags,e.error_codes].reduce((t,n)=>t+(n?.length??0),0)}function If(e,t,n={}){ia(e);let r=[...e.families].sort((l,u)=>l.id<u.id?-1:1),i=Ef({...e,families:r}),o=new Set(n.changed_item_ids??[]),s=n.previous_index?.policy_fingerprint===i,a=s?Object.fromEntries(Object.entries(n.previous_index?.item_families??{}).filter(([l])=>!o.has(l))):{},c=s?Object.keys(a).length:0;for(let l of t){let u=Oi(l),m=r.filter(p=>p.historical_item_ids.includes(l.id)||oa(p,u,{}).length>0).map(p=>p.id);m.length>0?a[l.id]=m:delete a[l.id]}let d=Object.fromEntries(Object.entries(a).sort(([l],[u])=>l<u?-1:1).map(([l,u])=>[l,we(u)]));return{version:1,policy_fingerprint:i,index_fingerprint:Ef({policy_fingerprint:i,item_families:d}),families:r,item_families:d,build:{items_scanned:t.length,items_reused:c,items_indexed:Object.keys(d).length}}}function Cf(e,t,n={}){let r=n.limit??25;if(!Number.isInteger(r)||r<1||r>100)throw new TypeError("defect change-risk limit must be an integer from 1 through 100");let i=BE(n.cursor,e.index_fingerprint),o=e.families.flatMap(l=>{let u=oa(l,t,e.item_families);return u.length===0?[]:[{family_id:l.id,family_version:l.version,owner_item_id:l.owner_item_id,escape_class:l.escape_class,reasons:u,local_checks:we(l.checks.local),hosted_checks:we(l.checks.hosted),budget:l.budget}]}),s=o.slice(i,i+r),a=i+s.length,c=a<o.length?Buffer.from(JSON.stringify({index_fingerprint:e.index_fingerprint,offset:a})).toString("base64url"):void 0,d={risk_detected:o.length>0,index_fingerprint:e.index_fingerprint,items:s,total:o.length,...c?{next_cursor:c}:{},required_local_checks:we(o.flatMap(l=>l.local_checks)),required_hosted_checks:we(o.flatMap(l=>l.hosted_checks)),row_contract:{row_keys:["items"],jq_selector:".items[]"}};return{...d,cost:{families_evaluated:e.families.length,signals_evaluated:GE(t),families_selected:o.length,estimated_output_tokens:Math.ceil(JSON.stringify(d).length/4)}}}function JE(e){return typeof e.type=="string"&&e.type.toLowerCase()==="issue"||(Array.isArray(e.tags)?e.tags:[]).some(t=>typeof t=="string"&&["bug","defect","security"].includes(t.toLowerCase()))}function Di(e){return typeof e=="string"&&e.trim().length>0}function Rf(e){return Array.isArray(e)&&e.length>0&&e.every(Di)}function VE(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,expired:!1};let n=e;if(!ra.includes(n.disposition)||typeof n.owner!="string"||!n.owner.trim())return{valid:!1,expired:!1};if(n.disposition==="explicit_waiver"){let r=Date.parse(n.waiver_expires_at??"");return{valid:Di(n.waiver_reason)&&Number.isFinite(r)&&r>=t,expired:Number.isFinite(r)&&r<t}}return{valid:Di(n.gate_id)&&Di(n.negative_control)&&Rf(n.local_checks)&&Rf(n.hosted_checks),expired:!1}}function KE(e,t){let n=[];if(!Number.isFinite(Date.parse(typeof e.completed_at=="string"?e.completed_at:""))&&!Number.isFinite(Date.parse(typeof e.closed_at=="string"?e.closed_at:""))&&n.push({item_id:e.id,kind:"invalid_completion_timestamp",detail:`${e.id} requires a valid completed_at or closed_at timestamp after the defect-evidence epoch.`}),typeof e.escape_class!="string"?n.push({item_id:e.id,kind:"missing_escape_class",detail:`${e.id} requires escape_class after the defect-evidence epoch.`}):Pi.includes(e.escape_class)||n.push({item_id:e.id,kind:"invalid_escape_class",detail:`${e.id} has unsupported escape_class ${e.escape_class}.`}),e.gate_evidence===void 0)return n.push({item_id:e.id,kind:"missing_gate_evidence",detail:`${e.id} requires structured gate_evidence after the defect-evidence epoch.`}),n;let r=VE(e.gate_evidence,t);return r.valid||n.push({item_id:e.id,kind:r.expired?"expired_waiver":"invalid_gate_evidence",detail:r.expired?`${e.id} carries an expired gate-evidence waiver.`:`${e.id} gate_evidence does not prove a gate or explicit waiver.`}),n}function oL(e,t,n,r=new Date){ia(t);let i=Date.parse(t.evidence_epoch),o=new Set(n),s=e.filter(m=>o.has(m.status)&&JE(m)),a=s.filter(m=>{let p=Date.parse(typeof m.completed_at=="string"?m.completed_at:"");if(Number.isFinite(p))return p>=i;let f=Date.parse(typeof m.closed_at=="string"?m.closed_at:"");if(Number.isFinite(f))return f>=i;let h=Date.parse(typeof m.created_at=="string"?m.created_at:"");return!Number.isFinite(h)||h>=i}),c=Object.fromEntries(Pi.map(m=>[m,0])),d=Object.fromEntries(ra.map(m=>[m,0])),l=s.filter(m=>typeof m.escape_class=="string"&&Pi.includes(m.escape_class));for(let m of l)if(c[m.escape_class]+=1,typeof m.gate_evidence=="object"&&m.gate_evidence!==null&&!Array.isArray(m.gate_evidence)){let p=m.gate_evidence.disposition;typeof p=="string"&&ra.includes(p)&&(d[p]+=1)}let u=a.flatMap(m=>KE(m,r.getTime()));return u.sort((m,p)=>m.item_id!==p.item_id?m.item_id.localeCompare(p.item_id):m.kind.localeCompare(p.kind)),{ok:u.length===0,governed_item_count:a.length,classified_item_count:l.length,class_counts:c,evidence_disposition_counts:d,findings:u}}function YE(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("defect recurrence policy must be an object");let t=e;if(!Array.isArray(t.families))throw new TypeError("defect recurrence policy families must be an array");return ia(t),t}function Tf(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("defect change-risk request must be an object");let t=e,n=Af(t.change,"defect change-risk request.change");if(t.cursor!==void 0&&typeof t.cursor!="string")throw new TypeError("defect change-risk request.cursor must be a string");if(t.limit!==void 0&&!Number.isInteger(t.limit))throw new TypeError("defect change-risk request.limit must be an integer");return{policy:YE(t.policy),change:n,...t.cursor===void 0?{}:{cursor:t.cursor},...t.limit===void 0?{}:{limit:t.limit}}}import{createHash as XE}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f66a964d-1352-5523-ab91-5177d0d93ce8")}catch{}})();var sa,$f=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk"],aa=["measurement","assertion","gate"];function ZE(e){if($f.includes(e))return e;throw Tr({command_path:"assurance",token:e,allowed:$f,display_name:"assurance action"})}function gn(e,t,n){throw new w(t,y.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function QE(e){if(!e)return gn("kind",`Assurance declaration kind is required. Expected: ${aa.join(", ")}`,"pm assurance list measurement");if(aa.includes(e))return e;throw new w(`Assurance declaration kind is required. Expected: ${aa.join(", ")}`,y.USAGE)}function Of(e){if(!e)return gn("preset",`Assurance preset is required. Expected: ${Cn.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(Cn.includes(e))return e;throw new w(`Assurance preset is required. Expected: ${Cn.join(", ")}`,y.USAGE)}function ca(e){return e.owner?.trim()?e.owner.trim():gn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function eR(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new w("assurance definition must be valid JSON",y.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new w("assurance put requires a JSON object definition",y.USAGE);return n}async function tR(e){let[t,n,r]=await Promise.all([In(e,"measurement"),In(e,"assertion"),In(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Df(e,t){return t===!0?{id:e.id}:e}async function nR(e,t){let n=t.authorization_decision;if(!n)return[];let r=await er(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(s=>s.id===n),o=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!o.has(i.status))throw new w(`Assurance authorization ${n} must name a terminal Decision item`,y.USAGE);return[i.id]}async function rR(e,t){let n=vo(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>Kt))throw new w(`assurance verdict limit must be an integer from 1 through ${Kt}`,y.USAGE);let r=await wd(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function iR(e,t,n){if(e==="presets"){if(t.preset??t.id)return Wr(Of(t.preset??t.id),ca(t));let i=Cn.map(o=>{let s=Wr(o,"pm-owner");return{id:o,title:s.title,description:s.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return Vt(()=>bd(n,Of(t.preset??t.id),ca(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await kd(await er(n,{resolve_tree:!1,trigger:"derive"}),ca(t)),o=t.apply?await Vt(()=>xd(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...o?{applied:o}:{}}}if(!t.id)return gn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new w("assurance promote requires --enforcement warn|block",y.USAGE);let r=await fo(n,"assertion",t.id);return Vt(()=>Sd(n,r,t.enforcement,{author:t.author,message:t.message}))}async function oR(e,t,n){if(!e.id)return gn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new w("assurance run requires a trigger",y.USAGE);if(!Et.includes(e.trigger))throw new w(`Unknown assurance trigger ${e.trigger}. Expected: ${Et.join(", ")}`,y.USAGE);let i=e.trigger,[o,s]=await Promise.all([tR(t),er(t,{...n.workspace,tree_id:e.tree,trigger:i})]),a=await rd(()=>hd(r,o,s,{trigger:i,dry_run:e.dry_run===!0}));return a.dry_run||await yd(t,a,{author:e.author,message:e.message}),a}function Pf(e){throw e instanceof w?e:new w(e instanceof Error?e.message:"assurance risk request is invalid",y.USAGE)}function sR(e){if(e.limit!==void 0)throw new w("assurance risk does not accept --limit; set limit inside the risk definition",y.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new w("assurance risk definition must be valid JSON",y.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return Tf(t)}catch(n){return Pf(n)}}function aR(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function cR(e,t,n){let r=Q(t.policy),i=sa?.pm_root===e?sa:void 0,o=new Map(n.map(d=>[d.id,XE("sha256").update(Q(Oi(d))).digest("hex")])),s=i?.policy_serialized===r?i:void 0,a=s?aR(s,o):new Set,c=If(t.policy,s?n.filter(d=>a.has(d.id)):n,s?{previous_index:s.index,changed_item_ids:[...a]}:{});return sa={pm_root:e,policy_serialized:r,item_fingerprints:o,index:c},c}async function dR(e,t){let n=sR(e),r=await er(t,{include_history:!1,resolve_tree:!1});try{return Cf(cR(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit})}catch(i){return Pf(i)}}async function lR(e,t={},n={}){let r=ZE(e.action),i=M(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return iR(r,e,i);if(r==="verdicts")return rR(e,i);if(r==="run")return oR(e,i,n);if(r==="risk")return dR(e,i);let o=QE(e.kind);if(r==="list")return In(i,o);if(!e.id)return gn("id",`assurance ${r} requires an id`,`pm assurance ${r} ${o} <id>`);let s=e.id;if(r==="show")return fo(i,o,s);if(r==="remove"){let l=await Vt(()=>_d(i,o,s,{author:e.author,message:e.message}));return Df(l,e.idOnly)}let a=eR(o,e.definition);if(a.id!==s)throw new w(`Assurance definition id ${a.id} does not match requested id ${s}`,y.USAGE);let c={author:e.author,message:e.message,...o==="assertion"?{authorized_decision_ids:await nR(i,a)}:{}},d=await Vt(()=>Ur(i,o,a,c));return Df(d,e.idOnly)}function bL(e,t,n){let r={...e,...t};return lR({action:$(r,"subcommand")??$(r,"assuranceAction")??$(r,"operation")??"",kind:$(r,"kind"),id:$(r,"id"),definition:r.definition,trigger:$(r,"trigger"),tree:$(r,"treeId")??$(r,"tree"),gate:$(r,"gate"),limit:vo(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:$(r,"author"),message:$(r,"message"),preset:$(r,"preset"),owner:$(r,"owner"),apply:r.apply===!0,enforcement:$(r,"enforcement")},n)}import{execFile as uR}from"node:child_process";import mR from"node:path";import{promisify as pR}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="46439d77-bb74-5f36-9383-ac3362f41b3e")}catch{}})();var fR=pR(uR),hR="@unbrained/pm-cli",gR="latest",_R={global:["--global"],project:[]};function Nf(e){let t=e.project===!0||e.local===!0||e.scope==="project",n=e.global===!0||e.scope==="global";if(t&&n)throw new w('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"}function Mi(e){return e.trim().toLowerCase()}function Mf(e,t){let n=Mi(t);return[e.name,e.directory,e.source.input,e.source.location,e.source.package,e.source.repository,e.source.owner&&e.source.repo?`${e.source.owner}/${e.source.repo}`:void 0].some(i=>typeof i=="string"&&Mi(i)===n)}function yR(e,t){let n=M(process.cwd(),t.path),r=Dt(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function wR(e,t,n){try{let r=await fR(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:r.stdout,stderr:r.stderr}}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr??""):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new w(`Command failed: ${e} ${t.join(" ")}
45
- ${o}`,y.GENERIC_FAILURE)}}async function vR(){return Sa(import.meta.url,["../../.."])}function Li(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():gR}function Ni(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():hR}async function bR(e,t){let n=e.commandRunner??wR,r=Ni(e),i=Li(e),o=`${r}@${i}`,s=["npm","install","-g",o];e.repair===!0&&s.push("--force");let a=await vR(),c={requested:!0,status:"planned",package:r,target:o,command:s,before_version:a,repair:e.repair===!0};if(t)return c;try{await n(s[0],s.slice(1));let d=await n("pm",["--version"]);return{...c,status:"updated",after_version:d.stdout.trim()||void 0}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function kR(e){return mR.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function xR(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!kR(n)&&e.package&&e.package.trim().length>0?`npm:${e.package.trim()}@${t}`:e.input.startsWith("npm:")?e.input:`npm:${e.input}`}return e.input}async function SR(e,t){let n=xR(e,t);return e.kind!=="local"||await D(n)?n:await D(e.location)?e.location:n}function ER(e,t,n,r){let i=["pm","package","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&r&&r.trim().length>0&&i.push("--ref",r.trim()),i}async function Lf(e,t){let n=yR(e,t);return(await ge(n.selected_root)).state.entries.filter(i=>i.scope===e)}async function RR(e,t,n){let r=await Lf(e,t);return r.find(i=>Mf(i,n.name))??r.find(i=>Mi(i.directory)===Mi(n.directory))}async function AR(e,t,n,r,i){let o=Li(t),s=await SR(e.source,o),a=ER(e.source,s,r,e.source.ref),c={name:e.name,directory:e.directory,scope:r,source:e.source,status:"planned",command:a,previous_version:e.manifest_version};if(i)return c;try{await us(s,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await RR(r,n,e);return{...c,status:"updated",installed_version:d?.manifest_version}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function IR(e,t,n,r){let i=[n?e.status:void 0,...t.map(o=>o.status)].filter(o=>typeof o=="string");return{requested_cli:n,requested_packages:r,planned:i.filter(o=>o==="planned").length,updated:i.filter(o=>o==="updated").length,skipped:i.filter(o=>o==="skipped").length,failed:i.filter(o=>o==="failed").length}}async function CL(e,t,n){let r=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&t.packagesOnly===!0){let m=["package","upgrade",...r?[r]:[],"--packages-only","--dry-run",..._R[Nf(t)]];throw new w('Options "--cli-only" and "--packages-only" are mutually exclusive.',y.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:Ue(m),suggested_retry_args:m}})}let i=Nf(t),o=t.dryRun===!0;if(t.cliOnly===!0&&r)throw new w('A package target cannot be used with "--cli-only".',y.USAGE);let s=!(t.packagesOnly===!0||r),a=t.cliOnly!==!0,c=s?await bR(t,o):{requested:!1,status:"skipped",package:Ni(t),target:`${Ni(t)}@${Li(t)}`,command:["npm","install","-g",`${Ni(t)}@${Li(t)}`],repair:t.repair===!0,reason:"not_requested"},d=a?await Lf(i,n):[];if(r&&(d=d.filter(m=>Mf(m,r)),d.length===0))throw new w(`Managed package "${r}" was not found in ${i} scope.`,y.NOT_FOUND);let l=[];for(let m of d)l.push(await AR(m,t,n,i,o));let u=IR(c,l,s,a);return{ok:u.failed===0,action:"upgrade",dry_run:o,scope:i,target:r,cli:c,packages:l,summary:u}}import _n from"node:fs/promises";import ji from"node:path";import Fi from"node:fs/promises";import da from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b26cf702-330e-5cf5-8371-204220d5c5c9")}catch{}})();var CR=864e5;function TR(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function $R(e,t){let n;try{n=await Fi.readdir(e,{withFileTypes:!0})}catch(i){if(U(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let o=da.join(e,i.name),s;try{s=await Fi.readdir(o)}catch(a){U(a)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of s)a.endsWith(".json")&&r.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function Ff(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*CR,s=da.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await $R(s,a.warnings);for(let d of c){let l=da.join(s,d),u=`checkpoints/${d}`;a.scanned+=1,r?.onRead&&a.warnings.push(...await r.onRead(l));let m;try{m=await Fi.readFile(l,"utf8")}catch(_){if(U(_)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let p=TR(m),f=p===null?Number.NaN:Date.parse(p);if(!Number.isFinite(f)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:p,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=i-f,g={file:u,created_at:p,age_seconds:Math.floor(h/1e3),stale:h>o,reason:h>o?"expired":"active"};if(!g.stale){a.retained.push(u),a.entries.push(g);continue}if(!n){try{await Fi.unlink(l)}catch(_){if(!U(_)){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(g);continue}}r?.onWrite&&a.warnings.push(...await r.onWrite(l))}a.removed.push(u),a.entries.push(g)}return a}import la from"node:fs/promises";import jf from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7df80849-51e1-5efa-b40a-b44088f941a9")}catch{}})();var OR=1440*60*1e3,DR=new Set(["committed","compensated"]);function PR(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function NR(e,t,n,r,i){let o=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(o))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let s=r-o;return DR.has(t)?s>i?{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"active"},remove:!1}}async function MR(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],o=PR(await la.readFile(e,"utf8")),s=NR(t,o.status,o.updatedAt,r.nowMs,r.retentionMs);return s.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),s.remove&&!r.dryRun&&(await la.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:s,warnings:i}}async function Uf(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*OR,s=jf.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await la.readdir(s)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(U(d))return a;throw d}for(let d of c){let l=jf.join(s,d),u=`transactions/sdk/${d}`,m=await MR(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:o});a.warnings.push(...m.warnings),a.scanned+=1;let{decision:p}=m;if(!p.remove){a.retained.push(u),a.entries.push(p.entry);continue}a.removed.push(u),a.entries.push(p.entry)}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="76f8405f-138d-5119-a300-f068354394a5")}catch{}})();var rr=["index","embeddings","runtime","locks","checkpoints","transactions"],LR=1440*60*1e3,FR=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function jR(e,t,n){let r=t.relativePath,i=ji.join(e,r),o=await Ve({path:i,scope:"project"});try{let s=await _n.stat(i);if(t.kind==="file"&&!s.isFile())return{removed:!1,warnings:[...o,`not_a_file:${r}`]};if(t.kind==="directory"&&!s.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await _n.unlink(i):await _n.rm(i,{recursive:!0,force:!0});let a=await ne({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...a]}}catch(s){if(U(s))return{removed:!1,warnings:o};throw s}}async function UR(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],o=[],s=Date.now()-LR;for(let a of n){let c=ji.join(e,a.relativePath);if(!await D(c))continue;let d=(await _n.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=ji.posix.join(a.relativePath,l),m=ji.join(c,l);o.push(...await Ve({path:m,scope:"project"}));let p=await _n.stat(m).catch(f=>{if(!U(f))throw f});if(p){if(p.mtimeMs>s){i.push(u);continue}r.push(u),!t&&(await _n.rm(m,{recursive:!0,force:!0}),o.push(...await ne({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:o}}function zR(e){if(!e||e.length===0)return[...rr];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new w(`--scope requires at least one value (${rr.join(",")})`,y.USAGE);let n=new Set;for(let r of t){if(!rr.includes(r))throw new w(`Invalid --scope value "${r}". Expected one or more of: ${rr.join(", ")}`,y.USAGE);n.add(r)}return rr.filter(r=>n.has(r))}function WR(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function ZL(e,t={}){let n=M(process.cwd(),e.path);await X(n);let r=await C(n),i=t.dryRun===!0,o=zR(t.scope),s=FR.filter(f=>o.includes(f.scope)),a=[],c=[],d=[];for(let f of s){let h=await jR(n,f,i);h.removed?a.push(f.relativePath):c.push(f.relativePath),d.push(...h.warnings)}if(o.includes("runtime")){let f=await UR(n,i);a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings)}let l;if(o.includes("locks")){let f=await rl(n,{dryRun:i,hooks:{onRead:h=>Ve({path:h,scope:"project"}),onWrite:h=>ne({path:h,scope:"project",op:"gc:lock_remove"})}});a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),l={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length}}let u;if(o.includes("transactions")){let f=r.checkpoints.retention_days,h=await Uf(n,{dryRun:i,retentionDays:f,hooks:{onRead:g=>Ve({path:g,scope:"project"}),onWrite:g=>ne({path:g,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:f}}let m;if(o.includes("checkpoints")){let f=r.checkpoints.retention_days,h=await Ff(n,{dryRun:i,retentionDays:f,hooks:{onRead:g=>Ve({path:g,scope:"project"}),onWrite:g=>ne({path:g,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),m={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:f}}d.push(...await wr({mode:i?"gc:dry-run":"gc",total_items:s.length}));let p=WR({dryRun:i,scopes:o,removed:a});return{ok:d.length===0,dry_run:i,scope:o,removed:a,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:p,generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e900c117-6d8d-55d3-86df-f543dc499930")}catch{}})();function zf(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function Wf(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?Ue([...r,"merge","report"],n):e==="history_evidence_invalid"?Ue([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?Ue([...r,"merge","reconcile"],n):e==="history_repair_required"?Ue([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?Ue([...r,"merge","install"],n):null}function qf(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(r=>typeof r=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(r=>typeof r=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function uF(e){let t=M(process.cwd(),e.path);await X(t);let n=await C(t),r=W(n,z()),i=[],o=await Si({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),s=await Ze(t),[a,c,d,l]=await Promise.all([Xr(t,en(n)),s===null?Promise.resolve(null):tn(s),rt(s??t,{includeLossless:!0,pmRoot:t}),Ei(t,o,!1)]),{pendingDecisions:u,lossless:m}=cn(d.receipts),p=[...new Set(u.map(_=>_.item_id))].sort((_,v)=>_.localeCompare(v)),f=l.check.details,h=qf(f),g=zf({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:m.length,historyEvidenceValid:h.evidence_valid,driftedItemCount:h.drifted_item_count,fence:a,drivers:c});return{ok:g==="ready",state:g,merge_fence:{committed:a,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:p.slice(0,25),pending_item_ids_truncated:p.length>25,lossless_count:m.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:h,next_action:{command:Wf(g,t),reason:g},warnings:[...new Set(i)].sort((_,v)=>_.localeCompare(v)),generated_at:T()}}function mF(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
46
- `)}var pF={commandForWorkspacePositionState:Wf,normalizeWorkspaceHistoryDrift:qf,selectWorkspacePositionState:zf};import qR from"node:fs/promises";import ir 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]="1bcd20e1-2995-56ef-8d04-f265b8282c19")}catch{}})();var ua="index/manifest.json",ma="search/embeddings.jsonl",HR="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function BR(e){return e.progress===!0||process.stderr.isTTY===!0}function ce(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
47
- `)}catch{}}function GR(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new w("Reindex mode must be one of keyword|semantic|hybrid",y.USAGE)}async function JR(e,t,n,r){let i=[];return{candidates:await Ec(e,t,n,i,r),warnings:i}}async function fa(e,t,n,r,i){let o=Ot(z()),s=[];for(let a of t)if(!(i&&!i.has(a.metadata.id))){if(typeof a.body=="string"){s.push({metadata:a.metadata,body:a.body});continue}try{let c=await qR.readFile(a.item_path,"utf8"),d=Ut(c,{format:a.item_format,schema:n,extensionFieldNames:o,onWarning:l=>r.push(l)});s.push({metadata:a.metadata,body:d.body})}catch{r.push(`item_list_item_read_failed:${ir.relative(e,a.item_path)}`),s.push({metadata:a.metadata,body:""})}}return s}function VR(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:Fc(e,{fields:n})}}var yn=Z;function KR(e){let t=z(),n=yn(e.search?.provider);if(!n)return null;let r=Tc(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=yn(i.name)??yn(r.definition.name);if(!o)return null;let s=i.embedBatch,a=i.embed_batch,c=i.embed,d=typeof s=="function"?s:typeof a=="function"?a:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:o,embedBatch:d,embed:l}}function YR(e){let t=z(),n=yn(e.vector_store?.adapter);if(!n)return null;let r=$c(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=yn(i.name)??yn(r.definition.name);if(!o)return null;let s=i.upsert,a=i.delete;return{adapterName:o,...typeof s=="function"?{upsert:s}:{},...typeof a=="function"?{delete:a}:{}}}function pa(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new w(`Invalid vector returned by ${t}`,y.GENERIC_FAILURE);return e}async function XR(e,t,n){let r=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let o=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:r}));if(!Array.isArray(o))throw new w(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,y.GENERIC_FAILURE);return o.map((s,a)=>pa(s,`extension search provider "${e.name}" embedBatch output at index ${a}`))}if(!e.embed)throw new w(`Extension search provider "${e.name}" does not implement embed/embedBatch`,y.GENERIC_FAILURE);let i=[];for(let[o,s]of n.entries()){let a=await Promise.resolve(e.embed({input:s,settings:t,model:r}));i.push(pa(a,`extension search provider "${e.name}" embed output at index ${o}`))}return i}function Hf(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function Bf(e,t,n){let r=n?St(n.name,Hf(e)):t?St(t.name,t.model):null;if(!r)throw new w("No embedding identity available for semantic reindex mode",y.USAGE);return r}function ZR(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function Gf(e,t,n,r,i,o,s,a){let c=r?.name??n?.name,d=jc(c,e.search.embedding_corpus_max_characters).maxCharacters,l=ro(e),u=i.map(f=>Uc(f,{providerName:c,maxCharacters:d,fields:l})),m=[],p=null;if(r)try{m=await XR(r,e,u),p=St(r.name,Hf(e))}catch(f){if(!n)throw new w(`Extension search provider "${r.name}" failed to generate embeddings: ${f instanceof Error?f.message:String(f)}`,y.GENERIC_FAILURE);o.push(`Extension search provider "${r.name}" failed; falling back to built-in provider (${f instanceof Error?f.message:String(f)})`)}if(m.length===0){if(!n)throw new w(`No embedding executor available for reindex mode '${t}'`,y.USAGE);let f=await zc(n,e,u,{onProgress:h=>{h.phase==="complete"&&(s.batches_completed=h.batch_index),ce(a,`embedding_batch_${h.phase} batch=${h.batch_index}/${h.batch_total} size=${h.batch_size} completed_inputs=${h.completed_inputs}/${h.total_inputs}`)}});o.push(...f.warnings),m=f.vectors,p=St(n.name,n.model)}if(ce(a,`embedding_complete vectors=${m.length}`),m.length!==i.length)throw new w(`Embedding output size mismatch (expected ${i.length}, received ${m.length})`,y.GENERIC_FAILURE);if(!p)throw new w(`No embedding identity available for reindex mode '${t}'`,y.USAGE);return{vectors:m,embeddingIdentity:p}}async function QR(e,t,n,r,i,o){let s=Object.keys(n);if(t){if(s.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:s.sort((a,c)=>a.localeCompare(c)),settings:r}))}catch(a){throw new w(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${a instanceof Error?a.message:String(a)}`,y.GENERIC_FAILURE)}else s.length>0&&i.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${s.length}`);if(!e)return}e&&await Hc(e,s,{},o)}async function Jf(e,t,n,r,i){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:r}))}catch(o){throw new w(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${o instanceof Error?o.message:String(o)}`,y.GENERIC_FAILURE)}else i.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await qc(e,n)}}function eA(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function tA(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(r=>({id:r.metadata.id,type:r.metadata.type,status:r.metadata.status,priority:r.metadata.priority,updated_at:r.metadata.updated_at}))}}function nA(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Sn(e.settings);if(!t.active&&!e.extensionEmbedding)throw new w(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,y.USAGE);let n=Dr(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new w(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,y.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function rA(e){let t=W(e.settings,z()),n=await JR(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(r=>({metadata:r.metadata,body:typeof r.body=="string"?r.body:""}))}}async function iA(e){let t=await Jt(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return Bf(e.settings,Sn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&Gt(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(HR))}async function oA(e){let t=await Jt(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=Bf(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(d=>d.metadata.id)),i=ZR(t.entries,r),o=Gt(t.embedding,n);e.forceFullSemantic&&!o&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let s=e.forceFullSemantic||o?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),a=new Set(s.map(d=>d.metadata.id)),c=a.size>0?await fa(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,a):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:i,resetRequired:o,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function sA(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await fa(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,ce(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await Gf(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:io(r.vectors,"Reindex embeddings")}}async function aA(e){let t=await Gf(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=io(n,"Reindex embeddings");if(!(!e.resetRequired&&(Gt(e.ledgerEmbedding,r)||Gc(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let s=await sA(e);return n=s.vectors,r=s.embeddingIdentity,i=s.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:s.staleDocuments,vectorDimension:i,resetRequired:!0}}async function cA(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(ce(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new w(`Extension vector adapter "${t}" does not support upserting vectors.`,y.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,ce(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof w)throw t;if(!e.activeVectorStore)throw new w(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,y.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),ce(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){ce(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Wc(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,ce(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new w(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,y.USAGE)}function dA(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:pa(t[r],`reindex embeddings output at index ${r}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function lA(e){ce(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await aA({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(ce(e.progressEnabled,"vector_reset_start"),await QR(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),ce(e.progressEnabled,"vector_reset_complete")):await Jf(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=dA(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await cA({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:Bc(t.embeddingIdentity,t.vectorDimension)}}async function uA(e){let t=await oA(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(o=>[o.metadata.id,o.metadata.updated_at]));if(ce(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return ce(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await Jf(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await lA({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let i=new Map(r.staleDocuments.map(o=>[o.metadata.id,o]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(o=>i.get(o.metadata.id)??o),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:r.embeddingMetadata}}async function mA(e){let t=ir.join(e.pmRoot,ua),n=ir.join(e.pmRoot,ma),r=ro(e.settings),i=e.documentsForKeywordArtifacts.map(s=>JSON.stringify(VR(s,e.mode,r))).join(`
48
- `);ce(e.progressEnabled,"writing keyword artifacts"),await de(t,`${JSON.stringify(e.manifest,null,2)}
49
- `),await de(n,`${i}
50
- `);let o=[];if(e.mode!=="keyword")try{ce(e.progressEnabled,"writing vectorization status ledger"),await Jc(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 wF(e,t){let n=GR(e.mode),r=BR(e),i=e.full===!0;ce(r,`start mode=${n}`);let o=M(process.cwd(),t.path);await X(o);let s=Or(await C(o)).settings,a=null;try{a=await fe(o,Lc,s.locks.ttl_seconds,V(void 0,"pm-reindex"),!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms)}catch(c){throw c instanceof w&&c.exitCode===y.CONFLICT?new w("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",y.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=KR(s),d=YR(s),l=nA({requestedMode:n,pmRoot:o,settings:s,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;ce(r,"loading item corpus");let m=await rA({pmRoot:o,settings:s}),p=m.warnings,{documentCandidates:f,metadataDocuments:h}=m;ce(r,`loaded_items=${h.length}`);let g=T(),_=tA(u,g,h),v=ir.join(o,ua),k=ir.join(o,ma),x=u==="keyword"?await fa(o,f,s.schema,p):h,b=[],I={},S=null,E=eA(u);if(u==="keyword"&&await iA({pmRoot:o,settings:s,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:p}),u!=="keyword"){let H=await uA({pmRoot:o,settings:s,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:f,metadataDocuments:h,documentsForKeywordArtifacts:x,forceFullSemantic:i,reindexWarnings:p,semanticWarnings:b,semanticSummary:E,progressEnabled:r});x=H.documentsForKeywordArtifacts,I=H.vectorizationLedgerEntries,S=H.vectorizationEmbeddingMetadata}let A=await mA({pmRoot:o,mode:u,manifest:_,documentsForKeywordArtifacts:x,settings:s,vectorizationLedgerEntries:I,vectorizationEmbeddingMetadata:S,progressEnabled:r}),F=[...await ne({path:v,scope:"project",op:"reindex:manifest"}),...await ne({path:k,scope:"project",op:"reindex:embeddings"}),...await wr({mode:u,total_items:h.length})];return ce(r,"done"),{ok:!0,mode:u,total_items:h.length,semantic:E,artifacts:{manifest:ua,embeddings:ma},warnings:[...p,...b,...A,...F],generated_at:g}}finally{await a?.()}}export{iC as a,Cl as b,P as c,ke as d,ze as e,Vt as f,rd as g,od as h,Et as i,so as j,rh as k,lo as l,uo as m,dd as n,Yt as o,An as p,po as q,kh as r,hd as s,In as t,fo as u,Ur as v,ho as w,_d as x,yd as y,wd as z,Cn as A,Wr as B,bd as C,kd as D,xd as E,Sd as F,Id as G,oI as H,$ as I,re as J,sI as K,vo as L,aI as M,cI as N,Md as O,dI as P,lI as Q,uI as R,mI as S,pI as T,bo as U,fI as V,hI as W,wo as X,gI as Y,_I as Z,Fd as _,yI as $,Uh as aa,zd as ba,II as ca,On as da,CI as ea,Jh as fa,Vh as ga,TI as ha,Kh as ia,yg as ja,wg as ka,Ze as la,EC as ma,Rg as na,p_ as oa,CT as pa,TT as qa,$T as ra,Mn as sa,OT as ta,DT as ua,PT as va,NT as wa,MT as xa,LT as ya,FT as za,jT as Aa,UT as Ba,zT as Ca,WT as Da,Gu as Ea,us as Fa,Bd as Ga,Gd as Ha,Kd as Ia,gi as Ja,GO as Ka,rt as La,JO as Ma,VO as Na,ws as Oa,vD as Pa,bD as Qa,Gr as Ra,Jr as Sa,Ym as Ta,hP as Ua,Zm as Va,xp as Wa,AP as Xa,np as Ya,Ep as Za,vN as _a,bN as $a,Qx as ab,eS as bb,EN as cb,RN as db,AN as eb,IN as fb,nS as gb,rS as hb,iS as ib,CN as jb,Ip as kb,sS as lb,Cp as mb,js as nb,$p as ob,aS as pb,cS as qb,dS as rb,qs as sb,Hs as tb,jN as ub,UN as vb,zN as wb,jS as xb,WM as yb,bf as zb,er as Ab,Pi as Bb,ra as Cb,If as Db,Cf as Eb,oL as Fb,YE as Gb,Tf as Hb,$f as Ib,aa as Jb,lR as Kb,bL as Lb,CL as Mb,ZL as Nb,uF as Ob,mF as Pb,pF as Qb,wF as Rb};
51
- //# sourceMappingURL=chunk-Y6JJIX6I.js.map
15
+ `;return c===i?{path:r,changed:!1}:(n||await k_(r,c,"utf8"),{path:r,changed:!0})}function tn(e){let t=W(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function Xr(e,t){let n=ie.resolve(e),r=null,i="",o=n;for(let v=0;v<8;v+=1){let k=ie.join(o,".gitattributes");try{let S=await Yr(k,"utf8");if(S.includes(en)||S.includes(Kr)){r=o,i=S;break}}catch{}let x=ie.dirname(o);if(x===o)break;o=x}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=ie.join(r,".gitattributes"),a=i.includes(en),c=a?en:Kr,d=a?Do:_l,l=i.indexOf(c),u=i.indexOf(d),m=u>l?i.slice(l+c.length,u).split(`
16
+ `).map(v=>v.trim()).filter(v=>v.length>0):[],p=Mo(No(r,n),t),f=new Set(m),h=new Set(p),_=p.filter(v=>!f.has(v)),g=m.filter(v=>!h.has(v));return{status:_.length>0||g.length>0?"drift":"ok",path:s,missing_patterns:_,stale_patterns:g,schema_scope:"project"}}async function nn(e){let t=gl(),n=[],r=[];for(let i of yl){let o=`merge.${i.key}.driver`,s=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`,a=`${t}${s}`;try{let{stdout:c}=await Po("git",["config","--local","--get",o],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),d=c.trim();d!==a&&!await A_(d,s)&&r.push(o)}catch{n.push(o)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function bl(e){let t;try{t=await wl(ie.resolve(e))}catch{return{status:"no_git"}}let n=No(t,ie.resolve(e)),r=await C(e),i=V(void 0,r.author_default),o=await fe(e,E_,r.locks.ttl_seconds,i,!1,Pe(r).force_required_for_stale_lock,r.locks.wait_ms);try{let s=ie.join(t,".gitattributes"),a;try{a=await Yr(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&U(u))return{status:"not_installed",path:s};throw u}if(!a.includes(en)&&!a.includes(Kr))return{status:"not_installed",path:s};let c=await C(e),d=tn(c),l=await vl(t,Mo(n,d),!1);return{status:l.changed?"refreshed":"unchanged",path:l.path}}finally{await o()}}async function $C(e,t){let n=R_({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await X(r);let i=await wl(n.workspace_start);return I_({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function I_(e){let t=ie.resolve(e.pmRoot),n=ie.resolve(e.workspaceRoot),r=e.dryRun===!0,i,o;try{[i,o]=await Promise.all([Oo(t),Oo(n)])}catch(p){throw new w(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(p)}`,y.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let s=No(o,i);if($o(s))throw new w(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,y.USAGE);let a=await C(i),c=tn(a),d=Mo(s,c),l=[],u=gl();for(let p of yl)l.push({key:`merge.${p.key}.name`,value:p.name}),l.push({key:`merge.${p.key}.driver`,value:`${u} merge driver ${p.artifact} "%O" "%A" "%B"${p.itemPath===void 0?"":` --item-path ${p.itemPath}`}`});if(!r)try{for(let p of l)await Po("git",["config","--local",p.key,p.value],{cwd:o,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new w(`Cannot install repository-local merge drivers in ${o}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,y.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await vl(o,d,r);return{ok:!0,dry_run:r,workspace_root:o,pm_root:i,gitattributes:{path:m.path,changed:m.changed,patterns:d,schema_scope:"project"},git_config:l,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();var C_=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function T_(e){let t=C_.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function $_(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function kl(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let s of e){let a=typeof s=="string"?s.trim():"";if(a.length===0)continue;let c=T_(a);if(c===void 0)continue;let d=i.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(a),i.set(c,d)}let o=[];for(let[s,a]of i.entries()){if(a.count<n)continue;let c=$_(s);o.push({name:c,prefix:s,count:a.count,examples:a.examples,shadows_builtin:Wa(c)!==void 0})}return o.sort((s,a)=>a.count-s.count||s.name.localeCompare(a.name)),o}import{createHash as Pl}from"node:crypto";import It from"node:fs/promises";import on from"node:path";import{mkdir as O_,readFile as D_}from"node:fs/promises";import Il 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]="6ed4a26f-2ae2-556a-87db-56844108757f")}catch{}})();var Lo=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},P_="sdk-workspace-transaction",N_=/^[a-zA-Z0-9._-]+$/,M_=30,L_=3e3;function xl(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!N_.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Sl(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function El(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function Cl(e,t){return Il.join(e,"transactions","sdk",`${t}.json`)}async function mt(e,t){t.updatedAt=T();let n=Cl(e,t.transactionId);await O_(Il.dirname(n),{recursive:!0}),await le(n,`${JSON.stringify(t,null,2)}
17
+ `)}function F_(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function At(e){return Object.assign(Object.create(null),e)}function j_(e,t){try{let n=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function Fo(e,t){return e===void 0?void 0:j_(e,t)}function jo(e,t,n,r){let i=Fo(n,r);i===void 0?delete e[t]:e[t]=i}function Rl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Al(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function U_(e,t){if(!Al(e.startedStepIds,t)||!Al(e.completedStepIds,t)||!Rl(e.results)||!Rl(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,o=new Set(i);return Object.keys(e.compensationData).some(s=>!r.has(s))||Object.keys(e.results).some(s=>!o.has(s))?!1:e.status==="committed"?t.every(s=>o.has(s)):e.status!=="compensated"||o.size===0&&r.size===0}function z_(e,t,n){let r;try{r=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let i=r,o=i.schemaVersion===1&&i.transactionId===t,s=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((l,u)=>l===n[u]),a=U_(i,n),c=F_(i),d=["applying","compensating","compensated","committed"].includes(String(i.status));if(!o||!s||!a||!c||!d)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...i,results:At(i.results),compensationData:At(i.compensationData)}}async function W_(e,t,n,r,i){let o=i,s=o!==void 0;if(o?.status==="compensating"&&await Tl(e,o),o===void 0||o.status==="compensated"){let a=T();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??a,updatedAt:a,stepIds:r,startedStepIds:[],completedStepIds:[],results:At(),compensationData:At()},await mt(e.pmRoot,o),await et(e,o,"prepared")}return{journal:o,recovered:s}}async function H_(e,t,n){try{await B_(t,e.steps),await mt(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let o of e.steps){if(r.has(o.id))continue;let s=await o.inspect(),a=Fo(s.result,`Step ${o.id} result`);if(s.state!=="applied"){let c=await o.prepareCompensation?.();jo(t.compensationData,o.id,c,`Step ${o.id} compensation data`),i.add(o.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await mt(e.pmRoot,t);let d=await o.apply();a=Fo(d,`Step ${o.id} result`)}await et(e,t,"step_applied",o.id),r.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),jo(t.results,o.id,a,`Step ${o.id} result`),await mt(e.pmRoot,t),await et(e,t,"step_recorded",o.id)}return await et(e,t,"committing"),t.status="committed",await mt(e.pmRoot,t),await et(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:At(t.results)}}catch(r){if(r instanceof Lo||t.status==="committed")throw r;try{await Tl(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function q_(e,t,n){try{return z_(await D_(Cl(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&U(r))return;throw r}}async function et(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function B_(e,t){let n=new Set,r=At();for(let i of t){let o=await i.inspect();o.state==="applied"&&(n.add(i.id),jo(r,i.id,o.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function Tl(e,t){t.status="compensating",await mt(e.pmRoot,t),await et(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!r.has(i.id)&&!n.has(i.id))continue;let o;try{o=r.has(i.id)&&(await i.inspect()).state==="applied"}catch{o=r.has(i.id)}o&&(await et(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),r.delete(i.id),t.completedStepIds=e.steps.map(s=>s.id).filter(s=>n.has(s)),t.startedStepIds=e.steps.map(s=>s.id).filter(s=>r.has(s)),delete t.results[i.id],delete t.compensationData[i.id],await mt(e.pmRoot,t),await et(e,t,"step_compensated",i.id)}t.status="compensated",await mt(e.pmRoot,t),await et(e,t,"compensated")}async function $l(e){let t=Sl(e.pmRoot,"Transaction pmRoot"),n=xl(e.transactionId,"Transaction id"),r=Sl(e.author,"Transaction author"),i=El(e.lockTtlSeconds,M_,"Transaction lock TTL"),o=El(e.lockWaitMs,L_,"Transaction lock wait"),s=[...e.steps];if(s.length===0)throw new TypeError("Workspace transaction requires at least one step");let a=s.map(l=>{let u=xl(l.id,"Transaction step id");if(u!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return u});if(new Set(a).size!==a.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:s,lockTtlSeconds:i,lockWaitMs:o},d=await fe(t,P_,i,r,!1,!1,o);try{let l=await q_(t,n,a),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:At(l.results)};let m=await W_(c,n,r,a,l);return await H_(c,m.journal,u||m.recovered)}finally{await d()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60738c1f-3b44-5f8a-82c9-99d2b2de1e51")}catch{}})();function tt(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Nl(e){let t=tt(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Ml(e,t){let n=zo(e),r=tt(t,"migrationScope");return`auto-${Pl("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function zo(e){let t=e.kind==="rename-type"?{kind:e.kind,from:tt(e.from,"source"),to:tt(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:ue(tt(e.from,"source")),to:ue(tt(e.to,"target")),...e.type===void 0?{}:{type:tt(e.type,"type")}}:{kind:e.kind,from:ue(tt(e.from,"source")),to:ue(tt(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function G_(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function J_(e,t,n){let r=be(t.schema),i=G_(n);return Ue(e,r.files[i],Ae[i])}function Ll(e,t){return on.join(e,"transactions","schema",`${t}-plan.json`)}function Zr(e){return e.length===0?null:JSON.parse(e)}async function rn(e){let t=await Y(e);return{exists:t!==null,raw:t??""}}async function Fl(e,t){t.exists?await le(e,t.raw):await It.rm(e,{force:!0})}function V_(e,t,n){let r=Ve(e),i=r.definitions.findIndex(s=>s.name.trim().toLowerCase()===t.from.toLowerCase()),o=r.definitions.findIndex(s=>s.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return lt(r);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[i],name:t.to})}else i>=0&&r.definitions.splice(i,1);return lt(r)}function K_(e,t,n){let r=Mt(e),i=r.fields.findIndex(s=>s.key===t.from),o=r.fields.findIndex(s=>s.key===t.to);if(n==="stage"){if(o>=0)return Lt(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let s=r.fields[i];r.fields.push({...s,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&r.fields.splice(i,1);return Lt(r)}function Y_(e,t,n){let r=Ft(e),i=r.statuses.findIndex(s=>s.id===t.from),o=r.statuses.findIndex(s=>s.id===t.to);if(n==="stage"){if(o>=0)return jt(r);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[i],id:t.to})}else i>=0&&r.statuses.splice(i,1);return jt(r)}function X_(e,t,n){return t.kind==="rename-type"?V_(e,t,n):t.kind==="rename-field"?K_(e,t,n):Y_(e,t,n)}function pt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Wo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function sn(e){return Array.isArray(e)?e.map(t=>Wo(t)).filter(t=>t!==void 0):[]}function Z_(e,t){for(let n of sn(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>pt(r,t)));for(let n of sn(e.type_workflows))n.type=pt(n.type,t)}function Q_(e,t){for(let r of sn(e.definitions))r.default_status=pt(r.default_status,t);let n=Wo(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=pt(i,t);for(let r of sn(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(o=>pt(o,t)):i))}function eg(e,t){for(let n of sn(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>pt(i,t)));for(let r of["options","command_option_policies"])for(let i of sn(n[r])){let o=r==="options"?"key":"option";i[o]=pt(i[o],t)}}}function tg(e,t){let n=Wo(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=pt(n[r],t)}function Uo(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?Z_(r,t):t.kind==="rename-field"?eg(r,t):Q_(r,t),tg(r,t),`${JSON.stringify(r,null,2)}
18
+ `}function jl(e,t){if(t.kind==="rename-type"){let r=Ve(e).definitions;return{source:r.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=Mt(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=Ft(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function ng(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function rg(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function Ul(e,t){let n=zo(t.request),r=t.migrationId===void 0?Ml(n,t.migrationScope??"plan"):Nl(t.migrationId),i=e.map(c=>rg(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),o=Pl("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),s=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),a=i.filter(c=>!s.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:o,affected_item_count:i.length,pending_item_count:a.length,skipped_completed_count:i.length-a.length,items:Object.freeze(a)})}async function ig(e){let t=W(e.settings,z()),n=[...new Set(Object.values(t.type_to_folder))],r=await Cr(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},o=r?await Ec({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:i}):null;return o?{items:o.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Ye(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function og(e,t){let n=await Y(Ll(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new w(`Stored schema migration plan "${t}" is invalid: ${$a(r)}`,y.GENERIC_FAILURE)}}async function sg(e,t){let n=Ll(e,t.migration_id);await It.mkdir(on.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await le(n,`${JSON.stringify(r,null,2)}
19
+ `)}function ag(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function cg(e){let t=await Bt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new w(`Schema migration item "${e.id}" no longer exists.`,y.NOT_FOUND);return(await ut(t,{schema:e.settings.schema})).document.metadata}function Ol(e,t,n){let r=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let o=e.metadata;if(Object.prototype.hasOwnProperty.call(o,i)&&!Object.prototype.hasOwnProperty.call(o,r))return[];if(!Object.prototype.hasOwnProperty.call(o,r)||Object.prototype.hasOwnProperty.call(o,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return o[i]=o[r],delete o[r],[r,i]}function Dl(e){return{id:e.id,inspect:async()=>{let t=await rn(e.filePath),n=jl(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await rn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await rn(e.filePath);return await le(e.filePath,X_(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await Fl(e.filePath,{exists:t.exists,raw:t.raw})}}}function dg(e){return{id:e.stepId,inspect:async()=>{let t=await rn(e.filePath);return{state:Uo(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await rn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await rn(e.filePath);return await le(e.filePath,Uo(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await Fl(e.filePath,{exists:t.exists,raw:t.raw})}}}function lg(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await C(e.pmRoot),n=W(t,z()).type_to_folder,r=await cg({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=ng(r,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await C(e.pmRoot),n=W(t,z()).type_to_folder,r=await xt({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:Ol(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await C(e.pmRoot),n=W(t,z()).type_to_folder;await xt({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:Ol(r,e.request,"reverse")}}})}}}async function ug(e){let t=await og(e.pmRoot,e.migrationId);if(t){if(!ag(t.request,e.request))throw new w(`Schema migration id "${e.migrationId}" already belongs to a different request.`,y.CONFLICT);return{plan:t,stored:!0}}let n=await ig({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Ul(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function mg(e){let t=jl(await Y(e.schemaPath)??"",e.request);if(!t.source)throw new w(`Schema migration source "${e.request.from}" is not a custom definition.`,y.NOT_FOUND);if(t.target)throw new w(`Schema migration target "${e.request.to}" already exists.`,y.CONFLICT);await sg(e.pmRoot,e.plan)}async function pg(e){let t=be(e.settings.schema),n=[...new Set([["types",Ae.types],["fields",Ae.fields],["workflows",Ae.workflows]].map(([i,o])=>Ue(e.pmRoot,t.files[i],o)).filter(i=>i!==e.schemaPath))];try{let i=on.join(e.pmRoot,"templates"),o=await It.readdir(i,{withFileTypes:!0});n.push(...o.filter(s=>s.isFile()&&s.name.toLowerCase().endsWith(".json")).map(s=>on.join(i,s.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!U(i))throw i}n.sort((i,o)=>i.localeCompare(o));let r=[];for(let i of n){let o=await Y(i);o!==null&&Uo(o,e.request)!==o&&r.push({filePath:i,beforeRaw:o})}return{paths:n,snapshots:r}}async function fg(e){for(let t of e.snapshots){let n=await It.readFile(t.filePath,"utf8"),r=on.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await to({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Zr(t.beforeRaw),after:Zr(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function hg(e,t,n){let r=zo(e),i=M(process.cwd(),n.path);await X(i);let o=t.migrationId===void 0?Ml(r,await It.realpath(i)):Nl(t.migrationId),s=await C(i),a=V(t.author,s.author_default),c=await ug({pmRoot:i,settings:s,migrationId:o,request:r}),d=c.plan;if(t.dryRun===!0)return{...d,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=J_(i,s,r),u=await It.readFile(l,"utf8");c.stored||await mg({pmRoot:i,schemaPath:l,request:r,plan:d});let m=await pg({pmRoot:i,schemaPath:l,settings:s,request:r}),p=[Dl({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...m.paths.map((g,v)=>dg({filePath:g,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(g=>lg({pmRoot:i,id:g.id,request:r,author:a,force:t.force===!0})),Dl({id:"retire-source",filePath:l,request:r,phase:"retire"})],f=await $l({pmRoot:i,transactionId:`schema-${o}`,author:a,steps:p,lockTtlSeconds:Math.max(s.locks.ttl_seconds,300),lockWaitMs:s.locks.wait_ms}),h=await It.readFile(l,"utf8"),{historyPath:_}=await to({pmRoot:i,author:a,documentPath:on.relative(i,l).replaceAll("\\","/"),before:Zr(u),after:Zr(h),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms});return await fg({pmRoot:i,author:a,settings:s,request:r,plan:d,snapshots:m.snapshots}),{...d,action:r.kind,applied:!0,recovered:f.recovered,migrated_item_count:d.affected_item_count,workspace_history_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]="264088a5-09d1-52ed-8b12-af00392e1a5f")}catch{}})();var NT=["add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Qr="schema-types",zl="schema-statuses",Wl="schema-fields";function ft(e){return Ar({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function MT(e,t,n){let r=M(process.cwd(),n.path);await nt(r);let i;try{i=Vi({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(p){throw new w(p instanceof Error?p.message:String(p),y.USAGE)}let o=await C(r),s=be(o.schema),a=Ue(r,s.files.types,Ae.types),c=[],d=V(t.author,o.author_default),l=Pe(o),u=await fe(r,Qr,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms),m;try{let p=await Y(a),f;try{f=Ve(p)}catch(h){throw new w(h instanceof Error?h.message:String(h),y.GENERIC_FAILURE)}try{Ha(i,f);let h=new Map,_=W(o,z());for(let[g,v]of Object.entries(_.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!h.has(k)&&h.set(k,g)}qa(i,f,h)}catch(h){throw new w(h instanceof Error?h.message:String(h),y.USAGE)}m=fr(f,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await ft({pmRoot:r,filePath:a,raw:lt(m.file),op:"schema:add-type",author:d,settings:o}),await Ln(r,[m.definition],c,"schema:add-type-folder"),c.push(...await ne({path:a,scope:"project",op:"schema:add-type"}))}finally{await u()}return await Hl(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:a,definitions:m.file.definitions.length},warnings:ht(c),generated_at:T()}}async function nt(e){await X(e)}async function Hl(e,t){try{let n=await bl(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function ht(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function yg(e,t,n,r){let i=W(t,z()),o=r.trim().toLowerCase();return(await Ye(e,t.item_format,i.type_to_folder,[],n)).filter(a=>typeof a.type=="string"&&a.type.toLowerCase()===o).length}async function wg(e,t,n,r){let i=W(t,z()),o=Ie(n),s=ue(r);return(await Ye(e,t.item_format,i.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(o.alias_to_id.get(ue(d))??ue(d))===s}).length}async function vg(e,t,n,r,i){if(i.length===0||Yi.has(i))return;let o=await wg(t,n,r,i);o>0&&e.push(`items_using_status:${o}`);let s=bg(r.workflow,i);s.length>0&&e.push(`status_referenced_by_workflow:${s.join(",")}`)}function bg(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,r])=>r!==void 0&&ue(r)===t).map(([r])=>r)}async function LT(e,t,n){let r=M(process.cwd(),n.path);await nt(r);let i=await C(r),o=be(i.schema),s=Ue(r,o.files.types,Ae.types),a=[],c=V(t.author,i.author_default),d=Pe(i),l=await fe(r,Qr,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(s),p;try{p=Ve(m)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.GENERIC_FAILURE)}try{u=Ba(p,e)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.USAGE)}if(u.removed){let f=(u.definition?.name??e??"").trim();if(f.length>0){let h=await yg(r,i,o,f);h>0&&a.push(`items_using_type:${h}`)}await ft({pmRoot:r,filePath:s,raw:lt(u.file),op:"schema:remove-type",author:c,settings:i}),a.push(...await ne({path:s,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await Hl(r,a),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:s,definitions:u.file.definitions.length},warnings:ht(a),generated_at:T()}}function Ho(e,t){return Ue(e,t.files.statuses,Ae.statuses)}function ei(e,t){return Ue(e,t.files.fields,Ae.fields)}function ql(e,t){return Ue(e,t.files.types,Ae.types)}async function Ln(e,t,n,r){for(let i of t){let o=Ia(i.folder??Aa(i.name)),s=_g.join(e,o);await D(s)||(await gg(s,{recursive:!0}),n.push(...await ne({path:s,scope:"project",op:r})))}}function qo(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function kg(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function xg(e){let t=new Map;for(let n of e){let r=ue(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let o=ue(i);o.length>0&&!t.has(o)&&t.set(o,r)}}}return t}async function FT(e,t,n){let r=M(process.cwd(),n.path);await nt(r);let i;try{i=Qa({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(_){throw new w(_ instanceof Error?_.message:String(_),y.USAGE)}let o=await C(r),s=be(o.schema),a=Ho(r,s),c=Ie(s);try{Xi(i,c.alias_to_id)}catch(_){throw new w(_ instanceof Error?_.message:String(_),y.USAGE)}let d=kg(c.by_id.get(i.id));if((i.roles??d?.roles??[]).length===0)throw new w(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,y.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Nt(i.id)}" --role active`,`pm schema add-status "${Nt(i.id)}" --role blocked`]});let u=[],m=V(t.author,o.author_default),p=Pe(o),f=await fe(r,zl,o.locks.ttl_seconds,m,!!t.force,p.force_required_for_stale_lock,o.locks.wait_ms),h;try{let _=await Y(a),g;try{g=Ft(_)}catch(k){throw new w(k instanceof Error?k.message:String(k),y.GENERIC_FAILURE)}let v=xg(g.statuses);try{Xi(i,v)}catch(k){throw new w(k instanceof Error?k.message:String(k),y.USAGE)}h=ec(g,i,d),await ft({pmRoot:r,filePath:a,raw:jt(h.file),op:"schema:add-status",author:m,settings:o}),u.push(...await ne({path:a,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:h.replaced,status:h.definition,file:{path:a,statuses:h.file.statuses.length},warnings:ht(u),generated_at:T()}}async function jT(e,t,n){let r=M(process.cwd(),n.path);await nt(r);let i=await C(r),o=be(i.schema),s=Ho(r,o),a=[],c=V(t.author,i.author_default),d=Pe(i),l=await fe(r,zl,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(s),p;try{p=Ft(m)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.GENERIC_FAILURE)}try{u=tc(p,e)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.USAGE)}if(u.removed){let f=ue(u.definition?.id??e);await vg(a,r,i,o,f),await ft({pmRoot:r,filePath:s,raw:jt(u.file),op:"schema:remove-status",author:c,settings:i}),a.push(...await ne({path:s,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:s,statuses:u.file.statuses.length},warnings:ht(a),generated_at:T()}}function Bl(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function Sg(e,t,n){return{...Bl(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function Gl(e){return{id:e.id,source:Yi.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Jl(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function Eg(){let e=new Map,t=z();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let i of r){if(typeof i!="object"||i===null||Array.isArray(i))continue;let o=i.name;typeof o=="string"&&o.trim().length>0&&e.set(o.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function Rg(e){let t=Ie(e),n=[],r=[];for(let i of t.definitions){let o=Gl(i);o.source==="builtin"?n.push(o):r.push(o)}return{builtin:n,custom:r}}async function Fn(e){let t=M(process.cwd(),e.path);await nt(t);let n=await C(t),r=be(n.schema),i=Ue(t,r.files.types,Ae.types),o=Ho(t,r),s=W(n,z()),a=Eg(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!a.has(d)));return{pmRoot:t,typesPath:i,statusesPath:o,byType:s.by_type,customNames:c,extensionProvenance:a,schema:r}}async function UT(e){let t=await Fn(e),n=[],r=[],i=[];for(let a of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Jl(a.name,t.customNames,new Set(t.extensionProvenance.keys())),d=Bl(a);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let o=Rg(t.schema),s=hr(t.schema).definitions.map(qo);return{action:"list",builtin:n,custom:r,extension:i,counts:{builtin:n.length,custom:r.length,extension:i.length,total:n.length+r.length+i.length},statuses:{builtin:o.builtin,custom:o.custom,counts:{builtin:o.builtin.length,custom:o.custom.length,total:o.builtin.length+o.custom.length}},fields:{custom:s,counts:{total:s.length}},file:{path:t.typesPath},generated_at:T()}}async function zT(e,t){let n=(e??"").trim();if(n.length===0)throw new w("Type name must not be empty.",y.USAGE);let r=await Fn(t),i=Object.values(r.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(s=>s.toLowerCase()===n.toLowerCase()));if(!i)throw new w(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Nt(n)}" to register it.`,y.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Sg(i,Jl(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:T()}}async function WT(e,t){let n=ue(e);if(n.length===0)throw new w("Status id must not be empty.",y.USAGE);let r=await Fn(t),i=Ie(r.schema),o=i.alias_to_id.get(n)??n,s=i.by_id.get(o);if(!s)throw new w(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Nt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Gl(s),file:{path:r.statusesPath},generated_at:T()}}async function HT(e,t,n){let r=M(process.cwd(),n.path);await nt(r);let i;try{i=Va({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(f){throw new w(f instanceof Error?f.message:String(f),y.USAGE)}let o=await C(r),s=be(o.schema),a=ei(r,s),c=[],d=_r(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=V(t.author,o.author_default),u=Pe(o),m=await fe(r,Wl,o.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,o.locks.wait_ms),p;try{let f=await Y(a),h;try{h=Mt(f)}catch(_){throw new w(_ instanceof Error?_.message:String(_),y.GENERIC_FAILURE)}p=Ka(h,i),await ft({pmRoot:r,filePath:a,raw:Lt(p.file),op:"schema:add-field",author:l,settings:o}),c.push(...await ne({path:a,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:p.replaced,field:p.definition,file:{path:a,fields:p.file.fields.length},warnings:ht(c),generated_at:T()}}async function Ag(e,t,n,r){let i=W(t,z());return(await Ye(e,t.item_format,i.type_to_folder,[],n)).filter(s=>{let a=s[r];return a==null?!1:Array.isArray(a)?a.length>0:typeof a=="string"?a.trim().length>0:!0}).length}async function qT(e,t,n){let r=M(process.cwd(),n.path);await nt(r);let i=await C(r),o=be(i.schema),s=ei(r,o),a=[],c=V(t.author,i.author_default),d=Pe(i),l=await fe(r,Wl,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(s),p;try{p=Mt(m)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.GENERIC_FAILURE)}try{u=Ya(p,e)}catch(f){throw new w(f instanceof Error?f.message:String(f),y.USAGE)}if(u.removed){let f=ue(u.definition?.key??e),h=ue(u.definition?.metadata_key??u.definition?.front_matter_key??f);if(h.length>0){let _=await Ag(r,i,o,h);_>0&&a.push(`items_using_field:${_}`)}await ft({pmRoot:r,filePath:s,raw:Lt(u.file),op:"schema:remove-field",author:c,settings:i}),a.push(...await ne({path:s,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:s,fields:u.file.fields.length},warnings:ht(a),generated_at:T()}}async function BT(e){let t=await Fn(e),n=hr(t.schema).definitions.map(qo);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:ei(t.pmRoot,t.schema)},generated_at:T()}}async function GT(e,t){let n=ue(e);if(n.length===0)throw new w("Field key must not be empty.",y.USAGE);let r=await Fn(t),i=hr(r.schema).by_key.get(n);if(!i)throw new w(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Nt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:qo(i),file:{path:ei(r.pmRoot,r.schema)},generated_at:T()}}async function JT(e,t,n){let r=M(process.cwd(),n.path);await nt(r);let i;try{let h=Ja(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${Ga.join(", ")}.`);i=h}catch(h){throw new w(h instanceof Error?h.message:String(h),y.USAGE)}let o=await C(r),s=be(o.schema),a=ql(r,s),c=[],d=V(t.author,o.author_default),l=Pe(o),u=[],m=[],p,f=await fe(r,Qr,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms);try{let h=await Y(a),_;try{_=Ve(h)}catch(v){throw new w(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let g=_;for(let v of Ki(i)){let k=fr(g,v);g=k.file,(k.replaced?m:u).push(k.definition.name)}p=g.definitions.length,await ft({pmRoot:r,filePath:a,raw:lt(g),op:"schema:apply-preset",author:d,settings:o}),await Ln(r,Ki(i),c,"schema:apply-preset-folder"),c.push(...await ne({path:a,scope:"project",op:"schema:apply-preset"}))}finally{await f()}return{action:"apply-preset",preset:i,registered:u,replaced:m,file:{path:a,definitions:p},warnings:ht(c),generated_at:T()}}function Ig(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new w("--min-count must be a positive integer (>= 1).",y.USAGE);return e}async function VT(e,t){let n=M(process.cwd(),t.path);await nt(n);let r=await C(n),i=be(r.schema),o=ql(n,i),s=Ig(e.minCount),a=W(r,z()),d=(await Ye(n,r.item_format,a.type_to_folder,[],i)).map(k=>typeof k.title=="string"?k.title:""),l=kl(d,{minCount:s}),u=[],m=[],p=[],f=[],h;if(!e.apply){let k;try{k=Ve(await Y(o))}catch(x){throw new w(x instanceof Error?x.message:String(x),y.GENERIC_FAILURE)}return h=k.definitions.length,{action:"infer-types",applied:!1,min_count:s,candidates:l,registered:m,replaced:p,skipped:f,file:{path:o,definitions:h},warnings:u,generated_at:T()}}let _=V(e.author,r.author_default),g=Pe(r),v=await fe(n,Qr,r.locks.ttl_seconds,_,!!e.force,g.force_required_for_stale_lock,r.locks.wait_ms);try{let k=await Y(o),x;try{x=Ve(k)}catch(I){throw new w(I instanceof Error?I.message:String(I),y.GENERIC_FAILURE)}let S=x;for(let I of l){if(I.shadows_builtin){f.push({name:I.name,reason:"shadows_builtin"});continue}let b;try{b=Vi({name:I.name})}catch{f.push({name:I.name,reason:"invalid_type_token"});continue}let E=fr(S,b);S=E.file,(E.replaced?p:m).push(E.definition.name)}h=S.definitions.length,await ft({pmRoot:n,filePath:o,raw:lt(S),op:"schema:infer-types",author:_,settings:r}),await Ln(n,S.definitions.filter(I=>m.includes(I.name)||p.includes(I.name)),u,"schema:infer-types-folder"),u.push(...await ne({path:o,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:s,candidates:l,registered:m,replaced:p,skipped:f,file:{path:o,definitions:h},warnings:ht(u),generated_at:T()}}import Vl from"node:fs/promises";import Bo 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]="af718efb-d1cf-5adc-9518-c858627e1b54")}catch{}})();function Se(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function R(e){return e.trim().toLowerCase()}function ti(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let i=t.slice(n,r);if(i.length===0)throw new w("Extension manifest name must resolve to a non-empty directory name.",y.USAGE);if(i==="."||i==="..")throw new w('Extension manifest name must not resolve to "." or "..".',y.USAGE);return i}function Go(e){return La(e)}async function Cg(e){try{let t=JSON.parse(await Vl.readFile(Bo.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(r=>typeof t.scripts?.[r]=="string")}}catch{return{has_build_script:!1}}}async function Tg(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new w(`Extension entry file is missing at "${t}".`,y.USAGE);let r=await Cg(n.source_root),i=r.package_name?`pm install npm:${r.package_name}`:void 0,o=n.source_input??n.source_root;return new w(`Extension entry "${e.entry}" is absent from GitHub source "${o}". pm install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,y.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${o}`,normalized_args:["install",o],...i?{next_best_command:i}:{}}})}async function an(e,t={}){let n=Bo.join(e,"manifest.json");if(!await D(n))throw new w(`Extension manifest is missing at "${n}".`,y.USAGE);let r;try{r=JSON.parse(await Vl.readFile(n,"utf8"))}catch(s){throw new w(`Failed to parse extension manifest at "${n}": ${$g(s)}`,y.USAGE)}let i=Go(r);if(!i)throw new w(`Extension manifest at "${n}" is invalid.`,y.USAGE);let o=Bo.resolve(e,i.entry);if(!ve(e,o))throw new w(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,y.USAGE);if(!await D(o))throw await Tg(i,o,t);if(!await Fa(e,o))throw new w(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,y.USAGE);return{directory:e,manifest_path:n,entry_path:o,manifest:i}}function $g(e){return e instanceof Error?e.message:String(e)}import Jo from"node:fs/promises";import Og from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="159d7bbd-1d2a-503d-b3ce-f32dcc6f6547")}catch{}})();var Dg=".managed-extensions.json",ni=1;function jn(e){return Og.join(e,Dg)}function Pg(){return{version:ni,updated_at:T(),entries:[]}}function Un(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function Kl(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function Ee(e){return typeof e=="string"?e:void 0}function Ng(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function Mg(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:Ee(t.name),package:Ee(t.package),version:Ee(t.version),repository:Ee(t.repository),owner:Ee(t.owner),repo:Ee(t.repo),ref:Ee(t.ref),subpath:Ee(t.subpath),commit:Ee(t.commit)}}function Lg(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Ng(t))return null;let n=Mg(t.source);if(!n)return null;let r=Pa(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Se(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Ee(t.last_update_check_at),last_update_remote_commit:Ee(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Ee(t.update_error)}}function Fg(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==ni||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=Lg(r);i&&n.push(i)}return{version:ni,updated_at:Ee(t.updated_at)??T(),entries:Un(n)}}async function _e(e){let t=jn(e),n=Pg();try{let r=await Jo.readFile(t,"utf8"),i=JSON.parse(r),o=Fg(i);if(!o)throw new w(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE);return{path:t,state:o,warnings:[]}}catch(r){if(r instanceof w)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&U(r))return{path:t,state:n,warnings:[]};throw new w(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE)}}async function Ct(e,t){let n=jn(e),r={version:ni,updated_at:T(),entries:Un(t.entries)};await Jo.mkdir(e,{recursive:!0}),await Jo.writeFile(n,`${JSON.stringify(r,null,2)}
20
+ `,"utf8")}function zn(e,t){let n=e.entries.filter(r=>R(r.name)!==R(t.name)&&R(r.directory)!==R(t.directory));return n.push(t),{...e,updated_at:T(),entries:Un(n)}}async function Yl(e,t,n,r){let i=t.entries.find(s=>R(s.name)===R(n));if(!i)return t;let o=zn(t,{...i,contributions:r});return await Ct(e,o),o}import{execFile as Kg}from"node:child_process";import J from"node:fs/promises";import Qo from"node:os";import N from"node:path";import{fileURLToPath as Yg}from"node:url";import{promisify as Xg}from"node:util";import Zg from"npm-package-arg";import{extract as Qg,list as ey}from"tar";import jg from"node:fs/promises";import Ne 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]="259656b0-09b7-52c5-8f54-52ac29eec607")}catch{}})();var Ug="PM_CLI_PACKAGE_ROOT",Xl={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},zg=new Set(["*","all"]);function Vo(){let e=[],t=process.env[Ug];return typeof t=="string"&&t.trim().length>0&&e.push(Ne.resolve(t.trim())),e.push(Re(import.meta.url,["../../.."])),[...new Set(e)]}async function Wn(e){let t=e.trim().toLowerCase(),n=await Ql(t);if(n)return n;let r=Xl[t];if(!r)return null;for(let i of Vo()){let o=Ne.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await D(Ne.join(o,"manifest.json")))return o}return null}function Zl(e){return zg.has(e.trim().toLowerCase())}function Wg(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Hg(e,t){let n=await jg.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=Ne.join(e,r.name);if(!await D(Ne.join(i,"package.json")))continue;let o=await mr(i),s=o.aliases&&o.aliases.length>0?o.aliases:[Wg(r.name)];for(let a of s){let c=a.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:i,package_name:o.package_name??null})}}}async function Ko(){let e=new Map;for(let t of Vo()){let n=Ne.join(t,"packages");await D(n)&&await Hg(n,e)}for(let[t,n]of Object.entries(Xl))if(!e.has(t))for(let r of Vo()){let i=Ne.join(r,"packages",n.package_directory);if(await D(Ne.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function ri(){return(await Ko()).map(e=>e.alias)}async function Ql(e){let t=e.trim().toLowerCase();return(await Ko()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function eu(e){let t=await Ql(e);return t?(await mr(t)).package_name??null:null}async function tu(e){let t=await Wn(e);if(!t)return null;try{let n=await pr(t);return n.length!==1?null:(await an(n[0])).manifest.name}catch{return null}}function qg(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function Bg(e,t,n,r,i,o){let s=r==="global"?"--global":"--project",a=Object.fromEntries(Ji.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||o.has(Ne.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${s}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:a,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:qg(e),media:e.catalog?.media}}}async function nu(e,t,n={}){let r=Pt(M(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,o=await _e(i),s=new Set(o.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>Ne.resolve(m.source.location))),a=new Set(o.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),c=[],d=new Map;for(let m of await Ko()){let p=Ne.resolve(m.package_root),f=d.get(p)??[];f.push(m),d.set(p,f)}for(let m of d.values()){let p=m[0],f=m.map(_=>_.alias).sort((_,g)=>_.localeCompare(g)),h=await mr(p.package_root);c.push(Bg(h,p,f,e,a,s))}let l=Jg(n.fields),u=l?c.map(m=>Vg(m,l)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Ji.filter(m=>m!=="extensions"),packages:u}}var Gg=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function Jg(e){if(e===void 0)return;let t=Zc(e);if(t.length===0)throw new w("Package catalog --fields requires a comma-separated list of field names",y.USAGE);let n=t.filter(r=>!Gg.has(r));if(n.length>0)throw new w(`Unknown package catalog --fields value(s): ${n.join(", ")}`,y.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function Vg(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="05f56edb-c08d-570c-b8b5-641fc694331e")}catch{}})();var iu=Xg(Kg),oi="@unbrained/pm-cli",ty={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},Yo;async function ou(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=N.resolve(t);for(;;){let i=N.join(r,"node_modules",...n.split("/")),o=N.join(i,"package.json");if(await D(o))try{let a=JSON.parse(await J.readFile(o,"utf8"));if(a.name===n)return{package:n,...typeof a.version=="string"?{version:a.version}:{},directory:i}}catch{return null}let s=N.dirname(r);if(s===r)return null;r=s}}function Xo(e,t,n){let r=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(r.length<2)return null;let i=r[0],o=r[1].replace(/\.git$/i,"");if(i.length===0||o.length===0)return null;let s=r.slice(2),a,c;return s[0]==="tree"&&s.length>=2?(a=s[1],c=s.slice(2).join("/")):s.length>0&&(c=s.join("/")),typeof n=="string"&&n.trim().length>0&&(a=n.trim()),{kind:"github",input:t,owner:i,repo:o,repository:`https://github.com/${i}/${o}.git`,ref:a,subpath:c&&c.length>0?c:void 0}}function ny(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new w('npm package source must include a package spec after "npm:".',y.USAGE);if(t)throw new w('Options "--gh/--github" cannot be combined with npm: package sources.',y.USAGE);if(n)throw new w('Option "--ref" cannot be combined with npm: package sources.',y.USAGE);return{kind:"npm",input:e,spec:r}}function si(e,t={}){let n=e.trim();if(n.length===0)throw new w("Extension source is required for --install.",y.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return ny(n,t.forceGithub===!0,r);let i=(()=>{try{let s=new URL(n);if(s.hostname!=="github.com")return null;let a=s.pathname.replace(/^\/+/,"");return Xo(a,n,r)}catch{return null}})();if(i)return i;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let s=Xo(o,n,r);if(!s)throw new w(`Invalid GitHub source "${n}".`,y.USAGE);return s}if(t.forceGithub){let s=Xo(n,n,r);if(!s)throw new w(`Invalid GitHub shorthand "${n}".`,y.USAGE);return s}if(/^https?:\/\//i.test(n))throw new w(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,y.USAGE);return{kind:"local",input:n,absolute_path:N.resolve(process.cwd(),n)}}async function ii(e,t=iu,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new w(`Git command failed: git ${e.join(" ")}
21
+ ${o}`,y.GENERIC_FAILURE)}}function ry(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function iy(e=process.platform){return e==="win32"}async function su(e,t,n=iu,r=process.platform,i=process.env){let o=ry(r),s=Object.fromEntries(Object.entries(i).filter(([a])=>a.toLowerCase()!=="npm_config_allow_scripts"));s.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(o,e,{cwd:t,encoding:"utf8",env:s,shell:iy(r)})).stdout??"").trim()}catch(a){let c=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr):"",d=c.trim().length>0?c.trim():a instanceof Error?a.message:String(a);throw new w(`npm command failed: ${o} ${e.join(" ")}
22
+ ${d}`,y.GENERIC_FAILURE)}}function au(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function cu(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function oy(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("npm err! code e404")||n.includes("404 not found")||n.includes("is not in this registry")}function sy(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return oy(e)||n.includes("not found")}function ay(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function cy(e){let t=au(e),n=ay(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,o=i?`pm install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:o?[o,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:o?[`Try ${o} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&o?{fallback_candidates:[{source:i,command:o,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:o}:{}}}}}function dy(e,t){if(!sy(t))return null;let n=cy(e);return new w(n.message,y.NOT_FOUND,n.context)}async function du(e){if(N.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=N.resolve(process.cwd(),e);return await D(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=Yg(t);return await D(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=N.resolve(process.cwd(),e);if(await D(t))return t}return null}async function ly(e){let t=await du(e);if(t)return t;let n=uy(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function uy(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!cu(e))return e;let i=e.slice(0,r),o=e.slice(r+n.length);if(o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${i}@${N.resolve(t,o)}`;let s;try{s=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let a=/^\/[A-Za-z]:/.test(s)?s.slice(1):s;return`${i}@${a}`}function ru(e,t){let n=N.resolve(e,t),r=N.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${N.sep}`)||N.isAbsolute(r))throw new w("npm pack reported a package archive outside its isolated destination.",y.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function my(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function py(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]).flatMap(({key:n,value:r})=>{let i=my(r,n);return i?[i]:[]})}function fy(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(s=>{let a=s.name?.trim().toLowerCase();return a!==void 0?a===n:s.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let i=e[0],o=i.name??i.key;return n&&o!==void 0&&o.trim().toLowerCase()!==n?void 0:i}function hy(e,t,n){let r;try{r=JSON.parse(e)}catch{let s=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0).at(-1);if(!s)throw new w("npm pack did not report a tarball filename.",y.GENERIC_FAILURE);return{tarball:ru(t,s)}}let i=py(r),o=fy(i,n);if(!o)throw new w("npm pack --json returned an unsupported or ambiguous package receipt.",y.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:ru(t,o.filename),package:o.name??o.key,version:o.version}}async function _y(e){return gy(e,su)}async function gy(e,t){let n=await du(e.spec);if(n){if((await J.stat(n)).isFile()&&lu(n))return Zo(n);let s=N.join(n,"package.json"),a=await D(s)?JSON.parse(await J.readFile(s,"utf8")):{};return{directory:await ai(n,e.input),package:typeof a.name=="string"?a.name:void 0,version:typeof a.version=="string"?a.version:void 0,cleanup:async()=>{}}}let r=await J.mkdtemp(N.join(Qo.tmpdir(),"pm-npm-package-source-")),i=N.join(r,"pack");await J.mkdir(i,{recursive:!0});try{let o=await ly(e.spec),s=await t(["pack",o,"--json","--pack-destination",i]),a=hy(s,i,cu(e.spec)?void 0:au(e.spec));if(!await D(a.tarball))throw new w("npm pack did not create its reported package archive.",y.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await Zo(a.tarball);return{directory:c.directory,package:a.package??c.package,version:a.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await J.rm(r,{recursive:!0,force:!0})}}}}catch(o){await J.rm(r,{recursive:!0,force:!0});let s=dy(e.spec,o);throw s||o}}function lu(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function rt(e){throw new w(e,y.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function yy(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&rt(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,i=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||i.some(o=>o===".."))&&rt(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&rt(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&rt(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&rt(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&rt(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&rt(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function Zo(e,t=ty){(await J.stat(e)).size>t.maxArchiveBytes&&rt(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await J.mkdtemp(N.join(Qo.tmpdir(),"pm-local-package-archive-")),i=N.join(r,"extract");await J.mkdir(i,{recursive:!0});let o={entries:0,expandedBytes:0,packageJsonEntries:0},s;try{if(await ey({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(s===void 0)try{yy(l,t,o)}catch(u){s=u}}}),s!==void 0)throw s;o.packageJsonEntries!==1&&rt(`Local package archive must contain exactly one package/package.json entry; found ${o.packageJsonEntries}.`),await Qg({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let a=N.join(i,"package"),c=N.join(a,"package.json"),d=JSON.parse(await J.readFile(c,"utf8"));return await wy(a),{directory:await ai(a,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await J.rm(r,{recursive:!0,force:!0})}}}catch(a){throw await J.rm(r,{recursive:!0,force:!0}),a}}async function wy(e,t=su){let n=N.join(e,"package.json");if(!await D(n))return;let r;try{r=JSON.parse(await J.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,o=Ey(i),s=vy(i);if(o.length===0&&!s)return;let a={...r};delete a.devDependencies;let c={...a};by(c),await J.writeFile(n,`${JSON.stringify(c,null,2)}
23
+ `,"utf8");try{await Promise.all([J.rm(N.join(e,"package-lock.json"),{force:!0}),J.rm(N.join(e,"npm-shrinkwrap.json"),{force:!0})]),o.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),s&&await ky(e)}finally{await J.writeFile(n,`${JSON.stringify(a,null,2)}
24
+ `,"utf8")}}function vy(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&oi in t)return!0;return!1}function by(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[oi],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function ky(e){let t=Re(import.meta.url,["../../.."]),[n,r]=oi.split("/"),i=N.join(e,"node_modules",n),o=N.join(i,r);await J.mkdir(i,{recursive:!0}),await J.rm(o,{recursive:!0,force:!0}),await J.symlink(t,o,xy(process.platform))}function xy(e){return e==="win32"?"junction":"dir"}function Sy(e,t){if(e.startsWith("-"))throw new w(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,y.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(r=>{let i=r.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(r)}))throw new w(`Extension runtime dependency "${e}" has an unsafe version specifier.`,y.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Zg.resolve(e,t)}catch{throw new w(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,y.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function Ey(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===oi||typeof i!="string"||i.trim().length===0||t.has(r))continue;let o=i.trim();t.set(r,Sy(r,o))}return[...t.values()]}async function ai(e,t){let n=await pr(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>N.relative(e,i).replaceAll(N.sep,"/")).sort((i,o)=>i.localeCompare(o));throw new w(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,y.USAGE)}throw new w(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,y.USAGE)}async function Ry(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(N.posix.join(".agents/pm/extensions",t.subpath)),n.push(N.posix.join(".custom/pm-extensions",t.subpath)),n.push(N.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let o=N.resolve(e,i);if(ve(e,o)&&await D(N.join(o,"manifest.json")))return{directory:o,resolved_subpath:i}}if(await D(N.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await ai(e,t.input);return{directory:r,resolved_subpath:N.relative(e,r).replaceAll(N.sep,"/")}}function Ay(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function Iy(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Ay(n))return new w(t,y.NOT_FOUND);let r=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,s=typeof o=="string"&&o.trim().length>0?N.resolve(o.trim()):"";Yo?.key!==s&&(Yo={key:s,aliases:await ri()}),r=Yo.aliases}catch{}let i=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${r.join(", ")}`];return new w(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,y.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function uu(e){if(e.kind==="local"){let r;try{r=await J.stat(e.absolute_path)}catch{throw await Iy(e)}if(r.isFile()&&lu(e.absolute_path)){let o=await Zo(e.absolute_path);return{source:e,directory:o.directory,source_root:N.dirname(o.directory),resolved_subpath:N.relative(N.dirname(o.directory),o.directory).replaceAll(N.sep,"/"),npm_package:o.package,npm_version:o.version,cleanup:o.cleanup}}if(!r.isDirectory())throw new w(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,y.USAGE);let i=await ai(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await _y(e);return{source:e,directory:r.directory,source_root:N.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:N.relative(N.dirname(r.directory),r.directory).replaceAll(N.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await J.mkdtemp(N.join(Qo.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await ii(n);let r=await ii(["-C",t,"rev-parse","HEAD"]),i=await Ry(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await J.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await J.rm(t,{recursive:!0,force:!0}),r}}async function mu(e,t){if(!await D(e)||!await D(t))return!1;let[n,r]=await Promise.all([J.realpath(e),J.realpath(t)]);return n===r}import Hn from"node:fs/promises";import qn 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]="5321d574-4de4-5f94-99db-0c49639673fc")}catch{}})();var es=1,Tt="2026.6.24",Cy=">=22.18.0",Ty={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},pu=new Set([...nc.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(za).map(e=>e.toLowerCase()),"scaffold"]),$y="^6.0.0",Oy="^22.0.0",_u=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],Be=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function fu(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function gu(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function yu(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var Dy={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},hu=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],wu={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},Py={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},Ny={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},My={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},vu="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Ly={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},Fy={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},jy={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},Uy={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function bu(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function ku(e,t){return e==="schema"?jy[t]:e==="profile"?Uy[t]:Fy[t]}function zy(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),o=r>0&&(r===t.length||i!==void 0&&pu.has(i));return`${(pu.has(n)||o?["starter",...t]:t).join(" ")} ping`}function xu(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],o=`${e.replace(/-/g,"_")}_owner`,s="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(s)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(o)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(s)}],`,` [${JSON.stringify(s)}, "in_progress"],`,` [${JSON.stringify(s)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function Wy(e,t,n){let r=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return s;if(n==="search")return[...s,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let a=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===a?[]:[d],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...s,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(a)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...s,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...xu(e).map(a=>` ${a}`)," });"]:n==="importers"?[...s,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(o)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(o)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...s,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...s,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...s,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...s,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function Hy(e,t,n){let r=n==="hooks",i=n==="search",o=n==="importers",s=n==="schema",a=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",m=Py[n],p=e,f=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,_=`${e}-0001-init`,g=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Be,"});",""]:[],k=i?ts(e,t,"search",m):[],x=o?ts(e,t,"importers",m):[],S=s?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...fu(gu({extensionName:e,itemTypeName:p,itemTypeFolder:f,fieldName:h,migrationId:_,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Be,"});",""]:[],I=a?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...fu(yu(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Be,"});",""]:[],b=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Be,"});",""]:[],E=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Be,"});",""]:[],A=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Be,"});",""]:[],F=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Be,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...g,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",..._u,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Be,"});","",...v,...k,...x,...S,...I,...b,...E,...A,...F,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
25
+ `)}function qy(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var By={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},Gy={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function Jy(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function Vy(e,t,n){let r=[],i=[...Jy(e,t,n)],o=[" commands: [pingCommand],"],s=`${e}-search`,a=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),m=u===d?[]:[u],p=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),o.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(s)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(a)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),o.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),o.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(f)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),o.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...xu(e),"});"),o.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),o.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),o.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),o.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),o.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:o}}function Ky(e,t,n){let r=Vy(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((o,s)=>o.localeCompare(s)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
26
+ `)}function ts(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,o=`${e}-vector`,s=`${e.replace(/-/g," ")} items`,a=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],m=p=>[...u," let deactivated = false;"," try {",...p.map(f=>f===""?f:` ${f}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Be];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(o)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(s)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(s)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(s)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(s)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(gu({extensionName:e,itemTypeName:a,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(yu(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function Yy(e,t,n){let r=n==="parser",i=JSON.stringify([...wu[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",..._u,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(Tt)},`," },",` target: { pmVersion: ${JSON.stringify(Tt)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Be,"});","",...ts(e,t,n,i)].join(`
27
+ `)}function Xy(e,t,n){let r=bu(n,"package"),i=ku(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${By[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",vu,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${Gy[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${es}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Tt}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
28
+ `)}function Zy(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function Qy(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function ew(e,t,n,r){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function tw(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function nw(e,t,n,r="commands",i=!1){let o=`pm-${e}`,s=wu[r],a=qy(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:es,pm_min_version:Tt,trusted:!0,sandbox_profile:"strict",permissions:{...Ty},capabilities:s,...a.length>0?{activation:{commands:a}}:{}},null,2)}
29
+ `,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Wy(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
30
+ `),l=`${JSON.stringify(Dy,null,2)}
31
+ `,u=Ny[r],m=bu(r,"package"),p=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Cy},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Tt}`},devDependencies:{"@types/node":Oy,typescript:$y},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
32
+ `,f=Hy(e,t,r),h=My[r],_=["node_modules/","*.log","*.tsbuildinfo",""].join(`
33
+ `),g=Zy(e),k=["```ts",`import { ${Qy(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...ew(e,t,r,g),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...tw(t,r,g),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],x=[`# ${o}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,h,vu,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...k,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Ly[r],...ku(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Tt}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${es}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Tt}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
34
+ `);return{"package.json":p,"manifest.json":c,"index.ts":i?Ky(e,t,r):d,"index.test.ts":i?Yy(e,t,r):f,"tsconfig.json":l,".gitignore":_,"README.md":i?Xy(o,t,r):x}}async function Su(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!hu.includes(i))throw new w(`Unknown scaffold capability "${n}". Supported capabilities: ${hu.join(", ")}.`,y.USAGE);let o=i;if(r&&t!=="package")throw new w("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",y.USAGE);let s=r?"declarative":"imperative",a=e.trim(),c=qn.resolve(process.cwd(),a),d=ti(qn.basename(c)).replace(/^(?:pm-)+/u,""),l=zy(d),u=nw(d,l,t,o,r),m=!1;if(await D(c)){if(!(await Hn.stat(c)).isDirectory())throw new w(`Scaffold target "${c}" exists and is not a directory.`,y.CONFLICT)}else await Hn.mkdir(c,{recursive:!0}),m=!0;for(let[f,h]of Object.entries(u)){let _=qn.join(c,f);if(!await D(_))continue;if(await Hn.readFile(_,"utf8")!==h)throw new w(`Scaffold file "${f}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,y.CONFLICT)}let p=[];for(let[f,h]of Object.entries(u)){let _=qn.join(c,f);if(await D(_)){p.push({path:f,status:"unchanged"});continue}await Hn.mkdir(qn.dirname(_),{recursive:!0}),await Hn.writeFile(_,h,"utf8"),p.push({path:f,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:o,style:s,target_path:c,created_directory:m,files:p}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="536ed530-7726-50ab-bb2d-ace030818f1d")}catch{}})();function Eu(e,t){return`${e}:${R(t)}`}function rw(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let s of i){let a=o.get(s.command)??[];o.set(s.command,[...a,s])}for(let[s,a]of o){if(t!==null&&!a.some(d=>t.has(R(d.name))))continue;let c=a.at(-1);n.push({command:s,surface:r,policy:"last_activated_wins",collision:a.length>1,claimants:a.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function Ru(e,t,n){let r=new Set(n.failed.map(d=>Eu(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(Eu(d.layer,d.name))?"failed":"ok",surfaces:Qt(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:Qt(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),o=typeof e=="string"?R(e):null,s=o===null?null:new Set(t.loaded.filter(d=>R(d.name)===o||typeof d.source_package=="string"&&R(d.source_package)===o||(d.source_aliases??[]).some(l=>R(l)===o)).map(d=>R(d.name)).concat(o)),a=s===null?i:i.filter(d=>s.has(R(d.name))),c=s===null?{}:{extensionNames:[...s]};return{target:typeof e=="string"?e.trim():null,total:a.length,extensions:a,union:Qt(n,c),command_ownership:rw(n,s)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function ns(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function ci(e,t,n){let r=R(t),i=n.trim();if(r.length===0||i.length===0)return;let o=e.get(r)??new Set;o.add(i),e.set(r,o)}function iw(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)ci(t,r.name,r.command),ci(n,r.name,r.action);for(let r of e.commands.handlers)ci(t,r.name,r.command);for(let r of e.commands.overrides)ci(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Au(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function ow(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:o}=e;return t?i.has(n)||o.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function di(e,t,n){let r=new Set(t.loaded.map(c=>R(c.name))),i=new Set(t.failed.map(c=>R(c.name))),o=new Set(n.failed.map(c=>R(c.name))),{commandPathsByExtension:s,actionPathsByExtension:a}=iw(n);return e.map(c=>{let d=R(c.name),l=Au(s.get(d)),u=Au(a.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},p=ow({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:i,activationFailedNames:o});return{...c,...p,...m}})}function sw(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function me(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Tu=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function aw(e){return Tu.has(Mu(e))}function Iu(e){return e==="project"||e==="global"}function $u(e){let t=e.split(":"),n=t[0];if(!n||!Tu.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),o=t.at(-2),s=t.at(-1)?.trim();return!Iu(r)||!Iu(o)||!i||!s?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:o,name:s}}}function cw(e){let t=new Set;for(let n of e){let r=$u(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function rs(e,t){let n=e.filter(aw);if(n.length===0)return null;let r=cw(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function dw(e,t,n,r){let i=t.map(u=>$u(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let o=e==="global"?"--global":"--project",s=me(r,"deactivate"),a=`${me(r,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(u=>[R(u.name),u])),d=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let p=R(m);d.set(p,(d.get(p)??0)+1)}let l=[...d.entries()].map(([u,m])=>{let p=c.get(u),f=p?.name??u,h=p?.command_paths??[],_=p?.action_paths??[];return{action:"deactivate",extension:f,command:`${s} ${f} ${o}`,affected_collisions:m,feature_loss:{command_paths:[...h].sort((g,v)=>g.localeCompare(v)),action_paths:[..._].sort((g,v)=>g.localeCompare(v))}}}).sort((u,m)=>{let p=m.affected_collisions-u.affected_collisions;if(p!==0)return p;let f=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,h=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return f!==h?f-h:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:d.size,next_best_command:a,collisions:i,remediation_candidates:l}}function Ou(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function Du(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function Pu(e,t){let n=[];for(let r of ic(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var lw=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${me(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${ar.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${me(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${me(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${me(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function uw(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:s,updateHealthPartial:a,skippedUnmanagedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=[],m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:s};if(t.length>0){let p=rs(t,{deactivate:`${me(n,"deactivate")} <name> ${i}`,doctor:`${me(n,"doctor")} ${i} --detail deep --trace`});p&&u.push(p);for(let f of lw)f.matches(t,m)&&u.push(f.build(m))}return a?u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${me(n,"manage")} ${i} --fix-managed-state (or ${me(n,"adopt-all")} ${i}, ${me(n,"adopt")} <name> ${i}, or reinstall via ${me(n,"install")} ${i} <source>).`):c>0&&u.push(`Loaded unmanaged extensions are currently treated as informational. Use ${me(n,"manage")} ${i} --fix-managed-state to adopt them for update checks.`),d>0&&u.push("Non-GitHub managed extensions are skipped by update checks. Use doctor output for non-update diagnostics."),l>0&&u.push(`Update available managed extensions via ${me(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${me(n,"manage")} ${i} after extension changes.`),u}function li(e,t,n,r={}){let i=[...new Set(t)].sort((A,F)=>A.localeCompare(F)),o=n.filter(A=>A.managed).length,s=n.filter(A=>A.enabled).length,a=n.filter(A=>A.active).length,c=n.filter(A=>A.update_available===!0).length,d=n.filter(A=>A.managed===!1),l=d.filter(A=>Cu(A)).map(A=>A.name).sort((A,F)=>A.localeCompare(F)),u=d.filter(A=>!Cu(A)).map(A=>A.name).sort((A,F)=>A.localeCompare(F)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let A of n)m[A.update_check_status]+=1;let p=m.failed,f=m.skipped_unmanaged,h=m.skipped_non_github,_=u.length>0,g=_?"partial":"full",v=_?[`extension_update_health_partial_coverage:skipped_unmanaged:${u.length}`]:[],k=[...new Set([...i,...v])].sort((A,F)=>A.localeCompare(F)),x=[...new Set(k.map(A=>Mu(A)))].sort((A,F)=>A.localeCompare(F)),S=sw(k),I=e==="global"?"--global":"--project",b=dw(e,i,n,r),E=uw({normalizedWarnings:i,options:r,scope:e,scopeFlag:I,updateCheckFailedTotal:p,policyWarningCount:S.warning_count,updateHealthPartial:_,skippedUnmanagedTotal:f,skippedNonGithubTotal:h,updateAvailableTotal:c});return{status:k.length===0?"ok":"warn",warning_count:k.length,warning_codes:x,warnings:k,policy_warning_count:S.warning_count,policy_violation_count:S.violation_count,policy_blocked_count:S.blocked_count,total_extensions:n.length,managed_total:o,enabled_total:s,active_total:a,update_available_total:c,update_health_coverage:g,update_health_partial:_,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(A=>A.name).sort((A,F)=>A.localeCompare(F)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:p,top_warnings:k.slice(0,8),remediation:E,...b?{collision_plan:b}:{}}}function Nu(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new w(`Invalid --detail value "${e}". Expected summary or deep.`,y.USAGE)}function Mu(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Bn(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let o=wa(r);return o?[o]:va(r)})();for(let o of i){let s=`${o.layer}:${o.name}:${o.capability}`;t.has(s)||(t.add(s),n.push(o))}}return n}function Gn(){return{version:cr.version,capabilities:[...cr.capabilities],legacy_aliases:{...cr.legacy_aliases}}}function Cu(e){let t=R(e.name),n=R(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Lu(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let o=[...new Set(t.filter(l=>l.active).map(l=>R(l.name)))].sort((l,u)=>l.localeCompare(u)),s=[...new Set(n.filter(l=>l.layer==="project").map(l=>R(l.name)))].sort((l,u)=>l.localeCompare(u)),a=new Set(r.map(l=>R(l.name))),c=o.filter(l=>!s.includes(l)&&!a.has(l)).sort((l,u)=>l.localeCompare(u));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:o.length,loaded_project_count:s.length,active_project_names:o,loaded_project_names:s,missing_active_project_names:c}}}import{randomUUID as mw}from"node:crypto";import oe from"node:fs/promises";import pw from"node:os";import K 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]="263602a2-c000-5df7-80d2-6f095985496f")}catch{}})();var Fu=3,fw=120,ju=250,hw=12e4,_w=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Uu=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,zu=e=>_w.has(String(Uu(e))),ui=(e,t)=>Uu(e)===t,Wu=e=>new Promise(t=>{setTimeout(t,e)}),Hu=async e=>{let t=K.join(e,"package.json");await D(t)||await oe.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
35
+ `,"utf8")},qu=async e=>{let t=Re(import.meta.url,["../../.."]),n=K.join(e,"node_modules","@unbrained"),r=K.join(n,"pm-cli");await oe.mkdir(n,{recursive:!0}),await oe.rm(r,{recursive:!0,force:!0}),await oe.symlink(t,r,process.platform==="win32"?"junction":"dir")},is=async e=>{let t=K.resolve(e),n=K.dirname(t),r=K.parse(n).root,i=await oe.realpath(r).catch(()=>r),o=K.relative(r,n),s=o===""?[]:o.split(K.sep);for(let[a,c]of s.entries()){let d=K.join(i,c);try{i=await oe.realpath(d)}catch{i=K.join(i,...s.slice(a));break}}return K.join(i,K.basename(t))},Bu=async(e,t,n,r=pw.tmpdir())=>{let i=K.resolve(e),o=await oe.realpath(i).catch(()=>i),s=await is(t);if(o===s)return;if(!ve(o,s)){await n(e,t,{recursive:!0,force:!0});return}let a=m=>{let p=K.resolve(m);if(p!==i&&!ve(i,p))return!1;let f=K.resolve(o,K.relative(i,p));if(f===s||ve(s,f))return!1;let _=K.relative(o,f).split(K.sep);return _.some(g=>g==="node_modules"||g.startsWith(".pm-extension-install-backup-"))?!1:_[0]!==".agents"},c=await oe.realpath(K.resolve(r)).catch(()=>is(r)),d=ve(o,c)?K.dirname(o):c;if(ve(o,d))throw new w(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,y.USAGE,{code:"extension_install_source_contains_destination"});let l=await oe.mkdtemp(K.join(d,"pm-extension-copy-")),u=K.join(l,"extension");try{await n(e,u,{recursive:!0,force:!0,filter:a}),await n(u,t,{recursive:!0,force:!0})}finally{await oe.rm(l,{recursive:!0,force:!0})}},Gu=async(e,t,n=oe.cp)=>{for(let r=1;r<=Fu;r+=1)try{await oe.rm(t,{recursive:!0,force:!0}),await Bu(e,t,n);return}catch(i){if(!zu(i)||r===Fu)throw i;await Wu(ju)}},os=async e=>{let t;try{t=await oe.readFile(K.join(e,"owner.json"),"utf8")}catch(i){if(!dt(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},Ju=async(e,t)=>await os(e)!==t?!1:(await oe.rm(e,{recursive:!0,force:!0}),!0),gw=async(e,t)=>{let n;try{n=await oe.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await os(e);return r===null?(await oe.rm(e,{recursive:!0,force:!0}),!0):Ju(e,r)},yw=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await os(e)!==t)return;let o=new Date;await oe.utimes(e,o,o)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},ww=async(e,t)=>{await oe.mkdir(e);try{await oe.writeFile(K.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
36
+ `,"utf8")}catch(n){throw await oe.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},vw=async(e,t,n,r,i)=>{for(let o=1;o<=n;o+=1)try{return await ww(e,t),!0}catch(s){if(!ui(s,"EEXIST"))throw s;await gw(e,i)?o-=1:await Wu(r)}return!1},ss=async(e,t,n,r)=>{let i=K.join(e,"runtime","extension-install-locks"),o=K.join(i,"scope.lock");await oe.mkdir(i,{recursive:!0});let{attempts:s=fw,delay_ms:a=ju,stale_ms:c=hw,heartbeat_ms:d}=r??{};if(![s,a,c,d].filter(g=>g!==void 0).every(Number.isFinite))throw new w("Extension install lock timings must be finite numbers.",y.USAGE);let l=Math.max(1,Math.floor(s)),u=Math.max(0,Math.floor(a)),m=Math.floor(c),p=Math.floor(d??m/3);if(m<=0||p<=0||p>=m)throw new w("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",y.USAGE);let f={pid:process.pid,token:mw(),created_at:T(),destination:t};if(!await vw(o,f,l,u,m))throw new w(`Timed out waiting for extension install lock for "${t}".`,y.CONFLICT);let _=yw(o,f.token,p);try{return await n()}finally{await _(),await Ju(o,f.token).catch(()=>!1)}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d3c62e9-9116-5cdc-bbda-48bbd2e39476")}catch{}})();var Vu=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");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])}});return await Promise.all(o),r};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b17dfc10-9e07-5912-b294-c5663133f192")}catch{}})();function Ku(e,t){let n=R(e),r=t.find(i=>R(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,o)=>i.localeCompare(o)),action_paths:[...r?.action_paths??[]].sort((i,o)=>i.localeCompare(o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5a4cea9-ac5d-5bda-9f7c-6cf8cf9e9998")}catch{}})();function Yu(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${R(o.name)}`]:[])),r=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>o.passThrough!==!0).filter(o=>!n.has(`${o.layer}:${R(o.name)}`)).map(o=>`extension_output_service_override_global:${o.service}:${o.layer}:${o.name}`),i=e.renderers.overrides.filter(o=>(o.commands?.length??0)===0&&o.resultDiscriminator===void 0).map(o=>`extension_output_renderer_override_global:${o.format}:${o.layer}:${o.name}`);return[...new Set([...r,...i])].sort((o,s)=>o.localeCompare(s))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var Xu=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=_r(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(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]="ccb857a5-045d-57a7-91d2-b761225fe53a")}catch{}})();var bw=1e4,kw=(e,t,n)=>{let r=e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).map(s=>{let[a,c=""]=s.split(/\s+/);return{commit:a,ref:c}}),i=r.find(s=>s.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let o=t?.trim();return o?{checked_at:n,remote_commit:i.commit,available:i.commit!==o}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},Zu=async(e,t=ii)=>{let n=T();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let r=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,bw);return kw(i,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import xw from"node:fs/promises";import Sw 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]="56290db9-933c-590d-8b9f-df62ff45e515")}catch{}})();function as(e){return Sw.join(e,"extension-migrations.json")}function Qu(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function em(e,t){return`${e.layer}:${e.name}:${t}`}async function Ew(e){let t=as(e);if(!await D(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await xw.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function cs(e,t){let n=await Ew(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let s=Qu(i,o),a=r.get(em(i,s));a&&(i.definition.status=a.status,a.status==="failed"?i.definition.reason=a.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function Rw(e){let t=await cs(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),r=[],i=!1,o=e.migrations.map((l,u)=>({migration:l,index:u})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:u}of o){let m=Qu(l,u),p=em(l,m),f=n.get(p),h=String(l.definition.status??"pending").toLowerCase(),_=f?.status??(h==="applied"||h==="failed"?h:"pending");if(_==="applied"){r.push({key:p,layer:l.layer,extension:l.name,id:m,before:_,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:p,layer:l.layer,extension:l.name,id:m,before:_,outcome:"pending"});continue}let g=l.runtime_definition?.run??l.definition.run;if(typeof g!="function"){r.push({key:p,layer:l.layer,extension:l.name,id:m,before:_,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(g({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:_}));let k={key:p,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(p,k),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:p,layer:l.layer,extension:l.name,id:m,before:_,outcome:"applied"}),i=!0}catch(k){let x=k instanceof Error?k.message:String(k),S={key:p,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:x};n.set(p,S),l.definition.status="failed",l.definition.reason=x,r.push({key:p,layer:l.layer,extension:l.name,id:m,before:_,outcome:"failed",error:x}),i=!0}}if(i){let l=await C(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,p)=>m.key.localeCompare(p.key))};await Ar({pmRoot:e.pmRoot,filePath:as(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
37
+ `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let s=r.filter(l=>l.outcome==="pending").length,a=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:as(e.pmRoot),total:r.length,pending_count:s,applied_count:a,skipped_count:c,failed_count:d,migrations:r}}async function tm(e){let t=await C(e.resolvedRoots.settings_root),n=await Fe({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await je(n);e.warnings.push(...n.warnings,...r.warnings);let i=await Rw({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}import Aw from"node:fs/promises";import Iw 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]="5755dee7-d2df-5ced-8a94-aeb51762edb7")}catch{}})();function Cw(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Tw(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function ds(e){let t=Iw.join(e,"manifest.json"),n;try{n=await Aw.readFile(t,"utf8")}catch(a){if(dt(a))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw a}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=r,o=Ea(i),s=Cw(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:o.findings,warnings:o.findings.map(a=>Tw(s,a)),remediation:o.findings.map(a=>a.message)}}function nm(e){return ds(Le(e))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39bc7f14-2d32-5b58-97ab-647f9f238273")}catch{}})();async function rm(e,t,n){let r=typeof t=="string"?null:await Wn(e),i=r===null?null:e.trim().toLowerCase(),o=i===null?null:await eu(i),s=si(r??e,{forceGithub:typeof t=="string",ref:n}),a=i===null?null:await ou(e);return{bundledAliasName:i,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:i===null?s.kind:"builtin",input:i??s.input,...o===null?{}:{package:o}},ambiguous:a!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...o===null?{}:{package:o},command:`pm install ${i}`}],...a===null?[]:[{kind:"npm",input:`npm:${a.package}`,package:a.package,...a.version===void 0?{}:{version:a.version},directory:a.directory,command:`pm install npm:${a.package}`}]]}}}import $t from"node:fs/promises";import $w 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]="98b47a2f-d48a-5c90-8b88-3f33bdd1c826")}catch{}})();var ls=async e=>$t.readFile(e).catch(t=>{if(ui(t,"ENOENT"))return null;throw t}),im=async(e,t,n,r,i)=>{let o=jn(e),s=bt(t),[a,c]=await Promise.all([ls(o),ls(s)]);return r&&await $t.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:o,managedStateContents:a,settingsPath:s,settingsContents:c}},om=async e=>{await $t.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await $t.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await $t.rm(t,{force:!0}):(await $t.mkdir($w.dirname(t),{recursive:!0}),await $t.writeFile(t,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]="8d5ed026-8d61-5083-956c-9281caa0168b")}catch{}})();var Ow=4,dm=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],Dw=dm.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Pw={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},Nw="__pm_native_output",Mw=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],lm=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Lw=["disabled","require_trusted","require_provenance"],um={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},Fw=e=>{let t=e??um,n={};for(let r of Mw)n[r]=Se(t[r]??[]);return n},jw=(e,t)=>{for(let n of lm)t[n].length>0&&(e[n]=t[n]);return e},Uw=(e,t)=>{for(let n of Lw)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},zw=e=>{let t={};for(let n of lm)t[n]=Se(e[n]??[]);return t},Ww=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:jw(Uw({name:t},e),zw(e))},Hw=e=>(e??[]).map(t=>Ww(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),qw=e=>{let t=Object.assign({},um,e??{}),n=Fw(e),r=Hw(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},mm=async(e,t)=>{let n=[t],r=await tu(t);r&&n.push(r);let i=[...new Set(n.map(o=>R(o)).filter(o=>o.length>0))];for(let o of i){let s=e.find(c=>R(c.name)===o);if(s)return s;let a=e.find(c=>R(c.directory)===o);if(a)return a}},pm=(e,t)=>{let n=t.trim(),r=new Set(Se(e.extensions.enabled));return new Set(Se(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},fm=(e,t)=>{let n=t.trim(),r=new Set(Se(e.extensions.enabled)),i=new Set(Se(e.extensions.disabled)),o=[...r],s=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},Bw=(e,t)=>{let n=t.trim(),r=new Set(Se(e.extensions.enabled)),i=new Set(Se(e.extensions.disabled)),o=[...r],s=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},Gw=(e,t)=>{let n=t.trim(),r=new Set(Se(e.extensions.enabled)),i=new Set(Se(e.extensions.disabled)),o=[...r],s=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},Jw=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=dm.map(([i,o,s])=>({action:o,flag:s,distance:ya(t,i,n)})).filter(i=>i.distance!==null).sort((i,o)=>i.distance-o.distance)[0];return r?{action:r.action,flag:r.flag}:null},Vw=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=Jw(e);if(!r)return new w(`One action flag is required. Use one of: ${Dw}. Bare \`pm package\` and \`pm extension\` default to --explore.`,y.USAGE);let i=`pm ${n} ${r.flag}`;return Tr({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(hm),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},Kw=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],hm={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Yw=e=>hm[e]??null,Xw=(e,t)=>{let n=[...new Set(Kw.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=Yw(e.trim().toLowerCase());if(r)return r;throw Vw(e,t)}if(n.length>1)throw new w("Extension action flags are mutually exclusive.",y.USAGE);return n[0]},Zw=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new w('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"},Qw=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&e.source.kind!=="github"?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],_m=e=>{for(let t of Qw){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},gm=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,update_error:i.update_error,update_check_status:r.status,update_check_reason:r.reason}},ev=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),o=r?pm(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:gm({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:o},t,r,_m(r))}},tv=async(e,t,n,r,i,o)=>{let s=Te.join(e,t),a=Te.join(s,"manifest.json"),c=o.get(R(t));if(!await D(a))return ev(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await _t.readFile(a,"utf8").then(p=>JSON.parse(p)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=Go(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(R(u.name))??o.get(R(t));return{summary:gm({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:pm(r,u.name)},n,m,_m(m))}},Ge=async(e,t,n,r)=>{if(!await D(e))return{extensions:[],warnings:[]};let o=(await _t.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),s=new Map(r.entries.map(l=>[R(l.name),l])),a=new Map(r.entries.map(l=>[R(l.directory),l])),c=[],d=[];for(let l of o){let u=await tv(e,l,t,n,s,a);u.warning&&c.push(u.warning),u.summary&&d.push(u.summary)}return{extensions:d.sort((l,u)=>l.name.localeCompare(u.name)),warnings:c.sort((l,u)=>l.localeCompare(u))}},nv=ac(),rv=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,iv=(e,t,n,r)=>{let i=n.command_paths.map(a=>`pm ${a} --help`),o=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,s=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&s.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:rv(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:s,...o?{sdk_dependency_status:"missing"}:{}}},ov=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},ym=e=>e.map(t=>ov(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),wm=(e,t,n)=>{let r=R(e);return t.find(i=>(n===void 0||i.layer===n)&&R(i.name)===r)},sv=(e,t,n,r)=>n.find(o=>o.scope===t&&R(o.name)===R(e))?.activation_status??(r?"failed":"unknown"),vm=(e,t,n,r,i)=>nv.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,s=await _t.mkdtemp(Te.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Re(import.meta.url,["../.."]);try{let a=await Fe({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:Bi(),cache_bust:!0,module_graph_snapshot_root:s}),c=await je({...a}),d=[...a.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...ym(c.failed)],l=Object.fromEntries(a.loaded.map(u=>[R(u.name),Na(Qt(c,{extensionName:u.name}))]));return{installed:di(r,a,c),warnings:[...a.warnings,...c.warnings],activation_failures:d,extensions_disabled:a.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await _t.rm(s,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),ms=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),o=[...i].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),s=r,a=[];for(let c of o){let d=Te.join(e,c.directory),l=await an(d),u=T(),m={kind:"local",input:c.name,location:d};s=zn(s,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:u,updated_at:u,source:m}),a.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return a.length>0&&await Ct(e,s),{state:s,adopted_entries:a,unmanaged_candidates:o,already_managed_count:n.length-i.length}},av=(e,t)=>{let n=M(process.cwd(),t.path),r=Pt(n,process.cwd()),i=e==="global"?lr(process.cwd()):n,o=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:o,roots:r}},mi=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new w('Options "--gh" and "--github" must match when both are provided.',y.USAGE);return n[0]},cv=e=>Pw[e],dv=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,o=cv(e),s=`<${r}>`,a=`pm ${n} ${o} ${s}`;throw new w(`Action "${e}" requires ${i} input.`,y.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${s}`,a,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:a,fallback_candidates:[{source:"lifecycle_action",command:a,reason:`flag-form ${e} command with required ${r} target`}]}})},pi=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new w('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',y.USAGE);return dv(t,n)},lv=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${R(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${R(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,i,o)=>o.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},uv=(e,t)=>{let r=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate",message:"--dry-run is only valid with --migrate."}].find(i=>i.triggered&&!i.allowed);if(r)throw new w(r.message,y.USAGE)},mv=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},pv=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},fv=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:pv(e),warnings:[...new Set(e.warnings)].sort((i,o)=>i.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(r,Nw,{value:!0,enumerable:!1,configurable:!1}),r},ps=async(e,t,n)=>{let r=Xw(e,t);uv(r,t);let i=mv(e,r,t),o=Zw(t),s=av(o,n),c={action:r,normalizedTarget:i,scope:o,resolvedRoots:s,warnings:[],options:t,global:n},l={...c,withResult:(u,m=!0)=>fv(c,u,m)};return await Jv(l)},hv=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=oc(r),o={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},s={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},a=[];return[n==="package",t.declarative===!0].every(Boolean)&&a.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[o[n],...a,`Install the scaffold: ${ze(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,s[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},_v=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([mi(r),r.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new w('Action "init" does not accept --gh/--github/--ref options.',y.USAGE);let a=pi(n,t,r),c=await Su(a,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:c.created_directory||c.files.some(d=>d.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:hv(c,r)})},gv=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:o,withResult:s}=e;if(t!==void 0)throw new w('Action "reload" does not accept a target argument.',y.USAGE);let a=await C(n.settings_root),c=Bi(),d=await Fe({pmRoot:n.settings_root,settings:a,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await je(d);r.push(...l.warnings);let u={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),s(u)},yv=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:o}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new w('Action "catalog" does not accept a package target.',y.USAGE);return o(await nu(n,i,r))},wv=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),vv=e=>({kind:"local",input:e.input,location:e.absolute_path}),bv=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),kv=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),xv=(e,t,n,r)=>e?wv(e,t):n.kind==="local"?vv(n):n.kind==="npm"?bv(n,r):kv(n,r),Sv=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:Kl(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},Ev=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:o,destinationDirectoryName:s}=t,a=await C(r.settings_root),c=await _e(r.selected_root);i.push(...c.warnings);let d=Te.join(r.selected_root,s),l=await D(d),u=await mu(o.directory,d);await _t.mkdir(r.selected_root,{recursive:!0});let m=await _t.mkdtemp(Te.join(r.selected_root,".pm-extension-install-backup-")),p=Te.join(m,"destination");try{let f=await im(r.selected_root,r.settings_root,d,l,p),h=xv(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),_=c.state.entries.find(x=>R(x.name)===R(o.manifest.name)),g=Sv(_,o.manifest.version,h,T()),v=zn(c.state,{name:o.manifest.name,directory:s,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,...g,source:h}),k=fm(a,o.manifest.name);try{u||await Gu(o.directory,d),await Hu(d),await qu(d),await Ct(r.selected_root,v),k&&await Ir(r.settings_root,a,"settings:write")}catch(x){try{await om(f)}catch(S){throw new AggregateError([x,S],`Extension install failed: ${String(x)}; rollback failed: ${String(S)}`,{cause:S})}throw x}return{settings:a,managedState:v,sourceRecord:h,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:k}}finally{await _t.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},Rv=async(e,t,n)=>{let r=n.filter(i=>R(i.name)===R(t)).flatMap(i=>i.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&r.length>0&&await Ln(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},Av=(e,t,n,r,i)=>{let o=wm(t,n.activation_failures,e.scope),s=sv(t,e.scope,n.installed,o),a=[!n.extensions_disabled,s==="ok"].every(Boolean);a||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${s}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:a,status:s,failure:o,verification:{status:c[String(a)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:s,activated:a,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(a)]}}},Iv=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:o,withResult:s}=e,{validated:a,destinationDirectoryName:c}=t,d=await Ev(e,t),l=await Ge(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let u=await vm(r.pm_root,Te.dirname(r.selected_root),d.settings,l.extensions,o);i.push(...u.warnings);let m=await Rv(e,a.manifest.name,u.item_type_registrations),p=Ku(a.manifest.name,u.installed),f=Av(e,a.manifest.name,u,p,m),h=u.contribution_inventories[R(a.manifest.name)];return h&&(d.managedState=await Yl(r.selected_root,d.managedState,a.manifest.name,h)),s({extension:{name:a.manifest.name,version:a.manifest.version,entry:a.manifest.entry,capabilities:a.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:f.activated,settings_changed:d.activationChanged,runtime_activation_status:f.status,command_paths:p.command_paths,action_paths:p.action_paths,contributions:h,command_discovery:iv(a.manifest.name,d.sourceRecord,p,f.failure),verification:f.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:f.failure??null}},f.activated)},Cv=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new w('Action "install all" does not accept --ref.',y.USAGE);let o=[],s=new Map;for(let c of await ri()){let d=await Wn(c),l=Te.resolve(d),u=s.get(l);u===void 0&&(u=await ps(c,{...t,install:!0},n),s.set(l,u)),o.push({alias:c,result:u})}r.push(...o.flatMap(c=>c.result.warnings));let a=o.every(c=>c.result.ok);return i({installed_all:a,installed_count:o.filter(c=>c.result.ok).length,failed_count:o.filter(c=>!c.result.ok).length,packages:o.map(c=>{let d=c.result.details;return{alias:c.alias,ok:c.result.ok,extension:d.extension,source:d.source,source_resolution:d.source_resolution,destination_path:d.destination_path,activated:d.activated,settings_changed:d.settings_changed,command_paths:d.command_paths,action_paths:d.action_paths,command_discovery:d.command_discovery,verification:d.verification,runtime_activation_status:d.runtime_activation_status,activation_diagnostics:d.activation_diagnostics,warnings:c.result.warnings}})},a)},Tv=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:o,installSource:s,sourceResolution:a}=await rm(t,n,e.options.ref);if(a.ambiguous){let d=a.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${d.package}`)}let c=await uu(s);try{let d=await an(c.directory,{source_kind:s.kind,source_input:s.input,source_root:c.source_root}),l=ti(d.manifest.name);return await ss(r.settings_root,l,()=>Iv(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:o,sourceResolution:a,installSource:s,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},$v=async e=>{let t=mi(e.options),n=t??pi(e.normalizedTarget,e.action,e.options);return[t===void 0,Zl(n)].every(Boolean)?Cv(e):Tv(e,n,t)},Ov=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:s}=e;if(t!==void 0)throw new w('Action "adopt-all" does not accept a target argument.',y.USAGE);if(mi(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new w('Action "adopt-all" does not accept --gh/--github/--ref options.',y.USAGE);let c=await C(r.settings_root),d=await _e(r.selected_root);i.push(...d.warnings);let l=await Ge(r.selected_root,n,c,d.state);i.push(...l.warnings);let u=await ms(r.selected_root,n,l.extensions,d.state),m=await Ge(r.selected_root,n,c,u.state);i.push(...m.warnings);let p=li(n,i,m.extensions,o);i.push(...p.warnings);let f=new Map(m.extensions.map(g=>[`${R(g.name)}:${R(g.directory)}`,g])),h=new Map(m.extensions.map(g=>[R(g.directory),g])),_=u.adopted_entries.map(g=>{let v=R(g.directory),k=f.get(`${R(g.name)}:${v}`)??h.get(v);return{...g,...bm(k)}});return s({adopted_all:_.length>0,adopted_count:_.length,already_managed_count:u.already_managed_count,extensions:_,triage:p,warning_codes:p.warning_codes,update_health_partial:p.update_health_partial,update_health_coverage:p.update_health_coverage})},bm=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Dv=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=si(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new w(`Invalid GitHub shorthand "${e}".`,y.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},Pv=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:s,withResult:a}=e,c=pi(n,t,s),d=mi(s),l=await C(i.settings_root),u=await _e(i.selected_root);o.push(...u.warnings);let m=await Ge(i.selected_root,r,l,u.state);o.push(...m.warnings);let p=await mm(m.extensions,c);if(!p)throw new w(`Installed extension "${c}" was not found in ${r} scope.`,y.NOT_FOUND);if(p.managed)return a({adopted:!1,already_managed:!0,extension:{name:p.name,directory:p.directory}});let f=Te.join(i.selected_root,p.directory),h=await an(f),_=T(),g=Dv(d,c,f,s.ref),v=zn(u.state,{name:h.manifest.name,directory:p.directory,scope:r,manifest_version:h.manifest.version,manifest_entry:h.manifest.entry,capabilities:[...h.manifest.capabilities],contributions:h.manifest.contributions,installed_at:_,updated_at:_,source:g});await Ct(i.selected_root,v);let k=await Ge(i.selected_root,r,l,v);o.push(...k.warnings);let x=k.extensions.find(S=>R(S.name)===R(h.manifest.name))??k.extensions.find(S=>R(S.directory)===R(p.directory));return a({adopted:!0,extension:{name:h.manifest.name,directory:p.directory,version:h.manifest.version,entry:h.manifest.entry},source:g,...bm(x)})},km=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:s}=e,a=pi(n,t,s),c=await C(i.settings_root),d=await _e(i.selected_root);o.push(...d.warnings);let l=await Ge(i.selected_root,r,c,d.state);o.push(...l.warnings);let u=await mm(l.extensions,a);if(!u)throw new w(`Installed extension "${a}" was not found in ${r} scope.`,y.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},Nv=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:o}=await km(e),s=Te.join(t.selected_root,o.directory);await _t.rm(s,{recursive:!0,force:!0});let a={...i.state,updated_at:T(),entries:i.state.entries.filter(d=>R(d.name)!==R(o.name)&&R(d.directory)!==R(o.directory))};await Ct(t.selected_root,a);let c=Gw(r,o.name);return c&&await Ir(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:s,settings_changed:c})},sm=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:o}=e,{settings:s,candidate:a}=await km(e),c=t==="activate"?fm(s,a.name):Bw(s,a.name);c&&await Ir(n.settings_root,s,"settings:write");let d=t==="activate"?await vm(n.pm_root,Te.dirname(n.selected_root),s,[a],i).then(l=>(r.push(...l.warnings),wm(a.name,l.activation_failures,e.scope))):void 0;return d&&r.push(`extension_activate_failed:${e.scope}:${a.name}`),o({extension:{name:a.name,directory:a.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...s.extensions.enabled],disabled:[...s.extensions.disabled]}},d===void 0)},Mv=(e,t,n,r,i,o)=>{let s=r==="package"?"package":"extension",a={package:"doctor",extension:"--doctor"}[s],c=i?.adopted_entries.length??0,d=[[o!==null,o??""],[t>0,`Run pm ${s} explore --project and pm ${s} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${s} ${a} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},us=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Lv=(e,t,n,r)=>{if(e!=="project"||t||!us(r))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Fv=(e,t,n)=>{if(String(e??"").trim().length>0)throw new w('Action "doctor" does not accept a target argument.',y.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new w("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",y.USAGE);let i=Nu(n.detail),o=n.trace===!0;if([o,i!=="deep"].every(Boolean))throw new w("--trace requires --detail deep with --doctor.",y.USAGE);return{isolated:r,detailMode:i,includeTrace:o}},jv=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await ms(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},Uv=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:us(r),rerun_command:null,pm_global_path_recipe:null};let o=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:us(r),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},zv=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:s,withResult:a}=e,{isolated:c,detailMode:d,includeTrace:l}=Fv(t,n,o),u=await C(r.settings_root),m=await _e(r.selected_root);i.push(...m.warnings);let p=await Ge(r.selected_root,n,u,m.state);i.push(...p.warnings);let{state:f,fix:h}=await jv(e,p.extensions,m.state),_=await Ge(r.selected_root,n,u,f);i.push(..._.warnings);let g=await Fe({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:s.noExtensions===!0,ignoreGlobalExtensions:c}),v=await je({...g,loaded:g.loaded}),k=await nm(r.pm_root);i.push(...k.warnings,...g.warnings),i.push(...Ou(g.failed)),i.push(...v.warnings),i.push(...Du(v.failed)),i.push(...Pu(g,v)),i.push(...Yu(v,g)),i.push(...lv(g,v)),i.push(...Xu(v));let x=di(_.extensions,g,v),S=Lu(n,x,g.loaded.map(j=>({layer:j.layer,name:j.name})),g.failed.map(j=>({name:j.name})),g.disabled_by_flag);i.push(...S.warnings);let I=x.filter(j=>j.update_check_status==="failed").map(j=>`extension_update_check_failed:${j.name}`);i.push(...I);let b=li(n,i,x,o);i.push(...b.warnings);let E=[...b.warnings],A={mode:g.policy.mode,trust_mode:g.policy.trust_mode,require_provenance:g.policy.require_provenance,default_sandbox_profile:g.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:g.policy.trusted_extensions.length,allowed_extensions_count:g.policy.allowed_extensions.length,blocked_extensions_count:g.policy.blocked_extensions.length,allowed_capabilities_count:g.policy.allowed_capabilities.length,blocked_capabilities_count:g.policy.blocked_capabilities.length,allowed_surfaces_count:g.policy.allowed_surfaces.length,blocked_surfaces_count:g.policy.blocked_surfaces.length,allowed_commands_count:g.policy.allowed_commands.length,blocked_commands_count:g.policy.blocked_commands.length,allowed_actions_count:g.policy.allowed_actions.length,blocked_actions_count:g.policy.blocked_actions.length,allowed_services_count:g.policy.allowed_services.length,blocked_services_count:g.policy.blocked_services.length,extension_override_count:g.policy.extension_overrides.length},F=Bn(E),q=Gn(),O=b.warning_codes,B=Lv(n,c,o.vocabulary,g),se=Mv(b.remediation,g.failed.length,v.failed.length,o.vocabulary,h,B),ae=Uv(n,c,o.vocabulary,g),he={status:b.status,scope:n,warning_count:b.warning_count,warning_codes:O,total_extensions:x.length,managed_total:x.filter(j=>j.managed).length,enabled_total:x.filter(j=>j.enabled).length,active_total:x.filter(j=>j.active).length,unmanaged_loaded_extension_count:b.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:b.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:b.unmanaged_expected_extension_count,runtime_active_total:x.filter(j=>j.runtime_active===!0).length,activation_status_totals:{ok:x.filter(j=>j.activation_status==="ok").length,failed:x.filter(j=>j.activation_status==="failed").length,not_loaded:x.filter(j=>j.activation_status==="not_loaded").length,unknown:x.filter(j=>j.activation_status==="unknown").length},unknown_capability_count:F.length,capability_contract_version:q.version,update_available_total:x.filter(j=>j.update_available===!0).length,update_health_coverage:b.update_health_coverage,update_health_partial:b.update_health_partial,update_check_failed_total:x.filter(j=>j.update_check_status==="failed").length,load_failure_count:g.failed.length,activation_failure_count:v.failed.length,load_failures:ns(g.failed),activation_failures:ns(v.failed),blocking_failure_count:g.failed.length+v.failed.length,has_blocking_failures:g.failed.length+v.failed.length>0,consistency_warning_count:S.warnings.length,trace_enabled:l,isolation:ae,policy:A,remediation:se},vt=h?{requested:!0,applied:h.adopted_entries.length>0,adopted_count:h.adopted_entries.length,already_managed_count:h.already_managed_count,adopted_extensions:h.adopted_entries.map(j=>j.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:_.extensions.filter(j=>j.managed).length,adopted_extensions:[]},vn={mode:d,summary:he,triage:b,trace_enabled:l,capability_contract:q,capability_guidance:F,managed_state_fix:vt,author_manifest:k,isolation:ae,policy:g.policy};if(d==="deep"){let j=l?v.failed:v.failed.map(G=>{let{trace:or,...sr}=G;return sr});vn.deep={warnings:E,warning_codes:O,capability_contract:q,capability_guidance:F,trace_enabled:l,managed_state:{path:m.path,count:f.entries.length,entries:f.entries},installed_extensions:x,load:{roots:g.roots,policy:g.policy,warnings:g.warnings,failed:g.failed,loaded:g.loaded.map(G=>({layer:G.layer,directory:G.directory,name:G.name,version:G.version,entry:G.entry,priority:G.priority}))},activation:{failed:j,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:S.summary},l&&(vn.deep.trace={activation_failures:v.failed.filter(G=>G.trace!==void 0).map(G=>({layer:G.layer,name:G.name,entry_path:G.entry_path,error:G.error,method:G.trace.method,command:G.trace.command,capability:G.trace.capability,missing_capability:G.trace.missing_capability,registration_index:G.trace.registration_index,expected_schema:G.trace.expected_schema,hint:G.trace.hint,received:G.trace.received}))})}return a(vn)},Wv=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:s,withResult:a}=e,c=await C(r.settings_root),d=await Fe({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:s.noExtensions===!0}),l=await je(d);i.push(...d.warnings),i.push(...l.warnings);let u=Ru(t,d,l);if(t!==void 0&&u.extensions.length===0){let m=o.vocabulary==="package"?"package":"extension",p=[...new Set(d.loaded.map(h=>o.vocabulary==="package"&&typeof h.source_package=="string"&&h.source_package.trim().length>0?h.source_package.trim():h.name))].sort((h,_)=>h.localeCompare(_)),f=p.length>0?` Loaded ${m} names: ${p.join(", ")}.`:"";throw new w(`No loaded ${m} named "${t}" was found in ${n} scope.${f} Run pm ${m} explore to list discovered ${m}s.`,y.NOT_FOUND)}return a({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},Hv=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await ms(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let o=await Vu(r.entries,Ow,async s=>{if(s.source.kind!=="github")return s;let a=await Zu(s.source);return{...s,last_update_check_at:a.checked_at,last_update_remote_commit:a.remote_commit,update_available:a.available,update_error:a.error}});r={...r,updated_at:T(),entries:Un(o)},await Ct(e.resolvedRoots.selected_root,r)}return{state:r,fix:i}},qv=async(e,t,n)=>{let r=await Fe({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await je({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:di(n,r,i),failures:ym(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...r.warnings,...i.warnings])].length,policy:r.policy}}},Bv=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},am=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:s}=e,a=await C(r.settings_root),c=qw(a.extensions.policy),d=await _e(r.selected_root);i.push(...d.warnings);let l=await Ge(r.selected_root,n,a,d.state);i.push(...l.warnings);let{state:u,fix:m}=await Hv(e,l.extensions,d.state),p=await Ge(r.selected_root,n,a,u);if(i.push(...p.warnings),t==="manage"){let v=p.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);i.push(...v)}let f=await qv(e,a,p.extensions),h=f.installed,_=li(n,i,h,o);i.push(..._.warnings);let g={total:h.length,managed_total:h.filter(v=>v.managed).length,enabled_total:h.filter(v=>v.enabled).length,active_total:h.filter(v=>v.active).length,extensions:h,triage:_,policy:c};return f.failures!==void 0&&(g.activation_diagnostics={failed_count:f.failures.length,failed:f.failures}),t==="explore"&&(g.runtime_probe=f.summary),t==="manage"&&(g.runtime_probe=f.summary,g.managed_state_fix=Bv(m,h)),s(g)},cm={init:_v,install:$v,uninstall:Nv,explore:am,manage:am,describe:Wv,reload:gv,doctor:zv,catalog:yv,adopt:Pv,"adopt-all":Ov,activate:sm,deactivate:sm,migrate:tm},Gv=e=>[e.action==="uninstall",e.action==="manage",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[e.action==="doctor",e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Jv=e=>Gv(e)?ss(e.resolvedRoots.settings_root,`${e.action}-state`,()=>cm[e.action](e)):cm[e.action](e);import{execFile as Vv}from"node:child_process";import{realpath as Kv}from"node:fs/promises";import xm from"node:path";import{promisify as Yv}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var Xv=Yv(Vv),Zv=32*1024*1024,Qv=1e4,eb=["search/eval-queries.json"];function fs(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function tb(e){return`'${e.replaceAll("'","'\\''")}'`}async function nb(e,t=Kv){return t(e).catch(()=>xm.resolve(e))}async function fi(e){let t=await Qe(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await nb(e),r=fs(xm.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=To.map(o=>`${r}/${fs(o)}`);try{let{stdout:o}=await Xv("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:Zv,windowsHide:!0,timeout:Qv}),s=new Set(eb.map(d=>`${r}/${d}`)),a=[...new Set(o.split("\0").filter(d=>d.length>0&&!s.has(fs(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>tb(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import{execFile as ab}from"node:child_process";import{randomUUID as cb}from"node:crypto";import{readdir as db,stat as lb}from"node:fs/promises";import ce from"node:path";import{promisify as ub}from"node:util";import{constants as Sm}from"node:fs";import{lstat as rb,open as ib}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ece0e15-aff5-5e2d-b18a-16ffaa0fe2ea")}catch{}})();var ob={lstat:rb,open:ib};function sb(e){return e.O_NOFOLLOW??0}async function Em(e,t,n=ob){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let i=await n.open(e,Sm.O_RDONLY|sb(Sm));try{let o=await i.stat();if(!o.isFile()||o.size>t)return null;let s=Buffer.alloc(o.size),a=0;for(;a<s.length;){let{bytesRead:d}=await i.read(s,a,s.length-a,a);if(d===0)break;a+=d}return(await i.stat()).size===o.size&&a===o.size?s.toString("utf8",0,a):null}finally{await i.close()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="df7d5bd9-8381-5961-bda1-9e8ed335afc9")}catch{}})();var mb=ub(ab),pb=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,fb=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,_s=2048,hb=16*1024*1024,_b=64,gb=1e5,hi=100,yb=new Set(["version","id","item_path","item_id","requested_preference","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","evidence_source"]);function gi(e){return pb.test(e)}var wb=new Set(["field","base","ours","theirs","retained","discarded"]);async function gs(e){try{let{stdout:t}=await mb("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Tm(e,t){let n=ce.dirname(ce.resolve(e,t));for(let r=0;r<12;r+=1){if(await D(ce.join(n,"settings.json")))return n;let i=ce.dirname(n);if(i===n)break;n=i}return null}function ys(e){return ce.join(e,"merge-receipts")}function cn(e){return`${e}.json`}function Vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $m(e,t){return Object.keys(e).every(n=>t.has(n))}function Rm(e){return Array.isArray(e)&&e.length<=_s&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Jn(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>gb||r.depth>_b)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(Vn(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function vb(e){return Vn(e)&&$m(e,wb)&&typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&Object.hasOwn(e,"base")&&Object.hasOwn(e,"ours")&&Object.hasOwn(e,"theirs")&&Object.hasOwn(e,"retained")&&Object.hasOwn(e,"discarded")&&Jn(e.base)&&Jn(e.ours)&&Jn(e.theirs)&&Jn(e.retained)&&Jn(e.discarded)}function bb(e){if(!Vn(e))return!1;let t=Object.entries(e);return t.length<=_s&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function kb(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||ce.posix.isAbsolute(e))return!1;let n=ce.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&ce.posix.basename(n,ce.posix.extname(n))===t}function xb(e){return!$m(e,yb)||e.version!==1?!1:typeof e.id=="string"&&gi(e.id)&&typeof e.item_id=="string"&&fb.test(e.item_id)&&kb(e.item_path,e.item_id)}function Sb(e){return!Rm(e.fields_from_theirs)||!Rm(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>_s||!e.decisions.every(vb)?!1:e.merged_field_hashes===void 0||bb(e.merged_field_hashes)}function Eb(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order"],r=[void 0,"clone_local","hash_only"],i=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&i.includes(e.evidence_source)}function Rb(e){return typeof e.created_at=="string"&&Qi(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&Qi(e.reconciled_at))}function Ab(e){return e.value_availability==="hash_only"&&e.decisions.every(t=>t.base===null&&t.ours===null&&t.theirs===null&&Im(t.retained)&&Im(t.discarded))}function ws(e,t){return!Vn(e)||!xb(e)||!Sb(e)||!Eb(e)||!Rb(e)?!1:t!=="durable"||Ab(e)}async function Om(e){return Em(e,hb)}async function Am(e){let t;try{t=await(e.readReceipt??Om)(e.receiptPath)}catch(o){if(dt(o))return null;throw o}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=JSON.parse(t)}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!ws(n,e.evidenceSource)||n.id!==e.receiptId||ce.basename(e.receiptPath)!==cn(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprint:_i(n),content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt},null,2)}
38
+ `}}function _i(e){return De(Q({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,decisions:yi(e).decisions}))}function Ib(e,t){if(e.state==="reconciled"&&t.state==="reconciled")return e;let{reconciled_at:n,...r}=e;return{...r,state:"pending"}}function yi(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:hs(t.retained)??De(Q(t.retained)),discarded_hash:hs(t.discarded)??De(Q(t.discarded))}))}}function hs(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function Im(e){return Vn(e)&&Object.keys(e).length===1&&hs(e)!==void 0}async function ZO(e){let t=await gs(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,i=ce.basename(r,ce.extname(r)),o={version:1,id:cb(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions),state:"pending",created_at:T(),value_availability:"clone_local"};await bn(t),await le(ce.join(t,cn(o.id)),`${JSON.stringify(o,null,2)}
39
+ `);let s=await Tm(e.cwd,o.item_path);if(s!==null){let a=ys(s),c=yi(o),d={...o,decisions:c.decisions.map(l=>({field:l.field,base:null,ours:null,theirs:null,retained:{pm_value_hash:l.retained_hash},discarded:{pm_value_hash:l.discarded_hash}})),value_availability:"hash_only"};await bn(a),await le(ce.join(a,cn(o.id)),`${JSON.stringify(d,null,2)}
40
+ `)}return o}async function Cm(e,t){let n;try{n=await db(e)}catch(a){let c=await Cb(e,a);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],i=0,o=[],s=(a,c)=>{if(i+=1,o.length>=hi)return;let d=a.slice(0,-5);o.push({evidence_source:t,reason:c,...gi(d)?{receipt_id:d}:{candidate_name_hash:De(a)}})};for(let a of n.sort((c,d)=>c.localeCompare(d))){if(!a.endsWith(".json"))continue;let c=await Tb(e,a,t);c.receipt!==void 0?r.push(c.receipt):s(a,c.reason)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:o,invalid_evidence_truncated:i>o.length}}async function Cb(e,t,n=lb){if(!U(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!U(i))return!1;let o=ce.dirname(r);if(o===r)return!0;r=o}}async function Tb(e,t,n){let r;try{r=await Om(ce.join(e,t))}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=JSON.parse(r)}catch{return{reason:"candidate_invalid_json"}}if(!ws(i,n)||t!==cn(i.id))return{reason:"schema_or_identity_invalid"};let{preferred:o,evidence_source:s,...a}=i;return{receipt:{...a,requested_preference:i.requested_preference??o??"ours",conflict_resolution:i.conflict_resolution??"preferred_side",evidence_source:n}}}async function it(e,t={}){let n=await gs(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await Cm(n,"clone_local"),i=t.pmRoot??ce.join(e,".agents","pm"),o=await Cm(ys(i),"durable"),s=new Map(o.receipts.map(d=>[d.id,d])),a=0,c=[];for(let d of r.receipts){let l=s.get(d.id);if(l!==void 0&&_i(l)!==_i(d)){s.delete(d.id),a+=1,r.invalid_evidence.length+o.invalid_evidence.length+c.length<hi&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:d.id});continue}s.set(d.id,l===void 0?d:Ib(d,l))}return{receipts:[...s.values()].filter(d=>(t.includeReconciled||d.state==="pending")&&(t.includeLossless!==!1||d.decisions.length>0)).sort((d,l)=>d.created_at.localeCompare(l.created_at)),invalid_evidence_count:r.invalid_evidence_count+o.invalid_evidence_count+a,invalid_evidence:[...r.invalid_evidence,...o.invalid_evidence,...c].slice(0,hi),invalid_evidence_truncated:r.invalid_evidence_truncated||o.invalid_evidence_truncated||r.invalid_evidence_count+o.invalid_evidence_count+a>hi,clone_local_evidence_resolved:n!==null}}function dn(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function QO(e,t,n={}){let r=await gs(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!ws(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let o=T(),s=ce.join(r,cn(t.id)),a=await Tm(e,t.item_path),c=a===null?null:ce.join(ys(a),cn(t.id)),l=(await Promise.all([Am({receiptPath:s,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:o}),...c===null?[]:[Am({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:o})]])).filter(m=>m!==null);if(l.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let u=_i(t);if(new Set([u,...l.map(m=>m.fingerprint)]).size!==1)throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let m of l)await le(m.path,m.content)}async function eD(e){let t=await it(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:T()}}import{realpath as Nm}from"node:fs/promises";import $b from"node:path";import Mm from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="151e5d26-d6f5-5fcf-84ab-ce89e2b7664e")}catch{}})();function Dm(e,t){return t==="body"?e.body:e.metadata[t]}function vs(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(i=>{let o=t.findIndex((s,a)=>!r.has(a)&&vs(i,s));return o<0?!1:(r.add(o),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,i])=>Object.hasOwn(n,r)&&vs(i,n[r]))}function Pm(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let o=e[i],s=new Set;for(let c of gc(o.patch))s.add($r(c.path)),c.from&&s.add($r(c.from));let a=[...n].filter(c=>s.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:i+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function Ob(e,t,n){let r=Mm.compare(t,n);if(r.length===0)return;let i=new Set;for(let f of r)i.add($r(f.path));let o=new Set([...i].filter(f=>vs(Dm(t,f),Dm(n,f)))),s=new Set([...i].filter(f=>!o.has(f))),a=Pm(e,s),c=Pm(e,o),d=[...i].sort((f,h)=>f.localeCompare(h)),l=[...s].sort((f,h)=>f.localeCompare(h)),u=[...o].sort((f,h)=>f.localeCompare(h)),m=[...new Set(a.map(f=>f.author))].sort((f,h)=>f.localeCompare(h)),p=[...new Set(c.map(f=>f.author))].sort((f,h)=>f.localeCompare(h));return{reconciled_field_count:i.size,reconciled_fields:d,reverted_field_count:s.size,reverted_fields:l,discarded_events:a,discarded_authors:m,preserved_field_count:o.size,preserved_fields:u,preserved_events:c,preserved_authors:p,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function Db(e){try{return await Nm(e)}catch{return null}}async function Pb(e){if(await Db($b.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let n=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let i=Object.keys(r).sort();if(n.length!==i.length||n.some((a,c)=>a!==i[c]))return null;let o=e.currentItemReplay.metadata;return n.every(a=>{let c=a==="body"?e.currentItemReplay.body:o[a];return r[a]===De(Q(c))})?{receipt:e.receipt,declaredFields:n}:null}async function Nb(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(s=>s.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Nm(e.itemPath),r=[];for(let s of t){let a=await Pb({receipt:s,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});a&&r.push(a)}let i=new Set(r.flatMap(({declaredFields:s})=>s)),o=e.reconciliation?.reconciled_fields;return r.length>0&&(o===void 0||o.length>0&&o.every(s=>i.has(s)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:s})=>s.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function Mb(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(s=>s.item_id===e.subjectId).map(s=>s.id)??[]),r=(e.options.mergeReceiptProof?await it(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(s=>s.item_id===e.subjectId&&t.has(s.id))??[],i=e.options.mergeReceiptProof?await Nb({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(i&&!i.trusted&&e.options.dryRun!==!0&&e.options.force!==!0)throw new w(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${i.reason}).`,y.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let o=i?.trusted?r.filter(s=>i.receipt_ids.includes(s.id)):[];return{mergeReceiptProof:i,effectiveAuditContext:o.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:o.map(yi)}}:e.options.auditContext}}async function Lb(e,t,n,r){let i=e.located?.itemPath??null,o=e.located?await ut(e.located,{schema:t.schema}):null;if(!o)return{currentItemReplay:null,currentItemPath:i,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=_c(o.document),a=n[n.length-1].after_hash;return{currentItemReplay:s,currentItemPath:i,matchedChainBefore:qt(s,r).includes(a),currentItemRawBeforeLock:o.raw,loadedItem:o}}function Fb(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function jb(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=qt(e.finalReplay,e.itemHashVersion),i=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=r.indexOf(i),s=qt(n,e.itemHashVersion);return t.push({ts:T(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Mm.compare(e.finalReplay,e.currentItemReplay):[],before_hash:r[o],after_hash:s[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function Ub(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function zb(e){return Cc({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Ic({historyPath:e.historyPath,nextHistoryRaw:vc(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>ne({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function bs(e,t,n){let r=M(process.cwd(),n.path);await X(r);let i=await C(r),o=W(i,z()),s=await Tc(r,e,i,o.type_to_folder);if(!await D(s.historyPath))throw new w(`No history stream exists for ${s.id}.`,y.NOT_FOUND);let a=await Y(s.historyPath),c=await Wt(s.historyPath,s.id);if(c.length===0)throw new w(`No history entries exist for ${s.id}; nothing to repair.`,y.USAGE);let d=eo(c),l=xr(c),u=t.normalizeProvenance?Jd(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},m=yc(u.entries),p=new Set(u.entries.map(se=>se.item_hash_version).filter(se=>se!==void 0)),f=wc(u.entries,m),h=await Lb(s,i,c,m),_=f.finalDocument,g=qt(_,m),v=!1;if(h.currentItemReplay!==null){let se=qt(h.currentItemReplay,m);v=!g.some((ae,he)=>ae===se[he])}let k=v&&h.currentItemReplay?Ob(f.entries,_,h.currentItemReplay):void 0,{mergeReceiptProof:x,effectiveAuditContext:S}=await Mb({options:t,pmRoot:r,subjectId:s.id,itemReplayContext:h,reconciliation:k}),I=[f.entriesRehashed>0,f.entriesPatchRepaired>0,v,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),b=V(t.author,i.author_default),E=!!t.dryRun,A=Fb({message:t.message,entriesRehashed:f.entriesRehashed,entriesPatchRepaired:f.entriesPatchRepaired,reconcileNeeded:v}),{rewrittenEntries:F,auditEntryAdded:q}=jb({reanchorEntries:f.entries,changed:I,reconcileNeeded:v,currentItemReplay:h.currentItemReplay,finalReplay:_,author:b,message:A,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...S,provenance_normalization:u.receipt}:S,itemHashVersion:m,explicitItemHashVersion:f.explicitItemHashVersion}),O=eo(F);if(!O.ok)throw new w(`history-repair produced an invalid rewritten chain (${O.errors.join(", ")}).`,y.GENERIC_FAILURE);let B=Ub(I,f.skippedOps,k);return I&&!E&&B.push(...await zb({pmRoot:r,subject:s,settings:i,typeRegistry:o,historyRawBeforeLock:a,currentItemRawBeforeLock:h.currentItemRawBeforeLock,author:b,force:t.force,loadedItem:h.loadedItem,historyPath:s.historyPath,rewrittenEntries:F})),{id:s.id,dry_run:E,changed:I,history:{path:s.historyPath,entries_scanned:c.length,chain_drift_before:!d.ok,entries_rehashed:f.entriesRehashed,entries_patch_repaired:f.entriesPatchRepaired,converted_replace_to_add:f.convertedReplaceToAdd,skipped_ops:f.skippedOps,reconciled_with_item:v,audit_entry_added:q,verify_ok:O.ok,verify_errors:O.errors,item_hash_version_before:l.item_hash_version??null,item_hash_version_after:m,version_disposition:p.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:h.currentItemPath!==null,path:h.currentItemPath,matched_chain_before:h.matchedChainBefore},provenance_normalization:{requested:t.normalizeProvenance===!0,...u.receipt},...k?{reconciliation:k}:{},...x?{merge_receipt_proof:x}:{},warnings:[...new Set(B)].sort((se,ae)=>se.localeCompare(ae)),generated_at:T()}}function RD(e,t){if(t&&e!==void 0)throw new w("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",y.USAGE);if(!t&&e===void 0)throw new w("history-repair: provide an item <id> or pass --all to repair every drifted stream.",y.USAGE)}async function AD(e,t){let n=M(process.cwd(),t.path);await X(n);let r=await C(n),i=W(r,z()),o=[],s=await kt(n,r.item_format,i.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await Rt(n,s),c=e.normalizeProvenance?await Vd(n):[],d=[...new Set([...a.driftedItems,...c])].sort((p,f)=>p.localeCompare(f)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let p of d)try{let f=await bs(p,{...e,auditContext:e.auditContextById?.[p],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[p]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=f.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...f.warnings.map(_=>`${p}:${_}`)),l.push({id:p,outcome:h,entries_rehashed:f.history.entries_rehashed,entries_patch_repaired:f.history.entries_patch_repaired,reconciled_with_item:f.history.reconciled_with_item,...f.reconciliation?{reconciliation:f.reconciliation}:{},...f.merge_receipt_proof?{merge_receipt_proof:f.merge_receipt_proof}:{},warnings:f.warnings})}catch(f){m.failed+=1,l.push({id:p,outcome:"failed",error:f instanceof Error?f.message:String(f)})}return e.dryRun||await fc(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:s.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...o,...u])].sort((p,f)=>p.localeCompare(f)),generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f27cb24d-f2c8-5034-b655-84c577de7a16")}catch{}})();var Wb=new Set(td),Fm=25,un=8,Ot=100,Hb=ge.join("runtime","telemetry","events.jsonl"),qb=ge.join("runtime","telemetry","state.json"),Bb=2500,Gb=500,jm=ed-3,Jb=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function As(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Is(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function mn(e){return e.trim().toLowerCase()}function Ss(e,t){let n=mn(e),r=mn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function Cs(e){try{return(await ot.stat(e)).isDirectory()}catch{return!1}}async function Vb(e){let t=(await ot.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>ot.readdir(ge.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>kn.some(o=>i.name.endsWith(o))).map(i=>ge.parse(i.name).name)))}async function Kb(e,t,n,r){let i=await Ke({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:i,overThreshold:!1,classification:"live"};let s;try{s=await ot.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(o){let d=s.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?s.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function Yb(e,t,n){let r=ge.join(e,"history");if(!await Cs(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await ot.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),s=t.enabled?t.max_entries:null,a=[],c=[],d=[],l=[];for(let u of i){let m=ge.join(r,u),p=u.slice(0,-6),f=await Kb(m,p,t,n);a.push(...f.warnings),f.classification==="tombstone"&&d.push(p),f.classification==="orphaned"&&l.push(p),f.overThreshold&&c.push(p)}return{count:i.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:s,tombstones:d,orphaned:l}}function Es(e,t){return ge.relative(e,t).replaceAll("\\","/")}async function Um(e,t){let n=[...new Set(Object.values(t))].sort((i,o)=>i.localeCompare(o)),r=[];for(let i of n){let o=ge.join(e,i),s=[];try{s=await ot.readdir(o)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&U(a))continue;continue}for(let a of s)kn.some(c=>a.toLowerCase().endsWith(c))&&r.push(ge.join(o,a))}return r.sort((i,o)=>Es(e,i).localeCompare(Es(e,o))),r}function Xb(e){return!(typeof e=="object"&&e!==null&&"code"in e&&U(e))}async function Zb(e,t,n){let r=await Um(e,t),i=[],o=[],s=[],a=[],c=Dt(z());for(let d of r){let l=Es(e,d),u;try{u=await ot.readFile(d,"utf8")}catch{i.push(l);continue}let m=Ut(u);if(m){o.push({path:l,...m});continue}try{let p=zt(u,{format:Ca(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:vr(p.metadata)})}catch{s.push(l)}}return{paths:r,unreadable:i,conflictMarkers:o,parseFailures:s,formatVersions:a}}function Qb(e){if(typeof e!="object"||e===null||Array.isArray(e))return[];let t=e.context;if(typeof t!="object"||t===null||Array.isArray(t))return[];let n=t.merge;if(typeof n!="object"||n===null||Array.isArray(n))return[];let r=n.receipts;return Array.isArray(r)?r.flatMap(i=>{if(typeof i!="object"||i===null||Array.isArray(i))return[];let o=i.receipt_id;return typeof o=="string"&&o.length>0?[o]:[]}):[]}async function ek(e){let t=ge.join(e,"history"),n=[],r=[],i=[],o=[],s=[];try{s=(await ot.readdir(t)).filter(a=>a.endsWith(".jsonl")).sort((a,c)=>a.localeCompare(c))}catch(a){Xb(a)&&n.push("history")}for(let a of s){let c=a.slice(0,-6),d;try{d=await ot.readFile(ge.join(t,a),"utf8")}catch{n.push(c);continue}let l=Ut(d);if(l){r.push({id:c,...l});continue}d.split(/\r?\n/).forEach((u,m)=>{if(u.trim())try{let p=JSON.parse(u);o.push(...Qb(p).map(f=>({itemId:c,line:m+1,receiptId:f})))}catch{i.push({id:c,line:m+1})}})}return{files:s,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:o}}function zm(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}function tk(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}async function nk(e,t,n,r,i){let o=await Zb(e,t,n),s=await ek(e),a=br(o.formatVersions),c=Ie(n),d=Pr(i,b=>pc(b,c),Rn()),l=await fi(e),u=await Qe(e),m=u===null?null:await nn(u),p=await it(u??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),f=new Set(p.receipts.map(b=>b.id)),h=s.mergeReceiptReferences.filter(b=>!f.has(b.receiptId)).map(b=>({item_id:b.itemId,history_line:b.line,...gi(b.receiptId)?{receipt_id:b.receiptId}:{receipt_reference_hash:De(b.receiptId)}})),_=p.receipts.filter(b=>b.state==="pending"),{pendingDecisions:g,lossless:v}=dn(_),k=m?.status==="missing"&&m.missing_keys.length===5&&m.drifted_keys.length===0,x=[...o.unreadable.map(b=>`integrity_item_unreadable:${b}`),...o.conflictMarkers.map(b=>`integrity_item_conflict_marker:${b.path}:L${b.line}`),...o.parseFailures.map(b=>`integrity_item_parse_failed:${b}`),...s.unreadable.map(b=>`integrity_history_unreadable:${b}`),...s.conflictMarkers.map(b=>`integrity_history_conflict_marker:${b.id}:L${b.line}`),...s.invalidJson.map(b=>`integrity_history_invalid_json:${b.id}:L${b.line}`),...a.outdated.map(b=>`integrity_item_outdated_format_version:${b}`),...a.ahead.map(b=>`integrity_item_ahead_format_version:${b}`),...zm(d),...l.tracked_path_count>0?[`tracked_runtime_cache_files:${l.tracked_path_count}`]:[],...m!==null&&m.status!=="ok"?[`merge_driver_configuration_${k?"missing":"drift"}:${m.missing_keys.length+m.drifted_keys.length}`]:[],...g.length>0?[`merge_decisions_unreviewed:${g.length}`]:[],...v.length>0?[`merge_receipts_pending:${v.length}`]:[],...tk({invalidEvidenceCount:p.invalid_evidence_count,missingHistoryReferenceCount:h.length})],S=[...new Set(x)].sort((b,E)=>b.localeCompare(E)),I=S.filter(b=>!b.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:I.length===0?"ok":"warn",ok:I.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:s.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:s.unreadable.length,history_conflict_markers:s.conflictMarkers.length,history_invalid_json:s.invalidJson.length,item_outdated_format_version:a.outdated.length,item_ahead_format_version:a.ahead.length,hierarchy_cycles:d.cycles.length,hierarchy_cardinality_violations:d.cardinality_violations.length,hierarchy_parent_divergences:d.divergences.length,tracked_runtime_cache_files:l.tracked_path_count,merge_driver_configuration:m===null||m.status==="ok"?0:m.missing_keys.length+m.drifted_keys.length,pending_merge_decisions:g.length,lossless_merge_receipts:v.length,invalid_merge_receipt_evidence:p.invalid_evidence_count,missing_merge_receipt_history_references:h.length},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:a.outdated,item_ahead_format_version:a.ahead,hierarchy_integrity:{...d,relations:Je(d.relations,un)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.invalidJson,tracked_runtime_cache:{tracker_relative_root:l.tracker_relative_root,tracked_paths:l.tracked_paths,tracked_path_count:l.tracked_path_count,remediation_command:l.remediation_command},merge_driver_configuration:m===null?null:{...m,required:r},pending_merge_decision_items:[...new Set(g.map(b=>b.item_id))].sort((b,E)=>b.localeCompare(E)),lossless_merge_receipt_items:[...new Set(v.map(b=>b.item_id))].sort((b,E)=>b.localeCompare(E)),invalid_merge_receipt_evidence_details:p.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:p.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:h.slice(0,Ot),missing_merge_receipt_history_reference_details_truncated:h.length>Ot}},warnings:S,gitWorkspaceRoot:u,pendingMergeReceipts:_}}function rk(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function ik(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:rk(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function ok(e,t){let n=Z(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function sk(e){let n=Z(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function ak(e){return Z(e.reason)??Z(e.error)??Z(e.message)}function ks(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function ck(e){let t=[],n=[],r=[];e.forEach((o,s)=>{let a=ok(o.definition,s),c=sk(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:a,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:a,status:c,reason:ak(o.definition)});return}n.push({layer:o.layer,name:o.name,id:a,status:c})}),t.sort(ks),n.sort(ks),r.sort(ks);let i=[...r.map(o=>`extension_migration_failed:${o.layer}:${o.name}:${o.id}`),...n.map(o=>`extension_migration_pending:${o.layer}:${o.name}:${o.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function Wm(e,t,n,r,i,o,s,a,c){let d=[...new Set(e)].sort((_,g)=>_.localeCompare(g)),l=[...new Set(d.map(_=>Is(_)))].sort((_,g)=>_.localeCompare(g)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,p=m?"partial":"full",f=[],h=rs(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&f.push(h),t>0&&f.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&f.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&f.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&f.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&f.push(`Unknown extension capabilities detected. Allowed capabilities: ${ar.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(_=>_.startsWith("extension_capability_legacy_alias:"))&&f.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(_=>_.startsWith("extension_command_definition_legacy_handler_alias:"))&&f.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?f.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):s.length>0&&f.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),f.length===0&&f.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:o,unmanaged_loaded_extension_count:s.length,unmanaged_loaded_extensions:s,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:p,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:f}}async function dk(e,t,n){let r=await ds(Le(e)),i=await Fe({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),o=i.loaded.map(b=>ik(b)),s=await Td(i.loaded,Le(e)),a=await je({...i,loaded:i.loaded}),[c,d]=await Promise.all([_e(i.roots.project),_e(i.roots.global)]);await cs(e,a.registrations.migrations);let l=ck(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},m=new Set(c.state.entries.map(b=>mn(b.name))),p=new Set(d.state.entries.map(b=>mn(b.name))),f=[...new Map(i.loaded.filter(b=>!(b.layer==="project"?m:p).has(mn(b.name))).map(b=>[`${b.layer}:${b.name}`,{layer:b.layer,name:b.name,directory:b.directory}])).values()].sort((b,E)=>{let A=`${b.layer}:${b.name}`,F=`${E.layer}:${E.name}`;return A.localeCompare(F)}),h=f.map(b=>`${b.layer}:${b.name}`).sort((b,E)=>b.localeCompare(E)),_=f.filter(b=>Ss(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,E)=>b.localeCompare(E)),g=f.filter(b=>!Ss(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,E)=>b.localeCompare(E)),v=g.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${g.length}`]:[],k=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...s.warnings],x=Bn(k),S=Gn(),I=Wm(k,i.failed.length,a.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,_,g);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...i,loaded:o,warnings:k,activation:u,author_manifest:r,triage:I,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:S,capability_guidance:x,host_version_census:s}},warnings:k}}function lk(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Je(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function uk(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function wi(e,t){let n=Je(e,t);return{...n,sample:n.sample.map(r=>uk(r))}}function H(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function mk(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var pk={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:H(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:H(e.missing_required,t),missing_optional:H(e.missing_optional,t),missing:H(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:H(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:wi(e.discovered,t),effective:wi(e.effective,t),loaded:wi(e.loaded,t),failed:Je(e.failed,t),warnings:H(e.warnings,t),activation:{failed:Je(n.failed,t),warnings:H(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:mk(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Je(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:H(n.affected_item_ids,t),samples:Je(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:H(e.item_unreadable,t),item_conflict_markers:Je(e.item_conflict_markers,t),item_parse_failures:H(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:H(n.tracked_paths,t)},history_unreadable:H(e.history_unreadable,t),history_conflict_markers:Je(e.history_conflict_markers,t),history_invalid_json:Je(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:H(n.candidate_items,t),confirmed_items:H(n.confirmed_items,t),resolved_false_positive_items:H(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:H(e.drifted_items,t),merge_receipt_attributed_items:H(e.merge_receipt_attributed_items,t),missing_streams:H(e.missing_streams,t),unreadable_streams:H(e.unreadable_streams,t),hash_mismatches:H(e.hash_mismatches,t),chain_mismatches:H(e.chain_mismatches,t),version_skews:H(e.version_skews,t),workspace_state_mismatches:H(e.workspace_state_mismatches,t),workspace_state_missing:H(e.workspace_state_missing,t),workspace_state_unreadable:H(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:H(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:H(e.stale_items_after,t),skipped:e.skipped})};function Hm(e,t){let n=pk[e.name];return n?n(e.details,t):e.details}function fk(e){let t=H(e.warnings,un);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:Hm(n,un)})),warnings:t.sample,findings:e.findings.filter(n=>t.sample.includes(n.warning)||e.failed_because.includes(n.warning)),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:un},generated_at:e.generated_at}}function Lm(e){return e.details.skipped===!0}function hk(e){let t=H(e.warnings,un),n=e.checks.filter(Lm).map(r=>r.name);return{ok:e.ok,checks:e.checks.filter(r=>!Lm(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:e.findings.filter(r=>t.sample.includes(r.warning)||e.failed_because.includes(r.warning)),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:un,omitted_checks:n},generated_at:e.generated_at}}function Rs(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=lk(e,Fm);return{values:n.values,truncated:n.truncated,total:e.length}}function ln(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function _k(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return Wb.has(e)?e:null}function vi(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function qm(e){let t=0,n=0,r=0,i=0,o=0;for(let s of e.split(`
41
+ `)){let a=s.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,o=Math.max(o,d),d>=jm&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:o}}function gk(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function yk(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function wk(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await Bm(n)}}function vk(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,o=n.last_failed_flush_at,s=o&&(!i||o>i),a=!i,c=t.validEntries>=Gb;return(s||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function bk(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function kk(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Qc?[`telemetry_schema_version_behind:${t}`]:[]}function xk(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function Sk(){return{telemetry_disabled:ln("PM_TELEMETRY_DISABLED")||ln("PM_NO_TELEMETRY"),pm_no_telemetry:ln("PM_NO_TELEMETRY"),telemetry_otel_disabled:ln("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:ln("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:_k()}}function Ek(e,t){return e.telemetry.enabled&&t.validEntries>0}function Rk(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Bm(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(Bb)});return{probe_url:vi(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of Jb){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:vi(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function Ak(e,t){let n=lr(process.cwd()),r=ge.join(n,Hb),i=ge.join(n,qb),o=await Y(r),s=o!==null,a=o?Buffer.byteLength(o,"utf8"):0,c=o?qm(o):gk(),d=await Y(i),{runtimeState:l,stateParseFailed:u}=yk(d),m=e.telemetry.endpoint.trim(),p=vi(m),f=await wk(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...vk(e,c,l),...bk(f),...kk(f),...xk(e,l));let _=Ek(e,c),g=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:p,global_pm_root:n,queue_path:r,queue_exists:s,queue_entries:c.validEntries,queue_draining:Rk(_,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:a,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:jm,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:g,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:f??{attempted:!1},env_overrides:Sk()}},warnings:h}}async function Ik(e){let t;try{t=await il(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function Ck(e){let t="metadata",n=e.items,r=await Rt(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((g,v)=>g.localeCompare(v)),o=[],s=[];if(i.length>0){n=await kt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Rt(e.pmRoot,n),o=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,k)=>v.localeCompare(k));let g=new Set(o);s=i.filter(v=>!g.has(v))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:p,workspaceStateMissing:f,workspaceStateUnreadable:h}=r,_=[...a.map(g=>`history_drift_missing_stream:${g}`),...c.map(g=>`history_drift_unreadable_stream:${g}`),...d.map(g=>`history_drift_hash_mismatch:${g}`),...l.map(g=>`history_drift_chain_mismatch:${g}`),...u.map(g=>`history_drift_version_skew:${g}`),...p.map(g=>`history_drift_workspace_state_mismatch:${g}`),...f.map(g=>`history_drift_workspace_state_missing:${g}`),...h.map(g=>`history_drift_workspace_state_unreadable:${g}`)];return{check:{name:"history_drift",status:_.length===0?"ok":"warn",ok:_.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:o,resolved_false_positive_items:s,authoritative_item_source:i.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:p.length,workspace_state_missing:f.length,workspace_state_unreadable:h.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:p,workspace_state_missing:f,workspace_state_unreadable:h}},warnings:_}}function Tk(e,t){let n=Or(e),r=En(n.settings),i=Dr(n.settings,t),o=r.active?St(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(r.active&&i.active)}}function $k(){return{refreshed:[],skipped:[],warnings:[]}}async function Ok(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?$k():Yc(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function Dk(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Jt(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function Pk(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function Nk(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Gm(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:io(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:io(r,e.vector_store?.adapter??null)}}function Mk(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function Lk(e,t,n){return e.enabled&&n.length>0&&t}async function Fk(e,t,n,r,i){let o=Tk(t,e),s=await Vt(e),a=o.semanticRuntimeAvailable?ao(n,s.entries):[],c=await Ok({pmRoot:e,snapshot:o,refreshPolicy:r,staleBefore:a}),d=await Vt(e),l=o.semanticRuntimeAvailable?ao(n,d.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,m=Dk({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:s,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),p=Pk({ledgerBefore:s,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),f=Rs(a,i),h=Rs(l,i),_=Lk(r,o.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:p.length===0?"ok":"warn",ok:p.length===0,details:{semantic_runtime_available:o.semanticRuntimeAvailable,compatibility_mode_auto_defaults:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:o.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:o.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:Mk(r),...Gm(t,o),embedding_identity_changed:m,embedding_identity_before:s.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(s.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Fm,stale_items_before_total:f.total,stale_items_before:f.values,stale_items_before_truncated:f.truncated,refresh_attempted:_,refresh_skipped_reason:Nk(r,o.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:p}}function jk(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function Jm(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new w("--check-only cannot be combined with --refresh-vectors",y.USAGE);if(n&&e.noRefresh===!0)throw new w("--no-refresh cannot be combined with --refresh-vectors",y.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var Uk=new Set(["extensions","locks","search"]);function zk(e){let t=new Set(ka.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(xa));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of Uk)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,o)=>i.localeCompare(o)),optionalDirs:[...n].sort((i,o)=>i.localeCompare(o)),optionalDirSet:n}}async function Wk(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:o}=zk(t),s=[],a=[],c=[];for(let d of[...r,...i]){let l=ge.join(e,d);c.push(...await Ke({path:l,scope:"project"})),!await Cs(l)&&(o.has(d)?a.push(d):s.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:s,missingOptionalDirs:a,missingDirs:n?[...s,...a]:[...s],hookWarnings:c}}function Vm(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function Hk(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Ye(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):kt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function xs(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function qk(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function Bk(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function Gk(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var Ts=e=>e.unknown_event_count??0,$s=e=>e.actionable_unknown_event_count??Ts(e);function Jk(e,t,n,r,i,o,s){let a=Ts(r),c=$s(r),d=a>0,l=c>0,u=i.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...d?{author_attribution:r}:{},...u?{stale_in_progress:i}:{},...o.length>0?{provenance_resolver_outcomes:o}:{},...s.length>0?{provenance_invalid_values:s}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Km(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function Vk(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function Kk(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function Yk(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.over_threshold.map(t=>`history_stream_over_compact_threshold:${t}`),...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function Ym(e){let t=new Map;for(let[i,o]of Object.entries(e.remediationSources))for(let s of o)t.has(s)||t.set(s,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let o=t.get(i)??"integrity",s=Ao(i)?.code??Is(i),a=n.get(o)?.details,d=(typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{})[s],l=As(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:s,check:o,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function Xk(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function Zk(e){for(let t of e.checks){let n=Io(e.remediationSources[t.name]);Xk({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function Qk(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(s=>typeof s=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(s=>Array.isArray(s)?s:[])),i=new Map;for(let s of e.pendingMergeReceipts){if(s.evidence_source!=="clone_local")continue;let a=i.get(s.item_id)??[];a.push(s),i.set(s.item_id,a)}let o=[];for(let s of n){if(r.has(s))continue;let a=i.get(s);if(!(!a||a.length===0))try{(await bs(s,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global)).merge_receipt_proof?.trusted&&o.push(s)}catch{}}return[...new Set(o)].sort((s,a)=>s.localeCompare(a))}function ex(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}function Xm(e,t,n){let r=e.warning_count??e.warnings.length,i={...e,warning_count:r,warning_limit:Ot,warnings_truncated:r>Ot,warnings:e.warnings.slice(0,Ot),findings:(e.findings??[]).filter(s=>e.warnings.slice(0,Ot).includes(s.warning)||e.failed_because.includes(s.warning))},o=n?hk(i):t.brief===!0?fk(i):i;return{...o,warning_count:r,warning_limit:Ot,warnings_truncated:r>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:r,warnings_truncated:r>o.warnings.length}}:{}}}async function Zm(e,t={}){let n=M(process.cwd(),e.path);await X(n);let r=bt(n),{settings:i,warnings:o}=await xc(n),s=[...new Set(o)],a=W(i,z()),c=t.strictDirectories===!0,d=Jm(t),l=await Wk(n,a,c),u=jk(i),m=await Ak(i,{checkTelemetry:t.checkTelemetry===!0}),p=await dk(n,i,!!e.noExtensions),f=Vm(t),h=[],_=await Hk({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:f,itemReadWarnings:h}),g=_,v=Gr(Ie(i.schema),_),k=[...u,...Jr(v)],x=f.skipDrift?{warnings:[]}:await Sc({pmRoot:n,settings:i,itemIds:_.map(Wi=>Wi.id),commandLabel:"health"}),S=await Yb(n,i.history.compact_policy,await Vb(n)),I=await Dn(n,20,t.verboseAuthorEvents===!0),b=$s(I),E=b>0?[`history_unknown_author_events:${b}`]:[],A=Km(await Xc(n,_,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),F=await Xd(n),q=F.outcomes,O=F.invalid_values,B=F.warnings,se=await Ik(n),ae=f.skipIntegrity?{...xs("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await nk(n,a.type_to_folder,i.schema,t.requireMergeDrivers===!0,_),he=f.skipDrift?xs("history_drift"):await Ck({pmRoot:n,items:g,settings:i,typeRegistry:a,itemReadWarnings:h}),vt=[...new Set(h)],vn=await Qk({gitWorkspaceRoot:ae.gitWorkspaceRoot,pendingMergeReceipts:ae.pendingMergeReceipts,historyDriftCheck:he,global:e});ex(he,vn);let j=f.skipVectors?xs("vectorization"):await Fk(n,i,g,d,t.verboseStaleItems===!0),G=[qk(r,i,s),Bk(l,c),Gk(k,v),m.check,p.check,Jk(_,i,S,I,A.scan,q,O),se.check,ae.check,he.check,j.check],or=Vk({directoryState:l,normalizedSettingsReadWarnings:s,settingWarnings:k,normalizedItemReadWarnings:vt,telemetryCheck:m,extensionCheck:p,historyPolicyWarnings:x.warnings,historySummary:S,authorAttributionWarnings:E,staleInProgressWarnings:A.warnings,provenanceWarnings:B,locksCheck:se,integrityCheck:ae,historyDriftCheck:he,vectorizationCheck:j}),sr=Yk({directoryState:l,normalizedSettingsReadWarnings:s,settingWarnings:k,normalizedItemReadWarnings:vt,telemetryCheck:m,extensionCheck:p,historyPolicyWarnings:x.warnings,historySummary:S,authorAttributionWarnings:E,staleInProgressWarnings:A.warnings,provenanceWarnings:B,locksCheck:se,integrityCheck:ae,historyDriftCheck:he,vectorizationCheck:j});Zk({checks:G,remediationSources:sr,historyDriftedCount:Kk(he),overThresholdCount:S.over_threshold.length});let ga=or.filter(Wi=>!As(Wi,t.requireMergeDrivers===!0)),Yf=Ym({warnings:or,checks:G,remediationSources:sr,requireMergeDrivers:t.requireMergeDrivers===!0}),Xf={ok:ga.length===0,checks:G,warnings:or,findings:Yf,failed_because:ga,generated_at:T()};return Xm(Xf,t,f.summaryMode)}var kP={buildHierarchyIntegrityWarnings:zm,buildExtensionHealthTriageSummary:Wm,buildHealthFindings:Ym,buildCapabilityContractMetadata:Gn,buildStaleInProgressHealthSummary:Km,buildVectorizationProviderDetails:Gm,collectUnknownCapabilityGuidance:Bn,isAdvisoryHealthWarning:As,isDirectory:Cs,isExpectedUnmanagedExtension:Ss,listItemDocumentPaths:Um,normalizeEndpointForDisplay:vi,normalizeExtensionNameForMatch:mn,parseTelemetryQueue:qm,probeTelemetryEndpointHealth:Bm,projectHealthResult:Xm,resolveActionableUnknownAuthorEventCount:$s,resolveHealthSkipPolicy:Vm,resolveUnknownAuthorEventCount:Ts,resolveVectorRefreshPolicy:Jm,selectStaleItemDetail:Rs,summarizeHealthCheckDetails:Hm,summarizeExtensionList:wi,summarizeRecordList:Je,summarizeStringList:H,telemetryEnvFlagEnabled:ln,warningCode:Is};import pn from"node:fs/promises";import fn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function tx(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let o;try{o=await pn.readdir(fn.join(e,i))}catch{return}for(let s of o)for(let a of kn)if(s.toLowerCase().endsWith(a)){r.push({relativePath:`${i}/${s}`,id:s.slice(0,-a.length)});break}})),r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath))}function nx(e,t){let{id:n,relativePath:r,liveItemIds:i,out:o}=e,s=Ut(t);if(s){o.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=null,c=t.split(/\r?\n/).map((d,l)=>({content:d.trim(),number:l+1})).filter(d=>d.content.length>0);for(let d of c)try{let l=JSON.parse(d.content);if(typeof l!="object"||l===null||Array.isArray(l))throw new TypeError("history entry must be an object");a=l}catch{o.unparseable.push({id:n,path:r,line:d.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&i.has(n)&&o.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(o.repairReconciliations+=1))}function Os(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function rx(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await pn.readdir(fn.join(e,"history"))}catch{return n}for(let i of r.sort((o,s)=>o.localeCompare(s))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await pn.readFile(fn.join(e,"history",i),"utf8")}catch(s){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Os("history stream",s)});continue}nx({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},o)}return n}function Qm(e){let t=Ut(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function ix(e){let t=[],n=0,r=null;try{r=await Y(bt(e))}catch(o){n+=1,t.push({path:"settings.json",detail:Os("configuration file",o)})}if(r!==null){n+=1;let o=Qm(r);o!==null&&t.push({path:"settings.json",detail:o})}let i;try{i=await pn.readdir(fn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of i.sort((s,a)=>s.localeCompare(a))){if(!o.endsWith(".json"))continue;n+=1;let s;try{s=await pn.readFile(fn.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:Os("configuration file",c)});continue}let a=Qm(s);a!==null&&t.push({path:`schema/${o}`,detail:a})}return{scanned:n,unparseable:t}}async function ep(e,t,n,r={}){let i=await tx(e,n),o=new Set(i.map(u=>u.id)),s=new Map;for(let u of i){let m=s.get(u.id);m===void 0?s.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((p,f)=>p.localeCompare(f))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=fn.join(e,u.relativePath);return zt(await pn.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await rx(e,o),l=await ix(e);return{item_files_on_disk:i.length,item_ids_on_disk:o.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import{execFile as ox}from"node:child_process";import tp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b8b3f729-be32-5a77-b08f-f616ee068e0f")}catch{}})();function np(e,t){return new Promise((n,r)=>{ox("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,o)=>{i?r(i):n(o)})})}function rp(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 PP(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(rp(n),!n)throw new RangeError("Source line range must use start:end.");return n}function sx(e){let t=new Map;for(let n of e.split(`
42
+ `)){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 ax(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 cx(e){let t=tp.relative(e.workspaceRoot,tp.resolve(e.workspaceRoot,e.sourcePath)),n=await np(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await np(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:sx(n),commitItems:ax(r),available:!0}}function dx(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 lx(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=dx({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 ux(e,t,n){let r=rd(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=lx({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 mx(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await cx({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function px(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 fx(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function ip(e){rp(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 mx(e),r=fx(n),i=new Map;for(let o of e.candidates){let s=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(o.item.id)),a=s.reduce((l,[,u])=>l+u,0),c=ux(o.item.id,e.corpus,t),d=px({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(l=>({kind:"linked_file",reference:l.path})),...s.map(([l,u])=>({kind:"git_commit",reference:l.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:d})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}import ta from"node:fs/promises";import{realpathSync as AS}from"node:fs";import{execFile as IS}from"node:child_process";import ye from"node:path";import{promisify as CS}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var hx=["metadata","resolution"],Ds=["metadata","resolution","estimates","lifecycle"],_x="completed";function Ps(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function op(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function sp(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=op(n.close_reason)??_x;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Ps(r)}`,gate:"resolution"})}return t}function ap(e){let t=[];for(let n of e){let r=op(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${Ps(r)}`,gate:"metadata"})}return t}function cp(e,t){return e.map(n=>{let r=kc(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function dp(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function lp(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${Ps(n.path)}`})}return t}function up(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new w(`--fix-scope values must not be empty. Supported values: ${Ds.join(", ")}.`,y.USAGE);return new Set(hx)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Ds.includes(i)){n.add(i);continue}throw new w(`Unknown --fix-scope value "${r}". Supported values: ${Ds.join(", ")}.`,y.USAGE)}return n}function mp(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function Kn(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a7fbaf1-917f-5067-b9b6-a9f27c80e291")}catch{}})();var gx=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function yx(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=gx.exec(n);if(!r)return null;let i=r[1],o=i.toUpperCase(),s=i.slice(0,i.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(m=>m.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${o}`)||d.includes(`ISSUE CODE \`${o}\``)||d.includes(`\`${o}\``)||d.includes(`[${o}]`);return s===s.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(s.toUpperCase())||l?o:null}function pp(e){return typeof e=="string"&&e.trim().length>0}function fp(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||pp(i.duplicate_of))continue;let o=yx(i.title,{...t,evidenceText:i.body});if(o===null)continue;let s=n.get(o);s||(s=[],n.set(o,s)),s.some(a=>a.id===i.id)||s.push({id:i.id,title:i.title,parent:pp(i.parent)?i.parent.trim():null})}let r=[];for(let[i,o]of n){if(o.length<2)continue;let s=new Set(o.map(d=>d.id.toLowerCase())),a=o.filter(d=>d.parent===null||!s.has(d.parent.toLowerCase()));if(a.length<2)continue;let c=[...a].sort((d,l)=>d.id.localeCompare(l.id));r.push({code:i,count:c.length,ids:c.map(d=>d.id),titles:c.map(d=>d.title)})}return r.sort((i,o)=>i.code.localeCompare(o.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function hp(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,o)=>i.localeCompare(o))){let i=t.get(r),o={};for(let s of[...i.keys()].sort((a,c)=>a.localeCompare(c)))o[s]=i.get(s);n[r]=o}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var _p=3;function gp(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function yp(e,t,n=_p){let r=Number.isFinite(n)&&n>=1?Math.floor(n):_p,i=new Map;for(let o of t){let s=gp(o);if(s.length===0)continue;let a=i.get(s);a?a.push(o):i.set(s,[o])}return e.map(o=>{let s=(i.get(gp(o))??[]).filter(a=>a!==o).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:o,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:o,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function wp(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var wx=/^[a-z][a-z0-9+.-]+:\/\//i;function Yn(e){return wx.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function vx(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function vp(e){return`${e.item_id} ${e.link_kind}`}function bp(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=vx(i.classification,r.classification),i.owners.set(vp(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[vp(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(o=>{let s=t(o.item_id);return{id:o.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:o.link_kind}}).sort((o,s)=>{let a=o.id.localeCompare(s.id);return a!==0?a:o.field.localeCompare(s.field)})}))}function bx(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function kp(e){let t=[];for(let n of e)for(let r of n.items)t.push(`${n.path}:${n.classification} owner=${r.id} status=${r.status} field=${r.field} title="${bx(r.title)}"`);return t}import kx from"node:fs/promises";import $e from"node:path";import xx from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accd0229-6974-5950-8cea-74f517706878")}catch{}})();var Sx=["path","scope","note"],Ex=["pattern","glob","path","scope","note"],Rx=["path"],Ax=["from","to"],Ix=new Set(["note","scope"]);function Sp(e){let t=e??"project";if(!Hi.includes(t))throw new w(`Invalid scope "${e}". Valid scopes: ${Hi.join(", ")} (default: project).`,y.USAGE);return t}function Ns(e){if(e.startsWith("```")||e.includes(`
43
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||Pc(e)}function Cx(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function Tx(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Ns(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let o=e.slice(t+2,-1).trim();if(o.length>0&&Cx(o))return{path:o,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function $x(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let o=Tx(r);if(o!==void 0)return[o]}Nc(r,"--add",`${t} path`,Ns(r));let i=Ns(r)?xn(n,"--add"):{path:r};if(Sn(i,"--add",Sx),!i.path)throw new w(`--add requires path=<value> or a bare ${t} path`,y.USAGE);return[{path:i.path,scope:Sp(i.scope),note:i.note?.trim()||void 0}]}):[]}function Ox(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new w("--add-glob requires a glob pattern value",y.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=xn(n,"--add-glob");Sn(r,"--add-glob",Ex);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new w("--add-glob key/value form requires pattern=<glob>",y.USAGE);return{pattern:i,scope:Sp(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Dx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new w("--remove requires a path value",y.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=xn(n,"--remove"),i=Object.keys(r).filter(o=>Ix.has(o.toLowerCase()));if(i.length>0)throw new w(`--remove identifies a linked artifact by path only and does not accept ${i.map(o=>`"${o}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,y.USAGE);if(Sn(r,"--remove",Rx),!r.path)throw new w("--remove key/value form requires path=<value>",y.USAGE);return r.path}return n}):[]}function Px(e){return e?e.map(t=>{let n=xn(t,"--migrate");Sn(n,"--migrate",Ax);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new w("--migrate requires from=<value> and to=<value>",y.USAGE);return{from:r,to:i}}):[]}function Xn(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function Nx(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(o=>Xn(o.path,n))),i=[...new Set(t.map(o=>Xn(o,n)).filter(o=>r.has(o)))].sort((o,s)=>o.localeCompare(s));if(i.length!==0)throw new w(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,y.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function st(e){return e.split($e.sep).join("/")}function Ms(e,t,n=process.cwd()){let r=e.trim();if(Yn(r))return r;if($e.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return st(r.replaceAll("\\",$e.sep));let i=$e.relative(t,n);return i.startsWith(`..${$e.sep}`)||i===".."||$e.isAbsolute(i)?st($e.normalize(r)):st($e.relative(t,$e.resolve(n,r)))}async function Mx(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){let o=$e.isAbsolute(i.pattern),s=await xx(i.pattern,{cwd:n,absolute:o,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>Ms(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of a)r.push({path:c,scope:i.scope,note:i.note})}return r}function Lx(e,t,n){if(t===void 0)return e;if(!n)throw new w("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",y.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function Fx(e){return`${e.path}::${e.scope}`}function Ls(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function Fs(e){return[...new Map(e.map(t=>[Fx(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function jx(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],i=[],o=[],s=[];for(let a of n){if(Yn(a)){s.push(a.trim());continue}let c=$e.isAbsolute(a)?a:$e.resolve(t,a);try{(await kx.stat(c)).isFile()?r.push(a):o.push(a)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&dt(d)){i.push(a);continue}o.push(a)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:o,remote_references:s}}function Ux(e,t,n,r){let i=0;for(let s=0;s<e.length;s+=1){let a=Xn(e[s].path,r);a!==e[s].path&&(e[s]={...e[s],path:a},i+=1)}return{adds:t.map(s=>{let a=Xn(s.path,r);return a!==s.path&&(i+=1),{...s,path:a}}),removes:n.map(s=>Xn(s,r)),count:i}}function zx(e,t,n,r){for(let o of t)e.some(s=>s.path===o.path&&s.scope===o.scope)||e.push(o);if(n.length>0)for(let o=e.length-1;o>=0;o-=1)n.includes(e[o].path)&&e.splice(o,1);let i=Fs(e);return r?i:Ls(i)}async function xp(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await jx(t,e.workspaceRoot):void 0}}async function bi(e,t,n,r){let{metadataKey:i}=r,o=Fc(),s=M(process.cwd(),n.path),a=Le(s),c=process.cwd();await X(s);let d=await C(s),l=W(d,z()),u=await o.resolveList(t.add,"--add"),m=await o.resolveList(t.addGlob,"--add-glob"),p=await o.resolveList(t.remove,"--remove"),f=await o.resolveList(t.migrate,"--migrate"),h=$x(u,r.bareNoun).map(q=>({...q,path:Ms(q.path,a,c)})),_=Ox(m),g=await Mx(_,a,c),v=Lx([...h,...g],t.note,h.length>0||_.length>0),k=Dx(p).map(q=>Ms(q,a,c)),x=Px(f);if(Nx(v,k,x),!(v.length>0||k.length>0||x.length>0)){let q=await Bt(s,e,d.id_prefix,d.item_format,l.type_to_folder);if(!q)throw new w(`Item ${e} not found`,y.NOT_FOUND);let B=(await ut(q,{schema:d.schema})).document.metadata[i]??[];return xp({id:q.id,artifacts:B,changed:!1,options:t,workspaceRoot:a})}let I=V(t.author,d.author_default),b=await xt({pmRoot:s,settings:d,id:e,op:r.op,author:I,message:t.message,force:t.force,skipNoop:!0,mutate(q){let O=q.metadata,B=O[i]??[],se=[...B],ae=Ux(se,v,k,x),he=zx(se,ae.adds,ae.removes,r.supportsAppendStable&&t.appendStable===!0);he.length>0?O[i]=he:delete O[i];let vt=!Ma(B,he);return{changedFields:vt?[i]:[],warnings:vt&&ae.count>0?[`path_migrations_applied:${ae.count}`]:[]}}}),E=b.item[i]??[],A=b.warnings.find(q=>q.startsWith("path_migrations_applied:")),F=A?Number(A.slice(24)):0;return xp({id:b.item.id,artifacts:E,changed:b.changedFields.includes(i),migrationsApplied:F,options:t,workspaceRoot:a})}function ki(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function Ep(e,t,n){let r=await bi(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return ki(r,"docs")}import Rp from"node:fs/promises";import Oe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed504f2b-8b78-5fca-a4a7-7b0709a65533")}catch{}})();var Wx=32768;function js(e){return st(Oe.normalize(e))}async function xi(e){try{return await Rp.realpath(e)}catch{return Oe.resolve(e)}}function hn(e,t){let n=Oe.isAbsolute(e.path)?Oe.resolve(e.path):Oe.resolve(t,e.path);return`${js(n)}::${e.scope}`}function Si(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>Si(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))Si(i,t?`${t}.${r}`:r,n)}function Hx(e){let t=[];return Si(e.metadata,"metadata",t),Si(e.body,"body",t),t}function qx(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function Bx(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let o=new Set,s=i.value.slice(0,Wx);for(let[a,c]of[[n,i.value],[r,s]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=qx(d[0]);!l||o.has(l)||(o.add(l),t.push({field:i.field,value:l}))}}}return t}async function Gx(e,t,n=t){let r=Oe.isAbsolute(e)?Oe.resolve(e):Oe.resolve(n,e),i;try{i=await Rp.stat(r)}catch{return}if(!i.isFile())return;let[o,s]=await Promise.all([xi(t),xi(r)]);if(ve(o,s)){let a=Oe.relative(o,s);return!a||a.startsWith("..")||Oe.isAbsolute(a)?void 0:{path:js(a),scope:"project"}}return{path:js(r),scope:"global"}}async function Jx(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>hn(c,t))),i=new Map,o=Bx(Hx(e)),s=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{s.set(c,await Gx(c,t,n))}));let a=o.map(c=>({reference:c,resolved:s.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=hn(d,t),u=i.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function Ap(e,t,n){let r=await bi(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return ki(r,"files")}async function Vx(e,t){let n=await xi(t),r=await Promise.all(e.map(async o=>{let s=o.trim();if(!s)throw new w("Files lookup paths must not be empty.",y.USAGE);if(!Oe.isAbsolute(s))return st(s);let a=await xi(s);return ve(n,a)?st(Oe.relative(n,a)):st(a)})),i=[...new Set(r)].sort((o,s)=>o.localeCompare(s));if(i.length===0)throw new w("Files lookup requires at least one path.",y.USAGE);return i}function Kx(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new w(`Files lookup ${r} must be a non-negative integer.`,y.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function Ip(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Cp(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function Yx(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(st(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(Cp)}async function Xx(e){if(e.explain)return ip({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function Zx(e){if([e.strictRead,e.noTruncate,e.explain,dc()].includes(!0))return null;let t=await Cr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Rc({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function Qx(e){let t=[],n=await Gt(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=Yx({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&i.length>0)throw new w(`Files lookup could not read every item: ${i.join("; ")}`,y.GENERIC_FAILURE);let o=await Xx({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(o?[...r].sort((c,d)=>{let l=o.explanations.get(d.item.id).score-o.explanations.get(c.item.id).score;return l!==0?l:Cp(c,d)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<r.length,truncated:e.offset+a.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:Ip(c.item),files:c.files,...o?{traceability:o.explanations.get(c.item.id)}:{}})),...o?{traceability_receipt:o.receipt}:{}}}async function AN(e,t){let n=M(process.cwd(),t.path),r=Le(n);await X(n);let i=await Vx(e.paths,r);if(e.lineRange&&i.length!==1)throw new w("Files lookup line attribution requires exactly one source path.",y.USAGE);let o=await C(n),s=W(o,z()),{offset:a,limit:c}=Kx(e),d=await Zx({pmRoot:n,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:a,limit:c,has_more:a+d.matches.length<d.total,truncated:a+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:Ip(l.item),files:l.files}))}:Qx({pmRoot:n,settings:o,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function IN(e,t,n){let r=M(process.cwd(),n.path),i=Le(r);await X(r);let o=await C(r),s=W(o,z()),a=await Bt(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!a)throw new w(`Item ${e} not found`,y.NOT_FOUND);let c=await ut(a,{schema:o.schema}),d=await Jx(c.document,i,process.cwd()),l=d.filter(E=>E.status==="addable"),u=d.filter(E=>E.status==="already_linked"),m=t.apply===!0,p=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let E=c.document.metadata.files??[];return{id:a.id,files:E,changed:!1,apply:m,count:E.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let f=V(t.author,o.author_default),h=l.map(E=>({path:E.path,scope:E.scope,note:p})),_=[],g=new Set,v=await xt({pmRoot:r,settings:o,id:e,op:"files_discover",author:f,message:t.message??"Discover referenced file links",force:t.force,mutate(E){let A=[...E.metadata.files??[]],F=new Set(A.map(B=>hn(B,i)));_=[],g.clear();for(let[B,se]of h.entries()){let ae=hn(se,i);F.has(ae)||(A.push(se),F.add(ae),_.push(se),g.add(B))}let q=Fs(A),O=t.appendStable?q:Ls(q);return O.length>0?E.metadata.files=O:delete E.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==h.length?[`files_discover_skipped_existing:${h.length-_.length}`]:[]}}}),k=v.item.files??[],x=new Set(_.map(E=>hn(E,i))),S=k.filter(E=>x.has(hn(E,i))),I=l.filter((E,A)=>!g.has(A)),b=[...u,...I];return{id:v.item.id,files:k,changed:S.length>0,apply:!0,count:k.length,candidate_count:d.length,addable_count:l.length,added_count:S.length,skipped_existing_count:b.length,candidates:d,added:S,skipped_existing:b}}import{readFileSync as eS}from"node:fs";import Ei from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var tS=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Us=new Set(["--pm-path","--path","--author"]),nS={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},rS=new Set(["-p","--package"]),iS=new Set(["-c","--call"]),oS=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),sS=new Set(["-C","--prefix","--userconfig","--cache"]),ON=new Set(["--cwd"]),DN=new Set(["--cwd"]),aS=new Set(["exec","x"]),PN=new Set(["run","run-script"]),NN=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function cS(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function dS(e,t=process.cwd()){let n=lS(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...i]=n;if(Tp(r)||$p(r,t))return i;if(r==="node"&&i[0]&&$p(i[0],t))return i.slice(1);let o=r==="npx"||r==="bunx"?zs(i):r==="pnpm"?pS(i):r==="npm"?fS(i):null;return o&&(Tp(o.command)||mS(o.command))?o.args:null}var Op=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let o=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of cS(o)){let c=dS(a),d=c?hS(c):null,l=d&&tS.has(d.subcommand)?_S(d.remaining,nS[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&s.add(l)}return[...s].sort((a,c)=>a.localeCompare(c))};function lS(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function MN(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Us.has(n)){t+=2;continue}t+=1;continue}return n}}function Tp(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function uS(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function mS(e){let t=uS(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function $p(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=Ei.resolve(t,e);try{return JSON.parse(eS(Ei.join(Ei.dirname(Ei.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function zs(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let o=i[1];return o?{command:o,args:e.slice(t+1)}:null}if(iS.has(r)){t+=1;break}t+=rS.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Dp(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function pS(e){let t=Dp(e,oS);return t?.subcommand!=="dlx"?null:zs(t.args)}function fS(e){let t=Dp(e,sS);return!t||!aS.has(t.subcommand)?null:zs(t.args)}function hS(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Us.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function _S(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Us.has(r)||t.has(r))&&(n+=1)}}import{execFile as gS}from"node:child_process";import{readFile as yS}from"node:fs/promises";import Np from"node:path";import{promisify as wS}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="30a61f26-5db8-50ba-af37-1990a4742ce8")}catch{}})();var vS=wS(gS),Ws=1,bS="linked-test-trust.json";function Hs(e){return Np.join(Ta(e),bS)}function Pp(){return{version:Ws,acknowledged:{}}}async function qs(e){try{let t=JSON.parse(await yS(Hs(e),"utf8"));return t.version!==Ws||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Pp():{version:Ws,acknowledged:t.acknowledged}}catch{return Pp()}}async function Bs(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await vS("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function Gs(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function kS(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&lc(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Zn(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function xS(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function GN(e,t,n){if(!e||e.length===0)return e;let r=Gs();return xS(e,t,n,await Bs(r))}function Mp(e){return De(Q({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function JN(e,t,n){let r=await qs(e);return Lp(t,n,r)}function Lp(e,t,n){let r=Mp(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let o=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!kS(e.provenance)?o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Zn(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...Zn(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...Zn(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Zn(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...Zn(i,t)}}async function Fp(e,t,n){let r=await qs(e);return t.map(i=>Lp(i,n,r))}async function VN(e,t,n){let r=await qs(e),i=t.filter(o=>typeof o.command=="string"&&o.command.length>0).map(Mp);for(let o of i)r.acknowledged[o]={acknowledged_at:n};return await bn(Np.dirname(Hs(e))),await le(Hs(e),`${JSON.stringify(r,null,2)}
44
+ `),{acknowledged:i.length,fingerprints:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function Ri(e){return e.includeBody?kt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Gt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8bec3c39-b871-5c7c-907c-6da66274d9be")}catch{}})();var SS=5;async function Ai(e,t,n){let r=await Rt(e,t),o=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),s=n?Number.POSITIVE_INFINITY:SS,a=r.driftedItems.slice(0,s);return{check:{name:"history_drift",status:o.length===0?"ok":"warn",ok:o.length===0,details:{checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,s)}},warnings:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77a3c404-bbcd-5a5e-80bf-cb61c45af55d")}catch{}})();function Ii(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],o=new Set([n]),s=a=>{for(let c of(t.get(a)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!o.has(c)){if(o.add(c),i.push(c),s(c))return!0;i.pop(),o.delete(c)}}return!1};return s(n)?[...i]:[...e,n]}function ES(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function RS(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let o=r.resolve(i.kind);if(!o?.hierarchy)continue;let s=n.get(i.id.toLowerCase());s&&(o.hierarchyDirection==="source_parent"?t.get(s).push(e.id):t.get(e.id).push(s))}}function Js(e,t=Rn()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((o,s)=>o.id.localeCompare(s.id))){let o=r.get(i.id),s=ES(i.parent,n);s&&o.push(s),RS(i,r,n,t)}for(let[i,o]of r)r.set(i,[...new Set(o)].sort());return r}function Vs(e,t,n=Rn()){let r=Pr(e,s=>t?Za(s,t):s==="closed"||s==="canceled",n),i=Js(e,n),o=r.cycles.map(s=>s.item_ids);return{cycle_count:o.length,active_cycle_count:r.cycles.filter(s=>!s.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(s=>s.legacy_terminal).length,cycle_item_ids:[...new Set(o.flat())].sort(),cycle_sample_paths:o.map(s=>Ii(s,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(s=>!s.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(s=>s.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(s=>`${s.child_id}:${s.parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(s=>!s.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(s=>s.legacy_terminal).length,parent_divergence_rows:r.divergences.map(s=>`${s.child_id}:scalar=${s.scalar_parent_id}:dependencies=${s.dependency_parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de2cc648-965a-59c9-b688-0fe12edeec82")}catch{}})();function gt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Ks(e){return gt(e).replace(/\/+$/,"")}function Me(e){let t=Z(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0d466293-869d-54bb-b07d-facb3be51e8c")}catch{}})();var TS=["src","tests","docs"],$S=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],OS=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),DS=["resolution","expected_result","actual_result"],PS=["default","tracked-all","tracked-all-strict"],jp=["core","strict","custom"],$i=["off","warn","error"],Zs=["author","acceptance_criteria","estimated_minutes","close_reason"],Wp=[...Zs,"reviewer","risk","confidence","sprint","release"],na=Array.from(new Set(Wp)),NS={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},MS={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},LS={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},FS={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},jS={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},US=32*1024*1024,zS=1e4,Hp=40,ct=5,WS=4096,HS=255,qS=CS(IS);function qp(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?qp(r):r);return t}function BS(e){return{...e,checks:e.checks.map(t=>({...t,details:qp(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function Di(e,t){return mc(e,t)??e}function Qn(e,t){return t.terminal_statuses.has(Di(e,t))}function yt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ci(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function GS(e){let t=yt(Sa),n={blocked_reason:yt(dr.blocked_reason),resolution:yt(dr.resolution),actual_result:yt(dr.actual_result)},r=yt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:yt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:yt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:yt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Ci(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Ci(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Ci(i.resolution,n.resolution)?"default":"settings",actual_result:Ci(i.actual_result,n.actual_result)?"default":"settings"}}}function Bp(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(jp.includes(t))return t;throw new w(`Unknown --metadata-profile value "${e}". Supported values: ${jp.join(", ")}.`,y.USAGE)}function Gp(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if($i.includes(t))return t;throw new w(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${$i.join(", ")}.`,y.USAGE)}function Jp(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if($i.includes(t))return t;throw new w(`Unknown --parent-cycle-severity value "${e}". Supported values: ${$i.join(", ")}.`,y.USAGE)}function JS(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>NS[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function VS(e,t,n){let r=JS(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Zs],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Wp],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Zs],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var KS=new Set(["acceptance_criteria","estimated_minutes"]);function Vp(e,t,n,r){return!r&&KS.has(t)&&Qn(e.status,n)?!1:t==="author"?!Z(e.author):t==="acceptance_criteria"?!Z(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Di(e.status,n)===n.close_status&&!Z(e.close_reason):t==="reviewer"?!Z(e.reviewer):t==="risk"?!Z(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!Z(e.confidence):t==="sprint"?!Z(e.sprint):!Z(e.release)}function Kp(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new w(`Unknown --scan-mode value "${e}". Supported values: ${PS.join(", ")}.`,y.USAGE)}function Yp(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return ye.resolve(t);let n=ye.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return ye.dirname(ye.dirname(n));let i=ye.resolve(process.cwd()),o=Up(n),s=Up(i),a=ye.relative(o,s);return a.length===0||!a.startsWith("..")&&!ye.isAbsolute(a)?n:i}function Up(e){try{return AS.native(e)}catch{return ye.resolve(e)}}function YS(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function ra(e,t,n){let r=t.length>0?ye.join(e,t):e,i;try{i=await ta.readdir(r,{withFileTypes:!0})}catch(o){if(U(o))return;throw o}for(let o of i){if(o.name.startsWith("."))continue;let s=t.length>0?ye.join(t,o.name):o.name;if(o.isDirectory()){if(OS.has(o.name))continue;await ra(e,s,n);continue}o.isFile()&&n.push(gt(s))}}async function Qs(e){let t=[];for(let n of TS)await ra(e,n,t);for(let n of $S){let r=ye.join(e,n);try{(await ta.stat(r)).isFile()&&t.push(gt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function Xp(e){try{let{stdout:t}=await qS("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:US,windowsHide:!0,timeout:zS}),n=t.split("\0").map(r=>gt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function XS(e,t){let n=new Set,r=Ks(ba);r.length>0&&n.add(r);let i=Ks(ye.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((o,s)=>o.localeCompare(s))}function zp(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function ZS(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await Xp(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Qs(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Qs(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function te(e,t=ct){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function wt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=te(e,Hp);return{values:n.values,truncated:n.truncated,total:e.length}}var QS={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},eE={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function tE(e){let t=e.missing_fields.map(n=>`${QS[n]} "${eE[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Zp(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(s=>typeof s=="string"):sl(t);if(i.length===0)return;let o=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...o?{fix_hints_truncated:!0}:{}}}function Qp(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var nE="validate_metadata_duplicate_issue_codes";function ef(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:ct,r=e.slice(0,n);return{rows:r.map(o=>({code:o.code,count:o.count,ids:o.ids,titles:o.titles,remediation_hint:`Items ${o.ids.join(", ")} share issue code "${o.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${nE}:${e.length}`]}}function rE(){return Object.fromEntries(na.map(e=>[e,[]]))}function iE(e,t,n){let r=rE();for(let i of e)for(let o of na)Vp(i,o,t,n)&&r[o].push(i.id);return r}function oE(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let o=t[i];o.length>0&&r.push(`${MS[i]}:${o.length}`)}return r.push(...n),r}function tf(e,t){let n={};for(let r of e.required_fields){let i=t[r],o=i?i.length:0,s=LS[r];n[s]=o}return n}function nf(e,t,n){let r=[];for(let i of e.required_fields){let o=t[i];if(o)for(let s of o){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:i})}}return r}function sE(e,t,n,r){for(let i of t.required_fields){let o=n[i];if(!o||o.length===0)continue;let s=FS[i],a=jS[i];if(!s||!a)continue;let c=te(o,r?o.length:ct);e[s]=c.values,e[a]=c.truncated}}function rf(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:Z(n.get(i)?.resolution)})):[]}function of(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:Z(n.get(i)?.type)})):[]}function aE(e,t,n,r,i){let o=new Map(e.map(g=>[g.id,g])),s=t.profile==="strict",a=iE(e,n,s),c=fp(e,{configuredPrefixes:i}),d=ef(c,r),l=oE(t,a,d.warnings),u=tf(t,a),m=nf(t,a,o),p=hp(m),f={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...na],counts:u,missing_by_type:p,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),sE(f,t,a,r);let h=rf(t,a,o),_=of(t,a,o);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:f},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:_}}function cE(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Di(m.status,t))),o=[],s=[];for(let m of i){let p=DS.filter(f=>!Z(m[f]));p.length!==0&&(o.push({id:m.id,missing_fields:p}),s.push({id:m.id,missing_fields:p,close_reason:Z(m.close_reason)}))}let a=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:ct,d=te(o.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=o.map(m=>tE(m)),u=te(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:i.length,missing_resolution_items:o.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:s}}function sf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function af(e,t="pm",n=Da()){let r=new Set(e.map(o=>o.id)),i=[...e].sort((o,s)=>o.id.localeCompare(s.id));return new Map(i.map(o=>{let s=new Set,a=Me(o.blocked_by);a&&r.has(a)&&s.add(a),(o.dependencies??[]).filter(d=>{let l=Me(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Me(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>s.add(d));let c=Me(o.definition_of_ready);return df(c??"",t).filter(d=>r.has(d)).forEach(d=>s.add(d)),[o.id,[...s].sort((d,l)=>d.localeCompare(l))]}))}function cf(e,t,n){let r=nd(e,n?l=>Qn(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),o=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),s=t?Number.POSITIVE_INFINITY:ct,a=te(i,s),c=te(o,s),d=te(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),s);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+o.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:o.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function df(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${sf(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,o)=>i.localeCompare(o))}function lf(e){let t=0,n=new Map,r=new Map,i=[],o=new Set,s=[],a=l=>{n.set(l,t),r.set(l,t),t+=1,i.push(l),o.add(l);for(let m of e.get(l)??[])n.has(m)?o.has(m)&&r.set(l,Math.min(r.get(l),n.get(m))):(a(m),r.set(l,Math.min(r.get(l),r.get(m))));if(r.get(l)!==n.get(l))return;let u=[];for(;i.length>0;){let m=i.pop();if(o.delete(m),u.push(m),m===l)break}u.sort((m,p)=>m.localeCompare(p)),s.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return s.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function uf(e,t="pm"){let n=af(e,t),r=lf(n),i=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),o=r.map(s=>Ii(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:o}}function mf(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function Oi(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function pf(e,t){let n=Oi(e).split("/").filter(Boolean),r=Oi(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function dE(e,t){let n=Oi(t),r=Oi(e),i=t.endsWith("/")?t:`${t}/`,o=e.startsWith(i),s=n.length>0&&n===r,a=pf(e,t);return!o&&!s&&a===0?null:o?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function lE(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function uE(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(o=>(r==="docs"?o.docs??[]:o.files??[]).map(s=>({item:o,link:s}))).forEach(({item:o,link:s})=>{if(s.scope!=="project")return;let a=gt(s.path);if(a.length===0||a===e)return;let c=dE(e,a);c!==null&&lE(i,o,c.score)&&(i={item:o,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function ff(e,t){return e.map(n=>{let r=mf(n),i=r==="docs_unowned"?"docs":"files",o=uE(n,r,t),s=o?.id??"<id>";return{path:n,classification:r,owner_candidate:o,remediation_hint:`pm ${i} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function hf(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function mE(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Me(e[n]);return i?r.some(o=>i.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function pE(e,t,n,r,i){let o=Me(t.parent),s=o?n.get(r.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!Qn(s.status,i)}}function fE(e,t,n,r){let i=Me(e.blocked_by),o=Me(e.blocked_reason),s=o?.toLowerCase(),a=Di(e.status,n),c=[];return t.has(a)?(!i&&!o&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(d=>s.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function hE(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!Qn(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=mE(c,r);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=Me(c.parent),u=l?i.get(o.get(l.toLowerCase())??l):void 0;if(u&&Qn(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(pE(c,u,i,o,n))),t){let m=fE(c,s,n,r);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((p,f)=>p.localeCompare(f))})}}return a}function _E(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function Ti(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Ys(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function gE(e,t,n,r,i){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=Ti("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),a=Ti("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=Ti("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=Ti("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=Ys("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=Ys("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=Ys("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...o,...s?[s]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function _f(e){let t=gt(e);return t.length>WS||t.split(/[\\/]/).some(n=>n.length>HS)}async function yE(e,t){let n=ye.isAbsolute(t)?t:ye.resolve(e,t);if(_f(n))return!1;try{let r=await ta.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return YS(r,["ENOENT","ENOTDIR"])}}async function wE(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(o=>({item:i,artifact:o,link_kind:"files"})),...(i.docs??[]).map(o=>({item:i,artifact:o,link_kind:"docs"}))]);for(let{item:i,artifact:o,link_kind:s}of r){if(o.scope!=="project")continue;if(Yn(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let a=gt(o.path);a.length!==0&&(n.linkedProjectPaths.add(a),await yE(t,o.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:s})))}return n}function vE(e,t,n,r,i,o){let s=r==="tracked-all-strict",a=s&&!i,c=i||s,d=c?[]:XS(t,n),l=d.length===0?[]:e.candidateFiles.filter(p=>zp(p,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(p=>!zp(p,d)),m={};if(l.length>0){let p=wt(l,o);m.pm_internals={count:l.length,paths:p.values,paths_truncated:p.truncated,paths_total:p.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function gf(e,t,n,r,i,o,s,a="pm"){let c=hE(e,t,i,o);_E(c);let d=uf(c.activeItems,a),l=Vs(e,i),u=Gr(i,e,s?Number.POSITIVE_INFINITY:ct),m=[...gE(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...Jr(u)],p=s?Number.POSITIVE_INFINITY:ct,f=te(c.closureLikeRows.map(E=>`${E.id}:${E.fields.join(",")}`),p),h=te(c.terminalParentRows.map(E=>`${E.id}:${E.parent_id}:${E.parent_status}`),p),_=te(c.staleBlockerRows.map(E=>`${E.id}:${E.status}:${E.reasons.join(",")}`),p),g=te(d.cycle_item_ids,p),v=te(d.cycle_sample_paths,p),k=te(l.cycle_item_ids,p),x=te(l.cycle_sample_paths,p),S=te(l.cardinality_violation_rows,p),I=te(l.parent_divergence_rows,p),b=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:b?"error":m.length===0?"ok":"warn",ok:!b&&m.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:_.values,stale_blocker_rows_truncated:_.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:g.values,dependency_cycle_item_ids_truncated:g.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:x.values,parent_cycle_sample_paths_truncated:x.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:S.values,hierarchy_cardinality_violation_rows_truncated:S.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:I.values,hierarchy_parent_divergence_rows_truncated:I.truncated,stale_blocker_reason_patterns:[...o.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:o.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...o.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:o.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...o.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:o.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...o.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:o.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function yf(e,t,n,r,i,o){let s=await wE(e,t),a=new Map(e.map(O=>[O.id,O])),c=[...new Set(s.missingLinkedPaths)].sort((O,B)=>O.localeCompare(B)),d=await ZS(t,r),l=vE(d,n,t,r,i,o),u=l.candidateFiles.filter(O=>!s.linkedProjectPaths.has(O)),m=ff(u,e),p=yp(c,l.candidateFiles),f=new Map(p.map(O=>[O.path,O.classification])),h=p.filter(O=>O.classification==="moved").length,_=s.staleLinkRows.map(O=>({...O,classification:f.get(O.path)??"deleted"})).sort((O,B)=>O.item_id.localeCompare(B.item_id)||O.path.localeCompare(B.path)||O.link_kind.localeCompare(B.link_kind)),g=[];l.strictModeForcesPmInternals&&g.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&g.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&g.push(`validate_files_orphaned_paths:${u.length}`);let v=[...s.remoteLinkedPaths].sort((O,B)=>O.localeCompare(B)),k=wt(v,o),x=wt(c,o),S=wt(u,o),I=wt(m.map(O=>`${O.path}:${O.classification}:owner_candidate=${O.owner_candidate?.id??"unowned"}`),o),b=o?m:wt(hf(m),!1).values,E=wt(wp(p),o),A=_.map(O=>({item_id:O.item_id,path:O.path,link_kind:O.link_kind,classification:O.classification})),F=bp(A,O=>{let B=a.get(O);return B?{type:B.type,title:B.title,status:B.status}:void 0}),q=o?F:wt(kp(F),!1).values;return{check:{name:"files",status:g.length===0?"ok":"warn",ok:g.length===0,details:{workspace_root:t,scan_mode_requested:d.requestedMode,scan_mode_applied:d.appliedMode,strict_tracked_all_mode:l.strictTrackedAllMode,strict_mode_forces_pm_internals:l.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:l.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:o?"full":"summary",file_list_summary_limit:Hp,candidate_scan_source:d.source,include_pm_internals:l.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:l.pmInternalCandidatePrefixes,pm_internal_excluded_count:l.excludedPmInternalPaths.length,excluded_total:l.excludedPmInternalPaths.length,excluded_by_reason:l.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:k.total,remote_linked_paths:k.values,remote_linked_paths_truncated:k.truncated,candidate_total_raw:d.candidateTotal,candidate_scanned_raw:d.candidateScanned,candidate_total:l.candidateFiles.length,candidate_scanned:l.candidateFiles.length,scanned_candidate_files:l.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:x.total,missing_linked_paths:x.values,missing_linked_paths_truncated:x.truncated,missing_linked_paths_moved_count:h,missing_linked_paths_deleted_count:c.length-h,missing_linked_path_classifications:E.values,missing_linked_path_classifications_truncated:E.truncated,missing_linked_path_rows_count:F.length,missing_linked_path_rows:q,orphaned_paths_count:u.length,orphaned_paths_total:S.total,orphaned_paths:S.values,orphaned_paths_truncated:S.truncated,orphaned_path_classifications:I.values,orphaned_path_classifications_truncated:I.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:b}},warnings:g,staleLinkPruneRows:_}}function wf(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function bE(e,t,n){return`${e}:${t}:${wf(n)}`}function kE(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},o)=>{let s=t[o];if(s.trusted)return;let a=wf(i.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function vf(e,t,n,r){let i=new Set(e.map(S=>S.id.toLowerCase())),o=0,s=0,a=new Set,c=[],d=e.flatMap(S=>(S.tests??[]).map(I=>({item:S,linkedTest:I}))),l=await Bs(Gs()),u=await Fp(r,d.map(({linkedTest:S})=>S),l),m=kE(d,u);for(let{item:S,linkedTest:I}of d){if(typeof I.command!="string"||I.command.trim().length===0)continue;o+=1;let b=Op(I.command,t);if(b.length!==0){s+=b.length;for(let E of b)a.add(E),i.has(E.toLowerCase())||c.push(bE(S.id,E,I.command))}}let p=[...new Set(c)].sort((S,I)=>S.localeCompare(I)),f=[...new Set(p.map(S=>S.split(":")[1]??""))].filter(S=>S.length>0).sort((S,I)=>S.localeCompare(I)),h=[];p.length>0&&h.push(`validate_command_references_stale_pm_ids:${p.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let _=n?Number.POSITIVE_INFINITY:ct,g=te(p,_),v=te(f,_),k=te([...a].sort((S,I)=>S.localeCompare(I)),_),x=te(m,_);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:o,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:x.values,untrusted_linked_tests_truncated:x.truncated,stale_pm_id_references_count:p.length,stale_pm_ids_count:f.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:g.values,stale_pm_id_reference_rows_truncated:g.truncated}},warnings:h}}function xE(e,t){let n=br(e.map(c=>({ref:c.id,version:vr(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:ct,o=te(n.outdated,i),s=te(n.ahead,i),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:uc,outdated_items_count:n.outdated.length,outdated_items:o.values,outdated_items_truncated:o.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var ea="pm validate auto-fix";async function bf(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:ea};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new w("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",y.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Xs(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function kf(e,t,n){let r=[],i=[],o=new Map;for(let s of e.filter(a=>Xs(a)===null))try{await bf(s,t,n),r.push(s)}catch(a){i.push({fix:s,error:a})}for(let s of e.filter(a=>Xs(a)!==null)){let a=Xs(s),c=o.get(a);c?c.push(s):o.set(a,[s])}for(let s of o.values()){let a=s[0];if(!a)continue;let c=s.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await Ap(a.item_id,{remove:c,message:ea},t):await Ep(a.item_id,{remove:c,message:ea},t),r.push(...s)}catch(d){i.push(...s.map(l=>({fix:l,error:d})))}}return{applied:r,failed:i}}var KM={applyValidateFix:bf,applyValidateFixes:kf,attachValidateFixHints:Zp,buildCommandReferencesCheck:vf,buildDependencyReferencesCheck:cf,buildCloseReasonBackfillRows:rf,buildFilesCheck:yf,buildLifecycleCheck:gf,buildLifecycleDependencyGraph:af,buildLifecycleParentGraph:Js,buildEstimateBackfillRows:of,buildMetadataCounts:tf,buildMissingFieldOccurrences:nf,buildOrphanedPathRows:ff,classifyOrphanedPath:mf,collectDefaultProjectFileCandidates:Qs,collectTrackedGitFileCandidates:Xp,detectLifecycleDependencyCycles:uf,detectLifecycleParentCycles:Vs,escapeRegExp:sf,extractItemIds:df,findLifecycleDependencyCycleComponents:lf,isMetadataFieldMissing:Vp,linkedArtifactPathExceedsFilesystemLimits:_f,listFilesRecursive:ra,resolveDependencyCycleSeverity:Gp,resolveParentCycleSeverity:Jp,resolveFileScanMode:Kp,resolveLifecycleDependencyCycleSamplePath:Ii,resolveRequestedChecks:Qp,resolveValidateMetadataProfile:Bp,resolveWorkspaceRoot:Yp,sharedDirectoryPrefixLength:pf,summarizeOrphanedPathRows:hf,summarizeDuplicateIssueCodes:ef,toMeaningfulString:Me};function SE(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function EE(e,t,n,r){let i=await ep(e,new Set(t.map(_=>_.id)),n,{schema:r.schema,extensionFieldNames:Dt(z())}),o=[];i.unreadable_item_files.length>0&&o.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&o.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&o.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&o.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&o.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&o.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let s=o.length,a=await fi(e);a.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Xr(e,tn(r));c.status==="drift"&&o.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Qe(e),l=d===null?null:await nn(d);l!==null&&l.status!=="ok"&&o.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await it(d??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:p,lossless:f}=dn(m);p.length>0&&o.push(`validate_merge_decisions_unreviewed:${p.length}`),SE(o,u.invalid_evidence_count);let h=s>0?"error":o.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...i,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:p.length,pending_merge_decision_items:[...new Set(p.map(_=>_.item_id))].sort((_,g)=>_.localeCompare(g)),lossless_merge_receipt_count:f.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(f.map(_=>_.item_id))].sort((_,g)=>_.localeCompare(g)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:o}}function at(e,t,n){n&&Zp(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function RE(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let i=aE(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,at(t,i,n)}if(e.requestedChecks.has("resolution")){let i=cE(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,at(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=gf(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,at(t,i,n),at(t,cf(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await yf(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=i.staleLinkPruneRows,at(t,i,n)}return e.requestedChecks.has("command_references")&&at(t,await vf(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&at(t,await Ai(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&at(t,xE(e.items,r),n),e.requestedChecks.has("storage_integrity")&&at(t,await EE(e.pmRoot,e.items,W(e.settings,z()).type_to_folder,e.settings),n),t}function AE(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...ap(t.closeReasonBackfillRows)),r.push(...sp(t.resolutionBackfillRows)),r.push(...cp(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...dp(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...lp(t.staleLinkPruneRows)),r}async function IE(e,t,n,r,i,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=AE(e,t,n),{applicable:a,gated:c}=mp(s,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await kf(a,i,o);l.push(...m.applied.map(Kn)),u.push(...m.failed.map(({fix:p,error:f})=>({...Kn(p),error:f instanceof Error?f.message:String(f)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,p)=>m.localeCompare(p)),planned_count:s.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(Kn),applied_fixes:l,gated_fixes:c.map(m=>({...Kn(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function xf(e,t,n={}){sc(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new w("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",y.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new w("--fix-scope requires --auto-fix.",y.USAGE);let i=up(e.fixScope),o=M(process.cwd(),t.path);await X(o);let s=await C(o),a=Ie(s.schema),c=W(s,z()),d=Qp(e),l=[],u=await Ri({includeBody:d.has("history_drift")||d.has("metadata"),pmRoot:o,settings:s,typeToFolder:c.type_to_folder,warnings:l});if(d.has("history_drift")){let A=await Dn(o);A.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${A.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",p=Bp(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),f=VS(p,m,s.validation.metadata_required_fields),h=GS(s),_=Gp(e.dependencyCycleSeverity),g=Jp(e.parentCycleSeverity),v=Kp(e.scanMode),k=Yp(o),x=await RE({requestedChecks:d,options:e,global:t,pmRoot:o,workspaceRoot:k,settings:s,items:u,statusRegistry:a,metadataPolicy:f,lifecyclePatternPolicy:h,dependencyCycleSeverity:_,parentCycleSeverity:g,fileScanMode:v,initialWarnings:[...new Set(l)]}),S=r?await IE(e,x,s,i,t,n):void 0,I=[...new Set(x.warnings)].sort((A,F)=>A.localeCompare(F)),E={ok:!x.checks.some(A=>A.status==="error"),has_warnings:I.length>0,checks:x.checks,warnings:I,...S!==void 0?{fixes:S}:{},generated_at:T(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?E:{...BS(E),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as CE}from"node:child_process";import{promisify as TE}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f9c26dab-b2fb-5ca0-b575-682b4b0bb830")}catch{}})();var $E=TE(CE),OE=16,DE=3e4;function PE(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(o=>typeof o=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function NE(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let o of Object.entries(i).filter(([,s])=>s.required===!0).map(([s])=>s))if(!Object.hasOwn(r,o))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${o}`);for(let[o,s]of Object.entries(r)){let a=i[o];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${o}`);if(s===null||typeof s!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${o} must be ${a.type}`)}return{...r}}async function ME(e,t,n,r){let i=NE(e,t),o=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...cc(n)}));o.catch(()=>{});let s;try{let a=await Promise.race([o,new Promise((c,d)=>{s=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??DE),s.unref?.()})]);return PE(e,t.key,a)}finally{clearTimeout(s)}}function Ef(e,t,n,r){let i=e;for(let o of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new We(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[o]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(o=>typeof o=="string"))return i;throw new We(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function Sf(e,t,n,r){let i=e.checks.find(s=>s.name===t);if(!i)throw new We(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:Ef(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function LE(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await $E("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function FE(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(OE,t.length)},async()=>{for(;r<t.length;){let o=r;r+=1;let s=t[o],a=await Wt(ur(e,s.id),s.id);n[o]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function er(e,t={}){let n=await C(e),r=W(n),i=Ie(n.schema),s=(await Gt(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(p=>({...p,id:p.id,status:p.status,type:p.type})),a={path:e},c=z(),d=Object.fromEntries((c?.assurance_providers??[]).map(p=>[p.definition.id,{cost_class:p.runtime_definition.cost_class,network:p.runtime_definition.network}])),l=new Map,u,m;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await LE(e,t.tree_id),items:s,history:t.include_history===!1?[]:await FE(e,s),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async p=>{if(p.kind==="graph"){let _=Q({operation:p.operation,parameters:p.parameters??{}}),g=l.get(_);g===void 0&&(g=id(p.operation,void 0,void 0,{...p.parameters,full:!0},a),l.set(_,g));let v=await g;return{value:Ef(v,p.field,p.kind),population_size:s.length,cost:s.length}}if(p.kind==="validate"){u??=xf({counts:!0},a);let _=await u;return Sf(_,p.check,p.field,p.kind)}if(p.kind==="health"){m??=Zm(a,{checkOnly:!0,full:!0});let _=await m;return Sf(_,p.check,p.field,p.kind)}let f=t.providers?.[p.provider];if(f)return f(p);let h=$c(c,p.provider);if(!h)throw new TypeError(`assurance provider ${p.provider} is not registered`);return ME(h.runtime_definition,p,e,t.trigger??"sdk")}}}import{createHash as jE}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e78c3363-1741-52b9-8bd5-729e3ccada50")}catch{}})();function Pi(e){return{files:(Array.isArray(e.files)?e.files:[]).flatMap(t=>{if(typeof t!="object"||t===null||Array.isArray(t))return[];let n=t.path;return typeof n=="string"?[n]:[]}),package_names:Array.isArray(e.package_names)?e.package_names.filter(t=>typeof t=="string"):[],item_ids:[e.id],tags:Array.isArray(e.tags)?e.tags.filter(t=>typeof t=="string"):[],error_codes:Array.isArray(e.error_codes)?e.error_codes.filter(t=>typeof t=="string"):[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59f5918f-108e-5cad-905b-7f690c3c4794")}catch{}})();var Mi=["production_defect","nightly_regression","scanner_finding","review_caught_late"],oa=["gate_added","gate_strengthened","explicit_waiver"],Rf=256,UE=1024,tr=new Map,zE=["files","package_names","item_ids","tags","error_codes"];function we(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t<n?-1:1)}function Af(e){return jE("sha256").update(Q(e)).digest("hex")}function ia(e,t){if(typeof e!="string"||!e.trim())throw new TypeError(`${t} must be a non-empty string`)}function nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _n(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function Cf(e,t){if(!nr(e))throw new TypeError(`${t} must be an object`);for(let n of zE)if(e[n]!==void 0&&!_n(e[n]))throw new TypeError(`${t}.${n} must be an array of strings`);return e}function WE(e,t){if(!nr(e))throw new TypeError(`defect recurrence family ${t} triggers must be an object`);for(let r of["package_names","item_ids","tags","error_codes"])if(e[r]!==void 0&&!_n(e[r]))throw new TypeError(`defect recurrence family ${t} triggers.${r} must be an array of strings`);let n=e.file_patterns;if(n!==void 0&&!_n(n))throw new TypeError(`defect recurrence family ${t} triggers.file_patterns must be an array of strings`);for(let r of n??[])if(r.length>Rf)throw new TypeError(`defect recurrence family ${t} file pattern exceeds ${Rf} characters`)}function HE(e,t){if(ia(e.id,"defect recurrence family id"),t.has(e.id))throw new TypeError(`Duplicate defect recurrence family ${e.id}`);if(t.add(e.id),!Number.isInteger(e.version)||e.version<1)throw new TypeError(`defect recurrence family ${e.id} version must be a positive integer`);if(!Mi.includes(e.escape_class))throw new TypeError(`defect recurrence family ${e.id} has an invalid escape class`);ia(e.title,`defect recurrence family ${e.id} title`),ia(e.owner_item_id,`defect recurrence family ${e.id} owner_item_id`)}function qE(e){if(!_n(e.historical_item_ids)||e.historical_item_ids.length===0||e.historical_item_ids.some(t=>!t.trim()))throw new TypeError(`defect recurrence family ${e.id} requires historical_item_ids`);if(WE(e.triggers,e.id),!nr(e.checks)||!_n(e.checks.local)||!_n(e.checks.hosted)||e.checks.local.length===0||e.checks.hosted.length===0||e.checks.local.some(t=>!t.trim())||e.checks.hosted.some(t=>!t.trim()))throw new TypeError(`defect recurrence family ${e.id} checks must contain nonempty local and hosted string arrays`)}function BE(e){if(!nr(e.budget)||typeof e.budget.max_escape_rate!="number"||!Number.isFinite(e.budget.max_escape_rate)||typeof e.budget.max_false_positive_rate!="number"||!Number.isFinite(e.budget.max_false_positive_rate))throw new TypeError(`defect recurrence family ${e.id} requires numeric budgets`);if(e.budget.max_escape_rate<0||e.budget.max_escape_rate>1||e.budget.max_false_positive_rate<0||e.budget.max_false_positive_rate>1)throw new TypeError(`defect recurrence family ${e.id} budgets must be between 0 and 1`)}function GE(e){let t=Cf(e.negative_control,`defect recurrence family ${e.id} negative_control`);if(aa(e,t,{}).length===0)throw new TypeError(`defect recurrence family ${e.id} negative_control must select its own family`)}function sa(e){if(e.version!==1)throw new TypeError(`Unsupported defect recurrence policy version ${e.version}`);if(typeof e.evidence_epoch!="string"||!Number.isFinite(Date.parse(e.evidence_epoch)))throw new TypeError("defect recurrence evidence_epoch must be an ISO timestamp");let t=new Set;for(let n of e.families){if(!nr(n))throw new TypeError("defect recurrence family must be an object");HE(n,t),qE(n),BE(n),GE(n)}}function JE(e,t){let n=tr.get(e);if(n===void 0){if(tr.size>=UE){let i=tr.keys().next().value;tr.delete(i)}let r=e.replaceAll("**","\0").replaceAll(/[|\\{}()[\]^$+?./]/gu,"\\$&").replaceAll("*","[^/]*").replaceAll("\0",".*");n=new RegExp(`^${r}$`,"u"),tr.set(e,n)}return n.test(t)}function VE(e,t){let n=[],r=we(e.triggers.file_patterns??[]);for(let i of we(t.files??[]))for(let o of r)JE(o,i)&&n.push({signal:"file",value:i,matched:o});return n}function KE(e,t){let n=[{signal:"package",values:we(t.package_names??[]),triggers:we(e.triggers.package_names??[])},{signal:"tag",values:we(t.tags??[]),triggers:we(e.triggers.tags??[])},{signal:"error_code",values:we(t.error_codes??[]),triggers:we(e.triggers.error_codes??[])}],r=[];for(let i of n){let o=new Set(i.triggers);for(let s of i.values)o.has(s)&&r.push({signal:i.signal,value:s,matched:s})}return r}function YE(e,t,n){let r=new Set(e.triggers.item_ids??[]);return we(t.item_ids??[]).flatMap(i=>r.has(i)||n[i]?.includes(e.id)?[{signal:"item",value:i,matched:e.id}]:[])}function aa(e,t,n){return[...VE(e,t),...KE(e,t),...YE(e,t,n)].sort((i,o)=>i.signal!==o.signal?i.signal.localeCompare(o.signal):i.value!==o.value?i.value.localeCompare(o.value):i.matched.localeCompare(o.matched))}function XE(e,t){if(!e)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("defect change-risk cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n)||n.index_fingerprint!==t||!Number.isInteger(n.offset)||n.offset<0)throw new TypeError("defect change-risk cursor does not match this index");return n.offset}function ZE(e){return[e.files,e.package_names,e.item_ids,e.tags,e.error_codes].reduce((t,n)=>t+(n?.length??0),0)}function Tf(e,t,n={}){sa(e);let r=[...e.families].sort((l,u)=>l.id<u.id?-1:1),i=Af({...e,families:r}),o=new Set(n.changed_item_ids??[]),s=n.previous_index?.policy_fingerprint===i,a=s?Object.fromEntries(Object.entries(n.previous_index?.item_families??{}).filter(([l])=>!o.has(l))):{},c=s?Object.keys(a).length:0;for(let l of t){let u=Pi(l),m=r.filter(p=>p.historical_item_ids.includes(l.id)||aa(p,u,{}).length>0).map(p=>p.id);m.length>0?a[l.id]=m:delete a[l.id]}let d=Object.fromEntries(Object.entries(a).sort(([l],[u])=>l<u?-1:1).map(([l,u])=>[l,we(u)]));return{version:1,policy_fingerprint:i,index_fingerprint:Af({policy_fingerprint:i,item_families:d}),families:r,item_families:d,build:{items_scanned:t.length,items_reused:c,items_indexed:Object.keys(d).length}}}function $f(e,t,n={}){let r=n.limit??25;if(!Number.isInteger(r)||r<1||r>100)throw new TypeError("defect change-risk limit must be an integer from 1 through 100");let i=XE(n.cursor,e.index_fingerprint),o=e.families.flatMap(l=>{let u=aa(l,t,e.item_families);return u.length===0?[]:[{family_id:l.id,family_version:l.version,owner_item_id:l.owner_item_id,escape_class:l.escape_class,reasons:u,local_checks:we(l.checks.local),hosted_checks:we(l.checks.hosted),budget:l.budget}]}),s=o.slice(i,i+r),a=i+s.length,c=a<o.length?Buffer.from(JSON.stringify({index_fingerprint:e.index_fingerprint,offset:a})).toString("base64url"):void 0,d={risk_detected:o.length>0,index_fingerprint:e.index_fingerprint,items:s,total:o.length,...c?{next_cursor:c}:{},required_local_checks:we(o.flatMap(l=>l.local_checks)),required_hosted_checks:we(o.flatMap(l=>l.hosted_checks)),row_contract:{row_keys:["items"],jq_selector:".items[]"}};return{...d,cost:{families_evaluated:e.families.length,signals_evaluated:ZE(t),families_selected:o.length,estimated_output_tokens:Math.ceil(JSON.stringify(d).length/4)}}}function QE(e){return typeof e.type=="string"&&e.type.toLowerCase()==="issue"||(Array.isArray(e.tags)?e.tags:[]).some(t=>typeof t=="string"&&["bug","defect","security"].includes(t.toLowerCase()))}function Ni(e){return typeof e=="string"&&e.trim().length>0}function If(e){return Array.isArray(e)&&e.length>0&&e.every(Ni)}function eR(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,expired:!1};let n=e;if(!oa.includes(n.disposition)||typeof n.owner!="string"||!n.owner.trim())return{valid:!1,expired:!1};if(n.disposition==="explicit_waiver"){let r=Date.parse(n.waiver_expires_at??"");return{valid:Ni(n.waiver_reason)&&Number.isFinite(r)&&r>=t,expired:Number.isFinite(r)&&r<t}}return{valid:Ni(n.gate_id)&&Ni(n.negative_control)&&If(n.local_checks)&&If(n.hosted_checks),expired:!1}}function tR(e,t){let n=[];if(!Number.isFinite(Date.parse(typeof e.completed_at=="string"?e.completed_at:""))&&!Number.isFinite(Date.parse(typeof e.closed_at=="string"?e.closed_at:""))&&n.push({item_id:e.id,kind:"invalid_completion_timestamp",detail:`${e.id} requires a valid completed_at or closed_at timestamp after the defect-evidence epoch.`}),typeof e.escape_class!="string"?n.push({item_id:e.id,kind:"missing_escape_class",detail:`${e.id} requires escape_class after the defect-evidence epoch.`}):Mi.includes(e.escape_class)||n.push({item_id:e.id,kind:"invalid_escape_class",detail:`${e.id} has unsupported escape_class ${e.escape_class}.`}),e.gate_evidence===void 0)return n.push({item_id:e.id,kind:"missing_gate_evidence",detail:`${e.id} requires structured gate_evidence after the defect-evidence epoch.`}),n;let r=eR(e.gate_evidence,t);return r.valid||n.push({item_id:e.id,kind:r.expired?"expired_waiver":"invalid_gate_evidence",detail:r.expired?`${e.id} carries an expired gate-evidence waiver.`:`${e.id} gate_evidence does not prove a gate or explicit waiver.`}),n}function mL(e,t,n,r=new Date){sa(t);let i=Date.parse(t.evidence_epoch),o=new Set(n),s=e.filter(m=>o.has(m.status)&&QE(m)),a=s.filter(m=>{let p=Date.parse(typeof m.completed_at=="string"?m.completed_at:"");if(Number.isFinite(p))return p>=i;let f=Date.parse(typeof m.closed_at=="string"?m.closed_at:"");if(Number.isFinite(f))return f>=i;let h=Date.parse(typeof m.created_at=="string"?m.created_at:"");return!Number.isFinite(h)||h>=i}),c=Object.fromEntries(Mi.map(m=>[m,0])),d=Object.fromEntries(oa.map(m=>[m,0])),l=s.filter(m=>typeof m.escape_class=="string"&&Mi.includes(m.escape_class));for(let m of l)if(c[m.escape_class]+=1,typeof m.gate_evidence=="object"&&m.gate_evidence!==null&&!Array.isArray(m.gate_evidence)){let p=m.gate_evidence.disposition;typeof p=="string"&&oa.includes(p)&&(d[p]+=1)}let u=a.flatMap(m=>tR(m,r.getTime()));return u.sort((m,p)=>m.item_id!==p.item_id?m.item_id.localeCompare(p.item_id):m.kind.localeCompare(p.kind)),{ok:u.length===0,governed_item_count:a.length,classified_item_count:l.length,class_counts:c,evidence_disposition_counts:d,findings:u}}function nR(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("defect recurrence policy must be an object");let t=e;if(!Array.isArray(t.families))throw new TypeError("defect recurrence policy families must be an array");return sa(t),t}function Of(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("defect change-risk request must be an object");let t=e,n=Cf(t.change,"defect change-risk request.change");if(t.cursor!==void 0&&typeof t.cursor!="string")throw new TypeError("defect change-risk request.cursor must be a string");if(t.limit!==void 0&&!Number.isInteger(t.limit))throw new TypeError("defect change-risk request.limit must be an integer");return{policy:nR(t.policy),change:n,...t.cursor===void 0?{}:{cursor:t.cursor},...t.limit===void 0?{}:{limit:t.limit}}}import{createHash as rR}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f66a964d-1352-5523-ab91-5177d0d93ce8")}catch{}})();var ca,Df=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk"],da=["measurement","assertion","gate"];function iR(e){if(Df.includes(e))return e;throw Tr({command_path:"assurance",token:e,allowed:Df,display_name:"assurance action"})}function gn(e,t,n){throw new w(t,y.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function oR(e){if(!e)return gn("kind",`Assurance declaration kind is required. Expected: ${da.join(", ")}`,"pm assurance list measurement");if(da.includes(e))return e;throw new w(`Assurance declaration kind is required. Expected: ${da.join(", ")}`,y.USAGE)}function Pf(e){if(!e)return gn("preset",`Assurance preset is required. Expected: ${Tn.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(Tn.includes(e))return e;throw new w(`Assurance preset is required. Expected: ${Tn.join(", ")}`,y.USAGE)}function la(e){return e.owner?.trim()?e.owner.trim():gn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function sR(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new w("assurance definition must be valid JSON",y.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new w("assurance put requires a JSON object definition",y.USAGE);return n}async function aR(e){let[t,n,r]=await Promise.all([Cn(e,"measurement"),Cn(e,"assertion"),Cn(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Nf(e,t){return t===!0?{id:e.id}:e}async function cR(e,t){let n=t.authorization_decision;if(!n)return[];let r=await er(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(s=>s.id===n),o=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!o.has(i.status))throw new w(`Assurance authorization ${n} must name a terminal Decision item`,y.USAGE);return[i.id]}async function dR(e,t){let n=ko(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>Yt))throw new w(`assurance verdict limit must be an integer from 1 through ${Yt}`,y.USAGE);let r=await bd(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function lR(e,t,n){if(e==="presets"){if(t.preset??t.id)return Wr(Pf(t.preset??t.id),la(t));let i=Tn.map(o=>{let s=Wr(o,"pm-owner");return{id:o,title:s.title,description:s.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return Kt(()=>xd(n,Pf(t.preset??t.id),la(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await Sd(await er(n,{resolve_tree:!1,trigger:"derive"}),la(t)),o=t.apply?await Kt(()=>Ed(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...o?{applied:o}:{}}}if(!t.id)return gn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new w("assurance promote requires --enforcement warn|block",y.USAGE);let r=await _o(n,"assertion",t.id);return Kt(()=>Rd(n,r,t.enforcement,{author:t.author,message:t.message}))}async function uR(e,t,n){if(!e.id)return gn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new w("assurance run requires a trigger",y.USAGE);if(!Et.includes(e.trigger))throw new w(`Unknown assurance trigger ${e.trigger}. Expected: ${Et.join(", ")}`,y.USAGE);let i=e.trigger,[o,s]=await Promise.all([aR(t),er(t,{...n.workspace,tree_id:e.tree,trigger:i})]),a=await od(()=>gd(r,o,s,{trigger:i,dry_run:e.dry_run===!0}));return a.dry_run||await vd(t,a,{author:e.author,message:e.message}),a}function Mf(e){throw e instanceof w?e:new w(e instanceof Error?e.message:"assurance risk request is invalid",y.USAGE)}function mR(e){if(e.limit!==void 0)throw new w("assurance risk does not accept --limit; set limit inside the risk definition",y.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new w("assurance risk definition must be valid JSON",y.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return Of(t)}catch(n){return Mf(n)}}function pR(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function fR(e,t,n){let r=Q(t.policy),i=ca?.pm_root===e?ca:void 0,o=new Map(n.map(d=>[d.id,rR("sha256").update(Q(Pi(d))).digest("hex")])),s=i?.policy_serialized===r?i:void 0,a=s?pR(s,o):new Set,c=Tf(t.policy,s?n.filter(d=>a.has(d.id)):n,s?{previous_index:s.index,changed_item_ids:[...a]}:{});return ca={pm_root:e,policy_serialized:r,item_fingerprints:o,index:c},c}async function hR(e,t){let n=mR(e),r=await er(t,{include_history:!1,resolve_tree:!1});try{return $f(fR(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit})}catch(i){return Mf(i)}}async function _R(e,t={},n={}){let r=iR(e.action),i=M(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return lR(r,e,i);if(r==="verdicts")return dR(e,i);if(r==="run")return uR(e,i,n);if(r==="risk")return hR(e,i);let o=oR(e.kind);if(r==="list")return Cn(i,o);if(!e.id)return gn("id",`assurance ${r} requires an id`,`pm assurance ${r} ${o} <id>`);let s=e.id;if(r==="show")return _o(i,o,s);if(r==="remove"){let l=await Kt(()=>wd(i,o,s,{author:e.author,message:e.message}));return Nf(l,e.idOnly)}let a=sR(o,e.definition);if(a.id!==s)throw new w(`Assurance definition id ${a.id} does not match requested id ${s}`,y.USAGE);let c={author:e.author,message:e.message,...o==="assertion"?{authorized_decision_ids:await cR(i,a)}:{}},d=await Kt(()=>Ur(i,o,a,c));return Nf(d,e.idOnly)}function IL(e,t,n){let r={...e,...t};return _R({action:$(r,"subcommand")??$(r,"assuranceAction")??$(r,"operation")??"",kind:$(r,"kind"),id:$(r,"id"),definition:r.definition,trigger:$(r,"trigger"),tree:$(r,"treeId")??$(r,"tree"),gate:$(r,"gate"),limit:ko(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:$(r,"author"),message:$(r,"message"),preset:$(r,"preset"),owner:$(r,"owner"),apply:r.apply===!0,enforcement:$(r,"enforcement")},n)}import{execFile as gR}from"node:child_process";import yR from"node:path";import{promisify as wR}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="46439d77-bb74-5f36-9383-ac3362f41b3e")}catch{}})();var vR=wR(gR),bR="@unbrained/pm-cli",kR="latest",xR={global:["--global"],project:[]};function Lf(e){let t=e.project===!0||e.local===!0||e.scope==="project",n=e.global===!0||e.scope==="global";if(t&&n)throw new w('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"}function Fi(e){return e.trim().toLowerCase()}function Ff(e,t){let n=Fi(t);return[e.name,e.directory,e.source.input,e.source.location,e.source.package,e.source.repository,e.source.owner&&e.source.repo?`${e.source.owner}/${e.source.repo}`:void 0].some(i=>typeof i=="string"&&Fi(i)===n)}function SR(e,t){let n=M(process.cwd(),t.path),r=Pt(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function ER(e,t,n){try{let r=await vR(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:r.stdout,stderr:r.stderr}}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr??""):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new w(`Command failed: ${e} ${t.join(" ")}
45
+ ${o}`,y.GENERIC_FAILURE)}}async function RR(){return Ra(import.meta.url,["../../.."])}function ji(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():kR}function Li(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():bR}async function AR(e,t){let n=e.commandRunner??ER,r=Li(e),i=ji(e),o=`${r}@${i}`,s=["npm","install","-g",o];e.repair===!0&&s.push("--force");let a=await RR(),c={requested:!0,status:"planned",package:r,target:o,command:s,before_version:a,repair:e.repair===!0};if(t)return c;try{await n(s[0],s.slice(1));let d=await n("pm",["--version"]);return{...c,status:"updated",after_version:d.stdout.trim()||void 0}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function IR(e){return yR.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function CR(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!IR(n)&&e.package&&e.package.trim().length>0?`npm:${e.package.trim()}@${t}`:e.input.startsWith("npm:")?e.input:`npm:${e.input}`}return e.input}async function TR(e,t){let n=CR(e,t);return e.kind!=="local"||await D(n)?n:await D(e.location)?e.location:n}function $R(e,t,n,r){let i=["pm","package","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&r&&r.trim().length>0&&i.push("--ref",r.trim()),i}async function jf(e,t){let n=SR(e,t);return(await _e(n.selected_root)).state.entries.filter(i=>i.scope===e)}async function OR(e,t,n){let r=await jf(e,t);return r.find(i=>Ff(i,n.name))??r.find(i=>Fi(i.directory)===Fi(n.directory))}async function DR(e,t,n,r,i){let o=ji(t),s=await TR(e.source,o),a=$R(e.source,s,r,e.source.ref),c={name:e.name,directory:e.directory,scope:r,source:e.source,status:"planned",command:a,previous_version:e.manifest_version};if(i)return c;try{await ps(s,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await OR(r,n,e);return{...c,status:"updated",installed_version:d?.manifest_version}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function PR(e,t,n,r){let i=[n?e.status:void 0,...t.map(o=>o.status)].filter(o=>typeof o=="string");return{requested_cli:n,requested_packages:r,planned:i.filter(o=>o==="planned").length,updated:i.filter(o=>o==="updated").length,skipped:i.filter(o=>o==="skipped").length,failed:i.filter(o=>o==="failed").length}}async function ML(e,t,n){let r=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&t.packagesOnly===!0){let m=["package","upgrade",...r?[r]:[],"--packages-only","--dry-run",...xR[Lf(t)]];throw new w('Options "--cli-only" and "--packages-only" are mutually exclusive.',y.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:ze(m),suggested_retry_args:m}})}let i=Lf(t),o=t.dryRun===!0;if(t.cliOnly===!0&&r)throw new w('A package target cannot be used with "--cli-only".',y.USAGE);let s=!(t.packagesOnly===!0||r),a=t.cliOnly!==!0,c=s?await AR(t,o):{requested:!1,status:"skipped",package:Li(t),target:`${Li(t)}@${ji(t)}`,command:["npm","install","-g",`${Li(t)}@${ji(t)}`],repair:t.repair===!0,reason:"not_requested"},d=a?await jf(i,n):[];if(r&&(d=d.filter(m=>Ff(m,r)),d.length===0))throw new w(`Managed package "${r}" was not found in ${i} scope.`,y.NOT_FOUND);let l=[];for(let m of d)l.push(await DR(m,t,n,i,o));let u=PR(c,l,s,a);return{ok:u.failed===0,action:"upgrade",dry_run:o,scope:i,target:r,cli:c,packages:l,summary:u}}import yn from"node:fs/promises";import zi from"node:path";import Ui from"node:fs/promises";import ua from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b26cf702-330e-5cf5-8371-204220d5c5c9")}catch{}})();var NR=864e5;function MR(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function LR(e,t){let n;try{n=await Ui.readdir(e,{withFileTypes:!0})}catch(i){if(U(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let o=ua.join(e,i.name),s;try{s=await Ui.readdir(o)}catch(a){U(a)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of s)a.endsWith(".json")&&r.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function Uf(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*NR,s=ua.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await LR(s,a.warnings);for(let d of c){let l=ua.join(s,d),u=`checkpoints/${d}`;a.scanned+=1,r?.onRead&&a.warnings.push(...await r.onRead(l));let m;try{m=await Ui.readFile(l,"utf8")}catch(g){if(U(g)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let p=MR(m),f=p===null?Number.NaN:Date.parse(p);if(!Number.isFinite(f)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:p,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=i-f,_={file:u,created_at:p,age_seconds:Math.floor(h/1e3),stale:h>o,reason:h>o?"expired":"active"};if(!_.stale){a.retained.push(u),a.entries.push(_);continue}if(!n){try{await Ui.unlink(l)}catch(g){if(!U(g)){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(_);continue}}r?.onWrite&&a.warnings.push(...await r.onWrite(l))}a.removed.push(u),a.entries.push(_)}return a}import ma from"node:fs/promises";import zf from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7df80849-51e1-5efa-b40a-b44088f941a9")}catch{}})();var FR=1440*60*1e3,jR=new Set(["committed","compensated"]);function UR(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function zR(e,t,n,r,i){let o=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(o))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let s=r-o;return jR.has(t)?s>i?{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"active"},remove:!1}}async function WR(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],o=UR(await ma.readFile(e,"utf8")),s=zR(t,o.status,o.updatedAt,r.nowMs,r.retentionMs);return s.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),s.remove&&!r.dryRun&&(await ma.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:s,warnings:i}}async function Wf(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*FR,s=zf.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await ma.readdir(s)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(U(d))return a;throw d}for(let d of c){let l=zf.join(s,d),u=`transactions/sdk/${d}`,m=await WR(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:o});a.warnings.push(...m.warnings),a.scanned+=1;let{decision:p}=m;if(!p.remove){a.retained.push(u),a.entries.push(p.entry);continue}a.removed.push(u),a.entries.push(p.entry)}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="76f8405f-138d-5119-a300-f068354394a5")}catch{}})();var rr=["index","embeddings","runtime","locks","checkpoints","transactions"],HR=1440*60*1e3,qR=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function BR(e,t,n){let r=t.relativePath,i=zi.join(e,r),o=await Ke({path:i,scope:"project"});try{let s=await yn.stat(i);if(t.kind==="file"&&!s.isFile())return{removed:!1,warnings:[...o,`not_a_file:${r}`]};if(t.kind==="directory"&&!s.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await yn.unlink(i):await yn.rm(i,{recursive:!0,force:!0});let a=await ne({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...a]}}catch(s){if(U(s))return{removed:!1,warnings:o};throw s}}async function GR(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],o=[],s=Date.now()-HR;for(let a of n){let c=zi.join(e,a.relativePath);if(!await D(c))continue;let d=(await yn.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=zi.posix.join(a.relativePath,l),m=zi.join(c,l);o.push(...await Ke({path:m,scope:"project"}));let p=await yn.stat(m).catch(f=>{if(!U(f))throw f});if(p){if(p.mtimeMs>s){i.push(u);continue}r.push(u),!t&&(await yn.rm(m,{recursive:!0,force:!0}),o.push(...await ne({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:o}}function JR(e){if(!e||e.length===0)return[...rr];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new w(`--scope requires at least one value (${rr.join(",")})`,y.USAGE);let n=new Set;for(let r of t){if(!rr.includes(r))throw new w(`Invalid --scope value "${r}". Expected one or more of: ${rr.join(", ")}`,y.USAGE);n.add(r)}return rr.filter(r=>n.has(r))}function VR(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function oF(e,t={}){let n=M(process.cwd(),e.path);await X(n);let r=await C(n),i=t.dryRun===!0,o=JR(t.scope),s=qR.filter(f=>o.includes(f.scope)),a=[],c=[],d=[];for(let f of s){let h=await BR(n,f,i);h.removed?a.push(f.relativePath):c.push(f.relativePath),d.push(...h.warnings)}if(o.includes("runtime")){let f=await GR(n,i);a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings)}let l;if(o.includes("locks")){let f=await ol(n,{dryRun:i,hooks:{onRead:h=>Ke({path:h,scope:"project"}),onWrite:h=>ne({path:h,scope:"project",op:"gc:lock_remove"})}});a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),l={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length}}let u;if(o.includes("transactions")){let f=r.checkpoints.retention_days,h=await Wf(n,{dryRun:i,retentionDays:f,hooks:{onRead:_=>Ke({path:_,scope:"project"}),onWrite:_=>ne({path:_,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:f}}let m;if(o.includes("checkpoints")){let f=r.checkpoints.retention_days,h=await Uf(n,{dryRun:i,retentionDays:f,hooks:{onRead:_=>Ke({path:_,scope:"project"}),onWrite:_=>ne({path:_,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),m={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:f}}d.push(...await wr({mode:i?"gc:dry-run":"gc",total_items:s.length}));let p=VR({dryRun:i,scopes:o,removed:a});return{ok:d.length===0,dry_run:i,scope:o,removed:a,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:p,generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e900c117-6d8d-55d3-86df-f543dc499930")}catch{}})();function Hf(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function qf(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?ze([...r,"merge","report"],n):e==="history_evidence_invalid"?ze([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?ze([...r,"merge","reconcile"],n):e==="history_repair_required"?ze([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?ze([...r,"merge","install"],n):null}function Bf(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(r=>typeof r=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(r=>typeof r=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function yF(e){let t=M(process.cwd(),e.path);await X(t);let n=await C(t),r=W(n,z()),i=[],o=await Ri({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),s=await Qe(t),[a,c,d,l]=await Promise.all([Xr(t,tn(n)),s===null?Promise.resolve(null):nn(s),it(s??t,{includeLossless:!0,pmRoot:t}),Ai(t,o,!1)]),{pendingDecisions:u,lossless:m}=dn(d.receipts),p=[...new Set(u.map(g=>g.item_id))].sort((g,v)=>g.localeCompare(v)),f=l.check.details,h=Bf(f),_=Hf({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:m.length,historyEvidenceValid:h.evidence_valid,driftedItemCount:h.drifted_item_count,fence:a,drivers:c});return{ok:_==="ready",state:_,merge_fence:{committed:a,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:p.slice(0,25),pending_item_ids_truncated:p.length>25,lossless_count:m.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:h,next_action:{command:qf(_,t),reason:_},warnings:[...new Set(i)].sort((g,v)=>g.localeCompare(v)),generated_at:T()}}function wF(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
46
+ `)}var vF={commandForWorkspacePositionState:qf,normalizeWorkspaceHistoryDrift:Bf,selectWorkspacePositionState:Hf};import KR from"node:fs/promises";import ir 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]="1bcd20e1-2995-56ef-8d04-f265b8282c19")}catch{}})();var pa="index/manifest.json",fa="search/embeddings.jsonl",YR="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function XR(e){return e.progress===!0||process.stderr.isTTY===!0}function de(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
47
+ `)}catch{}}function ZR(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new w("Reindex mode must be one of keyword|semantic|hybrid",y.USAGE)}async function QR(e,t,n,r){let i=[];return{candidates:await Ac(e,t,n,i,r),warnings:i}}async function _a(e,t,n,r,i){let o=Dt(z()),s=[];for(let a of t)if(!(i&&!i.has(a.metadata.id))){if(typeof a.body=="string"){s.push({metadata:a.metadata,body:a.body});continue}try{let c=await KR.readFile(a.item_path,"utf8"),d=zt(c,{format:a.item_format,schema:n,extensionFieldNames:o,onWarning:l=>r.push(l)});s.push({metadata:a.metadata,body:d.body})}catch{r.push(`item_list_item_read_failed:${ir.relative(e,a.item_path)}`),s.push({metadata:a.metadata,body:""})}}return s}function eA(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:Uc(e,{fields:n})}}var wn=Z;function tA(e){let t=z(),n=wn(e.search?.provider);if(!n)return null;let r=Oc(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=wn(i.name)??wn(r.definition.name);if(!o)return null;let s=i.embedBatch,a=i.embed_batch,c=i.embed,d=typeof s=="function"?s:typeof a=="function"?a:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:o,embedBatch:d,embed:l}}function nA(e){let t=z(),n=wn(e.vector_store?.adapter);if(!n)return null;let r=Dc(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=wn(i.name)??wn(r.definition.name);if(!o)return null;let s=i.upsert,a=i.delete;return{adapterName:o,...typeof s=="function"?{upsert:s}:{},...typeof a=="function"?{delete:a}:{}}}function ha(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new w(`Invalid vector returned by ${t}`,y.GENERIC_FAILURE);return e}async function rA(e,t,n){let r=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let o=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:r}));if(!Array.isArray(o))throw new w(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,y.GENERIC_FAILURE);return o.map((s,a)=>ha(s,`extension search provider "${e.name}" embedBatch output at index ${a}`))}if(!e.embed)throw new w(`Extension search provider "${e.name}" does not implement embed/embedBatch`,y.GENERIC_FAILURE);let i=[];for(let[o,s]of n.entries()){let a=await Promise.resolve(e.embed({input:s,settings:t,model:r}));i.push(ha(a,`extension search provider "${e.name}" embed output at index ${o}`))}return i}function Gf(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function Jf(e,t,n){let r=n?St(n.name,Gf(e)):t?St(t.name,t.model):null;if(!r)throw new w("No embedding identity available for semantic reindex mode",y.USAGE);return r}function iA(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function Vf(e,t,n,r,i,o,s,a){let c=r?.name??n?.name,d=zc(c,e.search.embedding_corpus_max_characters).maxCharacters,l=oo(e),u=i.map(f=>Wc(f,{providerName:c,maxCharacters:d,fields:l})),m=[],p=null;if(r)try{m=await rA(r,e,u),p=St(r.name,Gf(e))}catch(f){if(!n)throw new w(`Extension search provider "${r.name}" failed to generate embeddings: ${f instanceof Error?f.message:String(f)}`,y.GENERIC_FAILURE);o.push(`Extension search provider "${r.name}" failed; falling back to built-in provider (${f instanceof Error?f.message:String(f)})`)}if(m.length===0){if(!n)throw new w(`No embedding executor available for reindex mode '${t}'`,y.USAGE);let f=await Hc(n,e,u,{onProgress:h=>{h.phase==="complete"&&(s.batches_completed=h.batch_index),de(a,`embedding_batch_${h.phase} batch=${h.batch_index}/${h.batch_total} size=${h.batch_size} completed_inputs=${h.completed_inputs}/${h.total_inputs}`)}});o.push(...f.warnings),m=f.vectors,p=St(n.name,n.model)}if(de(a,`embedding_complete vectors=${m.length}`),m.length!==i.length)throw new w(`Embedding output size mismatch (expected ${i.length}, received ${m.length})`,y.GENERIC_FAILURE);if(!p)throw new w(`No embedding identity available for reindex mode '${t}'`,y.USAGE);return{vectors:m,embeddingIdentity:p}}async function oA(e,t,n,r,i,o){let s=Object.keys(n);if(t){if(s.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:s.sort((a,c)=>a.localeCompare(c)),settings:r}))}catch(a){throw new w(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${a instanceof Error?a.message:String(a)}`,y.GENERIC_FAILURE)}else s.length>0&&i.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${s.length}`);if(!e)return}e&&await Gc(e,s,{},o)}async function Kf(e,t,n,r,i){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:r}))}catch(o){throw new w(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${o instanceof Error?o.message:String(o)}`,y.GENERIC_FAILURE)}else i.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Bc(e,n)}}function sA(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function aA(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(r=>({id:r.metadata.id,type:r.metadata.type,status:r.metadata.status,priority:r.metadata.priority,updated_at:r.metadata.updated_at}))}}function cA(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=En(e.settings);if(!t.active&&!e.extensionEmbedding)throw new w(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,y.USAGE);let n=Dr(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new w(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,y.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function dA(e){let t=W(e.settings,z()),n=await QR(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(r=>({metadata:r.metadata,body:typeof r.body=="string"?r.body:""}))}}async function lA(e){let t=await Vt(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return Jf(e.settings,En(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&Jt(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(YR))}async function uA(e){let t=await Vt(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=Jf(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(d=>d.metadata.id)),i=iA(t.entries,r),o=Jt(t.embedding,n);e.forceFullSemantic&&!o&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let s=e.forceFullSemantic||o?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),a=new Set(s.map(d=>d.metadata.id)),c=a.size>0?await _a(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,a):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:i,resetRequired:o,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function mA(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await _a(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,de(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await Vf(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:so(r.vectors,"Reindex embeddings")}}async function pA(e){let t=await Vf(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=so(n,"Reindex embeddings");if(!(!e.resetRequired&&(Jt(e.ledgerEmbedding,r)||Vc(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let s=await mA(e);return n=s.vectors,r=s.embeddingIdentity,i=s.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:s.staleDocuments,vectorDimension:i,resetRequired:!0}}async function fA(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(de(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new w(`Extension vector adapter "${t}" does not support upserting vectors.`,y.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,de(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof w)throw t;if(!e.activeVectorStore)throw new w(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,y.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),de(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){de(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await qc(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,de(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new w(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,y.USAGE)}function hA(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:ha(t[r],`reindex embeddings output at index ${r}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function _A(e){de(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await pA({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(de(e.progressEnabled,"vector_reset_start"),await oA(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),de(e.progressEnabled,"vector_reset_complete")):await Kf(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=hA(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await fA({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:Jc(t.embeddingIdentity,t.vectorDimension)}}async function gA(e){let t=await uA(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(o=>[o.metadata.id,o.metadata.updated_at]));if(de(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return de(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await Kf(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await _A({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let i=new Map(r.staleDocuments.map(o=>[o.metadata.id,o]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(o=>i.get(o.metadata.id)??o),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:r.embeddingMetadata}}async function yA(e){let t=ir.join(e.pmRoot,pa),n=ir.join(e.pmRoot,fa),r=oo(e.settings),i=e.documentsForKeywordArtifacts.map(s=>JSON.stringify(eA(s,e.mode,r))).join(`
48
+ `);de(e.progressEnabled,"writing keyword artifacts"),await le(t,`${JSON.stringify(e.manifest,null,2)}
49
+ `),await le(n,`${i}
50
+ `);let o=[];if(e.mode!=="keyword")try{de(e.progressEnabled,"writing vectorization status ledger"),await Kc(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 RF(e,t){let n=ZR(e.mode),r=XR(e),i=e.full===!0;de(r,`start mode=${n}`);let o=M(process.cwd(),t.path);await X(o);let s=Or(await C(o)).settings,a=null;try{a=await fe(o,jc,s.locks.ttl_seconds,V(void 0,"pm-reindex"),!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms)}catch(c){throw c instanceof w&&c.exitCode===y.CONFLICT?new w("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",y.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=tA(s),d=nA(s),l=cA({requestedMode:n,pmRoot:o,settings:s,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;de(r,"loading item corpus");let m=await dA({pmRoot:o,settings:s}),p=m.warnings,{documentCandidates:f,metadataDocuments:h}=m;de(r,`loaded_items=${h.length}`);let _=T(),g=aA(u,_,h),v=ir.join(o,pa),k=ir.join(o,fa),x=u==="keyword"?await _a(o,f,s.schema,p):h,S=[],I={},b=null,E=sA(u);if(u==="keyword"&&await lA({pmRoot:o,settings:s,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:p}),u!=="keyword"){let q=await gA({pmRoot:o,settings:s,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:f,metadataDocuments:h,documentsForKeywordArtifacts:x,forceFullSemantic:i,reindexWarnings:p,semanticWarnings:S,semanticSummary:E,progressEnabled:r});x=q.documentsForKeywordArtifacts,I=q.vectorizationLedgerEntries,b=q.vectorizationEmbeddingMetadata}let A=await yA({pmRoot:o,mode:u,manifest:g,documentsForKeywordArtifacts:x,settings:s,vectorizationLedgerEntries:I,vectorizationEmbeddingMetadata:b,progressEnabled:r}),F=[...await ne({path:v,scope:"project",op:"reindex:manifest"}),...await ne({path:k,scope:"project",op:"reindex:embeddings"}),...await wr({mode:u,total_items:h.length})];return de(r,"done"),{ok:!0,mode:u,total_items:h.length,semantic:E,artifacts:{manifest:pa,embeddings:fa},warnings:[...p,...S,...A,...F],generated_at:_}}finally{await a?.()}}export{lC as a,$l as b,P as c,ke as d,We as e,Kt as f,od as g,ad as h,Et as i,co as j,oh as k,mo as l,po as m,ud as n,Xt as o,In as p,ho as q,Sh as r,gd as s,Cn as t,_o as u,Ur as v,go as w,wd as x,vd as y,bd as z,Tn as A,Wr as B,xd as C,Sd as D,Ed as E,Rd as F,Td as G,uI as H,$ as I,re as J,mI as K,ko as L,pI as M,fI as N,Fd as O,hI as P,_I as Q,gI as R,yI as S,wI as T,xo as U,vI as V,bI as W,bo as X,kI as Y,xI as Z,Ud as _,SI as $,Wh as aa,Hd as ba,PI as ca,Dn as da,NI as ea,Kh as fa,Yh as ga,MI as ha,Xh as ia,v_ as ja,b_ as ka,Qe as la,$C as ma,I_ as na,hg as oa,NT as pa,MT as qa,LT as ra,Ln as sa,FT as ta,jT as ua,UT as va,zT as wa,WT as xa,HT as ya,qT as za,BT as Aa,GT as Ba,JT as Ca,VT as Da,Vu as Ea,ps as Fa,Jd as Ga,Vd as Ha,Xd as Ia,yi as Ja,ZO as Ka,it as La,QO as Ma,eD as Na,bs as Oa,RD as Pa,AD as Qa,Gr as Ra,Jr as Sa,Zm as Ta,kP as Ua,ep as Va,Ep as Wa,PP as Xa,ip as Ya,Ap as Za,AN as _a,IN as $a,oS as ab,sS as bb,ON as cb,DN as db,PN as eb,NN as fb,cS as gb,dS as hb,lS as ib,MN as jb,Tp as kb,mS as lb,$p as mb,zs as nb,Dp as ob,pS as pb,fS as qb,hS as rb,Bs as sb,Gs as tb,GN as ub,JN as vb,VN as wb,BS as xb,KM as yb,xf as zb,er as Ab,Mi as Bb,oa as Cb,Tf as Db,$f as Eb,mL as Fb,nR as Gb,Of as Hb,Df as Ib,da as Jb,_R as Kb,IL as Lb,ML as Mb,oF as Nb,yF as Ob,wF as Pb,vF as Qb,RF as Rb};
51
+ //# sourceMappingURL=chunk-O67VDLOT.js.map