@unbrained/pm-cli 2026.8.27 → 2026.8.28

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 (105) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +25 -1
  3. package/dist/cli/error-guidance.js +61 -7
  4. package/dist/cli/register-annotations.js +58 -41
  5. package/dist/cli-bundle/bundle-manifest.json +121 -121
  6. package/dist/cli-bundle/chunks/{chunk-SH6P7FXI.js → chunk-BY2FQ2NI.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-TNX6HC54.js → chunk-E73FDIWT.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-SHMDY36D.js → chunk-FEVBFFCQ.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-CVBBGWW5.js → chunk-M7OXRQE3.js} +10 -6
  10. package/dist/cli-bundle/chunks/{chunk-R4ETAOJC.js → chunk-NBCBFVZI.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-SKXLJIEK.js → chunk-NTXZHRKA.js} +45 -45
  12. package/dist/cli-bundle/chunks/{chunk-52EKTW6V.js → chunk-QE6WQXFO.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-MFNTKMTI.js → chunk-TIQ6AMH2.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-X2RROGZE.js +2 -0
  15. package/dist/cli-bundle/chunks/{chunk-OS27HHBN.js → chunk-XRVVYRRO.js} +28 -28
  16. package/dist/cli-bundle/chunks/{chunk-3OO3W6FW.js → chunk-XWEQGHHG.js} +2 -2
  17. package/dist/cli-bundle/chunks/{register-list-query-EUWM6VII.js → register-list-query-J35ZPQQ5.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-mutation-FD4HSAVU.js → register-mutation-J6XJJOGU.js} +4 -4
  19. package/dist/cli-bundle/chunks/{register-operations-HRMNFEC3.js → register-operations-AE3JEMFT.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-setup-33GNICLX.js → register-setup-OQERLLWE.js} +2 -2
  21. package/dist/cli-bundle/focused-chunks/{chunk-4BR5UU52.js → chunk-4ZDRZYYJ.js} +41 -41
  22. package/dist/cli-bundle/focused-chunks/{chunk-MXTYGECH.js → chunk-AHAM2HAU.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-SUBSWYW3.js → chunk-JZYPPMXF.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/chunk-LLNTHF5X.js +2 -0
  25. package/dist/cli-bundle/focused-chunks/chunk-LYFWQMVC.js +2 -0
  26. package/dist/cli-bundle/focused-chunks/{chunk-EKX37ZHA.js → chunk-THEPQMLX.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/chunk-YJLDHJOD.js +2 -0
  28. package/dist/cli-bundle/main.js +14 -14
  29. package/dist/cli-bundle/sdk-authoring.js +1 -1
  30. package/dist/cli-bundle/sdk-contracts.js +2 -2
  31. package/dist/cli-bundle/sdk-core.js +26 -26
  32. package/dist/cli-bundle/sdk-governance.js +1 -1
  33. package/dist/cli-bundle/sdk-merge.js +20 -20
  34. package/dist/cli-bundle/sdk-query.js +1 -1
  35. package/dist/cli-bundle/sdk-runtime.js +1 -1
  36. package/dist/cli-bundle/sdk-testing.js +1 -1
  37. package/dist/cli-bundle/sdk.js +10 -10
  38. package/dist/mcp/tool-definitions.js +5 -5
  39. package/dist/sdk/agent/command-recovery.js +3 -3
  40. package/dist/sdk/agent/task-transcript-contracts.d.ts +52 -0
  41. package/dist/sdk/agent/task-transcript-contracts.js +198 -0
  42. package/dist/sdk/annotations.d.ts +5 -2
  43. package/dist/sdk/annotations.js +66 -36
  44. package/dist/sdk/cli-bootstrap.d.ts +2 -8
  45. package/dist/sdk/cli-bootstrap.js +7 -67
  46. package/dist/sdk/cli-contracts/bootstrap-command-scanner.d.ts +23 -0
  47. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +80 -0
  48. package/dist/sdk/cli-contracts/flag-contracts.js +5 -2
  49. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +5 -5
  50. package/dist/sdk/cli-contracts/tool-parameter-tables.js +15 -2
  51. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  52. package/dist/sdk/cli-contracts/tool-schema.js +16 -3
  53. package/dist/sdk/comments.d.ts +4 -0
  54. package/dist/sdk/comments.js +2 -2
  55. package/dist/sdk/completion.js +9 -5
  56. package/dist/sdk/contracts.d.ts +1 -0
  57. package/dist/sdk/contracts.js +3 -2
  58. package/dist/sdk/extension/install-sources.d.ts +13 -0
  59. package/dist/sdk/extension/install-sources.js +62 -30
  60. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +26 -2
  61. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +26 -14
  62. package/dist/sdk/index.d.ts +1 -0
  63. package/dist/sdk/index.js +3 -2
  64. package/dist/sdk/learnings.d.ts +4 -0
  65. package/dist/sdk/learnings.js +7 -4
  66. package/dist/sdk/lifecycle/close.js +4 -3
  67. package/dist/sdk/notes.d.ts +4 -0
  68. package/dist/sdk/notes.js +2 -2
  69. package/dist/sdk/runtime-input.js +5 -2
  70. package/dist/sdk/runtime.d.ts +6 -6
  71. package/dist/sdk/runtime.js +8 -8
  72. package/docs/COMMANDS.md +4 -3
  73. package/docs/OUTPUT_TOKEN_ACCOUNTING.md +20 -7
  74. package/docs/RELEASING.md +9 -1
  75. package/docs/SDK.md +12 -0
  76. package/docs/SDK_CONTEXT_INTEGRITY.md +12 -1
  77. package/docs/SDK_RUNTIME_BOUNDARIES.md +10 -0
  78. package/docs/TESTING.md +6 -2
  79. package/docs/agent-task-token-baseline.json +97 -11
  80. package/docs/agent-task-transcripts.json +211 -0
  81. package/docs/generated/FLAG_LEXICON_BUDGETS.md +3 -3
  82. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  83. package/docs/performance/cli-transport-overhead.md +10 -2
  84. package/marketplace.json +2 -2
  85. package/package.json +2 -2
  86. package/packages/pm-beads/package.json +1 -1
  87. package/packages/pm-calendar/package.json +1 -1
  88. package/packages/pm-command-kit/package.json +1 -1
  89. package/packages/pm-digital-twin/package.json +1 -1
  90. package/packages/pm-governance-audit/package.json +1 -1
  91. package/packages/pm-guide-shell/package.json +1 -1
  92. package/packages/pm-kanban/package.json +1 -1
  93. package/packages/pm-lifecycle-hooks/package.json +1 -1
  94. package/packages/pm-linked-test-adapters/package.json +1 -1
  95. package/packages/pm-search-advanced/package.json +1 -1
  96. package/packages/pm-templates/package.json +1 -1
  97. package/packages/pm-todos/package.json +1 -1
  98. package/packages/pm-vcs/package.json +1 -1
  99. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  100. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  101. package/sdk/public-surface.json +197 -25
  102. package/dist/cli-bundle/chunks/chunk-QTO7USTH.js +0 -2
  103. package/dist/cli-bundle/focused-chunks/chunk-2AGZ5BRT.js +0 -2
  104. package/dist/cli-bundle/focused-chunks/chunk-AQ5IYEZZ.js +0 -2
  105. package/dist/cli-bundle/focused-chunks/chunk-YHWHX6YY.js +0 -2
@@ -1,50 +1,50 @@
1
- import{a as ji,c as or,d as ar,e as Ls,g as Fs,h as zi,i as js,j as $t,k as Ot,l as Us,m as zs,n as Wi,o as qs,p as Dt,q as Pt,r as Bs,s as Hs,t as qi}from"./chunk-Y3JJXRVK.js";import{e as mr,f as Bi}from"./chunk-EKX37ZHA.js";import{C as lr,a as Ts,g as Fi,i as $s}from"./chunk-AQ5IYEZZ.js";import{P as Gc}from"./chunk-FC2AXLB5.js";import{$ as Xi,A as Ac,E as Rc,I as Yi,J as Er,La as Uc,Ma as Ir,Qa as zc,Ra as Wc,Sa as qc,Ua as eo,Z as Ar,_ as Ic,aa as yn,ca as Zi,e as yc,f as wc,g as vc,ga as Cc,ha as Tc,ia as $c,ja as Oc,ka as Rr,m as bc,ma as Dc,n as kc,na as Pc,o as xc,oa as Nc,pa as vt,qa as Mc,ra as Wt,sa as Lc,ta as Qi,u as gn,ua as qt,v as Sc,va as Fc,w as _n,wa as jc,x as Ec,z as Ki}from"./chunk-YVVZ3LQ6.js";import{a as Ds,b as sr,c as Ui,d as Ps,e as Ns,f as He,g as cr,h as Ms,i as at}from"./chunk-HVQ22RC4.js";import{$ as Hi,$a as wr,Ab as Ut,Bb as Je,Ca as ic,Cb as zt,Ea as Gi,Ga as oc,Gb as wt,Ib as Sr,Ma as Ft,Mb as wn,Ob as Cr,Pa as ac,Qa as sc,Sa as _r,Ta as Ji,Ua as cc,Va as dc,Vb as Bc,Wa as lc,Xa as fe,Y as J,Ya as yr,Yb as Hc,Z as T,Za as uc,_ as ec,_a as Vi,ab as vr,b as Xs,bb as br,cb as mc,d as Zs,da as pe,db as Oe,eb as pc,fb as C,gb as kr,ib as fc,ja as tc,ka as hr,l as z,na as gr,nb as hc,o as ne,oa as nc,ob as gc,q as Ge,qa as rc,r as Qs,ra as Nt,s as fr,ta as Mt,tb as xr,vb as _c,wa as Lt,xb as Q,yb as jt,zb as st}from"./chunk-XDPYBQCF.js";import{$a as Vs,A as _s,Ca as Li,Da as Is,Ea as Cs,F as ys,Fa as Tt,G as ws,H as B,Ha as Ne,Ja as Me,La as ce,M as hn,Ma as Ae,N as L,O as Pe,Oa as ve,P as rr,Pa as Le,Q as yt,S as vs,T as ir,Ta as $e,V as bs,Va as dr,X as Z,Xa as Ws,Za as ur,_ as ks,_a as Js,a as ds,ca as xs,d as ls,e as us,fa as Ss,h as Ct,ha as Mi,p as gs,q as fn,r as D,s as it,t as U,ta as Es,u as Y,ua as As,v as se,y as we,z as Ee}from"./chunk-AD6ULRAF.js";import{a as Ks,b as pr,d as Ys}from"./chunk-6GCRSLPG.js";import{O as ms,Q as ps,S as fs,U as hs,V as nr,Y as _,Z as y,a as er,aa as X,ba as Rs,ca as ot,d as tr,fa as Os,oa as Gs,t as Ni}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"}},be=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Fe=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 Bt(e){try{return await e()}catch(t){throw t instanceof P?new y(t.message,_.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Jc(e){try{return await e()}catch(t){throw t instanceof be?new y(t.message,_.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as jf}from"node:crypto";import Uf 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 Ht=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 Kc=1,bt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],to=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],zf=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Wf=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Tr=30,$r=5e3,Yc=4,qf=50;function Ve(e,t){if(!Wf.test(e))throw new P(`${t} must be a stable lowercase id`)}function Bf(e,t){if(!Number.isFinite(e)||e<0)throw new P(`${t} must be a finite non-negative number`)}function vn(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 ro(e,t){return X(e)===X(t)}function Xc(e,t){if(t.polarity==="equals")return ro(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 Zc(e){let t=vn(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>Xc(r.observed,t)===(r.expected==="pass"))}function Hf(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!ro(e.value,t.value)}function Gf(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||X(e.scope)!==X(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Hf(vn(e),vn(t))||n[t.enforcement]<n[e.enforcement]||r}function Jf(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 Vf(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 Kf(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 io(e){Ve(e.id,"measurement.id"),e.max_cost!==void 0&&Bf(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 ${to.join(", ")}`);let n=Reflect.get(t,"kind");if(!to.includes(n))throw new P(`measurement.source.kind must be one of ${to.join(", ")}`);let r=t;if(r.kind==="items"&&Jf(r),r.kind==="dependency_kind"&&Vf(r),r.kind==="prose_edge_gap"&&Kf(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"&&(Ve(r.provider,"provider source provider"),Ve(r.key,"provider source key")),e}function oo(e){if(Ve(e.id,"assertion.id"),Ve(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=vn(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"&&Ve(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(!Zc(e))throw new P(`assertion ${e.id} negative control does not prove its bound`);return e}function Yf(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)Ve(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(!bt.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 Qc(e){if(Ve(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)Ve(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new P(`gate.triggers is required and must be an array of ${bt.join(", ")}`);if(e.triggers.length===0)throw new P("gate requires at least one trigger");for(let t of e.triggers)if(!bt.includes(t))throw new P(`gate trigger must be one of ${bt.join(", ")}`);return e.provider_policy&&Yf(e.provider_policy),e}function Gt(e){if(e.version!==Kc)throw new P(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(io(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(oo(r),t.has(`assertion:${r.id}`))throw new P(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){Qc(r);let i=r.assertion_ids.filter(o=>!e.assertions.some(a=>a.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 ed(e))if(!n.has(r))throw new P(`${i.join(", ")} references missing measurement ${r}`);return e}function ao(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)ao(n,t)}function ed(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=[];ao(r.source.expression,i);for(let o of i)n(o,`derived measurement ${r.id}`)}return t}function Xf(e,t){let n=e.assertion_ids.flatMap(o=>{let a=t.assertions.find(s=>s.id===o);return[a.measurement_id,...a.scope.kind==="filter"?[a.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 a=t.measurements.find(s=>s.id===o);a.source.kind==="provider"?i.add(a.source.provider):a.source.kind==="derived"&&ao(a.source.expression,n)}return i}function bn(){return{version:Kc,measurements:[],assertions:[],gates:[]}}function Zf(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 ro(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Qf(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 eh(e,t){let n=[],r=Mi(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let o of i.dependencies??[]){let a=Mi(o.kind)??o.kind.trim().toLowerCase(),s=o.source_kind?.trim();a===r&&Qf(e,s)&&n.push(`${i.id}->${o.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function th(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 nh(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 no(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function rh(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 a of e){t.set(a.id.toLowerCase(),a.id);for(let s of a.dependencies??[])n.add(no(a.id,s.id));for(let s of[a.parent,a.blocked_by])typeof s=="string"&&n.add(no(a.id,s));for(let s of th(a)){let c=[...s.matchAll(i)].map(d=>d[0]);o+=c.length,r.push({holder_id:a.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:o}}function ih(e,t){let n=rh(t.items),r=new Map;for(let a of n.prose_mentions){let s=a.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==a.holder_id),c=[...new Set(s)];for(let d of c){let l=no(a.holder_id,d);if(n.linked_pairs.has(l)||nh(e.exemptions??[],a.holder_id,d,a.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${a.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],o=i.map(a=>a.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(a=>a.explicit).length,implicit_subject:i.filter(a=>!a.explicit).length}}}function oh(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 ah(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 sh(e,t){let n=e.source;return n.kind==="items"?Zf(n,t):n.kind==="dependency_kind"?eh(n,t):n.kind==="prose_edge_gap"?ih(n,t):n.kind==="history"?oh(n,t):n.kind==="links"?ah(n,t):null}function td(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 ch(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 nd(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 a=i;i+=1,r[a]=await n(e[a],a)}});return await Promise.all(o),r}async function rd(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let a=n.find(d=>d.id===e.measurement);if(!a)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await id(a,t,n,r,i);if(typeof s.value!="number")throw new TypeError(`derived measurement ${a.id} is not numeric`);let c=i.charged.has(a.id)?[]:[s.cost];return i.charged.add(a.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let o=await nd(e.operands,Yc,a=>rd(a,t,n,r,i));return{value:ch(e.operator,o.map(a=>a.value)),costs:o.flatMap(a=>a.costs),population_size:Math.max(0,...o.map(a=>a.population_size)),contributors:[...new Set(o.flatMap(a=>a.contributors))]}}async function dh(e,t,n,r,i){io(e);let o=Date.now(),a,s=[],c=0;if(e.source.kind==="derived"){let u=await rd(e.source.expression,t,n,[...r,e.id],i);a={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=sh(e,t);u!==null?a=u:(a=await t.external(e.source),c=1)}let d={units:a.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-o},l=td([...s,d],Date.now()-o);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new be(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${jf("sha256").update(X(e)).digest("hex")}`,value:a.value,population_size:a.population_size,cost:l,contributors:a.contributors??[],...a.partitions?{partitions:a.partitions}:{}}}function id(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 a=dh(e,t,n,r,i).catch(s=>{if(s instanceof Fe&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new Fe(s.message,c);throw d.cause=s,d}throw s});return i.cache.set(e.id,a),a}async function so(e,t,n=[e]){return id(e,t,n,[],{cache:new Map,charged:new Set})}function lh(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 uh(e,t,n={}){oo(e);let r=vn(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:lh(t.value,r),verdict:i?"retired":Xc(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Zc(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function mh(e,t,n,r){let i=Xf(e,t);if(i.size===0)return;let o=e.provider_policy,a=o?.triggers[r];if(!o||!a)throw new be(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let s=new Set(o.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!s.has(d))throw new be(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new be(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[a.max_cost_class])throw new be(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!a.allow_network)throw new be(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function Vc(e,t,n,r,i){try{return await so(n,r,i)}catch(o){if(o instanceof Fe){let a=o.check?` check ${o.check}`:"",s=o.measurement_id??n.id,c=new be(`assurance gate ${e} assertion ${t} measurement ${s} source ${o.source_kind}${a} field ${o.field} could not resolve: ${o.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}});throw c.cause=o,c}throw o}}async function od(e,t,n,r){Gt(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new be(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new be(`assurance gate ${e} does not declare trigger ${r.trigger}`);mh(i,t,n,r.trigger);let o=await nd(i.assertion_ids,Yc,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(v=>v.id===p),g=await Vc(i.id,d.id,h,n,t.measurements),w=new Set(g.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return uh(d,await Vc(i.id,d.id,l,u,t.measurements),{owner_terminal:f})}),a=o.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=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:a?"block":s?"warn":"pass",exit_code:a?1:0,assertions:o,assertions_total:o.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:td(o.map(c=>c.cost),Math.max(0,...o.map(c=>c.cost.duration_ms)))}}function Or(e){return Uf.join(e,"assurance.json")}async function ad(e){let t=await Y(Or(e));return t===null?bn():Dr(t)}function Dr(e){try{return Gt(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",_.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 Pr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function ph(e,t){e==="measurement"?io(t):e==="assertion"?oo(t):Qc(t)}async function kn(e,t){let n=structuredClone(Pr(await ad(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function co(e,t,n){let r=Pr(await ad(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Nr(e,t,n,r={}){ph(t,n);let i=await C(e),o=J(r.author,i.author_default),a=await vr({pmRoot:e,filePath:Or(e),op:`assurance:${t}:put`,author:o,message:r.message,lockTtlSeconds:Tr,lockWaitMs:$r,mutate:s=>{let c=s===null?bn():Dr(s),d=Pr(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&Gf(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),Gt(c),{raw:`${JSON.stringify(c,null,2)}
2
- `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...a.result,changed:a.changed}}async function lo(e,t,n={}){let r=bn();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),Gt(r);let i=await C(e),o=J(n.author,i.author_default),a=await vr({pmRoot:e,filePath:Or(e),op:"assurance:bundle:apply",author:o,message:n.message,lockTtlSeconds:Tr,lockWaitMs:$r,mutate:s=>{let c=s===null?bn():Dr(s),d=[],l=[],u=(m,f,p)=>{for(let h of f){let g=m.find(w=>w.id===h.id);if(!g){m.push(structuredClone(h)),d.push(`${p}:${h.id}`);continue}if(X(g)!==X(h))throw new P(`assurance bundle refuses to replace divergent ${p} ${h.id}`);l.push(`${p}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),Gt(c),{raw:`${JSON.stringify(c,null,2)}
3
- `,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...a.result,changed:a.changed}}async function sd(e,t,n,r={}){let i=await C(e),o=J(r.author,i.author_default),a=await vr({pmRoot:e,filePath:Or(e),op:`assurance:${t}:remove`,author:o,message:r.message,lockTtlSeconds:Tr,lockWaitMs:$r,mutate:s=>{let c=s===null?bn():Dr(s);if(t==="measurement"){let u=ed(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=Pr(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),Gt(c),{raw:`${JSON.stringify(c,null,2)}
4
- `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...a.result,changed:a.changed}}async function cd(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await C(e);await wr({pmRoot:e,op:"assurance:gate:verdict",author:J(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Tr,lockWaitMs:$r})}async function dd(e,t={}){let n=t.limit??qf;if(!Number.isInteger(n)||n<1||n>Ht)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${Ht}`);return(await Lt(yr(e),fe)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="05c29627-6763-5aee-8579-71e563a98780")}catch{}})();var xn=["software-delivery","research","agent-evaluation","operations"];function ld(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 Mr(e,t,n,r,i){let o=`preset-${e}`,a=i.map(c=>({id:`${o}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),s=a.map(c=>ld(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:a,assertions:s,gates:[{id:`${o}-readiness`,description:n,assertion_ids:s.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Lr(e,t){return e==="software-delivery"?Mr(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Mr(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Mr(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Mr(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function ud(e,t,n,r={}){return lo(e,Lr(t,n).declarations,r)}async function md(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 a={id:`derived-active-missing-${o}`,description:`Observed active items missing ${o} evidence.`,source:{kind:"links",link:o,state:"missing"}},c=(await so(a,r)).value,d=ld(`${a.id}-ceiling`,a.id,t,c,"observe"),l=`active-missing-${o}`;return{id:l,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[a],assertions:[d],gates:[{id:`derived-${l}`,description:`Observe the accepted ${o} evidence baseline.`,assertion_ids:[d.id],triggers:["ci","scheduled"]}]}}}))}function pd(e,t,n={}){return lo(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 fd(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 Nr(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import _d from"node:fs/promises";import{createRequire as fh}from"node:module";import ke 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 hd(e,t){let n=ke.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${ke.sep}`)&&!ke.isAbsolute(n))return n.split(ke.sep).join("/");let r=ke.resolve(e),i=0xcbf29ce484222325n;for(let a=0;a<r.length;a+=1)i^=BigInt(r.charCodeAt(a)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${ke.basename(ke.dirname(e))}/package.json`}function hh(e){return e.includes(`${ke.sep}.pnpm${ke.sep}`)?"pnpm":e.includes(`${ke.sep}node_modules${ke.sep}`)?"npm":"other"}async function gd(e){try{let t=JSON.parse(await _d.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 uo(e){try{return await _d.realpath(e)}catch{return ke.resolve(e)}}async function yd(e,t,n=Ee(import.meta.url,["../../.."])){let r=await uo(t),i=await uo(ke.join(n,"package.json")),o=await gd(i),a=new Map;o!==void 0&&a.set(i,{version:o,path:hd(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=fh(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await uo(l),m=await gd(u);if(m===void 0)continue;let f=u,p=a.get(f);if(p){p.consumers.includes(d.name)||(p.consumers.push(d.name),p.consumers.sort((h,g)=>h.localeCompare(g)));continue}a.set(f,{version:m,path:hd(u,r),layout:hh(u),consumers:[d.name]})}catch{}let s=[...a.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=o===void 0?[]:s.filter(d=>d.version!==o);return{host_version:o??null,copies:s,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${o}:${d.version}:${d.consumers.join("+")}`)}}import{createHash as Td}from"node:crypto";import Sn from"node:fs/promises";import En from"node:path";import{Option as MR}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 gh(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(a=>typeof a=="string"))return;r.has(o)||(r.add(o),n.push(...o))}}return n.length>0?n.join("; "):void 0}function Fr(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function M(e,t){return e[t]===!0?!0:void 0}function Ke(e,t){return e[t]===!1?!0:void 0}function wd(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function vd(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function bd(e){let t=i=>Fi(e,Fr(mr,i)),n=i=>$s(e,Fr(Bi,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:gh(e,Fr(Bi,"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:wd(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:M(e,"replaceDeps"),replaceTests:M(e,"replaceTests"),replaceFiles:M(e,"replaceFiles"),replaceDocs:M(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:M(e,"clearDeps"),clearComments:M(e,"clearComments"),clearNotes:M(e,"clearNotes"),clearLearnings:M(e,"clearLearnings"),clearFiles:M(e,"clearFiles"),clearTests:M(e,"clearTests"),clearDocs:M(e,"clearDocs"),clearReminders:M(e,"clearReminders"),clearEvents:M(e,"clearEvents"),clearTypeOptions:M(e,"clearTypeOptions")};return vd(r,e),r}function ee(e,t){let n=Fr(Ts,t),r=Fi(e,n);if(r!==void 0)return r;for(let i of n.keys){let o=e[i];if(Array.isArray(o)){let a=o.filter(s=>typeof s=="string");if(a.length>0)return a.join(",")}if(t==="ids"&&typeof o=="string")return o;if(typeof o=="number"&&Number.isFinite(o))return String(o)}}function _h(e){let t=M(e,"filterFilesMissing"),n=M(e,"filterDocsMissing");return{filterReviewerMissing:M(e,"filterReviewerMissing"),filterRiskMissing:M(e,"filterRiskMissing"),filterConfidenceMissing:M(e,"filterConfidenceMissing"),filterSprintMissing:M(e,"filterSprintMissing"),filterReleaseMissing:M(e,"filterReleaseMissing"),hasNotes:M(e,"hasNotes"),hasLearnings:M(e,"hasLearnings"),hasFiles:M(e,"hasFiles"),hasDocs:M(e,"hasDocs"),hasTests:M(e,"hasTests"),hasComments:M(e,"hasComments"),hasDeps:M(e,"hasDeps"),hasBody:M(e,"hasBody"),hasLinkedCommand:M(e,"hasLinkedCommand"),noNotes:Ke(e,"notes"),noLearnings:Ke(e,"learnings"),noFiles:Ke(e,"files")??t,filterFilesMissing:t,noDocs:Ke(e,"docs")??n,filterDocsMissing:n,noTests:Ke(e,"tests"),noComments:Ke(e,"comments"),noDeps:Ke(e,"deps"),emptyBody:M(e,"emptyBody"),noLinkedCommand:Ke(e,"linkedCommand")}}function kd(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:M(e,"today"),recent:M(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:Ke(e,"truncate"),includeBody:M(e,"includeBody"),strictRead:M(e,"strictRead"),compact:M(e,"compact"),brief:M(e,"brief"),full:M(e,"full"),fields:ee(e,"fields"),sort:ee(e,"sort"),order:ee(e,"order"),tree:M(e,"tree"),treeDepth:ee(e,"treeDepth"),filterAcMissing:M(e,"filterAcMissing"),filterEstimatesMissing:wd(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:M(e,"filterResolutionMissing"),filterMetadataMissing:M(e,"filterMetadataMissing"),..._h(e)};return vd(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]="7949205a-ab1b-5457-961c-593498aff88b")}catch{}})();var yh=Symbol("pm.mcp-mutation-transport");function po(e){return yh in e}function Ur(e,t){return po(e)?Ec(t):Ki(e,t)}function JR(e,t,n=[]){let r=Ki(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 VR(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Jt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ho(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new y(`${t} must be a finite integer.`,_.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new y(`${t} must be a finite integer.`,_.USAGE);return n}}function KR(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 YR(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 wh=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Sd=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"]),vh=new Set([...Sd].filter(e=>e!=="file")),bh=new Set(["files","files-discover","docs","test","test-all"]),Ed=new Set(["comments","notes","learnings"]);function kh(e,t){if(!(!Ed.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new y(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,_.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var xh=new Set(["claim","release","start-task","pause-task","close-task"]),Sh={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"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Eh=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Ad(e,t=""){let n={},r=bh.has(t),i=t==="files"||t==="files-discover"||t==="docs",o=Ed.has(t)?vh:Sd;for(let[a,s]of Object.entries(e)){if(Array.isArray(s)&&wh.has(a)){n[a]=s.join(",");continue}if(a==="note"&&i){n[a]=s;continue}if(typeof s=="string"&&o.has(a)){n[a]=[s];continue}if(typeof s=="string"&&r&&(a==="add"||a==="remove")){n[a]=[s];continue}n[a]=s}return n}function Ah(e,t,n){let r=$(e,"author");return r!==void 0?r:n!==void 0&&xh.has(n)?$(e,"assignee")??$(t,"assignee"):void 0}function Rh(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function XR(e,t){let n=Jt(e.options)?e.options:void 0,r=xs(e.options),i={},o=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of Sh[t??""]??[])o(c);for(let c of Eh)o(c);t!==void 0&&po(e)&&kh(t,r);let a=Ad({...i,...r},t),s=po(e)?e:n??e;return Ur(s,Rh(a,Ah(e,a,t)))}function ZR(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 QR(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 eI(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 tI(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function go(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function nI(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[o,a]of Object.entries(e))n.has(o)||(r[o]=a);let i={...r,...t};return delete i.args,i}function rI(e,t){let n=Ur(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function fo(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:Yi(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 mo(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return go(e)}function jr(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function iI(e){let t=mo(e.kind),n=mo(e.exemptIsolate),r=mo(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:jr(e.maxDepth),limit:jr(e.limit),after:$(e,"after"),direction:$(e,"direction"),maxPaths:jr(e.maxPaths),sample:jr(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 Rd(e){let t=kd(e);return e.ids!==void 0&&(t.ids=Yi(e.ids)),t}function oI(e){return{status:$(e,"filterStatus"),list:Jt(e.list)?Rd(e.list):fo(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 Ih=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 xd(e){let t={};for(let[n,r]of Object.entries(e))Ih.has(n)||(t[n]=r);return Id(t)}function Id(e){let t=Ad(e,"update-many");for(let n of mr)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return bd(t)}function aI(e){if(Jt(e.list)||Jt(e.update)){let t=Jt(e.update)?e.update:xd(e),n=Ur(e,Id(t));return{status:re(e,"filterStatus"),list:Jt(e.list)?Rd(e.list):fo(e),update:Ac(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:fo(e),update:Ur(e,xd(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 Re(e,t){throw new y(e,_.USAGE,t)}var Ch="2026-07-15T06:22:12.276Z",Th=Date.parse(Ch),$h=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Cd=e=>typeof e=="string"?e:"",$d=e=>{let t=e??{},n=Cd(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Cd(t.ts))>=Th);return $h[r][i]};function Od(e,t,n=20,r=new Set,i=!1){let o=[],a=[],s={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}d+=1;let h=$d(p);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}s[h]+=1,i&&h==="actionable_unknown"&&a.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:s.legacy_unknown,actionable_unknown_event_count:s.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:s.legacy_unknown+s.actionable_unknown>o.length,actionable_events:a}}var gI=(e,t,n=20,r=new Set)=>Od(e,t,n,r);function Dd(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 a of o.events)typeof a=="object"&&a!==null&&typeof a.item_id=="string"&&Number.isSafeInteger(a.line)&&t.add(`${a.item_id}:${String(a.line)}`)}return t}var An=async(e,t=20,n=!1)=>{let r=En.join(e,"history"),i;try{i=(await Sn.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let o=new Set,a=[],s=[],c=0,d=0,l=0,u=0,m=0,f=0,p="_workspace.jsonl",h=new Set;if(i.includes(p))try{h=Dd(await Sn.readFile(En.join(r,p),"utf8"))}catch{h=new Set}for(let w of i){let v;try{v=await Sn.readFile(En.join(r,w),"utf8")}catch{continue}let x=w.slice(0,-6),S=Od(x,v,t-a.length,h,n);c+=1,d+=S.checked_events,l+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,f+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&o.add(x),a.push(...S.samples),n&&s.push(...S.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:f,affected_item_ids:[...o].sort((w,v)=>w.localeCompare(v)),samples:a,samples_truncated:g>a.length,...n?{actionable_events:s}:{}}};function Oh(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 Dh(e){try{return Dd(await Sn.readFile(En.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function Ph(e){return(e.item_id===fe||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function Nh(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Re(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return $d(i)!=="actionable_unknown"&&Re(`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:Td("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Pd(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Re("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Re("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Re("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let o=Oh(t.all_actionable===!0?(await An(e,0,!0)).actionable_events:r),a=await Dh(e),s=new Map;for(let m of o)if(Ph(m)||Re(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!s.has(m.item_id))try{s.set(m.item_id,(await Sn.readFile(En.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Re(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=o.map(m=>Nh(m,a,s.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Td("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 _I(e,t,n=50){return(await Pd(e,t,n)).plan}function Mh(e,t){let n=e.length>0;return n&&t&&Re("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&&Re("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:Lh(e),all_actionable:t}}function Lh(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),o=r===fe||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!o||!Number.isSafeInteger(i)||i<1)&&Re(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function yI(e,t){let n=Mh(go(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Fh(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 Fh(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",o=await Pd(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:_.SUCCESS,plan:o.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Re("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Re("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==o.plan.plan_fingerprint)throw new y("Author acknowledgment selection changed after preview; no history was mutated.",_.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let s=o.completeCoordinates.filter(({disposition:u})=>o.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:m})=>({item_id:u,line:m}));if(s.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:_.NO_EFFECT,plan:o.plan};let c=await C(e),d=await wr({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:s,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:_.PARTIAL_EFFECT}:{outcome:"effect",exit_code:_.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:s.length,...l,plan:o.plan,history_path:d.historyPath}}import _o from"node:fs/promises";import yo 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 jh=8388608,Uh=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 je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wo(e){return zh.find(t=>t.matches(e))?.kind}function Nd(e){let t=new Map,n=0,r=0;return{entries:e.map(o=>{let a=je(o.agent_provenance)?o.agent_provenance:void 0;if(a===void 0)return o;let s={},c=!1;for(let[l,u]of Object.entries(a)){let m=je(u)?wo(u.value):void 0;if(m===void 0){s[l]=u;continue}c=!0,r+=1;let f=o.agent_harness??"unknown",p=`${f}\0${l}\0${m}`,h=t.get(p)??{harness:f,dimension:l,kind:m,count:0};h.count+=1,t.set(p,h)}if(!c)return o;n+=1;let d={...o};return Object.keys(s).length===0?delete d.agent_provenance:d.agent_provenance=s,d}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((o,a)=>o.harness.localeCompare(a.harness)||o.dimension.localeCompare(a.dimension)||o.kind.localeCompare(a.kind))}}}async function Md(e){let t=[];for(let n of await Ld(e))try{let r=await _o.readFile(yo.join(e,"history",n),"utf8");for(let i of r.split(`
5
- `)){if(i.trim().length===0)continue;let o=Fd(i);if(o===null||!je(o.agent_provenance))continue;if(Object.values(o.agent_provenance).some(s=>je(s)&&wo(s.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Ld(e){try{return(await _o.readdir(yo.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function Wh(e,t,n){let r;try{r=await _o.open(yo.join(e,"history",t),"r");let i=(await r.stat()).size,o=Math.min(i,Math.max(0,n)),a=Buffer.alloc(o),{bytesRead:s}=await r.read(a,0,o,0),c=a.subarray(0,s).toString("utf8"),d=s>=i,l=c.lastIndexOf(`
6
- `),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:s,complete:d}}catch{return null}finally{await r?.close()}}function Fd(e){try{let t=JSON.parse(e);return je(t)?t:null}catch{return null}}function qh(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=je(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([a,s])=>{if(!je(s))return;let c=wo(s.value);if(!c)return;let d=`${r}\0${a}\0${c}`,l=n.get(d)??{harness:r,dimension:a,kind:c,count:0};l.count+=1,n.set(d,l)}),!je(e.context))return;let o=e.context.agent_provenance_outcomes;je(o)&&Object.entries(o).forEach(([a,s])=>{if(!je(s)||typeof s.resolver!="string"||!Uh.has(String(s.status)))return;let c=`${r}\0${a}\0${s.resolver}`,d=t.get(c)??{harness:r,dimension:a,resolver:s.resolver,attempts:0,successes:0};d.attempts+=1,s.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function Bh(e,t,n,r,i){let o=i;for(let a of e.split(`
7
- `)){if(a.trim().length===0)continue;if(o>=r)return{eventsRead:o,truncated:!0};o+=1;let s=Fd(a);s&&qh(s,t,n)}return{eventsRead:o,truncated:!1}}async function jd(e,t=1e4){let n=new Map,r=new Map,i=0,o=0,a=!1;for(let d of await Ld(e)){let l=await Wh(e,d,Math.max(0,jh-o));if(l===null)continue;o+=l.bytesRead;let u=Bh(l.content,n,r,t,i);if(i=u.eventsRead,u.truncated){a=!0;break}if(!l.complete){a=!0;break}}let s=[...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:s,invalid_values:c,warnings:a?[]:[...s.filter(d=>d.attempts>0&&d.successes===0).map(d=>`provenance_resolver_zero_success:${d.harness}:${d.dimension}:${d.resolver}:${String(d.attempts)}`),...c.map(d=>`provenance_value_domain_invalid:${d.harness}:${d.dimension}:${d.kind}:${String(d.count)}`)],events_read:i,truncated:a}}import et from"node:fs/promises";import ge from"node:path";import Vt from"node:fs/promises";import{createHash as Hh}from"node:crypto";import zd from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32538934-2cbb-50fe-b721-ad9197cef7d8")}catch{}})();var Wd=4,Gh="history-drift-cache.json";function qd(e){return zd.join(e,"runtime",Gh)}async function Jh(e){try{let t=await Vt.readFile(qd(e),"utf8"),n=JSON.parse(t);return n.version!==Wd||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}async function Vh(e,t,n,r,i){let o=yr(e),a;try{a=await Vt.stat(o)}catch(d){return U(d)||i.unreadableStreams.push(fe),!1}let s=i.missingStreams.length,c=await Hd({itemId:fe,historyPath:o,stat:a,cached:t[fe],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.chainOk||i.chainMismatches.push(fe),n[fe]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(i.missingStreams.splice(s),c.cacheDirty)}function Bd(e){return Hh("sha256").update(e).digest("hex")}async function Kh(e){let t=await Vt.readFile(e,"utf8");return Bd(t)}async function Yh(e){let t=await Vt.readFile(e,"utf8"),n=Bd(t);if(t.trim().length===0)return null;let r=[],i=null;for(let a of t.split(/\r?\n/)){let s=a.trim();if(s.length===0)continue;let c=JSON.parse(s);if(typeof c.after_hash!="string"||c.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(c),i=c.after_hash}if(!i)return null;let o=_r(r);return{latestAfterHash:i,chainOk:o.ok,contentHash:n,itemHashVersion:o.item_hash_version??Gi}}function Xh(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Ud(e,t,n){try{let r=await Yh(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Hd(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Xh(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Ud(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await Kh(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else r=t;return!e.verifyCacheHitByContent||r===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:r,itemHashVersion:e.cached.item_hash_version??Gi},cacheDirty:!1}:{verification:await Ud(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function Zh(e,t,n,r){let i=ir(e,t.id),o;try{o=await Vt.stat(i)}catch(l){return(U(l)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let a=await Hd({itemId:t.id,historyPath:i,stat:o,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!a.verification)return a.cacheDirty;a.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:a.verification.contentHash,latest_after_hash:a.verification.latestAfterHash,chain_ok:a.verification.chainOk,item_hash_version:a.verification.itemHashVersion};let{body:s,...c}=t;return oc({metadata:c,body:s},a.verification.itemHashVersion)!==a.verification.latestAfterHash&&r.hashMismatches.push(t.id),a.cacheDirty}async function Qh(e,t){if(!(t.unreadableStreams.includes(fe)||t.chainMismatches.includes(fe)))try{let n=await uc(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(fe)}}async function Kt(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},o=(await Jh(e))?.entries??{},a={},s=!1,c=n.cacheHitVerification!=="metadata",d={previousEntries:o,nextEntries:a,verifyCacheHitByContent:c};for(let m of t)await Zh(e,m,d,r)&&(s=!0);let l=await Vh(e,o,a,c,r);if(s||=l,await Qh(e,r),s||Object.keys(o).length!==Object.keys(a).length){let m=qd(e);try{await Vt.mkdir(zd.dirname(m),{recursive:!0}),await se(m,JSON.stringify({version:Wd,entries:a}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[fe]:[]])].sort((m,f)=>m.localeCompare(f));return{...r,driftedItems:u}}import Rn from"node:fs/promises";import zr 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 eg(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:a}=n;return typeof r!="string"||typeof i!="string"||typeof o!="string"||typeof a!="number"||!Number.isFinite(a)?null:{id:r,owner:i,created_at:o,ttl_seconds:a}}function Gd(e,t,n){let r=eg(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,a=Math.floor(o/1e3),s=o>r.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:a,stale:s,reason:s?"expired":"active"}}}async function Jd(e,t){let n=t??Date.now(),r=zr.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 Rn.readdir(r)).filter(s=>s.endsWith(".lock")).sort()}catch(a){if(U(a))return i;throw a}for(let a of o){let s;try{s=await Rn.readFile(zr.join(r,a),"utf8")}catch(d){if(U(d))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=Gd(a,s,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function Vd(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=zr.join(e,"locks"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await Rn.readdir(o)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if(U(c))return a;throw c}for(let c of s){a.scanned+=1;let d=zr.join(o,c),l=`locks/${c}`;if(r?.onRead){let f=await r.onRead(d);a.warnings.push(...f)}let u;try{u=await Rn.readFile(d,"utf8")}catch(f){if(U(f)){a.scanned-=1;continue}a.warnings.push(`lock_unreadable:${c}`),a.retained.push(l),a.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=Gd(c,u,i);if(m.detail==="unparseable_json"){a.warnings.push(`lock_unparseable:${c}`),a.retained.push(l),a.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){a.warnings.push(`lock_invalid_timestamp:${c}`),a.retained.push(l),a.entries.push(m.entry);continue}if(m.detail==="active"){a.retained.push(l),a.entries.push(m.entry);continue}if(!n){try{await Rn.unlink(d)}catch(f){if(!U(f)){a.warnings.push(`lock_remove_failed:${c}`),a.retained.push(l),a.entries.push(m.entry);continue}}if(r?.onWrite){let f=await r.onWrite(d);a.warnings.push(...f)}}a.removed.push(l),a.entries.push(m.entry)}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c088607b-1be3-54c8-a38b-79c188924102")}catch{}})();var tg=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 --dry-run",summary:"A lossless merge receipt is still pending; preview and run pm merge reconcile 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_merge_receipt",command:"pm merge reconcile --dry-run",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; preview reconciliation 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_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 vo(e){if(typeof e!="string")return;let t=e.trim();for(let n of tg)if(t===n.code||t.startsWith(`${n.code}:`))return n}function bo(e){let t={};for(let n of e){let r=vo(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Kd(e){return Object.values(bo(e))}import mt from"node:fs/promises";import Ie 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 ng=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Yt(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(ur(t.extensionName));for(let g of t.extensionNames??[])n.add(ur(g));let r=g=>n.size===0||n.has(ur(g)),i=(g,w)=>Yd(g.filter(v=>r(v.name)).map(w)),o=(g,w)=>Yd(g.filter(v=>r(v.name)).flatMap(w)),{registrations:a,commands:s,parsers:c,preflight:d,services:l,renderers:u,hooks:m}=e,f=o(a.relationship_kinds??[],g=>g.definitions.map(w=>w.kind)),p=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,w)=>g.format.localeCompare(w.format)),h=i(a.assurance_providers??[],g=>g.definition.id);return{capabilities:Js(e,t),commands:i(a.commands,g=>g.command),command_overrides:i(s.overrides,g=>g.command),command_handlers:i(s.handlers,g=>g.command),hooks:ng.filter(([g])=>m[g].some(w=>r(w.name))).map(([,g])=>g),flag_commands:i(a.flags,g=>g.target_command),item_types:o(a.item_types,g=>g.types.map(w=>w.name)),item_fields:o(a.item_fields,g=>g.fields.map(w=>w.name)),...f.length>0?{relationship_kinds:f}:{},migrations:o(a.migrations,g=>typeof g.definition.id=="string"?[g.definition.id]:[]),profiles:i(a.profiles,g=>g.profile.name),importers:i(a.importers,g=>g.importer),exporters:i(a.exporters,g=>g.exporter),search_providers:i(a.search_providers,g=>g.definition.name),vector_store_adapters:i(a.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),...p.length>0?{renderer_ownership:p}:{},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 Yd(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import r_ from"node:path";import{mkdir as i_}from"node:fs/promises";import{readFile as qr,realpath as Eo,writeFile as dg}from"node:fs/promises";import{execFile as lg}from"node:child_process";import ie from"node:path";import{promisify as ug}from"node:util";import{readFile as rg,writeFile as ig}from"node:fs/promises";import In 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 Zd="# pm-cli:runtime-cache:start",ko="# pm-cli:runtime-cache:end",Qd=".agents/pm",xo=["runtime/","search/","locks/","transactions/","checkpoints/"],og=["search/eval-queries.json"];async function Xd(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 y("The workspace .gitignore is not writable.",_.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 el(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function So(e){let t=e.replaceAll("\\","/");return In.isAbsolute(e)||t===".."||t.startsWith("../")}function ag(e=Qd){let t=el(e);return[Zd,...xo.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...og.map(n=>`!${t}/${n}`),ko].join(`
8
- `)}async function BI(e,t={}){let n=In.join(e,".gitignore"),r=Qd;if(t.pmRoot!==void 0){let l=el(In.relative(In.resolve(e),In.resolve(t.pmRoot)));if(So(l))return{path:n,changed:!1};l.length>0&&(r=l)}let i="";try{i=await Xd(()=>rg(n,"utf8"))}catch(l){if(!(l instanceof Error&&"code"in l&&U(l)))throw l}let o=i.indexOf(Zd),a=i.indexOf(ko),c=(o>=0&&a>=o?`${i.slice(0,o)}${i.slice(a+ko.length)}`:i).trimEnd(),d=`${c.length>0?`${c}
1
+ import{a as ji,c as ir,d as or,e as Ls,g as Fs,h as zi,i as js,j as $t,k as Ot,l as Us,m as zs,n as Wi,o as qs,p as Dt,q as Pt,r as Bs,s as Hs,t as qi}from"./chunk-Y3JJXRVK.js";import{e as ur,f as Bi}from"./chunk-THEPQMLX.js";import{C as dr,a as Ts,g as Fi,i as $s}from"./chunk-LYFWQMVC.js";import{P as Gc}from"./chunk-FC2AXLB5.js";import{$ as Xi,A as Ac,E as Rc,I as Yi,J as Sr,La as Uc,Ma as Rr,Qa as zc,Ra as Wc,Sa as qc,Ua as eo,Z as Er,_ as Ic,aa as yn,ca as Zi,e as yc,f as wc,g as vc,ga as Cc,ha as Tc,ia as $c,ja as Oc,ka as Ar,m as bc,ma as Dc,n as kc,na as Pc,o as xc,oa as Nc,pa as vt,qa as Mc,ra as Wt,sa as Lc,ta as Qi,u as gn,ua as qt,v as Sc,va as Fc,w as _n,wa as jc,x as Ec,z as Ki}from"./chunk-YVVZ3LQ6.js";import{a as Ds,b as ar,c as Ui,d as Ps,e as Ns,f as He,g as sr,h as Ms,i as at}from"./chunk-HVQ22RC4.js";import{$ as Hi,$a as yr,Ab as Ut,Bb as Je,Ca as ic,Cb as zt,Ea as Gi,Ga as oc,Gb as wt,Ib as xr,Ma as Ft,Mb as wn,Ob as Ir,Pa as ac,Qa as sc,Sa as gr,Ta as Ji,Ua as cc,Va as dc,Vb as Bc,Wa as lc,Xa as fe,Y as J,Ya as _r,Yb as Hc,Z as T,Za as uc,_ as ec,_a as Vi,ab as wr,b as Xs,bb as vr,cb as mc,d as Zs,da as pe,db as Oe,eb as pc,fb as C,gb as br,ib as fc,ja as tc,ka as fr,l as z,na as hr,nb as hc,o as ne,oa as nc,ob as gc,q as Ge,qa as rc,r as Qs,ra as Nt,s as pr,ta as Mt,tb as kr,vb as _c,wa as Lt,xb as Q,yb as jt,zb as st}from"./chunk-XDPYBQCF.js";import{$a as Vs,A as _s,Ca as Li,Da as Is,Ea as Cs,F as ys,Fa as Tt,G as ws,H as B,Ha as Ne,Ja as Me,La as ce,M as hn,Ma as Ae,N as L,O as Pe,Oa as ve,P as nr,Pa as Le,Q as yt,S as vs,T as rr,Ta as $e,V as bs,Va as cr,X as Z,Xa as Ws,Za as lr,_ as ks,_a as Js,a as ds,ca as xs,d as ls,e as us,fa as Ss,h as Ct,ha as Mi,p as gs,q as fn,r as D,s as it,t as U,ta as Es,u as Y,ua as As,v as se,y as we,z as Ee}from"./chunk-AD6ULRAF.js";import{a as Ks,b as mr,d as Ys}from"./chunk-6GCRSLPG.js";import{O as ms,Q as ps,S as fs,U as hs,V as tr,Y as _,Z as y,a as Qn,aa as X,ba as Rs,ca as ot,d as er,fa as Os,oa as Gs,t as Ni}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"}},be=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Fe=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 Bt(e){try{return await e()}catch(t){throw t instanceof P?new y(t.message,_.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Jc(e){try{return await e()}catch(t){throw t instanceof be?new y(t.message,_.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as Ff}from"node:crypto";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]="b911b43d-d14d-5e4f-a35e-5020b1a84542")}catch{}})();var Ht=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 Kc=1,bt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],to=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Uf=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],zf=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Cr=30,Tr=5e3,Yc=4,Wf=50;function Ve(e,t){if(!zf.test(e))throw new P(`${t} must be a stable lowercase id`)}function qf(e,t){if(!Number.isFinite(e)||e<0)throw new P(`${t} must be a finite non-negative number`)}function vn(e){let t=Uf.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 ro(e,t){return X(e)===X(t)}function Xc(e,t){if(t.polarity==="equals")return ro(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 Zc(e){let t=vn(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>Xc(r.observed,t)===(r.expected==="pass"))}function Bf(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!ro(e.value,t.value)}function Hf(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||X(e.scope)!==X(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Bf(vn(e),vn(t))||n[t.enforcement]<n[e.enforcement]||r}function Gf(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 Jf(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 Vf(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 io(e){Ve(e.id,"measurement.id"),e.max_cost!==void 0&&qf(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 ${to.join(", ")}`);let n=Reflect.get(t,"kind");if(!to.includes(n))throw new P(`measurement.source.kind must be one of ${to.join(", ")}`);let r=t;if(r.kind==="items"&&Gf(r),r.kind==="dependency_kind"&&Jf(r),r.kind==="prose_edge_gap"&&Vf(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"&&(Ve(r.provider,"provider source provider"),Ve(r.key,"provider source key")),e}function oo(e){if(Ve(e.id,"assertion.id"),Ve(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=vn(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"&&Ve(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(!Zc(e))throw new P(`assertion ${e.id} negative control does not prove its bound`);return e}function Kf(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)Ve(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(!bt.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 Qc(e){if(Ve(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)Ve(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new P(`gate.triggers is required and must be an array of ${bt.join(", ")}`);if(e.triggers.length===0)throw new P("gate requires at least one trigger");for(let t of e.triggers)if(!bt.includes(t))throw new P(`gate trigger must be one of ${bt.join(", ")}`);return e.provider_policy&&Kf(e.provider_policy),e}function Gt(e){if(e.version!==Kc)throw new P(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(io(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(oo(r),t.has(`assertion:${r.id}`))throw new P(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){Qc(r);let i=r.assertion_ids.filter(o=>!e.assertions.some(a=>a.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 ed(e))if(!n.has(r))throw new P(`${i.join(", ")} references missing measurement ${r}`);return e}function ao(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)ao(n,t)}function ed(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=[];ao(r.source.expression,i);for(let o of i)n(o,`derived measurement ${r.id}`)}return t}function Yf(e,t){let n=e.assertion_ids.flatMap(o=>{let a=t.assertions.find(s=>s.id===o);return[a.measurement_id,...a.scope.kind==="filter"?[a.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 a=t.measurements.find(s=>s.id===o);a.source.kind==="provider"?i.add(a.source.provider):a.source.kind==="derived"&&ao(a.source.expression,n)}return i}function bn(){return{version:Kc,measurements:[],assertions:[],gates:[]}}function Xf(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 ro(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Zf(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 Qf(e,t){let n=[],r=Mi(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let o of i.dependencies??[]){let a=Mi(o.kind)??o.kind.trim().toLowerCase(),s=o.source_kind?.trim();a===r&&Zf(e,s)&&n.push(`${i.id}->${o.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function eh(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 th(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 no(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function nh(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 a of e){t.set(a.id.toLowerCase(),a.id);for(let s of a.dependencies??[])n.add(no(a.id,s.id));for(let s of[a.parent,a.blocked_by])typeof s=="string"&&n.add(no(a.id,s));for(let s of eh(a)){let c=[...s.matchAll(i)].map(d=>d[0]);o+=c.length,r.push({holder_id:a.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:o}}function rh(e,t){let n=nh(t.items),r=new Map;for(let a of n.prose_mentions){let s=a.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==a.holder_id),c=[...new Set(s)];for(let d of c){let l=no(a.holder_id,d);if(n.linked_pairs.has(l)||th(e.exemptions??[],a.holder_id,d,a.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${a.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],o=i.map(a=>a.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(a=>a.explicit).length,implicit_subject:i.filter(a=>!a.explicit).length}}}function ih(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 oh(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 ah(e,t){let n=e.source;return n.kind==="items"?Xf(n,t):n.kind==="dependency_kind"?Qf(n,t):n.kind==="prose_edge_gap"?rh(n,t):n.kind==="history"?ih(n,t):n.kind==="links"?oh(n,t):null}function td(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 sh(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 nd(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 a=i;i+=1,r[a]=await n(e[a],a)}});return await Promise.all(o),r}async function rd(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let a=n.find(d=>d.id===e.measurement);if(!a)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await id(a,t,n,r,i);if(typeof s.value!="number")throw new TypeError(`derived measurement ${a.id} is not numeric`);let c=i.charged.has(a.id)?[]:[s.cost];return i.charged.add(a.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let o=await nd(e.operands,Yc,a=>rd(a,t,n,r,i));return{value:sh(e.operator,o.map(a=>a.value)),costs:o.flatMap(a=>a.costs),population_size:Math.max(0,...o.map(a=>a.population_size)),contributors:[...new Set(o.flatMap(a=>a.contributors))]}}async function ch(e,t,n,r,i){io(e);let o=Date.now(),a,s=[],c=0;if(e.source.kind==="derived"){let u=await rd(e.source.expression,t,n,[...r,e.id],i);a={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=ah(e,t);u!==null?a=u:(a=await t.external(e.source),c=1)}let d={units:a.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-o},l=td([...s,d],Date.now()-o);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new be(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${Ff("sha256").update(X(e)).digest("hex")}`,value:a.value,population_size:a.population_size,cost:l,contributors:a.contributors??[],...a.partitions?{partitions:a.partitions}:{}}}function id(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 a=ch(e,t,n,r,i).catch(s=>{if(s instanceof Fe&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new Fe(s.message,c);throw d.cause=s,d}throw s});return i.cache.set(e.id,a),a}async function so(e,t,n=[e]){return id(e,t,n,[],{cache:new Map,charged:new Set})}function dh(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 lh(e,t,n={}){oo(e);let r=vn(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:dh(t.value,r),verdict:i?"retired":Xc(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Zc(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function uh(e,t,n,r){let i=Yf(e,t);if(i.size===0)return;let o=e.provider_policy,a=o?.triggers[r];if(!o||!a)throw new be(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let s=new Set(o.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!s.has(d))throw new be(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new be(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[a.max_cost_class])throw new be(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!a.allow_network)throw new be(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function Vc(e,t,n,r,i){try{return await so(n,r,i)}catch(o){if(o instanceof Fe){let a=o.check?` check ${o.check}`:"",s=o.measurement_id??n.id,c=new be(`assurance gate ${e} assertion ${t} measurement ${s} source ${o.source_kind}${a} field ${o.field} could not resolve: ${o.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}});throw c.cause=o,c}throw o}}async function od(e,t,n,r){Gt(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new be(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new be(`assurance gate ${e} does not declare trigger ${r.trigger}`);uh(i,t,n,r.trigger);let o=await nd(i.assertion_ids,Yc,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(v=>v.id===p),g=await Vc(i.id,d.id,h,n,t.measurements),w=new Set(g.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return lh(d,await Vc(i.id,d.id,l,u,t.measurements),{owner_terminal:f})}),a=o.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=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:a?"block":s?"warn":"pass",exit_code:a?1:0,assertions:o,assertions_total:o.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:td(o.map(c=>c.cost),Math.max(0,...o.map(c=>c.cost.duration_ms)))}}function $r(e){return jf.join(e,"assurance.json")}async function ad(e){let t=await Y($r(e));return t===null?bn():Or(t)}function Or(e){try{return Gt(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",_.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 Dr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function mh(e,t){e==="measurement"?io(t):e==="assertion"?oo(t):Qc(t)}async function kn(e,t){let n=structuredClone(Dr(await ad(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function co(e,t,n){let r=Dr(await ad(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Pr(e,t,n,r={}){mh(t,n);let i=await C(e),o=J(r.author,i.author_default),a=await wr({pmRoot:e,filePath:$r(e),op:`assurance:${t}:put`,author:o,message:r.message,lockTtlSeconds:Cr,lockWaitMs:Tr,mutate:s=>{let c=s===null?bn():Or(s),d=Dr(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&Hf(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),Gt(c),{raw:`${JSON.stringify(c,null,2)}
2
+ `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...a.result,changed:a.changed}}async function lo(e,t,n={}){let r=bn();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),Gt(r);let i=await C(e),o=J(n.author,i.author_default),a=await wr({pmRoot:e,filePath:$r(e),op:"assurance:bundle:apply",author:o,message:n.message,lockTtlSeconds:Cr,lockWaitMs:Tr,mutate:s=>{let c=s===null?bn():Or(s),d=[],l=[],u=(m,f,p)=>{for(let h of f){let g=m.find(w=>w.id===h.id);if(!g){m.push(structuredClone(h)),d.push(`${p}:${h.id}`);continue}if(X(g)!==X(h))throw new P(`assurance bundle refuses to replace divergent ${p} ${h.id}`);l.push(`${p}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),Gt(c),{raw:`${JSON.stringify(c,null,2)}
3
+ `,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...a.result,changed:a.changed}}async function sd(e,t,n,r={}){let i=await C(e),o=J(r.author,i.author_default),a=await wr({pmRoot:e,filePath:$r(e),op:`assurance:${t}:remove`,author:o,message:r.message,lockTtlSeconds:Cr,lockWaitMs:Tr,mutate:s=>{let c=s===null?bn():Or(s);if(t==="measurement"){let u=ed(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=Dr(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),Gt(c),{raw:`${JSON.stringify(c,null,2)}
4
+ `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...a.result,changed:a.changed}}async function cd(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await C(e);await yr({pmRoot:e,op:"assurance:gate:verdict",author:J(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Cr,lockWaitMs:Tr})}async function dd(e,t={}){let n=t.limit??Wf;if(!Number.isInteger(n)||n<1||n>Ht)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${Ht}`);return(await Lt(_r(e),fe)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="05c29627-6763-5aee-8579-71e563a98780")}catch{}})();var xn=["software-delivery","research","agent-evaluation","operations"];function ld(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 Nr(e,t,n,r,i){let o=`preset-${e}`,a=i.map(c=>({id:`${o}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),s=a.map(c=>ld(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:a,assertions:s,gates:[{id:`${o}-readiness`,description:n,assertion_ids:s.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Mr(e,t){return e==="software-delivery"?Nr(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Nr(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Nr(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Nr(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function ud(e,t,n,r={}){return lo(e,Mr(t,n).declarations,r)}async function md(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 a={id:`derived-active-missing-${o}`,description:`Observed active items missing ${o} evidence.`,source:{kind:"links",link:o,state:"missing"}},c=(await so(a,r)).value,d=ld(`${a.id}-ceiling`,a.id,t,c,"observe"),l=`active-missing-${o}`;return{id:l,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[a],assertions:[d],gates:[{id:`derived-${l}`,description:`Observe the accepted ${o} evidence baseline.`,assertion_ids:[d.id],triggers:["ci","scheduled"]}]}}}))}function pd(e,t,n={}){return lo(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 fd(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 Pr(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import _d from"node:fs/promises";import{createRequire as ph}from"node:module";import ke 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 hd(e,t){let n=ke.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${ke.sep}`)&&!ke.isAbsolute(n))return n.split(ke.sep).join("/");let r=ke.resolve(e),i=0xcbf29ce484222325n;for(let a=0;a<r.length;a+=1)i^=BigInt(r.charCodeAt(a)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${ke.basename(ke.dirname(e))}/package.json`}function fh(e){return e.includes(`${ke.sep}.pnpm${ke.sep}`)?"pnpm":e.includes(`${ke.sep}node_modules${ke.sep}`)?"npm":"other"}async function gd(e){try{let t=JSON.parse(await _d.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 uo(e){try{return await _d.realpath(e)}catch{return ke.resolve(e)}}async function yd(e,t,n=Ee(import.meta.url,["../../.."])){let r=await uo(t),i=await uo(ke.join(n,"package.json")),o=await gd(i),a=new Map;o!==void 0&&a.set(i,{version:o,path:hd(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=ph(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await uo(l),m=await gd(u);if(m===void 0)continue;let f=u,p=a.get(f);if(p){p.consumers.includes(d.name)||(p.consumers.push(d.name),p.consumers.sort((h,g)=>h.localeCompare(g)));continue}a.set(f,{version:m,path:hd(u,r),layout:fh(u),consumers:[d.name]})}catch{}let s=[...a.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=o===void 0?[]:s.filter(d=>d.version!==o);return{host_version:o??null,copies:s,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${o}:${d.version}:${d.consumers.join("+")}`)}}import{createHash as Td}from"node:crypto";import Sn from"node:fs/promises";import En from"node:path";import{Option as MR}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 hh(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(a=>typeof a=="string"))return;r.has(o)||(r.add(o),n.push(...o))}}return n.length>0?n.join("; "):void 0}function Lr(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function M(e,t){return e[t]===!0?!0:void 0}function Ke(e,t){return e[t]===!1?!0:void 0}function wd(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function vd(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function bd(e){let t=i=>Fi(e,Lr(ur,i)),n=i=>$s(e,Lr(Bi,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:hh(e,Lr(Bi,"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:wd(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:M(e,"replaceDeps"),replaceTests:M(e,"replaceTests"),replaceFiles:M(e,"replaceFiles"),replaceDocs:M(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:M(e,"clearDeps"),clearComments:M(e,"clearComments"),clearNotes:M(e,"clearNotes"),clearLearnings:M(e,"clearLearnings"),clearFiles:M(e,"clearFiles"),clearTests:M(e,"clearTests"),clearDocs:M(e,"clearDocs"),clearReminders:M(e,"clearReminders"),clearEvents:M(e,"clearEvents"),clearTypeOptions:M(e,"clearTypeOptions")};return vd(r,e),r}function ee(e,t){let n=Lr(Ts,t),r=Fi(e,n);if(r!==void 0)return r;for(let i of n.keys){let o=e[i];if(Array.isArray(o)){let a=o.filter(s=>typeof s=="string");if(a.length>0)return a.join(",")}if(t==="ids"&&typeof o=="string")return o;if(typeof o=="number"&&Number.isFinite(o))return String(o)}}function gh(e){let t=M(e,"filterFilesMissing"),n=M(e,"filterDocsMissing");return{filterReviewerMissing:M(e,"filterReviewerMissing"),filterRiskMissing:M(e,"filterRiskMissing"),filterConfidenceMissing:M(e,"filterConfidenceMissing"),filterSprintMissing:M(e,"filterSprintMissing"),filterReleaseMissing:M(e,"filterReleaseMissing"),hasNotes:M(e,"hasNotes"),hasLearnings:M(e,"hasLearnings"),hasFiles:M(e,"hasFiles"),hasDocs:M(e,"hasDocs"),hasTests:M(e,"hasTests"),hasComments:M(e,"hasComments"),hasDeps:M(e,"hasDeps"),hasBody:M(e,"hasBody"),hasLinkedCommand:M(e,"hasLinkedCommand"),noNotes:Ke(e,"notes"),noLearnings:Ke(e,"learnings"),noFiles:Ke(e,"files")??t,filterFilesMissing:t,noDocs:Ke(e,"docs")??n,filterDocsMissing:n,noTests:Ke(e,"tests"),noComments:Ke(e,"comments"),noDeps:Ke(e,"deps"),emptyBody:M(e,"emptyBody"),noLinkedCommand:Ke(e,"linkedCommand")}}function kd(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:M(e,"today"),recent:M(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:Ke(e,"truncate"),includeBody:M(e,"includeBody"),strictRead:M(e,"strictRead"),compact:M(e,"compact"),brief:M(e,"brief"),full:M(e,"full"),fields:ee(e,"fields"),sort:ee(e,"sort"),order:ee(e,"order"),tree:M(e,"tree"),treeDepth:ee(e,"treeDepth"),filterAcMissing:M(e,"filterAcMissing"),filterEstimatesMissing:wd(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:M(e,"filterResolutionMissing"),filterMetadataMissing:M(e,"filterMetadataMissing"),...gh(e)};return vd(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 po(e){return _h in e}function jr(e,t){return po(e)?Ec(t):Ki(e,t)}function JR(e,t,n=[]){let r=Ki(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 VR(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Jt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ho(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new y(`${t} must be a finite integer.`,_.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new y(`${t} must be a finite integer.`,_.USAGE);return n}}function KR(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 YR(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 yh=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Sd=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"]),wh=new Set([...Sd].filter(e=>e!=="file")),vh=new Set(["files","files-discover","docs","test","test-all"]),Ed=new Set(["comments","notes","learnings"]);function bh(e,t){if(!(!Ed.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new y(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,_.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var kh=new Set(["claim","release","start-task","pause-task","close-task"]),xh={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"]},Sh=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Ad(e,t=""){let n={},r=vh.has(t),i=t==="files"||t==="files-discover"||t==="docs",o=Ed.has(t)?wh:Sd;for(let[a,s]of Object.entries(e)){if(Array.isArray(s)&&yh.has(a)){n[a]=s.join(",");continue}if(a==="note"&&i){n[a]=s;continue}if(typeof s=="string"&&o.has(a)){n[a]=[s];continue}if(typeof s=="string"&&r&&(a==="add"||a==="remove")){n[a]=[s];continue}n[a]=s}return n}function Eh(e,t,n){let r=$(e,"author");return r!==void 0?r:n!==void 0&&kh.has(n)?$(e,"assignee")??$(t,"assignee"):void 0}function Ah(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function XR(e,t){let n=Jt(e.options)?e.options:void 0,r=xs(e.options),i={},o=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of xh[t??""]??[])o(c);for(let c of Sh)o(c);t!==void 0&&po(e)&&bh(t,r);let a=Ad({...i,...r},t),s=po(e)?e:n??e;return jr(s,Ah(a,Eh(e,a,t)))}function ZR(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 QR(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 eI(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 tI(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function go(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function nI(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[o,a]of Object.entries(e))n.has(o)||(r[o]=a);let i={...r,...t};return delete i.args,i}function rI(e,t){let n=jr(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function fo(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:Yi(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 mo(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return go(e)}function Fr(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function iI(e){let t=mo(e.kind),n=mo(e.exemptIsolate),r=mo(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Fr(e.maxDepth),limit:Fr(e.limit),after:$(e,"after"),direction:$(e,"direction"),maxPaths:Fr(e.maxPaths),sample:Fr(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 Rd(e){let t=kd(e);return e.ids!==void 0&&(t.ids=Yi(e.ids)),t}function oI(e){return{status:$(e,"filterStatus"),list:Jt(e.list)?Rd(e.list):fo(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 Rh=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 xd(e){let t={};for(let[n,r]of Object.entries(e))Rh.has(n)||(t[n]=r);return Id(t)}function Id(e){let t=Ad(e,"update-many");for(let n of ur)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return bd(t)}function aI(e){if(Jt(e.list)||Jt(e.update)){let t=Jt(e.update)?e.update:xd(e),n=jr(e,Id(t));return{status:re(e,"filterStatus"),list:Jt(e.list)?Rd(e.list):fo(e),update:Ac(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:fo(e),update:jr(e,xd(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 Re(e,t){throw new y(e,_.USAGE,t)}var Ih="2026-07-15T06:22:12.276Z",Ch=Date.parse(Ih),Th=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Cd=e=>typeof e=="string"?e:"",$d=e=>{let t=e??{},n=Cd(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Cd(t.ts))>=Ch);return Th[r][i]};function Od(e,t,n=20,r=new Set,i=!1){let o=[],a=[],s={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}d+=1;let h=$d(p);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}s[h]+=1,i&&h==="actionable_unknown"&&a.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:s.legacy_unknown,actionable_unknown_event_count:s.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:s.legacy_unknown+s.actionable_unknown>o.length,actionable_events:a}}var gI=(e,t,n=20,r=new Set)=>Od(e,t,n,r);function Dd(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 a of o.events)typeof a=="object"&&a!==null&&typeof a.item_id=="string"&&Number.isSafeInteger(a.line)&&t.add(`${a.item_id}:${String(a.line)}`)}return t}var An=async(e,t=20,n=!1)=>{let r=En.join(e,"history"),i;try{i=(await Sn.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let o=new Set,a=[],s=[],c=0,d=0,l=0,u=0,m=0,f=0,p="_workspace.jsonl",h=new Set;if(i.includes(p))try{h=Dd(await Sn.readFile(En.join(r,p),"utf8"))}catch{h=new Set}for(let w of i){let v;try{v=await Sn.readFile(En.join(r,w),"utf8")}catch{continue}let x=w.slice(0,-6),S=Od(x,v,t-a.length,h,n);c+=1,d+=S.checked_events,l+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,f+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&o.add(x),a.push(...S.samples),n&&s.push(...S.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:f,affected_item_ids:[...o].sort((w,v)=>w.localeCompare(v)),samples:a,samples_truncated:g>a.length,...n?{actionable_events:s}:{}}};function $h(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 Oh(e){try{return Dd(await Sn.readFile(En.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function Dh(e){return(e.item_id===fe||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function Ph(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Re(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return $d(i)!=="actionable_unknown"&&Re(`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:Td("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Pd(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Re("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Re("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Re("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let o=$h(t.all_actionable===!0?(await An(e,0,!0)).actionable_events:r),a=await Oh(e),s=new Map;for(let m of o)if(Dh(m)||Re(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!s.has(m.item_id))try{s.set(m.item_id,(await Sn.readFile(En.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Re(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=o.map(m=>Ph(m,a,s.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Td("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 _I(e,t,n=50){return(await Pd(e,t,n)).plan}function Nh(e,t){let n=e.length>0;return n&&t&&Re("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&&Re("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:Mh(e),all_actionable:t}}function Mh(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),o=r===fe||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!o||!Number.isSafeInteger(i)||i<1)&&Re(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function yI(e,t){let n=Nh(go(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Lh(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 Lh(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",o=await Pd(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:_.SUCCESS,plan:o.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Re("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Re("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==o.plan.plan_fingerprint)throw new y("Author acknowledgment selection changed after preview; no history was mutated.",_.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let s=o.completeCoordinates.filter(({disposition:u})=>o.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:m})=>({item_id:u,line:m}));if(s.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:_.NO_EFFECT,plan:o.plan};let c=await C(e),d=await yr({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:s,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:_.PARTIAL_EFFECT}:{outcome:"effect",exit_code:_.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:s.length,...l,plan:o.plan,history_path:d.historyPath}}import _o from"node:fs/promises";import yo 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 Fh=8388608,jh=new Set(["resolved","failed"]),Uh=[{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 je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wo(e){return Uh.find(t=>t.matches(e))?.kind}function Nd(e){let t=new Map,n=0,r=0;return{entries:e.map(o=>{let a=je(o.agent_provenance)?o.agent_provenance:void 0;if(a===void 0)return o;let s={},c=!1;for(let[l,u]of Object.entries(a)){let m=je(u)?wo(u.value):void 0;if(m===void 0){s[l]=u;continue}c=!0,r+=1;let f=o.agent_harness??"unknown",p=`${f}\0${l}\0${m}`,h=t.get(p)??{harness:f,dimension:l,kind:m,count:0};h.count+=1,t.set(p,h)}if(!c)return o;n+=1;let d={...o};return Object.keys(s).length===0?delete d.agent_provenance:d.agent_provenance=s,d}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((o,a)=>o.harness.localeCompare(a.harness)||o.dimension.localeCompare(a.dimension)||o.kind.localeCompare(a.kind))}}}async function Md(e){let t=[];for(let n of await Ld(e))try{let r=await _o.readFile(yo.join(e,"history",n),"utf8");for(let i of r.split(`
5
+ `)){if(i.trim().length===0)continue;let o=Fd(i);if(o===null||!je(o.agent_provenance))continue;if(Object.values(o.agent_provenance).some(s=>je(s)&&wo(s.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Ld(e){try{return(await _o.readdir(yo.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function zh(e,t,n){let r;try{r=await _o.open(yo.join(e,"history",t),"r");let i=(await r.stat()).size,o=Math.min(i,Math.max(0,n)),a=Buffer.alloc(o),{bytesRead:s}=await r.read(a,0,o,0),c=a.subarray(0,s).toString("utf8"),d=s>=i,l=c.lastIndexOf(`
6
+ `),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:s,complete:d}}catch{return null}finally{await r?.close()}}function Fd(e){try{let t=JSON.parse(e);return je(t)?t:null}catch{return null}}function Wh(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=je(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([a,s])=>{if(!je(s))return;let c=wo(s.value);if(!c)return;let d=`${r}\0${a}\0${c}`,l=n.get(d)??{harness:r,dimension:a,kind:c,count:0};l.count+=1,n.set(d,l)}),!je(e.context))return;let o=e.context.agent_provenance_outcomes;je(o)&&Object.entries(o).forEach(([a,s])=>{if(!je(s)||typeof s.resolver!="string"||!jh.has(String(s.status)))return;let c=`${r}\0${a}\0${s.resolver}`,d=t.get(c)??{harness:r,dimension:a,resolver:s.resolver,attempts:0,successes:0};d.attempts+=1,s.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function qh(e,t,n,r,i){let o=i;for(let a of e.split(`
7
+ `)){if(a.trim().length===0)continue;if(o>=r)return{eventsRead:o,truncated:!0};o+=1;let s=Fd(a);s&&Wh(s,t,n)}return{eventsRead:o,truncated:!1}}async function jd(e,t=1e4){let n=new Map,r=new Map,i=0,o=0,a=!1;for(let d of await Ld(e)){let l=await zh(e,d,Math.max(0,Fh-o));if(l===null)continue;o+=l.bytesRead;let u=qh(l.content,n,r,t,i);if(i=u.eventsRead,u.truncated){a=!0;break}if(!l.complete){a=!0;break}}let s=[...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:s,invalid_values:c,warnings:a?[]:[...s.filter(d=>d.attempts>0&&d.successes===0).map(d=>`provenance_resolver_zero_success:${d.harness}:${d.dimension}:${d.resolver}:${String(d.attempts)}`),...c.map(d=>`provenance_value_domain_invalid:${d.harness}:${d.dimension}:${d.kind}:${String(d.count)}`)],events_read:i,truncated:a}}import et from"node:fs/promises";import ge from"node:path";import Vt from"node:fs/promises";import{createHash as Bh}from"node:crypto";import zd from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32538934-2cbb-50fe-b721-ad9197cef7d8")}catch{}})();var Wd=4,Hh="history-drift-cache.json";function qd(e){return zd.join(e,"runtime",Hh)}async function Gh(e){try{let t=await Vt.readFile(qd(e),"utf8"),n=JSON.parse(t);return n.version!==Wd||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}async function Jh(e,t,n,r,i){let o=_r(e),a;try{a=await Vt.stat(o)}catch(d){return U(d)||i.unreadableStreams.push(fe),!1}let s=i.missingStreams.length,c=await Hd({itemId:fe,historyPath:o,stat:a,cached:t[fe],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.chainOk||i.chainMismatches.push(fe),n[fe]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(i.missingStreams.splice(s),c.cacheDirty)}function Bd(e){return Bh("sha256").update(e).digest("hex")}async function Vh(e){let t=await Vt.readFile(e,"utf8");return Bd(t)}async function Kh(e){let t=await Vt.readFile(e,"utf8"),n=Bd(t);if(t.trim().length===0)return null;let r=[],i=null;for(let a of t.split(/\r?\n/)){let s=a.trim();if(s.length===0)continue;let c=JSON.parse(s);if(typeof c.after_hash!="string"||c.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(c),i=c.after_hash}if(!i)return null;let o=gr(r);return{latestAfterHash:i,chainOk:o.ok,contentHash:n,itemHashVersion:o.item_hash_version??Gi}}function Yh(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Ud(e,t,n){try{let r=await Kh(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Hd(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Yh(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Ud(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await Vh(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else r=t;return!e.verifyCacheHitByContent||r===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:r,itemHashVersion:e.cached.item_hash_version??Gi},cacheDirty:!1}:{verification:await Ud(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function Xh(e,t,n,r){let i=rr(e,t.id),o;try{o=await Vt.stat(i)}catch(l){return(U(l)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let a=await Hd({itemId:t.id,historyPath:i,stat:o,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!a.verification)return a.cacheDirty;a.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:a.verification.contentHash,latest_after_hash:a.verification.latestAfterHash,chain_ok:a.verification.chainOk,item_hash_version:a.verification.itemHashVersion};let{body:s,...c}=t;return oc({metadata:c,body:s},a.verification.itemHashVersion)!==a.verification.latestAfterHash&&r.hashMismatches.push(t.id),a.cacheDirty}async function Zh(e,t){if(!(t.unreadableStreams.includes(fe)||t.chainMismatches.includes(fe)))try{let n=await uc(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(fe)}}async function Kt(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},o=(await Gh(e))?.entries??{},a={},s=!1,c=n.cacheHitVerification!=="metadata",d={previousEntries:o,nextEntries:a,verifyCacheHitByContent:c};for(let m of t)await Xh(e,m,d,r)&&(s=!0);let l=await Jh(e,o,a,c,r);if(s||=l,await Zh(e,r),s||Object.keys(o).length!==Object.keys(a).length){let m=qd(e);try{await Vt.mkdir(zd.dirname(m),{recursive:!0}),await se(m,JSON.stringify({version:Wd,entries:a}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[fe]:[]])].sort((m,f)=>m.localeCompare(f));return{...r,driftedItems:u}}import Rn from"node:fs/promises";import Ur 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 Qh(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:a}=n;return typeof r!="string"||typeof i!="string"||typeof o!="string"||typeof a!="number"||!Number.isFinite(a)?null:{id:r,owner:i,created_at:o,ttl_seconds:a}}function Gd(e,t,n){let r=Qh(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,a=Math.floor(o/1e3),s=o>r.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:a,stale:s,reason:s?"expired":"active"}}}async function Jd(e,t){let n=t??Date.now(),r=Ur.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 Rn.readdir(r)).filter(s=>s.endsWith(".lock")).sort()}catch(a){if(U(a))return i;throw a}for(let a of o){let s;try{s=await Rn.readFile(Ur.join(r,a),"utf8")}catch(d){if(U(d))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=Gd(a,s,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function Vd(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Ur.join(e,"locks"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await Rn.readdir(o)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if(U(c))return a;throw c}for(let c of s){a.scanned+=1;let d=Ur.join(o,c),l=`locks/${c}`;if(r?.onRead){let f=await r.onRead(d);a.warnings.push(...f)}let u;try{u=await Rn.readFile(d,"utf8")}catch(f){if(U(f)){a.scanned-=1;continue}a.warnings.push(`lock_unreadable:${c}`),a.retained.push(l),a.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=Gd(c,u,i);if(m.detail==="unparseable_json"){a.warnings.push(`lock_unparseable:${c}`),a.retained.push(l),a.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){a.warnings.push(`lock_invalid_timestamp:${c}`),a.retained.push(l),a.entries.push(m.entry);continue}if(m.detail==="active"){a.retained.push(l),a.entries.push(m.entry);continue}if(!n){try{await Rn.unlink(d)}catch(f){if(!U(f)){a.warnings.push(`lock_remove_failed:${c}`),a.retained.push(l),a.entries.push(m.entry);continue}}if(r?.onWrite){let f=await r.onWrite(d);a.warnings.push(...f)}}a.removed.push(l),a.entries.push(m.entry)}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c088607b-1be3-54c8-a38b-79c188924102")}catch{}})();var eg=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 --dry-run",summary:"A lossless merge receipt is still pending; preview and run pm merge reconcile 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_merge_receipt",command:"pm merge reconcile --dry-run",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; preview reconciliation 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_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 vo(e){if(typeof e!="string")return;let t=e.trim();for(let n of eg)if(t===n.code||t.startsWith(`${n.code}:`))return n}function bo(e){let t={};for(let n of e){let r=vo(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Kd(e){return Object.values(bo(e))}import mt from"node:fs/promises";import Ie 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 tg=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Yt(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(lr(t.extensionName));for(let g of t.extensionNames??[])n.add(lr(g));let r=g=>n.size===0||n.has(lr(g)),i=(g,w)=>Yd(g.filter(v=>r(v.name)).map(w)),o=(g,w)=>Yd(g.filter(v=>r(v.name)).flatMap(w)),{registrations:a,commands:s,parsers:c,preflight:d,services:l,renderers:u,hooks:m}=e,f=o(a.relationship_kinds??[],g=>g.definitions.map(w=>w.kind)),p=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,w)=>g.format.localeCompare(w.format)),h=i(a.assurance_providers??[],g=>g.definition.id);return{capabilities:Js(e,t),commands:i(a.commands,g=>g.command),command_overrides:i(s.overrides,g=>g.command),command_handlers:i(s.handlers,g=>g.command),hooks:tg.filter(([g])=>m[g].some(w=>r(w.name))).map(([,g])=>g),flag_commands:i(a.flags,g=>g.target_command),item_types:o(a.item_types,g=>g.types.map(w=>w.name)),item_fields:o(a.item_fields,g=>g.fields.map(w=>w.name)),...f.length>0?{relationship_kinds:f}:{},migrations:o(a.migrations,g=>typeof g.definition.id=="string"?[g.definition.id]:[]),profiles:i(a.profiles,g=>g.profile.name),importers:i(a.importers,g=>g.importer),exporters:i(a.exporters,g=>g.exporter),search_providers:i(a.search_providers,g=>g.definition.name),vector_store_adapters:i(a.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),...p.length>0?{renderer_ownership:p}:{},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 Yd(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import n_ from"node:path";import{mkdir as r_}from"node:fs/promises";import{readFile as Wr,realpath as Eo,writeFile as cg}from"node:fs/promises";import{execFile as dg}from"node:child_process";import ie from"node:path";import{promisify as lg}from"node:util";import{readFile as ng,writeFile as rg}from"node:fs/promises";import In 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 Zd="# pm-cli:runtime-cache:start",ko="# pm-cli:runtime-cache:end",Qd=".agents/pm",xo=["runtime/","search/","locks/","transactions/","checkpoints/"],ig=["search/eval-queries.json"];async function Xd(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 y("The workspace .gitignore is not writable.",_.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 el(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function So(e){let t=e.replaceAll("\\","/");return In.isAbsolute(e)||t===".."||t.startsWith("../")}function og(e=Qd){let t=el(e);return[Zd,...xo.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...ig.map(n=>`!${t}/${n}`),ko].join(`
8
+ `)}async function BI(e,t={}){let n=In.join(e,".gitignore"),r=Qd;if(t.pmRoot!==void 0){let l=el(In.relative(In.resolve(e),In.resolve(t.pmRoot)));if(So(l))return{path:n,changed:!1};l.length>0&&(r=l)}let i="";try{i=await Xd(()=>ng(n,"utf8"))}catch(l){if(!(l instanceof Error&&"code"in l&&U(l)))throw l}let o=i.indexOf(Zd),a=i.indexOf(ko),c=(o>=0&&a>=o?`${i.slice(0,o)}${i.slice(a+ko.length)}`:i).trimEnd(),d=`${c.length>0?`${c}
9
9
 
10
- `:""}${ag(r)}
11
- `;return d===i?{path:n,changed:!1}:(await Xd(()=>ig(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 sg="PM_SOURCE_CONTEXT_ACCESS",cg="PM_ALLOW_SOURCE_CONTEXT_WRITES";function tl(e){let t=e[sg],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[cg]?.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 Ro=ug(lg),Wr="# pm-cli:merge-drivers:start",ol="# pm-cli:merge-drivers:end",Xt="# pm-cli:merge-drivers:v2:start",Ao="# pm-cli:merge-drivers:v2:end",mg="merge-fence";function nl(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function al(){let e=Ee(import.meta.url,["../../.."]);return`${nl(process.execPath)} ${nl(ie.join(e,"dist","cli.js"))}`}var sl=[{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 pg(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=tl(e.environment),o=!!(n&&r),a=t===void 0&&o&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let s=L(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:o,source_context_selected:!1,source_policy:i}}return a?{pm_root:ie.resolve(r),workspace_start:ie.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:o?L(e.cwd,".agents/pm"):L(e.cwd),workspace_start:e.cwd,source_coordinates_available:o,source_context_selected:!1,source_policy:i}}async function kt(e){try{let{stdout:t}=await Ro("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await Eo(t.trim())}catch{return null}}async function cl(e){let t=await kt(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",_.USAGE);return t}function Io(e,t){return ie.relative(e,t).replaceAll("\\","/")}function Ue(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function rl(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 fg(e,t){let n=rl(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=rl(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 qr(ie.join(i,"package.json"),"utf8")),a=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"||a==="dist/cli.js")}catch{return!1}}function Co(e,t){let n=e.length>0?`${e}/`:"",r=[`${Ue(`${n}**/*.toon`)} merge=pm-item-toon`,`${Ue(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${Ue(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${Ue(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${Ue(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${Ue(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${Ue(`${n}settings.json`)} merge=pm-json`),r.push(`${Ue(`${n}**/*.json`)} merge=pm-json`),r.push(`${Ue(`${n}extensions/**`)} -merge`),r.push(`${Ue(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function il(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 dl(e,t,n){let r=ie.join(e,".gitattributes"),i="";try{i=await qr(r,"utf8")}catch(d){if(!(d instanceof Error&&"code"in d&&U(d)))throw d}let o=[Xt,...t,Ao].join(`
12
- `),s=il(il(i,Xt,Ao),Wr,ol).trimEnd(),c=`${s.length>0?`${s}
10
+ `:""}${og(r)}
11
+ `;return d===i?{path:n,changed:!1}:(await Xd(()=>rg(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 ag="PM_SOURCE_CONTEXT_ACCESS",sg="PM_ALLOW_SOURCE_CONTEXT_WRITES";function tl(e){let t=e[ag],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[sg]?.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 Ro=lg(dg),zr="# pm-cli:merge-drivers:start",ol="# pm-cli:merge-drivers:end",Xt="# pm-cli:merge-drivers:v2:start",Ao="# pm-cli:merge-drivers:v2:end",ug="merge-fence";function nl(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function al(){let e=Ee(import.meta.url,["../../.."]);return`${nl(process.execPath)} ${nl(ie.join(e,"dist","cli.js"))}`}var sl=[{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 mg(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=tl(e.environment),o=!!(n&&r),a=t===void 0&&o&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let s=L(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:o,source_context_selected:!1,source_policy:i}}return a?{pm_root:ie.resolve(r),workspace_start:ie.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:o?L(e.cwd,".agents/pm"):L(e.cwd),workspace_start:e.cwd,source_coordinates_available:o,source_context_selected:!1,source_policy:i}}async function kt(e){try{let{stdout:t}=await Ro("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await Eo(t.trim())}catch{return null}}async function cl(e){let t=await kt(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",_.USAGE);return t}function Io(e,t){return ie.relative(e,t).replaceAll("\\","/")}function Ue(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function rl(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 pg(e,t){let n=rl(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=rl(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 Wr(ie.join(i,"package.json"),"utf8")),a=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"||a==="dist/cli.js")}catch{return!1}}function Co(e,t){let n=e.length>0?`${e}/`:"",r=[`${Ue(`${n}**/*.toon`)} merge=pm-item-toon`,`${Ue(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${Ue(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${Ue(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${Ue(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${Ue(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${Ue(`${n}settings.json`)} merge=pm-json`),r.push(`${Ue(`${n}**/*.json`)} merge=pm-json`),r.push(`${Ue(`${n}extensions/**`)} -merge`),r.push(`${Ue(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function il(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 dl(e,t,n){let r=ie.join(e,".gitattributes"),i="";try{i=await Wr(r,"utf8")}catch(d){if(!(d instanceof Error&&"code"in d&&U(d)))throw d}let o=[Xt,...t,Ao].join(`
12
+ `),s=il(il(i,Xt,Ao),zr,ol).trimEnd(),c=`${s.length>0?`${s}
13
13
 
14
14
  `:""}${o}
15
- `;return c===i?{path:r,changed:!1}:(n||await dg(r,c,"utf8"),{path:r,changed:!0})}function Br(e){let t=B(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function ll(e,t){let n=ie.resolve(e),r=null,i="",o=n;for(let v=0;v<8;v+=1){let x=ie.join(o,".gitattributes");try{let b=await qr(x,"utf8");if(b.includes(Xt)||b.includes(Wr)){r=o,i=b;break}}catch{}let S=ie.dirname(o);if(S===o)break;o=S}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let a=ie.join(r,".gitattributes"),s=i.includes(Xt),c=s?Xt:Wr,d=s?Ao:ol,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):[],f=Co(Io(r,n),t),p=new Set(m),h=new Set(f),g=f.filter(v=>!p.has(v)),w=m.filter(v=>!h.has(v));return{status:g.length>0||w.length>0?"drift":"ok",path:a,missing_patterns:g,stale_patterns:w,schema_scope:"project"}}async function Hr(e){let t=al(),n=[],r=[];for(let i of sl){let o=`merge.${i.key}.driver`,a=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`,s=`${t}${a}`;try{let{stdout:c}=await Ro("git",["config","--local","--get",o],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),d=c.trim();d!==s&&!await fg(d,a)&&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 ul(e){let t;try{t=await cl(ie.resolve(e))}catch{return{status:"no_git"}}let n=Io(t,ie.resolve(e)),r=await C(e),i=J(void 0,r.author_default),o=await pe(e,mg,r.locks.ttl_seconds,i,!1,Oe(r).force_required_for_stale_lock,r.locks.wait_ms);try{let a=ie.join(t,".gitattributes"),s;try{s=await qr(a,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&U(u))return{status:"not_installed",path:a};throw u}if(!s.includes(Xt)&&!s.includes(Wr))return{status:"not_installed",path:a};let c=await C(e),d=Br(c),l=await dl(t,Co(n,d),!1);return{status:l.changed?"refreshed":"unchanged",path:l.path}}finally{await o()}}async function uC(e,t){let n=pg({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await Q(r);let i=await cl(n.workspace_start);return hg({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function hg(e){let t=ie.resolve(e.pmRoot),n=ie.resolve(e.workspaceRoot),r=e.dryRun===!0,i,o;try{[i,o]=await Promise.all([Eo(t),Eo(n)])}catch(f){throw new y(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,_.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 a=Io(o,i);if(So(a))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,_.USAGE);let s=await C(i),c=Br(s),d=Co(a,c),l=[],u=al();for(let f of sl)l.push({key:`merge.${f.key}.name`,value:f.name}),l.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!r)try{for(let f of l)await Ro("git",["config","--local",f.key,f.value],{cwd:o,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new y(`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.`,_.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 dl(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 gg=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function _g(e){let t=gg.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function yg(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function ml(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 a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=_g(s);if(c===void 0)continue;let d=i.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(s),i.set(c,d)}let o=[];for(let[a,s]of i.entries()){if(s.count<n)continue;let c=yg(a);o.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:Ds(c)!==void 0})}return o.sort((a,s)=>s.count-a.count||a.name.localeCompare(s.name)),o}import{createHash as Sl}from"node:crypto";import St from"node:fs/promises";import Qt from"node:path";import{mkdir as wg,readFile as vg}from"node:fs/promises";import yl 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 To=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},bg="sdk-workspace-transaction",kg=/^[a-zA-Z0-9._-]+$/,xg=30,Sg=3e3;function pl(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!kg.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function fl(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 hl(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 wl(e,t){return yl.join(e,"transactions","sdk",`${t}.json`)}async function ct(e,t){t.updatedAt=T();let n=wl(e,t.transactionId);await wg(yl.dirname(n),{recursive:!0}),await se(n,`${JSON.stringify(t,null,2)}
17
- `)}function Eg(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function xt(e){return Object.assign(Object.create(null),e)}function Ag(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 $o(e,t){return e===void 0?void 0:Ag(e,t)}function Oo(e,t,n,r){let i=$o(n,r);i===void 0?delete e[t]:e[t]=i}function gl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _l(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Rg(e,t){if(!_l(e.startedStepIds,t)||!_l(e.completedStepIds,t)||!gl(e.results)||!gl(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(a=>!r.has(a))||Object.keys(e.results).some(a=>!o.has(a))?!1:e.status==="committed"?t.every(a=>o.has(a)):e.status!=="compensated"||o.size===0&&r.size===0}function Ig(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,a=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((l,u)=>l===n[u]),s=Rg(i,n),c=Eg(i),d=["applying","compensating","compensated","committed"].includes(String(i.status));if(!o||!a||!s||!c||!d)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...i,results:xt(i.results),compensationData:xt(i.compensationData)}}async function Cg(e,t,n,r,i){let o=i,a=o!==void 0;if(o?.status==="compensating"&&await vl(e,o),o===void 0||o.status==="compensated"){let s=T();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:xt(),compensationData:xt()},await ct(e.pmRoot,o),await Ye(e,o,"prepared")}return{journal:o,recovered:a}}async function Tg(e,t,n){try{await Og(t,e.steps),await ct(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 a=await o.inspect(),s=$o(a.result,`Step ${o.id} result`);if(a.state!=="applied"){let c=await o.prepareCompensation?.();Oo(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 ct(e.pmRoot,t);let d=await o.apply();s=$o(d,`Step ${o.id} result`)}await Ye(e,t,"step_applied",o.id),r.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),Oo(t.results,o.id,s,`Step ${o.id} result`),await ct(e.pmRoot,t),await Ye(e,t,"step_recorded",o.id)}return await Ye(e,t,"committing"),t.status="committed",await ct(e.pmRoot,t),await Ye(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:xt(t.results)}}catch(r){if(r instanceof To||t.status==="committed")throw r;try{await vl(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function $g(e,t,n){try{return Ig(await vg(wl(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&U(r))return;throw r}}async function Ye(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function Og(e,t){let n=new Set,r=xt();for(let i of t){let o=await i.inspect();o.state==="applied"&&(n.add(i.id),Oo(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 vl(e,t){t.status="compensating",await ct(e.pmRoot,t),await Ye(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 Ye(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(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>r.has(a)),delete t.results[i.id],delete t.compensationData[i.id],await ct(e.pmRoot,t),await Ye(e,t,"step_compensated",i.id)}t.status="compensated",await ct(e.pmRoot,t),await Ye(e,t,"compensated")}async function bl(e){let t=fl(e.pmRoot,"Transaction pmRoot"),n=pl(e.transactionId,"Transaction id"),r=fl(e.author,"Transaction author"),i=hl(e.lockTtlSeconds,xg,"Transaction lock TTL"),o=hl(e.lockWaitMs,Sg,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(l=>{let u=pl(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(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:a,lockTtlSeconds:i,lockWaitMs:o},d=await pe(t,bg,i,r,!1,!1,o);try{let l=await $g(t,n,s),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:xt(l.results)};let m=await Cg(c,n,r,s,l);return await Tg(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 Xe(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function El(e){let t=Xe(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Al(e,t){let n=Po(e),r=Xe(t,"migrationScope");return`auto-${Sl("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function Po(e){let t=e.kind==="rename-type"?{kind:e.kind,from:Xe(e.from,"source"),to:Xe(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:ce(Xe(e.from,"source")),to:ce(Xe(e.to,"target")),...e.type===void 0?{}:{type:Xe(e.type,"type")}}:{kind:e.kind,from:ce(Xe(e.from,"source")),to:ce(Xe(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Dg(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Pg(e,t,n){let r=ve(t.schema),i=Dg(n);return Le(e,r.files[i],Ae[i])}function Rl(e,t){return Qt.join(e,"transactions","schema",`${t}-plan.json`)}function Gr(e){return e.length===0?null:JSON.parse(e)}async function Zt(e){let t=await Y(e);return{exists:t!==null,raw:t??""}}async function Il(e,t){t.exists?await se(e,t.raw):await St.rm(e,{force:!0})}function Ng(e,t,n){let r=He(e),i=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),o=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return at(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 at(r)}function Mg(e,t,n){let r=$t(e),i=r.fields.findIndex(a=>a.key===t.from),o=r.fields.findIndex(a=>a.key===t.to);if(n==="stage"){if(o>=0)return Ot(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let a=r.fields[i];r.fields.push({...a,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 Ot(r)}function Lg(e,t,n){let r=Dt(e),i=r.statuses.findIndex(a=>a.id===t.from),o=r.statuses.findIndex(a=>a.id===t.to);if(n==="stage"){if(o>=0)return Pt(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 Pt(r)}function Fg(e,t,n){return t.kind==="rename-type"?Ng(e,t,n):t.kind==="rename-field"?Mg(e,t,n):Lg(e,t,n)}function dt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function No(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function en(e){return Array.isArray(e)?e.map(t=>No(t)).filter(t=>t!==void 0):[]}function jg(e,t){for(let n of en(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>dt(r,t)));for(let n of en(e.type_workflows))n.type=dt(n.type,t)}function Ug(e,t){for(let r of en(e.definitions))r.default_status=dt(r.default_status,t);let n=No(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=dt(i,t);for(let r of en(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(o=>dt(o,t)):i))}function zg(e,t){for(let n of en(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>dt(i,t)));for(let r of["options","command_option_policies"])for(let i of en(n[r])){let o=r==="options"?"key":"option";i[o]=dt(i[o],t)}}}function Wg(e,t){let n=No(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]=dt(n[r],t)}function Do(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"?jg(r,t):t.kind==="rename-field"?zg(r,t):Ug(r,t),Wg(r,t),`${JSON.stringify(r,null,2)}
18
- `}function Cl(e,t){if(t.kind==="rename-type"){let r=He(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=$t(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=Dt(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function qg(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 Bg(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 Tl(e,t){let n=Po(t.request),r=t.migrationId===void 0?Al(n,t.migrationScope??"plan"):El(t.migrationId),i=e.map(c=>Bg(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),o=Sl("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),a=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!a.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:o,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function Hg(e){let t=B(e.settings,z()),n=[...new Set(Object.values(t.type_to_folder))],r=await xr(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 hc({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 Je(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Gg(e,t){let n=await Y(Rl(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 y(`Stored schema migration plan "${t}" is invalid: ${ks(r)}`,_.GENERIC_FAILURE)}}async function Jg(e,t){let n=Rl(e,t.migration_id);await St.mkdir(Qt.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await se(n,`${JSON.stringify(r,null,2)}
19
- `)}function Vg(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Kg(e){let t=await jt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new y(`Schema migration item "${e.id}" no longer exists.`,_.NOT_FOUND);return(await st(t,{schema:e.settings.schema})).document.metadata}function kl(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 xl(e){return{id:e.id,inspect:async()=>{let t=await Zt(e.filePath),n=Cl(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 Zt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Zt(e.filePath);return await se(e.filePath,Fg(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 Il(e.filePath,{exists:t.exists,raw:t.raw})}}}function Yg(e){return{id:e.stepId,inspect:async()=>{let t=await Zt(e.filePath);return{state:Do(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Zt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Zt(e.filePath);return await se(e.filePath,Do(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 Il(e.filePath,{exists:t.exists,raw:t.raw})}}}function Xg(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await C(e.pmRoot),n=B(t,z()).type_to_folder,r=await Kg({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=qg(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=B(t,z()).type_to_folder,r=await wt({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:kl(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await C(e.pmRoot),n=B(t,z()).type_to_folder;await wt({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:kl(r,e.request,"reverse")}}})}}}async function Zg(e){let t=await Gg(e.pmRoot,e.migrationId);if(t){if(!Vg(t.request,e.request))throw new y(`Schema migration id "${e.migrationId}" already belongs to a different request.`,_.CONFLICT);return{plan:t,stored:!0}}let n=await Hg({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Tl(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Qg(e){let t=Cl(await Y(e.schemaPath)??"",e.request);if(!t.source)throw new y(`Schema migration source "${e.request.from}" is not a custom definition.`,_.NOT_FOUND);if(t.target)throw new y(`Schema migration target "${e.request.to}" already exists.`,_.CONFLICT);await Jg(e.pmRoot,e.plan)}async function e_(e){let t=ve(e.settings.schema),n=[...new Set([["types",Ae.types],["fields",Ae.fields],["workflows",Ae.workflows]].map(([i,o])=>Le(e.pmRoot,t.files[i],o)).filter(i=>i!==e.schemaPath))];try{let i=Qt.join(e.pmRoot,"templates"),o=await St.readdir(i,{withFileTypes:!0});n.push(...o.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>Qt.join(i,a.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&&Do(o,e.request)!==o&&r.push({filePath:i,beforeRaw:o})}return{paths:n,snapshots:r}}async function t_(e){for(let t of e.snapshots){let n=await St.readFile(t.filePath,"utf8"),r=Qt.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await Vi({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Gr(t.beforeRaw),after:Gr(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 n_(e,t,n){let r=Po(e),i=L(process.cwd(),n.path);await Q(i);let o=t.migrationId===void 0?Al(r,await St.realpath(i)):El(t.migrationId),a=await C(i),s=J(t.author,a.author_default),c=await Zg({pmRoot:i,settings:a,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=Pg(i,a,r),u=await St.readFile(l,"utf8");c.stored||await Qg({pmRoot:i,schemaPath:l,request:r,plan:d});let m=await e_({pmRoot:i,schemaPath:l,settings:a,request:r}),f=[xl({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...m.paths.map((w,v)=>Yg({filePath:w,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>Xg({pmRoot:i,id:w.id,request:r,author:s,force:t.force===!0})),xl({id:"retire-source",filePath:l,request:r,phase:"retire"})],p=await bl({pmRoot:i,transactionId:`schema-${o}`,author:s,steps:f,lockTtlSeconds:Math.max(a.locks.ttl_seconds,300),lockWaitMs:a.locks.wait_ms}),h=await St.readFile(l,"utf8"),{historyPath:g}=await Vi({pmRoot:i,author:s,documentPath:Qt.relative(i,l).replaceAll("\\","/"),before:Gr(u),after:Gr(h),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await t_({pmRoot:i,author:s,settings:a,request:r,plan:d,snapshots:m.snapshots}),{...d,action:r.kind,applied:!0,recovered:p.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]="6112923d-5e06-5839-b452-a32818c6398d")}catch{}})();var hT=["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"],Jr="schema-types",$l="schema-statuses",Ol="schema-fields";function lt(e){return br({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 gT(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i;try{i=Ui({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(f){throw new y(f instanceof Error?f.message:String(f),_.USAGE)}let o=await C(r),a=ve(o.schema),s=Le(r,a.files.types,Ae.types),c=[],d=J(t.author,o.author_default),l=Oe(o),u=await pe(r,Jr,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms),m;try{let f=await Y(s),p;try{p=He(f)}catch(h){throw new y(h instanceof Error?h.message:String(h),_.GENERIC_FAILURE)}try{Ps(i,p);let h=new Map,g=B(o,z());for(let[w,v]of Object.entries(g.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!h.has(x)&&h.set(x,w)}Ns(i,p,h)}catch(h){throw new y(h instanceof Error?h.message:String(h),_.USAGE)}m=cr(p,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await lt({pmRoot:r,filePath:s,raw:at(m.file),op:"schema:add-type",author:d,settings:o}),await Cn(r,[m.definition],c,"schema:add-type-folder"),c.push(...await ne({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await Dl(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:ut(c),generated_at:T()}}async function Ze(e){await Q(e)}async function Dl(e,t){try{let n=await ul(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 ut(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function o_(e,t,n,r){let i=B(t,z()),o=r.trim().toLowerCase();return(await Je(e,t.item_format,i.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===o).length}async function a_(e,t,n,r){let i=B(t,z()),o=$e(n),a=ce(r);return(await Je(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(ce(d))??ce(d))===a}).length}async function s_(e,t,n,r,i){if(i.length===0||Wi.has(i))return;let o=await a_(t,n,r,i);o>0&&e.push(`items_using_status:${o}`);let a=c_(r.workflow,i);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function c_(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&&ce(r)===t).map(([r])=>r)}async function _T(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i=await C(r),o=ve(i.schema),a=Le(r,o.files.types,Ae.types),s=[],c=J(t.author,i.author_default),d=Oe(i),l=await pe(r,Jr,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(a),f;try{f=He(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.GENERIC_FAILURE)}try{u=Ms(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.USAGE)}if(u.removed){let p=(u.definition?.name??e??"").trim();if(p.length>0){let h=await o_(r,i,o,p);h>0&&s.push(`items_using_type:${h}`)}await lt({pmRoot:r,filePath:a,raw:at(u.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await ne({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await Dl(r,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:a,definitions:u.file.definitions.length},warnings:ut(s),generated_at:T()}}function Mo(e,t){return Le(e,t.files.statuses,Ae.statuses)}function Vr(e,t){return Le(e,t.files.fields,Ae.fields)}function Pl(e,t){return Le(e,t.files.types,Ae.types)}async function Cn(e,t,n,r){for(let i of t){let o=ws(i.folder??ys(i.name)),a=r_.join(e,o);await D(a)||(await i_(a,{recursive:!0}),n.push(...await ne({path:a,scope:"project",op:r})))}}function Lo(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 d_(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 l_(e){let t=new Map;for(let n of e){let r=ce(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let o=ce(i);o.length>0&&!t.has(o)&&t.set(o,r)}}}return t}async function yT(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i;try{i=qs({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(h){throw new y(h instanceof Error?h.message:String(h),_.USAGE)}let o=await C(r),a=ve(o.schema),s=Mo(r,a),c=$e(a);try{qi(i,c.alias_to_id)}catch(h){throw new y(h instanceof Error?h.message:String(h),_.USAGE)}let d=d_(c.by_id.get(i.id)),l=[],u=J(t.author,o.author_default),m=Oe(o),f=await pe(r,$l,o.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,o.locks.wait_ms),p;try{let h=await Y(s),g;try{g=Dt(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),_.GENERIC_FAILURE)}let w=l_(g.statuses);try{qi(i,w)}catch(v){throw new y(v instanceof Error?v.message:String(v),_.USAGE)}p=Bs(g,i,d),await lt({pmRoot:r,filePath:s,raw:Pt(p.file),op:"schema:add-status",author:u,settings:o}),l.push(...await ne({path:s,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:p.replaced,status:p.definition,file:{path:s,statuses:p.file.statuses.length},warnings:ut(l),generated_at:T()}}async function wT(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i=await C(r),o=ve(i.schema),a=Mo(r,o),s=[],c=J(t.author,i.author_default),d=Oe(i),l=await pe(r,$l,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(a),f;try{f=Dt(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.GENERIC_FAILURE)}try{u=Hs(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.USAGE)}if(u.removed){let p=ce(u.definition?.id??e);await s_(s,r,i,o,p),await lt({pmRoot:r,filePath:a,raw:Pt(u.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await ne({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:a,statuses:u.file.statuses.length},warnings:ut(s),generated_at:T()}}function Nl(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 u_(e,t,n){return{...Nl(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 Ml(e){return{id:e.id,source:Wi.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 Ll(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function m_(){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 p_(e){let t=$e(e),n=[],r=[];for(let i of t.definitions){let o=Ml(i);o.source==="builtin"?n.push(o):r.push(o)}return{builtin:n,custom:r}}async function Tn(e){let t=L(process.cwd(),e.path);await Ze(t);let n=await C(t),r=ve(n.schema),i=Le(t,r.files.types,Ae.types),o=Mo(t,r),a=B(n,z()),s=m_(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:i,statusesPath:o,byType:a.by_type,customNames:c,extensionProvenance:s,schema:r}}async function vT(e){let t=await Tn(e),n=[],r=[],i=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Ll(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=Nl(s);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let o=p_(t.schema),a=dr(t.schema).definitions.map(Lo);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:a,counts:{total:a.length}},file:{path:t.typesPath},generated_at:T()}}async function bT(e,t){let n=(e??"").trim();if(n.length===0)throw new y("Type name must not be empty.",_.USAGE);let r=await Tn(t),i=Object.values(r.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!i)throw new y(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${sr(n)}" to register it.`,_.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:u_(i,Ll(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:T()}}async function kT(e,t){let n=ce(e);if(n.length===0)throw new y("Status id must not be empty.",_.USAGE);let r=await Tn(t),i=$e(r.schema),o=i.alias_to_id.get(n)??n,a=i.by_id.get(o);if(!a)throw new y(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${sr(e??"")}" to register it.`,_.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Ml(a),file:{path:r.statusesPath},generated_at:T()}}async function xT(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i;try{i=js({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(p){throw new y(p instanceof Error?p.message:String(p),_.USAGE)}let o=await C(r),a=ve(o.schema),s=Vr(r,a),c=[],d=lr(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=J(t.author,o.author_default),u=Oe(o),m=await pe(r,Ol,o.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,o.locks.wait_ms),f;try{let p=await Y(s),h;try{h=$t(p)}catch(g){throw new y(g instanceof Error?g.message:String(g),_.GENERIC_FAILURE)}f=Us(h,i),await lt({pmRoot:r,filePath:s,raw:Ot(f.file),op:"schema:add-field",author:l,settings:o}),c.push(...await ne({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:s,fields:f.file.fields.length},warnings:ut(c),generated_at:T()}}async function f_(e,t,n,r){let i=B(t,z());return(await Je(e,t.item_format,i.type_to_folder,[],n)).filter(a=>{let s=a[r];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function ST(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i=await C(r),o=ve(i.schema),a=Vr(r,o),s=[],c=J(t.author,i.author_default),d=Oe(i),l=await pe(r,Ol,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(a),f;try{f=$t(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.GENERIC_FAILURE)}try{u=zs(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.USAGE)}if(u.removed){let p=ce(u.definition?.key??e),h=ce(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(h.length>0){let g=await f_(r,i,o,h);g>0&&s.push(`items_using_field:${g}`)}await lt({pmRoot:r,filePath:a,raw:Ot(u.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await ne({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:a,fields:u.file.fields.length},warnings:ut(s),generated_at:T()}}async function ET(e){let t=await Tn(e),n=dr(t.schema).definitions.map(Lo);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Vr(t.pmRoot,t.schema)},generated_at:T()}}async function AT(e,t){let n=ce(e);if(n.length===0)throw new y("Field key must not be empty.",_.USAGE);let r=await Tn(t),i=dr(r.schema).by_key.get(n);if(!i)throw new y(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${sr(e??"")}" to register it.`,_.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Lo(i),file:{path:Vr(r.pmRoot,r.schema)},generated_at:T()}}async function RT(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i;try{let h=Fs(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${Ls.join(", ")}.`);i=h}catch(h){throw new y(h instanceof Error?h.message:String(h),_.USAGE)}let o=await C(r),a=ve(o.schema),s=Pl(r,a),c=[],d=J(t.author,o.author_default),l=Oe(o),u=[],m=[],f,p=await pe(r,Jr,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms);try{let h=await Y(s),g;try{g=He(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),_.GENERIC_FAILURE)}let w=g;for(let v of zi(i)){let x=cr(w,v);w=x.file,(x.replaced?m:u).push(x.definition.name)}f=w.definitions.length,await lt({pmRoot:r,filePath:s,raw:at(w),op:"schema:apply-preset",author:d,settings:o}),await Cn(r,zi(i),c,"schema:apply-preset-folder"),c.push(...await ne({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await p()}return{action:"apply-preset",preset:i,registered:u,replaced:m,file:{path:s,definitions:f},warnings:ut(c),generated_at:T()}}function h_(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new y("--min-count must be a positive integer (>= 1).",_.USAGE);return e}async function IT(e,t){let n=L(process.cwd(),t.path);await Ze(n);let r=await C(n),i=ve(r.schema),o=Pl(n,i),a=h_(e.minCount),s=B(r,z()),d=(await Je(n,r.item_format,s.type_to_folder,[],i)).map(x=>typeof x.title=="string"?x.title:""),l=ml(d,{minCount:a}),u=[],m=[],f=[],p=[],h;if(!e.apply){let x;try{x=He(await Y(o))}catch(S){throw new y(S instanceof Error?S.message:String(S),_.GENERIC_FAILURE)}return h=x.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:l,registered:m,replaced:f,skipped:p,file:{path:o,definitions:h},warnings:u,generated_at:T()}}let g=J(e.author,r.author_default),w=Oe(r),v=await pe(n,Jr,r.locks.ttl_seconds,g,!!e.force,w.force_required_for_stale_lock,r.locks.wait_ms);try{let x=await Y(o),S;try{S=He(x)}catch(R){throw new y(R instanceof Error?R.message:String(R),_.GENERIC_FAILURE)}let b=S;for(let R of l){if(R.shadows_builtin){p.push({name:R.name,reason:"shadows_builtin"});continue}let k;try{k=Ui({name:R.name})}catch{p.push({name:R.name,reason:"invalid_type_token"});continue}let I=cr(b,k);b=I.file,(I.replaced?f:m).push(I.definition.name)}h=b.definitions.length,await lt({pmRoot:n,filePath:o,raw:at(b),op:"schema:infer-types",author:g,settings:r}),await Cn(n,b.definitions.filter(R=>m.includes(R.name)||f.includes(R.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:a,candidates:l,registered:m,replaced:f,skipped:p,file:{path:o,definitions:h},warnings:ut(u),generated_at:T()}}import Fl from"node:fs/promises";import Fo 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 xe(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function E(e){return e.trim().toLowerCase()}function Kr(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 y("Extension manifest name must resolve to a non-empty directory name.",_.USAGE);if(i==="."||i==="..")throw new y('Extension manifest name must not resolve to "." or "..".',_.USAGE);return i}function jo(e){return Is(e)}async function g_(e){try{let t=JSON.parse(await Fl.readFile(Fo.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 __(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new y(`Extension entry file is missing at "${t}".`,_.USAGE);let r=await g_(n.source_root),i=r.package_name?`pm install npm:${r.package_name}`:void 0,o=n.source_input??n.source_root;return new y(`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."}`,_.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 tn(e,t={}){let n=Fo.join(e,"manifest.json");if(!await D(n))throw new y(`Extension manifest is missing at "${n}".`,_.USAGE);let r;try{r=JSON.parse(await Fl.readFile(n,"utf8"))}catch(a){throw new y(`Failed to parse extension manifest at "${n}": ${y_(a)}`,_.USAGE)}let i=jo(r);if(!i)throw new y(`Extension manifest at "${n}" is invalid.`,_.USAGE);let o=Fo.resolve(e,i.entry);if(!we(e,o))throw new y(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,_.USAGE);if(!await D(o))throw await __(i,o,t);if(!await Cs(e,o))throw new y(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,_.USAGE);return{directory:e,manifest_path:n,entry_path:o,manifest:i}}function y_(e){return e instanceof Error?e.message:String(e)}import Uo 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]="159d7bbd-1d2a-503d-b3ce-f32dcc6f6547")}catch{}})();var v_=".managed-extensions.json",Yr=1;function $n(e){return w_.join(e,v_)}function b_(){return{version:Yr,updated_at:T(),entries:[]}}function On(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 Se(e){return typeof e=="string"?e:void 0}function k_(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 x_(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:Se(t.name),package:Se(t.package),version:Se(t.version),repository:Se(t.repository),owner:Se(t.owner),repo:Se(t.repo),ref:Se(t.ref),subpath:Se(t.subpath),commit:Se(t.commit)}}function S_(e){if(typeof e!="object"||e===null)return null;let t=e;if(!k_(t))return null;let n=x_(t.source);if(!n)return null;let r=Es(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:xe(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Se(t.last_update_check_at),last_update_remote_commit:Se(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Se(t.update_error)}}function E_(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Yr||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=S_(r);i&&n.push(i)}return{version:Yr,updated_at:Se(t.updated_at)??T(),entries:On(n)}}async function he(e){let t=$n(e),n=b_();try{let r=await Uo.readFile(t,"utf8"),i=JSON.parse(r),o=E_(i);if(!o)throw new y(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,_.GENERIC_FAILURE);return{path:t,state:o,warnings:[]}}catch(r){if(r instanceof y)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&U(r))return{path:t,state:n,warnings:[]};throw new y(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,_.GENERIC_FAILURE)}}async function Et(e,t){let n=$n(e),r={version:Yr,updated_at:T(),entries:On(t.entries)};await Uo.mkdir(e,{recursive:!0}),await Uo.writeFile(n,`${JSON.stringify(r,null,2)}
20
- `,"utf8")}function Dn(e,t){let n=e.entries.filter(r=>E(r.name)!==E(t.name)&&E(r.directory)!==E(t.directory));return n.push(t),{...e,updated_at:T(),entries:On(n)}}async function Ul(e,t,n,r){let i=t.entries.find(a=>E(a.name)===E(n));if(!i)return t;let o=Dn(t,{...i,contributions:r});return await Et(e,o),o}import{execFile as M_}from"node:child_process";import H from"node:fs/promises";import Ho from"node:os";import N from"node:path";import{fileURLToPath as L_}from"node:url";import{promisify as F_}from"node:util";import j_ from"npm-package-arg";import{extract as U_,list as z_}from"tar";import A_ from"node:fs/promises";import De 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 R_="PM_CLI_PACKAGE_ROOT",zl={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},I_=new Set(["*","all"]);function zo(){let e=[],t=process.env[R_];return typeof t=="string"&&t.trim().length>0&&e.push(De.resolve(t.trim())),e.push(Ee(import.meta.url,["../../.."])),[...new Set(e)]}async function Pn(e){let t=e.trim().toLowerCase(),n=await ql(t);if(n)return n;let r=zl[t];if(!r)return null;for(let i of zo()){let o=De.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await D(De.join(o,"manifest.json")))return o}return null}function Wl(e){return I_.has(e.trim().toLowerCase())}function C_(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function T_(e,t){let n=await A_.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=De.join(e,r.name);if(!await D(De.join(i,"package.json")))continue;let o=await or(i),a=o.aliases&&o.aliases.length>0?o.aliases:[C_(r.name)];for(let s of a){let c=s.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 Wo(){let e=new Map;for(let t of zo()){let n=De.join(t,"packages");await D(n)&&await T_(n,e)}for(let[t,n]of Object.entries(zl))if(!e.has(t))for(let r of zo()){let i=De.join(r,"packages",n.package_directory);if(await D(De.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 Xr(){return(await Wo()).map(e=>e.alias)}async function ql(e){let t=e.trim().toLowerCase();return(await Wo()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function Bl(e){let t=await ql(e);return t?(await or(t)).package_name??null:null}async function Hl(e){let t=await Pn(e);if(!t)return null;try{let n=await ar(t);return n.length!==1?null:(await tn(n[0])).manifest.name}catch{return null}}function $_(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 O_(e,t,n,r,i,o){let a=r==="global"?"--global":"--project",s=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(De.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${a}`,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:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:$_(e),media:e.catalog?.media}}}async function Gl(e,t,n={}){let r=Tt(L(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,o=await he(i),a=new Set(o.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>De.resolve(m.source.location))),s=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 Wo()){let f=De.resolve(m.package_root),p=d.get(f)??[];p.push(m),d.set(f,p)}for(let m of d.values()){let f=m[0],p=m.map(g=>g.alias).sort((g,w)=>g.localeCompare(w)),h=await or(f.package_root);c.push(O_(h,f,p,e,s,a))}let l=P_(n.fields),u=l?c.map(m=>N_(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 D_=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 P_(e){if(e===void 0)return;let t=Ir(e);if(t.length===0)throw new y("Package catalog --fields requires a comma-separated list of field names",_.USAGE);let n=t.filter(r=>!D_.has(r));if(n.length>0)throw new y(`Unknown package catalog --fields value(s): ${n.join(", ")}`,_.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function N_(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]="89b84412-aa15-5868-95b3-c8d898b1f480")}catch{}})();var Go=F_(M_),Qr="@unbrained/pm-cli",W_={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},qo;async function Jl(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 s=JSON.parse(await H.readFile(o,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let a=N.dirname(r);if(a===r)return null;r=a}}function Bo(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 a=r.slice(2),s,c;return a[0]==="tree"&&a.length>=2?(s=a[1],c=a.slice(2).join("/")):a.length>0&&(c=a.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:o,repository:`https://github.com/${i}/${o}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function q_(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new y('npm package source must include a package spec after "npm:".',_.USAGE);if(t)throw new y('Options "--gh/--github" cannot be combined with npm: package sources.',_.USAGE);if(n)throw new y('Option "--ref" cannot be combined with npm: package sources.',_.USAGE);return{kind:"npm",input:e,spec:r}}function ei(e,t={}){let n=e.trim();if(n.length===0)throw new y("Extension source is required for --install.",_.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return q_(n,t.forceGithub===!0,r);let i=(()=>{try{let a=new URL(n);if(a.hostname!=="github.com")return null;let s=a.pathname.replace(/^\/+/,"");return Bo(s,n,r)}catch{return null}})();if(i)return i;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let a=Bo(o,n,r);if(!a)throw new y(`Invalid GitHub source "${n}".`,_.USAGE);return a}if(t.forceGithub){let a=Bo(n,n,r);if(!a)throw new y(`Invalid GitHub shorthand "${n}".`,_.USAGE);return a}if(/^https?:\/\//i.test(n))throw new y(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,_.USAGE);return{kind:"local",input:n,absolute_path:N.resolve(process.cwd(),n)}}async function Zr(e,t=Go,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 y(`Git command failed: git ${e.join(" ")}
21
- ${o}`,_.GENERIC_FAILURE)}}function B_(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function H_(e=process.platform){return e==="win32"}async function Vl(e,t,n=Go,r=process.platform,i=process.env){let o=B_(r),a=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(o,e,{cwd:t,encoding:"utf8",env:a,shell:H_(r)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",d=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new y(`npm command failed: ${o} ${e.join(" ")}
22
- ${d}`,_.GENERIC_FAILURE)}}function G_(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 J_(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 V_(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return J_(e)||n.includes("not found")}function K_(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Y_(e){let t=G_(e),n=K_(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 X_(e,t){if(!V_(t))return null;let n=Y_(e);return new y(n.message,_.NOT_FOUND,n.context)}async function Kl(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=L_(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 Z_(e){let t=await Kl(e);if(t)return t;let n=Q_(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Q_(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(r<=0)return e;let i=e.slice(0,r),o=e.slice(r+n.length);if(i.trim().length===0||o.trim().length===0||o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${i}@${N.resolve(t,o)}`;let a;try{a=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(a)?a.slice(1):a;return`${i}@${s}`}function ey(e,t){try{let r=JSON.parse(e),i=Array.isArray(r)?r[0]:void 0;if(i&&typeof i.filename=="string"&&i.filename.trim().length>0)return{tarball:N.resolve(t,i.filename),package:typeof i.name=="string"?i.name:void 0,version:typeof i.version=="string"?i.version:void 0}}catch{}let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).at(-1);if(!n)throw new y("npm pack did not report a tarball filename.",_.GENERIC_FAILURE);return{tarball:N.resolve(t,n)}}async function ty(e){return ny(e,Vl)}async function ny(e,t){let n=await Kl(e.spec);if(n){if((await H.stat(n)).isFile()&&Yl(n))return Xl(n);let s=N.join(n,"package.json"),c=await D(s)?JSON.parse(await H.readFile(s,"utf8")):{};return{directory:await Nn(n,e.input),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{}}}let r=await H.mkdtemp(N.join(Ho.tmpdir(),"pm-npm-package-source-")),i=N.join(r,"pack"),o=N.join(r,"extract");await H.mkdir(i,{recursive:!0}),await H.mkdir(o,{recursive:!0});try{let a=await Z_(e.spec),s=await t(["pack",a,"--json","--pack-destination",i]),c=ey(s,i);await Go("tar",["-xzf",c.tarball,"-C",o],{encoding:"utf8"});let d=N.join(o,"package");return await Zl(d),{directory:await Nn(d,e.input),package:c.package,version:c.version,cleanup:async()=>{await H.rm(r,{recursive:!0,force:!0})}}}catch(a){await H.rm(r,{recursive:!0,force:!0});let s=X_(e.spec,a);throw s||a}}function Yl(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function Qe(e){throw new y(e,_.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 ry(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&Qe(`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===".."))&&Qe(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&Qe(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&Qe(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&Qe(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&Qe(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&Qe(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function Xl(e,t=W_){(await H.stat(e)).size>t.maxArchiveBytes&&Qe(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await H.mkdtemp(N.join(Ho.tmpdir(),"pm-local-package-archive-")),i=N.join(r,"extract");await H.mkdir(i,{recursive:!0});let o={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await z_({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(a===void 0)try{ry(l,t,o)}catch(u){a=u}}}),a!==void 0)throw a;o.packageJsonEntries!==1&&Qe(`Local package archive must contain exactly one package/package.json entry; found ${o.packageJsonEntries}.`),await U_({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=N.join(i,"package"),c=N.join(s,"package.json"),d=JSON.parse(await H.readFile(c,"utf8"));return await Zl(s),{directory:await Nn(s,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await H.rm(r,{recursive:!0,force:!0})}}}catch(s){throw await H.rm(r,{recursive:!0,force:!0}),s}}async function Zl(e,t=Vl){let n=N.join(e,"package.json");if(!await D(n))return;let r;try{r=JSON.parse(await H.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,o=dy(i),a=iy(i);if(o.length===0&&!a)return;let s={...r};delete s.devDependencies;let c={...s};oy(c),await H.writeFile(n,`${JSON.stringify(c,null,2)}
15
+ `;return c===i?{path:r,changed:!1}:(n||await cg(r,c,"utf8"),{path:r,changed:!0})}function qr(e){let t=B(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function ll(e,t){let n=ie.resolve(e),r=null,i="",o=n;for(let v=0;v<8;v+=1){let x=ie.join(o,".gitattributes");try{let b=await Wr(x,"utf8");if(b.includes(Xt)||b.includes(zr)){r=o,i=b;break}}catch{}let S=ie.dirname(o);if(S===o)break;o=S}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let a=ie.join(r,".gitattributes"),s=i.includes(Xt),c=s?Xt:zr,d=s?Ao:ol,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):[],f=Co(Io(r,n),t),p=new Set(m),h=new Set(f),g=f.filter(v=>!p.has(v)),w=m.filter(v=>!h.has(v));return{status:g.length>0||w.length>0?"drift":"ok",path:a,missing_patterns:g,stale_patterns:w,schema_scope:"project"}}async function Br(e){let t=al(),n=[],r=[];for(let i of sl){let o=`merge.${i.key}.driver`,a=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`,s=`${t}${a}`;try{let{stdout:c}=await Ro("git",["config","--local","--get",o],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),d=c.trim();d!==s&&!await pg(d,a)&&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 ul(e){let t;try{t=await cl(ie.resolve(e))}catch{return{status:"no_git"}}let n=Io(t,ie.resolve(e)),r=await C(e),i=J(void 0,r.author_default),o=await pe(e,ug,r.locks.ttl_seconds,i,!1,Oe(r).force_required_for_stale_lock,r.locks.wait_ms);try{let a=ie.join(t,".gitattributes"),s;try{s=await Wr(a,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&U(u))return{status:"not_installed",path:a};throw u}if(!s.includes(Xt)&&!s.includes(zr))return{status:"not_installed",path:a};let c=await C(e),d=qr(c),l=await dl(t,Co(n,d),!1);return{status:l.changed?"refreshed":"unchanged",path:l.path}}finally{await o()}}async function uC(e,t){let n=mg({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await Q(r);let i=await cl(n.workspace_start);return fg({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function fg(e){let t=ie.resolve(e.pmRoot),n=ie.resolve(e.workspaceRoot),r=e.dryRun===!0,i,o;try{[i,o]=await Promise.all([Eo(t),Eo(n)])}catch(f){throw new y(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,_.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 a=Io(o,i);if(So(a))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,_.USAGE);let s=await C(i),c=qr(s),d=Co(a,c),l=[],u=al();for(let f of sl)l.push({key:`merge.${f.key}.name`,value:f.name}),l.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!r)try{for(let f of l)await Ro("git",["config","--local",f.key,f.value],{cwd:o,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new y(`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.`,_.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 dl(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 hg=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function gg(e){let t=hg.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function _g(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function ml(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 a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=gg(s);if(c===void 0)continue;let d=i.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(s),i.set(c,d)}let o=[];for(let[a,s]of i.entries()){if(s.count<n)continue;let c=_g(a);o.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:Ds(c)!==void 0})}return o.sort((a,s)=>s.count-a.count||a.name.localeCompare(s.name)),o}import{createHash as Sl}from"node:crypto";import St from"node:fs/promises";import Qt from"node:path";import{mkdir as yg,readFile as wg}from"node:fs/promises";import yl 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 To=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},vg="sdk-workspace-transaction",bg=/^[a-zA-Z0-9._-]+$/,kg=30,xg=3e3;function pl(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!bg.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function fl(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 hl(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 wl(e,t){return yl.join(e,"transactions","sdk",`${t}.json`)}async function ct(e,t){t.updatedAt=T();let n=wl(e,t.transactionId);await yg(yl.dirname(n),{recursive:!0}),await se(n,`${JSON.stringify(t,null,2)}
17
+ `)}function Sg(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function xt(e){return Object.assign(Object.create(null),e)}function Eg(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 $o(e,t){return e===void 0?void 0:Eg(e,t)}function Oo(e,t,n,r){let i=$o(n,r);i===void 0?delete e[t]:e[t]=i}function gl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _l(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Ag(e,t){if(!_l(e.startedStepIds,t)||!_l(e.completedStepIds,t)||!gl(e.results)||!gl(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(a=>!r.has(a))||Object.keys(e.results).some(a=>!o.has(a))?!1:e.status==="committed"?t.every(a=>o.has(a)):e.status!=="compensated"||o.size===0&&r.size===0}function Rg(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,a=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((l,u)=>l===n[u]),s=Ag(i,n),c=Sg(i),d=["applying","compensating","compensated","committed"].includes(String(i.status));if(!o||!a||!s||!c||!d)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...i,results:xt(i.results),compensationData:xt(i.compensationData)}}async function Ig(e,t,n,r,i){let o=i,a=o!==void 0;if(o?.status==="compensating"&&await vl(e,o),o===void 0||o.status==="compensated"){let s=T();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:xt(),compensationData:xt()},await ct(e.pmRoot,o),await Ye(e,o,"prepared")}return{journal:o,recovered:a}}async function Cg(e,t,n){try{await $g(t,e.steps),await ct(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 a=await o.inspect(),s=$o(a.result,`Step ${o.id} result`);if(a.state!=="applied"){let c=await o.prepareCompensation?.();Oo(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 ct(e.pmRoot,t);let d=await o.apply();s=$o(d,`Step ${o.id} result`)}await Ye(e,t,"step_applied",o.id),r.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),Oo(t.results,o.id,s,`Step ${o.id} result`),await ct(e.pmRoot,t),await Ye(e,t,"step_recorded",o.id)}return await Ye(e,t,"committing"),t.status="committed",await ct(e.pmRoot,t),await Ye(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:xt(t.results)}}catch(r){if(r instanceof To||t.status==="committed")throw r;try{await vl(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function Tg(e,t,n){try{return Rg(await wg(wl(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&U(r))return;throw r}}async function Ye(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function $g(e,t){let n=new Set,r=xt();for(let i of t){let o=await i.inspect();o.state==="applied"&&(n.add(i.id),Oo(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 vl(e,t){t.status="compensating",await ct(e.pmRoot,t),await Ye(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 Ye(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(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>r.has(a)),delete t.results[i.id],delete t.compensationData[i.id],await ct(e.pmRoot,t),await Ye(e,t,"step_compensated",i.id)}t.status="compensated",await ct(e.pmRoot,t),await Ye(e,t,"compensated")}async function bl(e){let t=fl(e.pmRoot,"Transaction pmRoot"),n=pl(e.transactionId,"Transaction id"),r=fl(e.author,"Transaction author"),i=hl(e.lockTtlSeconds,kg,"Transaction lock TTL"),o=hl(e.lockWaitMs,xg,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(l=>{let u=pl(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(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:a,lockTtlSeconds:i,lockWaitMs:o},d=await pe(t,vg,i,r,!1,!1,o);try{let l=await Tg(t,n,s),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:xt(l.results)};let m=await Ig(c,n,r,s,l);return await Cg(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 Xe(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function El(e){let t=Xe(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Al(e,t){let n=Po(e),r=Xe(t,"migrationScope");return`auto-${Sl("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function Po(e){let t=e.kind==="rename-type"?{kind:e.kind,from:Xe(e.from,"source"),to:Xe(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:ce(Xe(e.from,"source")),to:ce(Xe(e.to,"target")),...e.type===void 0?{}:{type:Xe(e.type,"type")}}:{kind:e.kind,from:ce(Xe(e.from,"source")),to:ce(Xe(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Og(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Dg(e,t,n){let r=ve(t.schema),i=Og(n);return Le(e,r.files[i],Ae[i])}function Rl(e,t){return Qt.join(e,"transactions","schema",`${t}-plan.json`)}function Hr(e){return e.length===0?null:JSON.parse(e)}async function Zt(e){let t=await Y(e);return{exists:t!==null,raw:t??""}}async function Il(e,t){t.exists?await se(e,t.raw):await St.rm(e,{force:!0})}function Pg(e,t,n){let r=He(e),i=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),o=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return at(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 at(r)}function Ng(e,t,n){let r=$t(e),i=r.fields.findIndex(a=>a.key===t.from),o=r.fields.findIndex(a=>a.key===t.to);if(n==="stage"){if(o>=0)return Ot(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let a=r.fields[i];r.fields.push({...a,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 Ot(r)}function Mg(e,t,n){let r=Dt(e),i=r.statuses.findIndex(a=>a.id===t.from),o=r.statuses.findIndex(a=>a.id===t.to);if(n==="stage"){if(o>=0)return Pt(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 Pt(r)}function Lg(e,t,n){return t.kind==="rename-type"?Pg(e,t,n):t.kind==="rename-field"?Ng(e,t,n):Mg(e,t,n)}function dt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function No(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function en(e){return Array.isArray(e)?e.map(t=>No(t)).filter(t=>t!==void 0):[]}function Fg(e,t){for(let n of en(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>dt(r,t)));for(let n of en(e.type_workflows))n.type=dt(n.type,t)}function jg(e,t){for(let r of en(e.definitions))r.default_status=dt(r.default_status,t);let n=No(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=dt(i,t);for(let r of en(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(o=>dt(o,t)):i))}function Ug(e,t){for(let n of en(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>dt(i,t)));for(let r of["options","command_option_policies"])for(let i of en(n[r])){let o=r==="options"?"key":"option";i[o]=dt(i[o],t)}}}function zg(e,t){let n=No(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]=dt(n[r],t)}function Do(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"?Fg(r,t):t.kind==="rename-field"?Ug(r,t):jg(r,t),zg(r,t),`${JSON.stringify(r,null,2)}
18
+ `}function Cl(e,t){if(t.kind==="rename-type"){let r=He(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=$t(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=Dt(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function Wg(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 qg(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 Tl(e,t){let n=Po(t.request),r=t.migrationId===void 0?Al(n,t.migrationScope??"plan"):El(t.migrationId),i=e.map(c=>qg(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),o=Sl("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),a=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!a.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:o,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function Bg(e){let t=B(e.settings,z()),n=[...new Set(Object.values(t.type_to_folder))],r=await kr(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 hc({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 Je(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Hg(e,t){let n=await Y(Rl(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 y(`Stored schema migration plan "${t}" is invalid: ${ks(r)}`,_.GENERIC_FAILURE)}}async function Gg(e,t){let n=Rl(e,t.migration_id);await St.mkdir(Qt.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await se(n,`${JSON.stringify(r,null,2)}
19
+ `)}function Jg(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Vg(e){let t=await jt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new y(`Schema migration item "${e.id}" no longer exists.`,_.NOT_FOUND);return(await st(t,{schema:e.settings.schema})).document.metadata}function kl(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 xl(e){return{id:e.id,inspect:async()=>{let t=await Zt(e.filePath),n=Cl(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 Zt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Zt(e.filePath);return await se(e.filePath,Lg(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 Il(e.filePath,{exists:t.exists,raw:t.raw})}}}function Kg(e){return{id:e.stepId,inspect:async()=>{let t=await Zt(e.filePath);return{state:Do(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Zt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Zt(e.filePath);return await se(e.filePath,Do(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 Il(e.filePath,{exists:t.exists,raw:t.raw})}}}function Yg(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await C(e.pmRoot),n=B(t,z()).type_to_folder,r=await Vg({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=Wg(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=B(t,z()).type_to_folder,r=await wt({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:kl(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await C(e.pmRoot),n=B(t,z()).type_to_folder;await wt({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:kl(r,e.request,"reverse")}}})}}}async function Xg(e){let t=await Hg(e.pmRoot,e.migrationId);if(t){if(!Jg(t.request,e.request))throw new y(`Schema migration id "${e.migrationId}" already belongs to a different request.`,_.CONFLICT);return{plan:t,stored:!0}}let n=await Bg({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Tl(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Zg(e){let t=Cl(await Y(e.schemaPath)??"",e.request);if(!t.source)throw new y(`Schema migration source "${e.request.from}" is not a custom definition.`,_.NOT_FOUND);if(t.target)throw new y(`Schema migration target "${e.request.to}" already exists.`,_.CONFLICT);await Gg(e.pmRoot,e.plan)}async function Qg(e){let t=ve(e.settings.schema),n=[...new Set([["types",Ae.types],["fields",Ae.fields],["workflows",Ae.workflows]].map(([i,o])=>Le(e.pmRoot,t.files[i],o)).filter(i=>i!==e.schemaPath))];try{let i=Qt.join(e.pmRoot,"templates"),o=await St.readdir(i,{withFileTypes:!0});n.push(...o.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>Qt.join(i,a.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&&Do(o,e.request)!==o&&r.push({filePath:i,beforeRaw:o})}return{paths:n,snapshots:r}}async function e_(e){for(let t of e.snapshots){let n=await St.readFile(t.filePath,"utf8"),r=Qt.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await Vi({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Hr(t.beforeRaw),after:Hr(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 t_(e,t,n){let r=Po(e),i=L(process.cwd(),n.path);await Q(i);let o=t.migrationId===void 0?Al(r,await St.realpath(i)):El(t.migrationId),a=await C(i),s=J(t.author,a.author_default),c=await Xg({pmRoot:i,settings:a,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=Dg(i,a,r),u=await St.readFile(l,"utf8");c.stored||await Zg({pmRoot:i,schemaPath:l,request:r,plan:d});let m=await Qg({pmRoot:i,schemaPath:l,settings:a,request:r}),f=[xl({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...m.paths.map((w,v)=>Kg({filePath:w,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>Yg({pmRoot:i,id:w.id,request:r,author:s,force:t.force===!0})),xl({id:"retire-source",filePath:l,request:r,phase:"retire"})],p=await bl({pmRoot:i,transactionId:`schema-${o}`,author:s,steps:f,lockTtlSeconds:Math.max(a.locks.ttl_seconds,300),lockWaitMs:a.locks.wait_ms}),h=await St.readFile(l,"utf8"),{historyPath:g}=await Vi({pmRoot:i,author:s,documentPath:Qt.relative(i,l).replaceAll("\\","/"),before:Hr(u),after:Hr(h),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await e_({pmRoot:i,author:s,settings:a,request:r,plan:d,snapshots:m.snapshots}),{...d,action:r.kind,applied:!0,recovered:p.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]="6112923d-5e06-5839-b452-a32818c6398d")}catch{}})();var hT=["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"],Gr="schema-types",$l="schema-statuses",Ol="schema-fields";function lt(e){return vr({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 gT(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i;try{i=Ui({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(f){throw new y(f instanceof Error?f.message:String(f),_.USAGE)}let o=await C(r),a=ve(o.schema),s=Le(r,a.files.types,Ae.types),c=[],d=J(t.author,o.author_default),l=Oe(o),u=await pe(r,Gr,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms),m;try{let f=await Y(s),p;try{p=He(f)}catch(h){throw new y(h instanceof Error?h.message:String(h),_.GENERIC_FAILURE)}try{Ps(i,p);let h=new Map,g=B(o,z());for(let[w,v]of Object.entries(g.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!h.has(x)&&h.set(x,w)}Ns(i,p,h)}catch(h){throw new y(h instanceof Error?h.message:String(h),_.USAGE)}m=sr(p,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await lt({pmRoot:r,filePath:s,raw:at(m.file),op:"schema:add-type",author:d,settings:o}),await Cn(r,[m.definition],c,"schema:add-type-folder"),c.push(...await ne({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await Dl(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:ut(c),generated_at:T()}}async function Ze(e){await Q(e)}async function Dl(e,t){try{let n=await ul(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 ut(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function i_(e,t,n,r){let i=B(t,z()),o=r.trim().toLowerCase();return(await Je(e,t.item_format,i.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===o).length}async function o_(e,t,n,r){let i=B(t,z()),o=$e(n),a=ce(r);return(await Je(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(ce(d))??ce(d))===a}).length}async function a_(e,t,n,r,i){if(i.length===0||Wi.has(i))return;let o=await o_(t,n,r,i);o>0&&e.push(`items_using_status:${o}`);let a=s_(r.workflow,i);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function s_(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&&ce(r)===t).map(([r])=>r)}async function _T(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i=await C(r),o=ve(i.schema),a=Le(r,o.files.types,Ae.types),s=[],c=J(t.author,i.author_default),d=Oe(i),l=await pe(r,Gr,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(a),f;try{f=He(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.GENERIC_FAILURE)}try{u=Ms(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.USAGE)}if(u.removed){let p=(u.definition?.name??e??"").trim();if(p.length>0){let h=await i_(r,i,o,p);h>0&&s.push(`items_using_type:${h}`)}await lt({pmRoot:r,filePath:a,raw:at(u.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await ne({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await Dl(r,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:a,definitions:u.file.definitions.length},warnings:ut(s),generated_at:T()}}function Mo(e,t){return Le(e,t.files.statuses,Ae.statuses)}function Jr(e,t){return Le(e,t.files.fields,Ae.fields)}function Pl(e,t){return Le(e,t.files.types,Ae.types)}async function Cn(e,t,n,r){for(let i of t){let o=ws(i.folder??ys(i.name)),a=n_.join(e,o);await D(a)||(await r_(a,{recursive:!0}),n.push(...await ne({path:a,scope:"project",op:r})))}}function Lo(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 c_(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 d_(e){let t=new Map;for(let n of e){let r=ce(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let o=ce(i);o.length>0&&!t.has(o)&&t.set(o,r)}}}return t}async function yT(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i;try{i=qs({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(h){throw new y(h instanceof Error?h.message:String(h),_.USAGE)}let o=await C(r),a=ve(o.schema),s=Mo(r,a),c=$e(a);try{qi(i,c.alias_to_id)}catch(h){throw new y(h instanceof Error?h.message:String(h),_.USAGE)}let d=c_(c.by_id.get(i.id)),l=[],u=J(t.author,o.author_default),m=Oe(o),f=await pe(r,$l,o.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,o.locks.wait_ms),p;try{let h=await Y(s),g;try{g=Dt(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),_.GENERIC_FAILURE)}let w=d_(g.statuses);try{qi(i,w)}catch(v){throw new y(v instanceof Error?v.message:String(v),_.USAGE)}p=Bs(g,i,d),await lt({pmRoot:r,filePath:s,raw:Pt(p.file),op:"schema:add-status",author:u,settings:o}),l.push(...await ne({path:s,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:p.replaced,status:p.definition,file:{path:s,statuses:p.file.statuses.length},warnings:ut(l),generated_at:T()}}async function wT(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i=await C(r),o=ve(i.schema),a=Mo(r,o),s=[],c=J(t.author,i.author_default),d=Oe(i),l=await pe(r,$l,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(a),f;try{f=Dt(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.GENERIC_FAILURE)}try{u=Hs(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.USAGE)}if(u.removed){let p=ce(u.definition?.id??e);await a_(s,r,i,o,p),await lt({pmRoot:r,filePath:a,raw:Pt(u.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await ne({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:a,statuses:u.file.statuses.length},warnings:ut(s),generated_at:T()}}function Nl(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 l_(e,t,n){return{...Nl(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 Ml(e){return{id:e.id,source:Wi.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 Ll(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function u_(){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 m_(e){let t=$e(e),n=[],r=[];for(let i of t.definitions){let o=Ml(i);o.source==="builtin"?n.push(o):r.push(o)}return{builtin:n,custom:r}}async function Tn(e){let t=L(process.cwd(),e.path);await Ze(t);let n=await C(t),r=ve(n.schema),i=Le(t,r.files.types,Ae.types),o=Mo(t,r),a=B(n,z()),s=u_(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:i,statusesPath:o,byType:a.by_type,customNames:c,extensionProvenance:s,schema:r}}async function vT(e){let t=await Tn(e),n=[],r=[],i=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Ll(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=Nl(s);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let o=m_(t.schema),a=cr(t.schema).definitions.map(Lo);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:a,counts:{total:a.length}},file:{path:t.typesPath},generated_at:T()}}async function bT(e,t){let n=(e??"").trim();if(n.length===0)throw new y("Type name must not be empty.",_.USAGE);let r=await Tn(t),i=Object.values(r.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!i)throw new y(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${ar(n)}" to register it.`,_.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:l_(i,Ll(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:T()}}async function kT(e,t){let n=ce(e);if(n.length===0)throw new y("Status id must not be empty.",_.USAGE);let r=await Tn(t),i=$e(r.schema),o=i.alias_to_id.get(n)??n,a=i.by_id.get(o);if(!a)throw new y(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${ar(e??"")}" to register it.`,_.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Ml(a),file:{path:r.statusesPath},generated_at:T()}}async function xT(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i;try{i=js({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(p){throw new y(p instanceof Error?p.message:String(p),_.USAGE)}let o=await C(r),a=ve(o.schema),s=Jr(r,a),c=[],d=dr(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=J(t.author,o.author_default),u=Oe(o),m=await pe(r,Ol,o.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,o.locks.wait_ms),f;try{let p=await Y(s),h;try{h=$t(p)}catch(g){throw new y(g instanceof Error?g.message:String(g),_.GENERIC_FAILURE)}f=Us(h,i),await lt({pmRoot:r,filePath:s,raw:Ot(f.file),op:"schema:add-field",author:l,settings:o}),c.push(...await ne({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:s,fields:f.file.fields.length},warnings:ut(c),generated_at:T()}}async function p_(e,t,n,r){let i=B(t,z());return(await Je(e,t.item_format,i.type_to_folder,[],n)).filter(a=>{let s=a[r];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function ST(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i=await C(r),o=ve(i.schema),a=Jr(r,o),s=[],c=J(t.author,i.author_default),d=Oe(i),l=await pe(r,Ol,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await Y(a),f;try{f=$t(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.GENERIC_FAILURE)}try{u=zs(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),_.USAGE)}if(u.removed){let p=ce(u.definition?.key??e),h=ce(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(h.length>0){let g=await p_(r,i,o,h);g>0&&s.push(`items_using_field:${g}`)}await lt({pmRoot:r,filePath:a,raw:Ot(u.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await ne({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:a,fields:u.file.fields.length},warnings:ut(s),generated_at:T()}}async function ET(e){let t=await Tn(e),n=cr(t.schema).definitions.map(Lo);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Jr(t.pmRoot,t.schema)},generated_at:T()}}async function AT(e,t){let n=ce(e);if(n.length===0)throw new y("Field key must not be empty.",_.USAGE);let r=await Tn(t),i=cr(r.schema).by_key.get(n);if(!i)throw new y(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${ar(e??"")}" to register it.`,_.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Lo(i),file:{path:Jr(r.pmRoot,r.schema)},generated_at:T()}}async function RT(e,t,n){let r=L(process.cwd(),n.path);await Ze(r);let i;try{let h=Fs(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${Ls.join(", ")}.`);i=h}catch(h){throw new y(h instanceof Error?h.message:String(h),_.USAGE)}let o=await C(r),a=ve(o.schema),s=Pl(r,a),c=[],d=J(t.author,o.author_default),l=Oe(o),u=[],m=[],f,p=await pe(r,Gr,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms);try{let h=await Y(s),g;try{g=He(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),_.GENERIC_FAILURE)}let w=g;for(let v of zi(i)){let x=sr(w,v);w=x.file,(x.replaced?m:u).push(x.definition.name)}f=w.definitions.length,await lt({pmRoot:r,filePath:s,raw:at(w),op:"schema:apply-preset",author:d,settings:o}),await Cn(r,zi(i),c,"schema:apply-preset-folder"),c.push(...await ne({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await p()}return{action:"apply-preset",preset:i,registered:u,replaced:m,file:{path:s,definitions:f},warnings:ut(c),generated_at:T()}}function f_(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new y("--min-count must be a positive integer (>= 1).",_.USAGE);return e}async function IT(e,t){let n=L(process.cwd(),t.path);await Ze(n);let r=await C(n),i=ve(r.schema),o=Pl(n,i),a=f_(e.minCount),s=B(r,z()),d=(await Je(n,r.item_format,s.type_to_folder,[],i)).map(x=>typeof x.title=="string"?x.title:""),l=ml(d,{minCount:a}),u=[],m=[],f=[],p=[],h;if(!e.apply){let x;try{x=He(await Y(o))}catch(S){throw new y(S instanceof Error?S.message:String(S),_.GENERIC_FAILURE)}return h=x.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:l,registered:m,replaced:f,skipped:p,file:{path:o,definitions:h},warnings:u,generated_at:T()}}let g=J(e.author,r.author_default),w=Oe(r),v=await pe(n,Gr,r.locks.ttl_seconds,g,!!e.force,w.force_required_for_stale_lock,r.locks.wait_ms);try{let x=await Y(o),S;try{S=He(x)}catch(R){throw new y(R instanceof Error?R.message:String(R),_.GENERIC_FAILURE)}let b=S;for(let R of l){if(R.shadows_builtin){p.push({name:R.name,reason:"shadows_builtin"});continue}let k;try{k=Ui({name:R.name})}catch{p.push({name:R.name,reason:"invalid_type_token"});continue}let I=sr(b,k);b=I.file,(I.replaced?f:m).push(I.definition.name)}h=b.definitions.length,await lt({pmRoot:n,filePath:o,raw:at(b),op:"schema:infer-types",author:g,settings:r}),await Cn(n,b.definitions.filter(R=>m.includes(R.name)||f.includes(R.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:a,candidates:l,registered:m,replaced:f,skipped:p,file:{path:o,definitions:h},warnings:ut(u),generated_at:T()}}import Fl from"node:fs/promises";import Fo 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 xe(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function E(e){return e.trim().toLowerCase()}function Vr(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 y("Extension manifest name must resolve to a non-empty directory name.",_.USAGE);if(i==="."||i==="..")throw new y('Extension manifest name must not resolve to "." or "..".',_.USAGE);return i}function jo(e){return Is(e)}async function h_(e){try{let t=JSON.parse(await Fl.readFile(Fo.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 g_(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new y(`Extension entry file is missing at "${t}".`,_.USAGE);let r=await h_(n.source_root),i=r.package_name?`pm install npm:${r.package_name}`:void 0,o=n.source_input??n.source_root;return new y(`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."}`,_.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 tn(e,t={}){let n=Fo.join(e,"manifest.json");if(!await D(n))throw new y(`Extension manifest is missing at "${n}".`,_.USAGE);let r;try{r=JSON.parse(await Fl.readFile(n,"utf8"))}catch(a){throw new y(`Failed to parse extension manifest at "${n}": ${__(a)}`,_.USAGE)}let i=jo(r);if(!i)throw new y(`Extension manifest at "${n}" is invalid.`,_.USAGE);let o=Fo.resolve(e,i.entry);if(!we(e,o))throw new y(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,_.USAGE);if(!await D(o))throw await g_(i,o,t);if(!await Cs(e,o))throw new y(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,_.USAGE);return{directory:e,manifest_path:n,entry_path:o,manifest:i}}function __(e){return e instanceof Error?e.message:String(e)}import Uo from"node:fs/promises";import y_ from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="159d7bbd-1d2a-503d-b3ce-f32dcc6f6547")}catch{}})();var w_=".managed-extensions.json",Kr=1;function $n(e){return y_.join(e,w_)}function v_(){return{version:Kr,updated_at:T(),entries:[]}}function On(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 Se(e){return typeof e=="string"?e:void 0}function b_(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 k_(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:Se(t.name),package:Se(t.package),version:Se(t.version),repository:Se(t.repository),owner:Se(t.owner),repo:Se(t.repo),ref:Se(t.ref),subpath:Se(t.subpath),commit:Se(t.commit)}}function x_(e){if(typeof e!="object"||e===null)return null;let t=e;if(!b_(t))return null;let n=k_(t.source);if(!n)return null;let r=Es(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:xe(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Se(t.last_update_check_at),last_update_remote_commit:Se(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Se(t.update_error)}}function S_(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Kr||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=x_(r);i&&n.push(i)}return{version:Kr,updated_at:Se(t.updated_at)??T(),entries:On(n)}}async function he(e){let t=$n(e),n=v_();try{let r=await Uo.readFile(t,"utf8"),i=JSON.parse(r),o=S_(i);if(!o)throw new y(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,_.GENERIC_FAILURE);return{path:t,state:o,warnings:[]}}catch(r){if(r instanceof y)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&U(r))return{path:t,state:n,warnings:[]};throw new y(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,_.GENERIC_FAILURE)}}async function Et(e,t){let n=$n(e),r={version:Kr,updated_at:T(),entries:On(t.entries)};await Uo.mkdir(e,{recursive:!0}),await Uo.writeFile(n,`${JSON.stringify(r,null,2)}
20
+ `,"utf8")}function Dn(e,t){let n=e.entries.filter(r=>E(r.name)!==E(t.name)&&E(r.directory)!==E(t.directory));return n.push(t),{...e,updated_at:T(),entries:On(n)}}async function Ul(e,t,n,r){let i=t.entries.find(a=>E(a.name)===E(n));if(!i)return t;let o=Dn(t,{...i,contributions:r});return await Et(e,o),o}import{execFile as N_}from"node:child_process";import H from"node:fs/promises";import Go from"node:os";import N from"node:path";import{fileURLToPath as M_}from"node:url";import{promisify as L_}from"node:util";import F_ from"npm-package-arg";import{extract as j_,list as U_}from"tar";import E_ from"node:fs/promises";import De 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 A_="PM_CLI_PACKAGE_ROOT",zl={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},R_=new Set(["*","all"]);function zo(){let e=[],t=process.env[A_];return typeof t=="string"&&t.trim().length>0&&e.push(De.resolve(t.trim())),e.push(Ee(import.meta.url,["../../.."])),[...new Set(e)]}async function Pn(e){let t=e.trim().toLowerCase(),n=await ql(t);if(n)return n;let r=zl[t];if(!r)return null;for(let i of zo()){let o=De.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await D(De.join(o,"manifest.json")))return o}return null}function Wl(e){return R_.has(e.trim().toLowerCase())}function I_(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function C_(e,t){let n=await E_.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=De.join(e,r.name);if(!await D(De.join(i,"package.json")))continue;let o=await ir(i),a=o.aliases&&o.aliases.length>0?o.aliases:[I_(r.name)];for(let s of a){let c=s.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 Wo(){let e=new Map;for(let t of zo()){let n=De.join(t,"packages");await D(n)&&await C_(n,e)}for(let[t,n]of Object.entries(zl))if(!e.has(t))for(let r of zo()){let i=De.join(r,"packages",n.package_directory);if(await D(De.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 Yr(){return(await Wo()).map(e=>e.alias)}async function ql(e){let t=e.trim().toLowerCase();return(await Wo()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function Bl(e){let t=await ql(e);return t?(await ir(t)).package_name??null:null}async function Hl(e){let t=await Pn(e);if(!t)return null;try{let n=await or(t);return n.length!==1?null:(await tn(n[0])).manifest.name}catch{return null}}function T_(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 $_(e,t,n,r,i,o){let a=r==="global"?"--global":"--project",s=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(De.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${a}`,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:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:T_(e),media:e.catalog?.media}}}async function Gl(e,t,n={}){let r=Tt(L(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,o=await he(i),a=new Set(o.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>De.resolve(m.source.location))),s=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 Wo()){let f=De.resolve(m.package_root),p=d.get(f)??[];p.push(m),d.set(f,p)}for(let m of d.values()){let f=m[0],p=m.map(g=>g.alias).sort((g,w)=>g.localeCompare(w)),h=await ir(f.package_root);c.push($_(h,f,p,e,s,a))}let l=D_(n.fields),u=l?c.map(m=>P_(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 O_=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 D_(e){if(e===void 0)return;let t=Rr(e);if(t.length===0)throw new y("Package catalog --fields requires a comma-separated list of field names",_.USAGE);let n=t.filter(r=>!O_.has(r));if(n.length>0)throw new y(`Unknown package catalog --fields value(s): ${n.join(", ")}`,_.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function P_(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]="404342eb-68ab-5b7d-9a5a-ade1c8e98546")}catch{}})();var Jl=L_(N_),Zr="@unbrained/pm-cli",z_={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},qo;async function Vl(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 s=JSON.parse(await H.readFile(o,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let a=N.dirname(r);if(a===r)return null;r=a}}function Bo(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 a=r.slice(2),s,c;return a[0]==="tree"&&a.length>=2?(s=a[1],c=a.slice(2).join("/")):a.length>0&&(c=a.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:o,repository:`https://github.com/${i}/${o}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function W_(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new y('npm package source must include a package spec after "npm:".',_.USAGE);if(t)throw new y('Options "--gh/--github" cannot be combined with npm: package sources.',_.USAGE);if(n)throw new y('Option "--ref" cannot be combined with npm: package sources.',_.USAGE);return{kind:"npm",input:e,spec:r}}function Qr(e,t={}){let n=e.trim();if(n.length===0)throw new y("Extension source is required for --install.",_.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return W_(n,t.forceGithub===!0,r);let i=(()=>{try{let a=new URL(n);if(a.hostname!=="github.com")return null;let s=a.pathname.replace(/^\/+/,"");return Bo(s,n,r)}catch{return null}})();if(i)return i;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let a=Bo(o,n,r);if(!a)throw new y(`Invalid GitHub source "${n}".`,_.USAGE);return a}if(t.forceGithub){let a=Bo(n,n,r);if(!a)throw new y(`Invalid GitHub shorthand "${n}".`,_.USAGE);return a}if(/^https?:\/\//i.test(n))throw new y(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,_.USAGE);return{kind:"local",input:n,absolute_path:N.resolve(process.cwd(),n)}}async function Xr(e,t=Jl,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 y(`Git command failed: git ${e.join(" ")}
21
+ ${o}`,_.GENERIC_FAILURE)}}function q_(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function B_(e=process.platform){return e==="win32"}async function Kl(e,t,n=Jl,r=process.platform,i=process.env){let o=q_(r),a=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(o,e,{cwd:t,encoding:"utf8",env:a,shell:B_(r)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",d=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new y(`npm command failed: ${o} ${e.join(" ")}
22
+ ${d}`,_.GENERIC_FAILURE)}}function H_(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 G_(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 J_(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return G_(e)||n.includes("not found")}function V_(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function K_(e){let t=H_(e),n=V_(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 Y_(e,t){if(!J_(t))return null;let n=K_(e);return new y(n.message,_.NOT_FOUND,n.context)}async function Yl(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=M_(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 X_(e){let t=await Yl(e);if(t)return t;let n=Z_(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Z_(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(r<=0)return e;let i=e.slice(0,r),o=e.slice(r+n.length);if(i.trim().length===0||o.trim().length===0||o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${i}@${N.resolve(t,o)}`;let a;try{a=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(a)?a.slice(1):a;return`${i}@${s}`}function Q_(e,t){let n;try{n=JSON.parse(e)}catch{}let r=Array.isArray(n)?n[0]:void 0,i=r&&typeof r.filename=="string"&&r.filename.trim().length>0?r.filename:e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!i)throw new y("npm pack did not report a tarball filename.",_.GENERIC_FAILURE);let o=N.resolve(t,i),a=N.relative(t,o);if(a.length===0||a===".."||a.startsWith(`..${N.sep}`)||N.isAbsolute(a))throw new y("npm pack reported a package archive outside its isolated destination.",_.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{tarball:o,package:typeof r?.name=="string"?r.name:void 0,version:typeof r?.version=="string"?r.version:void 0}}async function ey(e){return ty(e,Kl)}async function ty(e,t){let n=await Yl(e.spec);if(n){if((await H.stat(n)).isFile()&&Xl(n))return Ho(n);let a=N.join(n,"package.json"),s=await D(a)?JSON.parse(await H.readFile(a,"utf8")):{};return{directory:await ei(n,e.input),package:typeof s.name=="string"?s.name:void 0,version:typeof s.version=="string"?s.version:void 0,cleanup:async()=>{}}}let r=await H.mkdtemp(N.join(Go.tmpdir(),"pm-npm-package-source-")),i=N.join(r,"pack");await H.mkdir(i,{recursive:!0});try{let o=await X_(e.spec),a=await t(["pack",o,"--json","--pack-destination",i]),s=Q_(a,i);if(!await D(s.tarball))throw new y("npm pack did not create its reported package archive.",_.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 Ho(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await H.rm(r,{recursive:!0,force:!0})}}}}catch(o){await H.rm(r,{recursive:!0,force:!0});let a=Y_(e.spec,o);throw a||o}}function Xl(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function Qe(e){throw new y(e,_.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 ny(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&Qe(`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===".."))&&Qe(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&Qe(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&Qe(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&Qe(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&Qe(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&Qe(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function Ho(e,t=z_){(await H.stat(e)).size>t.maxArchiveBytes&&Qe(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await H.mkdtemp(N.join(Go.tmpdir(),"pm-local-package-archive-")),i=N.join(r,"extract");await H.mkdir(i,{recursive:!0});let o={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await U_({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(a===void 0)try{ny(l,t,o)}catch(u){a=u}}}),a!==void 0)throw a;o.packageJsonEntries!==1&&Qe(`Local package archive must contain exactly one package/package.json entry; found ${o.packageJsonEntries}.`),await j_({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=N.join(i,"package"),c=N.join(s,"package.json"),d=JSON.parse(await H.readFile(c,"utf8"));return await ry(s),{directory:await ei(s,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await H.rm(r,{recursive:!0,force:!0})}}}catch(s){throw await H.rm(r,{recursive:!0,force:!0}),s}}async function ry(e,t=Kl){let n=N.join(e,"package.json");if(!await D(n))return;let r;try{r=JSON.parse(await H.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,o=dy(i),a=iy(i);if(o.length===0&&!a)return;let s={...r};delete s.devDependencies;let c={...s};oy(c),await H.writeFile(n,`${JSON.stringify(c,null,2)}
23
23
  `,"utf8");try{await Promise.all([H.rm(N.join(e,"package-lock.json"),{force:!0}),H.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),a&&await ay(e)}finally{await H.writeFile(n,`${JSON.stringify(s,null,2)}
24
- `,"utf8")}}function iy(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Qr in t)return!0;return!1}function oy(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Qr],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function ay(e){let t=Ee(import.meta.url,["../../.."]),[n,r]=Qr.split("/"),i=N.join(e,"node_modules",n),o=N.join(i,r);await H.mkdir(i,{recursive:!0}),await H.rm(o,{recursive:!0,force:!0}),await H.symlink(t,o,sy(process.platform))}function sy(e){return e==="win32"?"junction":"dir"}function cy(e,t){if(e.startsWith("-"))throw new y(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,_.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 y(`Extension runtime dependency "${e}" has an unsafe version specifier.`,_.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{j_.resolve(e,t)}catch{throw new y(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,_.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 dy(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===Qr||typeof i!="string"||i.trim().length===0||t.has(r))continue;let o=i.trim();t.set(r,cy(r,o))}return[...t.values()]}async function Nn(e,t){let n=await ar(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 y(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,_.USAGE)}throw new y(`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.`,_.USAGE)}async function ly(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(we(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 Nn(e,t.input);return{directory:r,resolved_subpath:N.relative(e,r).replaceAll(N.sep,"/")}}function uy(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 my(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!uy(n))return new y(t,_.NOT_FOUND);let r=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,a=typeof o=="string"&&o.trim().length>0?N.resolve(o.trim()):"";qo?.key!==a&&(qo={key:a,aliases:await Xr()}),r=qo.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 y(`${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}".`,_.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 Ql(e){if(e.kind==="local"){let r;try{r=await H.stat(e.absolute_path)}catch{throw await my(e)}if(r.isFile()&&Yl(e.absolute_path)){let o=await Xl(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 y(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,_.USAGE);let i=await Nn(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await ty(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 H.mkdtemp(N.join(Ho.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Zr(n);let r=await Zr(["-C",t,"rev-parse","HEAD"]),i=await ly(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await H.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await H.rm(t,{recursive:!0,force:!0}),r}}async function eu(e,t){if(!await D(e)||!await D(t))return!1;let[n,r]=await Promise.all([H.realpath(e),H.realpath(t)]);return n===r}import Mn from"node:fs/promises";import Ln 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 Jo=1,At="2026.6.24",py=">=22.18.0",fy={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},tu=new Set([...Gs.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Os).map(e=>e.toLowerCase()),"scaffold"]),hy="^6.0.0",gy="^22.0.0",iu=["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."," }"," }","}",""],ze=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function nu(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function ou(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 au(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"]},ru=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],su={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"]},yy={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"]'},wy={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."},vy={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."},cu="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",by={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."]},ky={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."]},xy={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`."]},Sy={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 du(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 lu(e,t){return e==="schema"?xy[t]:e==="profile"?Sy[t]:ky[t]}function Ey(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&&tu.has(i));return`${(tu.has(n)||o?["starter",...t]:t).join(" ")} ping`}function uu(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],o=`${e.replace(/-/g,"_")}_owner`,a="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(a)},`,' 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(a)}],`,` [${JSON.stringify(a)}, "in_progress"],`,` [${JSON.stringify(a)}, "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 Ay(e,t,n){let r=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,a=[" 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 a;if(n==="search")return[...a,""," // 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 s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...a,""," // 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(s)},`," // 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"?[...a,""," // 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({",...uu(e).map(s=>` ${s}`)," });"]:n==="importers"?[...a,""," // 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"?[...a,""," // 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"?[...a,""," // 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"?[...a,""," // 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 };`," });"]:[...a,""," // 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 Ry(e,t,n){let r=n==="hooks",i=n==="search",o=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",m=yy[n],f=e,p=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,g=`${e}-0001-init`,w=[" 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;",...ze,"});",""]:[],x=i?Vo(e,t,"search",m):[],S=o?Vo(e,t,"importers",m):[],b=a?[`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 {",...nu(ou({extensionName:e,itemTypeName:f,itemTypeFolder:p,fieldName:h,migrationId:g,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],R=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...nu(au(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],k=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;",...ze,"});",""]:[],I=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;",...ze,"});",""]:[],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;",...ze,"});",""]:[],j=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;",...ze,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...iu,`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;",...ze,"});","",...v,...x,...S,...b,...R,...k,...I,...A,...j,`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 Iy(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 Cy={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"},Ty={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 $y(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 Oy(e,t,n){let r=[],i=[...$y(e,t,n)],o=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),m=u===d?[]:[u],f=`${e.replace(/-/g,"_")}_note`,p=`${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(a)},`," 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(s)},`,' 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(f)},`,' 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(p)},`,` 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({",...uu(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 Dy(e,t,n){let r=Oy(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((o,a)=>o.localeCompare(a)).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 Vo(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,o=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,s=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=f=>[...u," let deactivated = false;"," try {",...f.map(p=>p===""?p:` ${p}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze];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(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' 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(a)},`,' 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(ou({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(au(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 Py(e,t,n){let r=n==="parser",i=JSON.stringify([...su[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" };',"",...iu,`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(At)},`," },",` target: { pmVersion: ${JSON.stringify(At)} },`," });"," // 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;",...ze,"});","",...Vo(e,t,n,i)].join(`
27
- `)}function Ny(e,t,n){let r=du(n,"package"),i=lu(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 (${Cy[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`.",cu,"- `.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 ${Ty[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 \`${Jo}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${At}\`. 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 My(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 Ly(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 Fy(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 jy(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 Uy(e,t,n,r="commands",i=!1){let o=`pm-${e}`,a=su[r],s=Iy(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Jo,pm_min_version:At,trusted:!0,sandbox_profile:"strict",permissions:{...fy},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
24
+ `,"utf8")}}function iy(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Zr in t)return!0;return!1}function oy(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Zr],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function ay(e){let t=Ee(import.meta.url,["../../.."]),[n,r]=Zr.split("/"),i=N.join(e,"node_modules",n),o=N.join(i,r);await H.mkdir(i,{recursive:!0}),await H.rm(o,{recursive:!0,force:!0}),await H.symlink(t,o,sy(process.platform))}function sy(e){return e==="win32"?"junction":"dir"}function cy(e,t){if(e.startsWith("-"))throw new y(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,_.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 y(`Extension runtime dependency "${e}" has an unsafe version specifier.`,_.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{F_.resolve(e,t)}catch{throw new y(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,_.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 dy(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===Zr||typeof i!="string"||i.trim().length===0||t.has(r))continue;let o=i.trim();t.set(r,cy(r,o))}return[...t.values()]}async function ei(e,t){let n=await or(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 y(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,_.USAGE)}throw new y(`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.`,_.USAGE)}async function ly(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(we(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 ei(e,t.input);return{directory:r,resolved_subpath:N.relative(e,r).replaceAll(N.sep,"/")}}function uy(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 my(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!uy(n))return new y(t,_.NOT_FOUND);let r=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,a=typeof o=="string"&&o.trim().length>0?N.resolve(o.trim()):"";qo?.key!==a&&(qo={key:a,aliases:await Yr()}),r=qo.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 y(`${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}".`,_.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 Zl(e){if(e.kind==="local"){let r;try{r=await H.stat(e.absolute_path)}catch{throw await my(e)}if(r.isFile()&&Xl(e.absolute_path)){let o=await Ho(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 y(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,_.USAGE);let i=await ei(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await ey(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 H.mkdtemp(N.join(Go.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Xr(n);let r=await Xr(["-C",t,"rev-parse","HEAD"]),i=await ly(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await H.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await H.rm(t,{recursive:!0,force:!0}),r}}async function Ql(e,t){if(!await D(e)||!await D(t))return!1;let[n,r]=await Promise.all([H.realpath(e),H.realpath(t)]);return n===r}import Nn 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]="5321d574-4de4-5f94-99db-0c49639673fc")}catch{}})();var Jo=1,At="2026.6.24",py=">=22.18.0",fy={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},eu=new Set([...Gs.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Os).map(e=>e.toLowerCase()),"scaffold"]),hy="^6.0.0",gy="^22.0.0",ru=["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."," }"," }","}",""],ze=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function tu(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function iu(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 ou(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"]},nu=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],au={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"]},yy={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"]'},wy={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."},vy={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."},su="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",by={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."]},ky={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."]},xy={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`."]},Sy={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 cu(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 du(e,t){return e==="schema"?xy[t]:e==="profile"?Sy[t]:ky[t]}function Ey(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&&eu.has(i));return`${(eu.has(n)||o?["starter",...t]:t).join(" ")} ping`}function lu(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],o=`${e.replace(/-/g,"_")}_owner`,a="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(a)},`,' 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(a)}],`,` [${JSON.stringify(a)}, "in_progress"],`,` [${JSON.stringify(a)}, "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 Ay(e,t,n){let r=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,a=[" 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 a;if(n==="search")return[...a,""," // 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 s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...a,""," // 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(s)},`," // 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"?[...a,""," // 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({",...lu(e).map(s=>` ${s}`)," });"]:n==="importers"?[...a,""," // 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"?[...a,""," // 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"?[...a,""," // 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"?[...a,""," // 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 };`," });"]:[...a,""," // 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 Ry(e,t,n){let r=n==="hooks",i=n==="search",o=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",m=yy[n],f=e,p=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,g=`${e}-0001-init`,w=[" 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;",...ze,"});",""]:[],x=i?Vo(e,t,"search",m):[],S=o?Vo(e,t,"importers",m):[],b=a?[`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 {",...tu(iu({extensionName:e,itemTypeName:f,itemTypeFolder:p,fieldName:h,migrationId:g,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],R=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...tu(ou(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze,"});",""]:[],k=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;",...ze,"});",""]:[],I=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;",...ze,"});",""]:[],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;",...ze,"});",""]:[],j=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;",...ze,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...ru,`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;",...ze,"});","",...v,...x,...S,...b,...R,...k,...I,...A,...j,`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 Iy(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 Cy={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"},Ty={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 $y(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 Oy(e,t,n){let r=[],i=[...$y(e,t,n)],o=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),m=u===d?[]:[u],f=`${e.replace(/-/g,"_")}_note`,p=`${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(a)},`," 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(s)},`,' 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(f)},`,' 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(p)},`,` 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({",...lu(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 Dy(e,t,n){let r=Oy(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((o,a)=>o.localeCompare(a)).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 Vo(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,o=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,s=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=f=>[...u," let deactivated = false;"," try {",...f.map(p=>p===""?p:` ${p}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ze];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(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' 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(a)},`,' 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(iu({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(ou(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 Py(e,t,n){let r=n==="parser",i=JSON.stringify([...au[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" };',"",...ru,`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(At)},`," },",` target: { pmVersion: ${JSON.stringify(At)} },`," });"," // 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;",...ze,"});","",...Vo(e,t,n,i)].join(`
27
+ `)}function Ny(e,t,n){let r=cu(n,"package"),i=du(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 (${Cy[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`.",su,"- `.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 ${Ty[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 \`${Jo}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${At}\`. 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 My(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 Ly(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 Fy(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 jy(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 Uy(e,t,n,r="commands",i=!1){let o=`pm-${e}`,a=au[r],s=Iy(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Jo,pm_min_version:At,trusted:!0,sandbox_profile:"strict",permissions:{...fy},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
29
29
  `,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Ay(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
30
  `),l=`${JSON.stringify(_y,null,2)}
31
- `,u=wy[r],m=du(r,"package"),f=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:py},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${At}`},devDependencies:{"@types/node":gy,typescript:hy},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)}
31
+ `,u=wy[r],m=cu(r,"package"),f=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:py},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${At}`},devDependencies:{"@types/node":gy,typescript:hy},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
32
  `,p=Ry(e,t,r),h=vy[r],g=["node_modules/","*.log","*.tsbuildinfo",""].join(`
33
- `),w=My(e),x=["```ts",`import { ${Ly(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Fy(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...jy(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],S=[`# ${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,cu,"- `.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:",...x,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...by[r],...lu(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${At}\`. 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 \`${Jo}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${At}\`. 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":f,"manifest.json":c,"index.ts":i?Dy(e,t,r):d,"index.test.ts":i?Py(e,t,r):p,"tsconfig.json":l,".gitignore":g,"README.md":i?Ny(o,t,r):S}}async function mu(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!ru.includes(i))throw new y(`Unknown scaffold capability "${n}". Supported capabilities: ${ru.join(", ")}.`,_.USAGE);let o=i;if(r&&t!=="package")throw new y("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",_.USAGE);let a=r?"declarative":"imperative",s=e.trim(),c=Ln.resolve(process.cwd(),s),d=Kr(Ln.basename(c)).replace(/^(?:pm-)+/u,""),l=Ey(d),u=Uy(d,l,t,o,r),m=!1;if(await D(c)){if(!(await Mn.stat(c)).isDirectory())throw new y(`Scaffold target "${c}" exists and is not a directory.`,_.CONFLICT)}else await Mn.mkdir(c,{recursive:!0}),m=!0;for(let[p,h]of Object.entries(u)){let g=Ln.join(c,p);if(!await D(g))continue;if(await Mn.readFile(g,"utf8")!==h)throw new y(`Scaffold file "${p}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,_.CONFLICT)}let f=[];for(let[p,h]of Object.entries(u)){let g=Ln.join(c,p);if(await D(g)){f.push({path:p,status:"unchanged"});continue}await Mn.mkdir(Ln.dirname(g),{recursive:!0}),await Mn.writeFile(g,h,"utf8"),f.push({path:p,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:o,style:a,target_path:c,created_directory:m,files:f}}(function(){try{var e=typeof window<"u"?window:typeof 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 pu(e,t){return`${e}:${E(t)}`}function zy(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let a of i){let s=o.get(a.command)??[];o.set(a.command,[...s,a])}for(let[a,s]of o){if(t!==null&&!s.some(d=>t.has(E(d.name))))continue;let c=s.at(-1);n.push({command:a,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.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 fu(e,t,n){let r=new Set(n.failed.map(d=>pu(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(pu(d.layer,d.name))?"failed":"ok",surfaces:Yt(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:Yt(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),o=typeof e=="string"?E(e):null,a=o===null?null:new Set(t.loaded.filter(d=>E(d.name)===o||typeof d.source_package=="string"&&E(d.source_package)===o||(d.source_aliases??[]).some(l=>E(l)===o)).map(d=>E(d.name)).concat(o)),s=a===null?i:i.filter(d=>a.has(E(d.name))),c=a===null?{}:{extensionNames:[...a]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Yt(n,c),command_ownership:zy(n,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]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function Ko(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function ti(e,t,n){let r=E(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 Wy(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)ti(t,r.name,r.command),ti(n,r.name,r.action);for(let r of e.commands.handlers)ti(t,r.name,r.command);for(let r of e.commands.overrides)ti(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function hu(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function qy(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 ni(e,t,n){let r=new Set(t.loaded.map(c=>E(c.name))),i=new Set(t.failed.map(c=>E(c.name))),o=new Set(n.failed.map(c=>E(c.name))),{commandPathsByExtension:a,actionPathsByExtension:s}=Wy(n);return e.map(c=>{let d=E(c.name),l=hu(a.get(d)),u=hu(s.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},f=qy({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:i,activationFailedNames:o});return{...c,...f,...m}})}function By(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 de(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var yu=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 Hy(e){return yu.has(Su(e))}function gu(e){return e==="project"||e==="global"}function wu(e){let t=e.split(":"),n=t[0];if(!n||!yu.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),o=t.at(-2),a=t.at(-1)?.trim();return!gu(r)||!gu(o)||!i||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:o,name:a}}}function Gy(e){let t=new Set;for(let n of e){let r=wu(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Yo(e,t){let n=e.filter(Hy);if(n.length===0)return null;let r=Gy(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 Jy(e,t,n,r){let i=t.map(u=>wu(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",a=de(r,"deactivate"),s=`${de(r,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(u=>[E(u.name),u])),d=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let f=E(m);d.set(f,(d.get(f)??0)+1)}let l=[...d.entries()].map(([u,m])=>{let f=c.get(u),p=f?.name??u,h=f?.command_paths??[],g=f?.action_paths??[];return{action:"deactivate",extension:p,command:`${a} ${p} ${o}`,affected_collisions:m,feature_loss:{command_paths:[...h].sort((w,v)=>w.localeCompare(v)),action_paths:[...g].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let f=m.affected_collisions-u.affected_collisions;if(f!==0)return f;let p=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 p!==h?p-h:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:d.size,next_best_command:s,collisions:i,remediation_candidates:l}}function vu(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 bu(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 ku(e,t){let n=[];for(let r of Vs(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 Vy=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${de(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: ${er.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 ${de(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 ${de(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 ${de(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 ${de(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 ${de(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${de(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 Ky(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:a,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=[],m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:a};if(t.length>0){let f=Yo(t,{deactivate:`${de(n,"deactivate")} <name> ${i}`,doctor:`${de(n,"doctor")} ${i} --detail deep --trace`});f&&u.push(f);for(let p of Vy)p.matches(t,m)&&u.push(p.build(m))}return s?u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${de(n,"manage")} ${i} --fix-managed-state (or ${de(n,"adopt-all")} ${i}, ${de(n,"adopt")} <name> ${i}, or reinstall via ${de(n,"install")} ${i} <source>).`):c>0&&u.push(`Loaded unmanaged extensions are currently treated as informational. Use ${de(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 ${de(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${de(n,"manage")} ${i} after extension changes.`),u}function ri(e,t,n,r={}){let i=[...new Set(t)].sort((A,j)=>A.localeCompare(j)),o=n.filter(A=>A.managed).length,a=n.filter(A=>A.enabled).length,s=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=>_u(A)).map(A=>A.name).sort((A,j)=>A.localeCompare(j)),u=d.filter(A=>!_u(A)).map(A=>A.name).sort((A,j)=>A.localeCompare(j)),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 f=m.failed,p=m.skipped_unmanaged,h=m.skipped_non_github,g=u.length>0,w=g?"partial":"full",v=g?[`extension_update_health_partial_coverage:skipped_unmanaged:${u.length}`]:[],x=[...new Set([...i,...v])].sort((A,j)=>A.localeCompare(j)),S=[...new Set(x.map(A=>Su(A)))].sort((A,j)=>A.localeCompare(j)),b=By(x),R=e==="global"?"--global":"--project",k=Jy(e,i,n,r),I=Ky({normalizedWarnings:i,options:r,scope:e,scopeFlag:R,updateCheckFailedTotal:f,policyWarningCount:b.warning_count,updateHealthPartial:g,skippedUnmanagedTotal:p,skippedNonGithubTotal:h,updateAvailableTotal:c});return{status:x.length===0?"ok":"warn",warning_count:x.length,warning_codes:S,warnings:x,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:a,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:g,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(A=>A.name).sort((A,j)=>A.localeCompare(j)),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:f,top_warnings:x.slice(0,8),remediation:I,...k?{collision_plan:k}:{}}}function xu(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new y(`Invalid --detail value "${e}". Expected summary or deep.`,_.USAGE)}function Su(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Fn(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let o=ls(r);return o?[o]:us(r)})();for(let o of i){let a=`${o.layer}:${o.name}:${o.capability}`;t.has(a)||(t.add(a),n.push(o))}}return n}function jn(){return{version:tr.version,capabilities:[...tr.capabilities],legacy_aliases:{...tr.legacy_aliases}}}function _u(e){let t=E(e.name),n=E(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Eu(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=>E(l.name)))].sort((l,u)=>l.localeCompare(u)),a=[...new Set(n.filter(l=>l.layer==="project").map(l=>E(l.name)))].sort((l,u)=>l.localeCompare(u)),s=new Set(r.map(l=>E(l.name))),c=o.filter(l=>!a.includes(l)&&!s.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:a.length,active_project_names:o,loaded_project_names:a,missing_active_project_names:c}}}import{randomUUID as Yy}from"node:crypto";import oe from"node:fs/promises";import Xy from"node:os";import V from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="263602a2-c000-5df7-80d2-6f095985496f")}catch{}})();var Au=3,Zy=120,Ru=250,Qy=12e4,ew=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Iu=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Cu=e=>ew.has(String(Iu(e))),ii=(e,t)=>Iu(e)===t,Tu=e=>new Promise(t=>{setTimeout(t,e)}),$u=async e=>{let t=V.join(e,"package.json");await D(t)||await oe.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
35
- `,"utf8")},Ou=async e=>{let t=Ee(import.meta.url,["../../.."]),n=V.join(e,"node_modules","@unbrained"),r=V.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")},Xo=async e=>{let t=V.resolve(e),n=V.dirname(t),r=V.parse(n).root,i=await oe.realpath(r).catch(()=>r),o=V.relative(r,n),a=o===""?[]:o.split(V.sep);for(let[s,c]of a.entries()){let d=V.join(i,c);try{i=await oe.realpath(d)}catch{i=V.join(i,...a.slice(s));break}}return V.join(i,V.basename(t))},Du=async(e,t,n,r=Xy.tmpdir())=>{let i=V.resolve(e),o=await oe.realpath(i).catch(()=>i),a=await Xo(t);if(o===a)return;if(!we(o,a)){await n(e,t,{recursive:!0,force:!0});return}let s=m=>{let f=V.resolve(m);if(f!==i&&!we(i,f))return!1;let p=V.resolve(o,V.relative(i,f));if(p===a||we(a,p))return!1;let g=V.relative(o,p).split(V.sep);return g.some(w=>w==="node_modules"||w.startsWith(".pm-extension-install-backup-"))?!1:g[0]!==".agents"},c=await oe.realpath(V.resolve(r)).catch(()=>Xo(r)),d=we(o,c)?V.dirname(o):c;if(we(o,d))throw new y(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,_.USAGE,{code:"extension_install_source_contains_destination"});let l=await oe.mkdtemp(V.join(d,"pm-extension-copy-")),u=V.join(l,"extension");try{await n(e,u,{recursive:!0,force:!0,filter:s}),await n(u,t,{recursive:!0,force:!0})}finally{await oe.rm(l,{recursive:!0,force:!0})}},Pu=async(e,t,n=oe.cp)=>{for(let r=1;r<=Au;r+=1)try{await oe.rm(t,{recursive:!0,force:!0}),await Du(e,t,n);return}catch(i){if(!Cu(i)||r===Au)throw i;await Tu(Ru)}},Zo=async e=>{let t;try{t=await oe.readFile(V.join(e,"owner.json"),"utf8")}catch(i){if(!it(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},Nu=async(e,t)=>await Zo(e)!==t?!1:(await oe.rm(e,{recursive:!0,force:!0}),!0),tw=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 Zo(e);return r===null?(await oe.rm(e,{recursive:!0,force:!0}),!0):Nu(e,r)},nw=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await Zo(e)!==t)return;let o=new Date;await oe.utimes(e,o,o)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},rw=async(e,t)=>{await oe.mkdir(e);try{await oe.writeFile(V.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
36
- `,"utf8")}catch(n){throw await oe.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},iw=async(e,t,n,r,i)=>{for(let o=1;o<=n;o+=1)try{return await rw(e,t),!0}catch(a){if(!ii(a,"EEXIST"))throw a;await tw(e,i)?o-=1:await Tu(r)}return!1},Qo=async(e,t,n,r)=>{let i=V.join(e,"runtime","extension-install-locks"),o=V.join(i,"scope.lock");await oe.mkdir(i,{recursive:!0});let{attempts:a=Zy,delay_ms:s=Ru,stale_ms:c=Qy,heartbeat_ms:d}=r??{};if(![a,s,c,d].filter(w=>w!==void 0).every(Number.isFinite))throw new y("Extension install lock timings must be finite numbers.",_.USAGE);let l=Math.max(1,Math.floor(a)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),f=Math.floor(d??m/3);if(m<=0||f<=0||f>=m)throw new y("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",_.USAGE);let p={pid:process.pid,token:Yy(),created_at:T(),destination:t};if(!await iw(o,p,l,u,m))throw new y(`Timed out waiting for extension install lock for "${t}".`,_.CONFLICT);let g=nw(o,p.token,f);try{return await n()}finally{await g(),await Nu(o,p.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 Mu=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 a=i;i+=1,r[a]=await n(e[a])}});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 Lu(e,t){let n=E(e),r=t.find(i=>E(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 Fu(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${E(o.name)}`]:[])),r=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>o.passThrough!==!0).filter(o=>!n.has(`${o.layer}:${E(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,a)=>o.localeCompare(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]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var ju=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=lr(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 ow=1e4,aw=(e,t,n)=>{let r=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),i=r.find(a=>a.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"}},Uu=async(e,t=Zr)=>{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,ow);return aw(i,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import sw 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]="56290db9-933c-590d-8b9f-df62ff45e515")}catch{}})();function ea(e){return cw.join(e,"extension-migrations.json")}function zu(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 Wu(e,t){return`${e.layer}:${e.name}:${t}`}async function dw(e){let t=ea(e);if(!await D(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await sw.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 ta(e,t){let n=await dw(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let a=zu(i,o),s=r.get(Wu(i,a));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function lw(e){let t=await ta(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=zu(l,u),f=Wu(l,m),p=n.get(f),h=String(l.definition.status??"pending").toLowerCase(),g=p?.status??(h==="applied"||h==="failed"?h:"pending");if(g==="applied"){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:g,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:g,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:g,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:g}));let x={key:f,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(f,x),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:f,layer:l.layer,extension:l.name,id:m,before:g,outcome:"applied"}),i=!0}catch(x){let S=x instanceof Error?x.message:String(x),b={key:f,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:S};n.set(f,b),l.definition.status="failed",l.definition.reason=S,r.push({key:f,layer:l.layer,extension:l.name,id:m,before:g,outcome:"failed",error:S}),i=!0}}if(i){let l=await C(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,f)=>m.key.localeCompare(f.key))};await br({pmRoot:e.pmRoot,filePath:ea(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 a=r.filter(l=>l.outcome==="pending").length,s=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:ea(e.pmRoot),total:r.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function qu(e){let t=await C(e.resolvedRoots.settings_root),n=await Ne({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Me(n);e.warnings.push(...n.warnings,...r.warnings);let i=await lw({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 uw from"node:fs/promises";import mw 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 pw(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function fw(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 na(e){let t=mw.join(e,"manifest.json"),n;try{n=await uw.readFile(t,"utf8")}catch(s){if(it(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}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=gs(i),a=pw(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:o.findings,warnings:o.findings.map(s=>fw(a,s)),remediation:o.findings.map(s=>s.message)}}function Bu(e){return na(Pe(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 Hu(e,t,n){let r=typeof t=="string"?null:await Pn(e),i=r===null?null:e.trim().toLowerCase(),o=i===null?null:await Bl(i),a=ei(r??e,{forceGithub:typeof t=="string",ref:n}),s=i===null?null:await Jl(e);return{bundledAliasName:i,bundledPackageName:o,installSource:a,sourceResolution:{requested:e,selected:{kind:i===null?a.kind:"builtin",input:i??a.input,...o===null?{}:{package:o}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...o===null?{}:{package:o},command:`pm install ${i}`}],...s===null?[]:[{kind:"npm",input:`npm:${s.package}`,package:s.package,...s.version===void 0?{}:{version:s.version},directory:s.directory,command:`pm install npm:${s.package}`}]]}}}import Rt from"node:fs/promises";import hw 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 ra=async e=>Rt.readFile(e).catch(t=>{if(ii(t,"ENOENT"))return null;throw t}),Gu=async(e,t,n,r,i)=>{let o=$n(e),a=yt(t),[s,c]=await Promise.all([ra(o),ra(a)]);return r&&await Rt.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:o,managedStateContents:s,settingsPath:a,settingsContents:c}},Ju=async e=>{await Rt.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Rt.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 Rt.rm(t,{force:!0}):(await Rt.mkdir(hw.dirname(t),{recursive:!0}),await Rt.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 gw=4,Xu=[["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=Xu.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),yw={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"},ww="__pm_native_output",vw=["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"],Zu=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],bw=["disabled","require_trusted","require_provenance"],Qu={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:[]},kw=e=>{let t=e??Qu,n={};for(let r of vw)n[r]=xe(t[r]??[]);return n},xw=(e,t)=>{for(let n of Zu)t[n].length>0&&(e[n]=t[n]);return e},Sw=(e,t)=>{for(let n of bw)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Ew=e=>{let t={};for(let n of Zu)t[n]=xe(e[n]??[]);return t},Aw=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:xw(Sw({name:t},e),Ew(e))},Rw=e=>(e??[]).map(t=>Aw(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Iw=e=>{let t=Object.assign({},Qu,e??{}),n=kw(e),r=Rw(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}},em=async(e,t)=>{let n=[t],r=await Hl(t);r&&n.push(r);let i=[...new Set(n.map(o=>E(o)).filter(o=>o.length>0))];for(let o of i){let a=e.find(c=>E(c.name)===o);if(a)return a;let s=e.find(c=>E(c.directory)===o);if(s)return s}},tm=(e,t)=>{let n=t.trim(),r=new Set(xe(e.extensions.enabled));return new Set(xe(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},nm=(e,t)=>{let n=t.trim(),r=new Set(xe(e.extensions.enabled)),i=new Set(xe(e.extensions.disabled)),o=[...r],a=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Cw=(e,t)=>{let n=t.trim(),r=new Set(xe(e.extensions.enabled)),i=new Set(xe(e.extensions.disabled)),o=[...r],a=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Tw=(e,t)=>{let n=t.trim(),r=new Set(xe(e.extensions.enabled)),i=new Set(xe(e.extensions.disabled)),o=[...r],a=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},$w=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=Xu.map(([i,o,a])=>({action:o,flag:a,distance:ds(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},Ow=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=$w(e);if(!r)return new y(`One action flag is required. Use one of: ${_w}. Bare \`pm package\` and \`pm extension\` default to --explore.`,_.USAGE);let i=`pm ${n} ${r.flag}`;return Sr({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(rm),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},Dw=[["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"]],rm={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Pw=e=>rm[e]??null,Nw=(e,t)=>{let n=[...new Set(Dw.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=Pw(e.trim().toLowerCase());if(r)return r;throw Ow(e,t)}if(n.length>1)throw new y("Extension action flags are mutually exclusive.",_.USAGE);return n[0]},Mw=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new y('Options "--project/--local" and "--global" are mutually exclusive.',_.USAGE);return n?"global":"project"},Lw=[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"}}],im=e=>{for(let t of Lw){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},om=(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}},Fw=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),o=r?tm(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:om({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:o},t,r,im(r))}},jw=async(e,t,n,r,i,o)=>{let a=Ie.join(e,t),s=Ie.join(a,"manifest.json"),c=o.get(E(t));if(!await D(s))return Fw(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await mt.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=jo(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(E(u.name))??o.get(E(t));return{summary:om({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:tm(r,u.name)},n,m,im(m))}},We=async(e,t,n,r)=>{if(!await D(e))return{extensions:[],warnings:[]};let o=(await mt.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),a=new Map(r.entries.map(l=>[E(l.name),l])),s=new Map(r.entries.map(l=>[E(l.directory),l])),c=[],d=[];for(let l of o){let u=await jw(e,l,t,n,a,s);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))}},Uw=Xs(),zw=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Ww=(e,t,n,r)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),o=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&a.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:zw(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:a,...o?{sdk_dependency_status:"missing"}:{}}},qw=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},am=e=>e.map(t=>qw(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),sm=(e,t,n)=>{let r=E(e);return t.find(i=>(n===void 0||i.layer===n)&&E(i.name)===r)},Bw=(e,t,n,r)=>n.find(o=>o.scope===t&&E(o.name)===E(e))?.activation_status??(r?"failed":"unknown"),cm=(e,t,n,r,i)=>Uw.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,a=await mt.mkdtemp(Ie.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Ee(import.meta.url,["../.."]);try{let s=await Ne({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:Li(),cache_bust:!0,module_graph_snapshot_root:a}),c=await Me({...s}),d=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...am(c.failed)],l=Object.fromEntries(s.loaded.map(u=>[E(u.name),As(Yt(c,{extensionName:u.name}))]));return{installed:ni(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await mt.rm(a,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),oa=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)}),a=r,s=[];for(let c of o){let d=Ie.join(e,c.directory),l=await tn(d),u=T(),m={kind:"local",input:c.name,location:d};a=Dn(a,{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}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return s.length>0&&await Et(e,a),{state:a,adopted_entries:s,unmanaged_candidates:o,already_managed_count:n.length-i.length}},Hw=(e,t)=>{let n=L(process.cwd(),t.path),r=Tt(n,process.cwd()),i=e==="global"?rr(process.cwd()):n,o=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:o,roots:r}},oi=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 y('Options "--gh" and "--github" must match when both are provided.',_.USAGE);return n[0]},Gw=e=>yw[e],Jw=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,o=Gw(e),a=`<${r}>`,s=`pm ${n} ${o} ${a}`;throw new y(`Action "${e}" requires ${i} input.`,_.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},ai=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new y('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',_.USAGE);return Jw(t,n)},Vw=(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}:${E(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${E(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))},Kw=(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 y(r.message,_.USAGE)},Yw=(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},Xw=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},Zw=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:Xw(e),warnings:[...new Set(e.warnings)].sort((i,o)=>i.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(r,ww,{value:!0,enumerable:!1,configurable:!1}),r},aa=async(e,t,n)=>{let r=Nw(e,t);Kw(r,t);let i=Yw(e,r,t),o=Mw(t),a=Hw(o,n),c={action:r,normalizedTarget:i,scope:o,resolvedRoots:a,warnings:[],options:t,global:n},l={...c,withResult:(u,m=!0)=>Zw(c,u,m)};return await $v(l)},Qw=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=Ks(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"`},a={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"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[o[n],...s,`Install the scaffold: ${pr(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},ev=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([oi(r),r.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new y('Action "init" does not accept --gh/--github/--ref options.',_.USAGE);let s=ai(n,t,r),c=await mu(s,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:Qw(c,r)})},tv=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:o,withResult:a}=e;if(t!==void 0)throw new y('Action "reload" does not accept a target argument.',_.USAGE);let s=await C(n.settings_root),c=Li(),d=await Ne({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await Me(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"),a(u)},nv=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 y('Action "catalog" does not accept a package target.',_.USAGE);return o(await Gl(n,i,r))},rv=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),iv=e=>({kind:"local",input:e.input,location:e.absolute_path}),ov=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),av=(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}),sv=(e,t,n,r)=>e?rv(e,t):n.kind==="local"?iv(n):n.kind==="npm"?ov(n,r):av(n,r),cv=(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},dv=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:o,destinationDirectoryName:a}=t,s=await C(r.settings_root),c=await he(r.selected_root);i.push(...c.warnings);let d=Ie.join(r.selected_root,a),l=await D(d),u=await eu(o.directory,d);await mt.mkdir(r.selected_root,{recursive:!0});let m=await mt.mkdtemp(Ie.join(r.selected_root,".pm-extension-install-backup-")),f=Ie.join(m,"destination");try{let p=await Gu(r.selected_root,r.settings_root,d,l,f),h=sv(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),g=c.state.entries.find(S=>E(S.name)===E(o.manifest.name)),w=cv(g,o.manifest.version,h,T()),v=Dn(c.state,{name:o.manifest.name,directory:a,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,...w,source:h}),x=nm(s,o.manifest.name);try{u||await Pu(o.directory,d),await $u(d),await Ou(d),await Et(r.selected_root,v),x&&await kr(r.settings_root,s,"settings:write")}catch(S){try{await Ju(p)}catch(b){throw new AggregateError([S,b],`Extension install failed: ${String(S)}; rollback failed: ${String(b)}`,{cause:b})}throw S}return{settings:s,managedState:v,sourceRecord:h,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:x}}finally{await mt.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},lv=async(e,t,n)=>{let r=n.filter(i=>E(i.name)===E(t)).flatMap(i=>i.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&r.length>0&&await Cn(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},uv=(e,t,n,r,i)=>{let o=sm(t,n.activation_failures,e.scope),a=Bw(t,e.scope,n.installed,o),s=[!n.extensions_disabled,a==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${a}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:a,failure:o,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:a,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},mv=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:o,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,d=await dv(e,t),l=await We(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let u=await cm(r.pm_root,Ie.dirname(r.selected_root),d.settings,l.extensions,o);i.push(...u.warnings);let m=await lv(e,s.manifest.name,u.item_type_registrations),f=Lu(s.manifest.name,u.installed),p=uv(e,s.manifest.name,u,f,m),h=u.contribution_inventories[E(s.manifest.name)];return h&&(d.managedState=await Ul(r.selected_root,d.managedState,s.manifest.name,h)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.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:p.activated,settings_changed:d.activationChanged,runtime_activation_status:p.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:h,command_discovery:Ww(s.manifest.name,d.sourceRecord,f,p.failure),verification:p.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:p.failure??null}},p.activated)},pv=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new y('Action "install all" does not accept --ref.',_.USAGE);let o=[],a=new Map;for(let c of await Xr()){let d=await Pn(c),l=Ie.resolve(d),u=a.get(l);u===void 0&&(u=await aa(c,{...t,install:!0},n),a.set(l,u)),o.push({alias:c,result:u})}r.push(...o.flatMap(c=>c.result.warnings));let s=o.every(c=>c.result.ok);return i({installed_all:s,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}})},s)},fv=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:o,installSource:a,sourceResolution:s}=await Hu(t,n,e.options.ref);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${d.package}`)}let c=await Ql(a);try{let d=await tn(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),l=Kr(d.manifest.name);return await Qo(r.settings_root,l,()=>mv(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:o,sourceResolution:s,installSource:a,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},hv=async e=>{let t=oi(e.options),n=t??ai(e.normalizedTarget,e.action,e.options);return[t===void 0,Wl(n)].every(Boolean)?pv(e):fv(e,n,t)},gv=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:a}=e;if(t!==void 0)throw new y('Action "adopt-all" does not accept a target argument.',_.USAGE);if(oi(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new y('Action "adopt-all" does not accept --gh/--github/--ref options.',_.USAGE);let c=await C(r.settings_root),d=await he(r.selected_root);i.push(...d.warnings);let l=await We(r.selected_root,n,c,d.state);i.push(...l.warnings);let u=await oa(r.selected_root,n,l.extensions,d.state),m=await We(r.selected_root,n,c,u.state);i.push(...m.warnings);let f=ri(n,i,m.extensions,o);i.push(...f.warnings);let p=new Map(m.extensions.map(w=>[`${E(w.name)}:${E(w.directory)}`,w])),h=new Map(m.extensions.map(w=>[E(w.directory),w])),g=u.adopted_entries.map(w=>{let v=E(w.directory),x=p.get(`${E(w.name)}:${v}`)??h.get(v);return{...w,...dm(x)}});return a({adopted_all:g.length>0,adopted_count:g.length,already_managed_count:u.already_managed_count,extensions:g,triage:f,warning_codes:f.warning_codes,update_health_partial:f.update_health_partial,update_health_coverage:f.update_health_coverage})},dm=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=ei(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new y(`Invalid GitHub shorthand "${e}".`,_.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}},yv=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:a,withResult:s}=e,c=ai(n,t,a),d=oi(a),l=await C(i.settings_root),u=await he(i.selected_root);o.push(...u.warnings);let m=await We(i.selected_root,r,l,u.state);o.push(...m.warnings);let f=await em(m.extensions,c);if(!f)throw new y(`Installed extension "${c}" was not found in ${r} scope.`,_.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let p=Ie.join(i.selected_root,f.directory),h=await tn(p),g=T(),w=_v(d,c,p,a.ref),v=Dn(u.state,{name:h.manifest.name,directory:f.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:w});await Et(i.selected_root,v);let x=await We(i.selected_root,r,l,v);o.push(...x.warnings);let S=x.extensions.find(b=>E(b.name)===E(h.manifest.name))??x.extensions.find(b=>E(b.directory)===E(f.directory));return s({adopted:!0,extension:{name:h.manifest.name,directory:f.directory,version:h.manifest.version,entry:h.manifest.entry},source:w,...dm(S)})},lm=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:a}=e,s=ai(n,t,a),c=await C(i.settings_root),d=await he(i.selected_root);o.push(...d.warnings);let l=await We(i.selected_root,r,c,d.state);o.push(...l.warnings);let u=await em(l.extensions,s);if(!u)throw new y(`Installed extension "${s}" was not found in ${r} scope.`,_.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},wv=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:o}=await lm(e),a=Ie.join(t.selected_root,o.directory);await mt.rm(a,{recursive:!0,force:!0});let s={...i.state,updated_at:T(),entries:i.state.entries.filter(d=>E(d.name)!==E(o.name)&&E(d.directory)!==E(o.directory))};await Et(t.selected_root,s);let c=Tw(r,o.name);return c&&await kr(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:a,settings_changed:c})},Vu=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:o}=e,{settings:a,candidate:s}=await lm(e),c=t==="activate"?nm(a,s.name):Cw(a,s.name);c&&await kr(n.settings_root,a,"settings:write");let d=t==="activate"?await cm(n.pm_root,Ie.dirname(n.selected_root),a,[s],i).then(l=>(r.push(...l.warnings),sm(s.name,l.activation_failures,e.scope))):void 0;return d&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),o({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},d===void 0)},vv=(e,t,n,r,i,o)=>{let a=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=i?.adopted_entries.length??0,d=[[o!==null,o??""],[t>0,`Run pm ${a} explore --project and pm ${a} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${a} ${s} --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))]},ia=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),bv=(e,t,n,r)=>{if(e!=="project"||t||!ia(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.`},kv=(e,t,n)=>{if(String(e??"").trim().length>0)throw new y('Action "doctor" does not accept a target argument.',_.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new y("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",_.USAGE);let i=xu(n.detail),o=n.trace===!0;if([o,i!=="deep"].every(Boolean))throw new y("--trace requires --detail deep with --doctor.",_.USAGE);return{isolated:r,detailMode:i,includeTrace:o}},xv=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await oa(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},Sv=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:ia(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:ia(r),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},Ev=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:a,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=kv(t,n,o),u=await C(r.settings_root),m=await he(r.selected_root);i.push(...m.warnings);let f=await We(r.selected_root,n,u,m.state);i.push(...f.warnings);let{state:p,fix:h}=await xv(e,f.extensions,m.state),g=await We(r.selected_root,n,u,p);i.push(...g.warnings);let w=await Ne({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Me({...w,loaded:w.loaded}),x=await Bu(r.pm_root);i.push(...x.warnings,...w.warnings),i.push(...vu(w.failed)),i.push(...v.warnings),i.push(...bu(v.failed)),i.push(...ku(w,v)),i.push(...Fu(v,w)),i.push(...Vw(w,v)),i.push(...ju(v));let S=ni(g.extensions,w,v),b=Eu(n,S,w.loaded.map(F=>({layer:F.layer,name:F.name})),w.failed.map(F=>({name:F.name})),w.disabled_by_flag);i.push(...b.warnings);let R=S.filter(F=>F.update_check_status==="failed").map(F=>`extension_update_check_failed:${F.name}`);i.push(...R);let k=ri(n,i,S,o);i.push(...k.warnings);let I=[...k.warnings],A={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},j=Fn(I),q=jn(),O=k.warning_codes,W=bv(n,c,o.vocabulary,w),me=vv(k.remediation,w.failed.length,v.failed.length,o.vocabulary,h,W),ue=Sv(n,c,o.vocabulary,w),gt={status:k.status,scope:n,warning_count:k.warning_count,warning_codes:O,total_extensions:S.length,managed_total:S.filter(F=>F.managed).length,enabled_total:S.filter(F=>F.enabled).length,active_total:S.filter(F=>F.active).length,unmanaged_loaded_extension_count:k.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:k.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:k.unmanaged_expected_extension_count,runtime_active_total:S.filter(F=>F.runtime_active===!0).length,activation_status_totals:{ok:S.filter(F=>F.activation_status==="ok").length,failed:S.filter(F=>F.activation_status==="failed").length,not_loaded:S.filter(F=>F.activation_status==="not_loaded").length,unknown:S.filter(F=>F.activation_status==="unknown").length},unknown_capability_count:j.length,capability_contract_version:q.version,update_available_total:S.filter(F=>F.update_available===!0).length,update_health_coverage:k.update_health_coverage,update_health_partial:k.update_health_partial,update_check_failed_total:S.filter(F=>F.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Ko(w.failed),activation_failures:Ko(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:b.warnings.length,trace_enabled:l,isolation:ue,policy:A,remediation:me},rt=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(F=>F.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:g.extensions.filter(F=>F.managed).length,adopted_extensions:[]},_t={mode:d,summary:gt,triage:k,trace_enabled:l,capability_contract:q,capability_guidance:j,managed_state_fix:rt,author_manifest:x,isolation:ue,policy:w.policy};if(d==="deep"){let F=l?v.failed:v.failed.map(G=>{let{trace:Oi,...Di}=G;return Di});_t.deep={warnings:I,warning_codes:O,capability_contract:q,capability_guidance:j,trace_enabled:l,managed_state:{path:m.path,count:p.entries.length,entries:p.entries},installed_extensions:S,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(G=>({layer:G.layer,directory:G.directory,name:G.name,version:G.version,entry:G.entry,priority:G.priority}))},activation:{failed:F,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&&(_t.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 s(_t)},Av=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:a,withResult:s}=e,c=await C(r.settings_root),d=await Ne({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),l=await Me(d);i.push(...d.warnings),i.push(...l.warnings);let u=fu(t,d,l);if(t!==void 0&&u.extensions.length===0){let m=o.vocabulary==="package"?"package":"extension",f=[...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)),p=f.length>0?` Loaded ${m} names: ${f.join(", ")}.`:"";throw new y(`No loaded ${m} named "${t}" was found in ${n} scope.${p} Run pm ${m} explore to list discovered ${m}s.`,_.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},Rv=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await oa(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let o=await Mu(r.entries,gw,async a=>{if(a.source.kind!=="github")return a;let s=await Uu(a.source);return{...a,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});r={...r,updated_at:T(),entries:On(o)},await Et(e.resolvedRoots.selected_root,r)}return{state:r,fix:i}},Iv=async(e,t,n)=>{let r=await Ne({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Me({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:ni(n,r,i),failures:am(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}}},Cv=(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},Ku=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:a}=e,s=await C(r.settings_root),c=Iw(s.extensions.policy),d=await he(r.selected_root);i.push(...d.warnings);let l=await We(r.selected_root,n,s,d.state);i.push(...l.warnings);let{state:u,fix:m}=await Rv(e,l.extensions,d.state),f=await We(r.selected_root,n,s,u);if(i.push(...f.warnings),t==="manage"){let v=f.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);i.push(...v)}let p=await Iv(e,s,f.extensions),h=p.installed,g=ri(n,i,h,o);i.push(...g.warnings);let w={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 p.failures!==void 0&&(w.activation_diagnostics={failed_count:p.failures.length,failed:p.failures}),t==="explore"&&(w.runtime_probe=p.summary),t==="manage"&&(w.runtime_probe=p.summary,w.managed_state_fix=Cv(m,h)),a(w)},Yu={init:ev,install:hv,uninstall:wv,explore:Ku,manage:Ku,describe:Av,reload:tv,doctor:Ev,catalog:nv,adopt:yv,"adopt-all":gv,activate:Vu,deactivate:Vu,migrate:qu},Tv=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),$v=e=>Tv(e)?Qo(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Yu[e.action](e)):Yu[e.action](e);import{execFile as Ov}from"node:child_process";import{realpath as Dv}from"node:fs/promises";import um from"node:path";import{promisify as Pv}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 Nv=Pv(Ov),Mv=32*1024*1024,Lv=1e4,Fv=["search/eval-queries.json"];function sa(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function jv(e){return`'${e.replaceAll("'","'\\''")}'`}async function Uv(e,t=Dv){return t(e).catch(()=>um.resolve(e))}async function si(e){let t=await kt(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 Uv(e),r=sa(um.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=xo.map(o=>`${r}/${sa(o)}`);try{let{stdout:o}=await Nv("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:Mv,windowsHide:!0,timeout:Lv}),a=new Set(Fv.map(d=>`${r}/${d}`)),s=[...new Set(o.split("\0").filter(d=>d.length>0&&!a.has(sa(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>s.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:s,tracked_path_count:s.length,remediation_command:s.length===0?null:`git rm --cached -r -- ${c.map(d=>jv(`:(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 Hv}from"node:child_process";import{randomUUID as Gv}from"node:crypto";import{readdir as Jv}from"node:fs/promises";import le from"node:path";import{promisify as Vv}from"node:util";import{constants as mm}from"node:fs";import{lstat as zv,open as Wv}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 qv={lstat:zv,open:Wv};function Bv(e){return e.O_NOFOLLOW??0}async function pm(e,t,n=qv){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let i=await n.open(e,mm.O_RDONLY|Bv(mm));try{let o=await i.stat();if(!o.isFile()||o.size>t)return null;let a=Buffer.alloc(o.size),s=0;for(;s<a.length;){let{bytesRead:d}=await i.read(a,s,a.length-s,s);if(d===0)break;s+=d}return(await i.stat()).size===o.size&&s===o.size?a.toString("utf8",0,s):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]="145a6d31-5e14-5b0b-95fb-6f837d11e2f4")}catch{}})();var Kv=Vv(Hv),Yv=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,Xv=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,da=2048,Zv=16*1024*1024,Qv=64,eb=1e5,tb=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"]),nb=new Set(["field","base","ours","theirs","retained","discarded"]);async function la(e){try{let{stdout:t}=await Kv("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 ym(e,t){let n=le.dirname(le.resolve(e,t));for(let r=0;r<12;r+=1){if(await D(le.join(n,"settings.json")))return n;let i=le.dirname(n);if(i===n)break;n=i}return null}function ua(e){return le.join(e,"merge-receipts")}function nn(e){return`${e}.json`}function zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wm(e,t){return Object.keys(e).every(n=>t.has(n))}function fm(e){return Array.isArray(e)&&e.length<=da&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Un(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>eb||r.depth>Qv)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(zn(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function rb(e){return zn(e)&&wm(e,nb)&&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")&&Un(e.base)&&Un(e.ours)&&Un(e.theirs)&&Un(e.retained)&&Un(e.discarded)}function ib(e){if(!zn(e))return!1;let t=Object.entries(e);return t.length<=da&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function ob(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||le.posix.isAbsolute(e))return!1;let n=le.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&le.posix.basename(n,le.posix.extname(n))===t}function ab(e){return!wm(e,tb)||e.version!==1?!1:typeof e.id=="string"&&Yv.test(e.id)&&typeof e.item_id=="string"&&Xv.test(e.item_id)&&ob(e.item_path,e.item_id)}function sb(e){return!fm(e.fields_from_theirs)||!fm(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>da||!e.decisions.every(rb)?!1:e.merged_field_hashes===void 0||ib(e.merged_field_hashes)}function cb(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 db(e){return typeof e.created_at=="string"&&Hi(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&Hi(e.reconciled_at))}function lb(e){return e.value_availability==="hash_only"&&e.decisions.every(t=>t.base===null&&t.ours===null&&t.theirs===null&&gm(t.retained)&&gm(t.discarded))}function ma(e,t){return!zn(e)||!ab(e)||!sb(e)||!cb(e)||!db(e)?!1:t!=="durable"||lb(e)}async function vm(e){return pm(e,Zv)}async function hm(e){let t;try{t=await(e.readReceipt??vm)(e.receiptPath)}catch(o){if(it(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(!ma(n,e.evidenceSource)||n.id!==e.receiptId||le.basename(e.receiptPath)!==nn(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:ci(n),content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt},null,2)}
38
- `}}function ci(e){return ot(X({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:di(e).decisions}))}function ub(e,t){if(e.state==="reconciled"&&t.state==="reconciled")return e;let{reconciled_at:n,...r}=e;return{...r,state:"pending"}}function di(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:ca(t.retained)??ot(X(t.retained)),discarded_hash:ca(t.discarded)??ot(X(t.discarded))}))}}function ca(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 gm(e){return zn(e)&&Object.keys(e).length===1&&ca(e)!==void 0}async function OO(e){let t=await la(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=le.basename(r,le.extname(r)),o={version:1,id:Gv(),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 fn(t),await se(le.join(t,nn(o.id)),`${JSON.stringify(o,null,2)}
39
- `);let a=await ym(e.cwd,o.item_path);if(a!==null){let s=ua(a),c=di(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 fn(s),await se(le.join(s,nn(o.id)),`${JSON.stringify(d,null,2)}
40
- `)}return o}async function _m(e,t){if(!await D(e))return{receipts:[],invalid_evidence_count:0};let n;try{n=await Jv(e)}catch{return{receipts:[],invalid_evidence_count:1}}let r=[],i=0;for(let o of n.sort((a,s)=>a.localeCompare(s)))if(o.endsWith(".json"))try{let a=le.join(e,o),s=await vm(a);if(s===null){i+=1;continue}let c=JSON.parse(s);if(!ma(c,t)||o!==nn(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 Wn(e,t={}){let n=await la(e),r=n===null?{receipts:[],invalid_evidence_count:0}:await _m(n,"clone_local"),i=t.pmRoot??le.join(e,".agents","pm"),o=await _m(ua(i),"durable"),a=new Map(o.receipts.map(c=>[c.id,c])),s=0;for(let c of r.receipts){let d=a.get(c.id);if(d!==void 0&&ci(d)!==ci(c)){a.delete(c.id),s+=1;continue}a.set(c.id,d===void 0?c:ub(c,d))}return{receipts:[...a.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+s}}async function mb(e,t={}){return(await Wn(e,t)).receipts}function li(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 DO(e,t,n={}){let r=await la(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(!ma(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let o=T(),a=le.join(r,nn(t.id)),s=await ym(e,t.item_path),c=s===null?null:le.join(ua(s),nn(t.id)),l=(await Promise.all([hm({receiptPath:a,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:o}),...c===null?[]:[hm({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=ci(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 se(m.path,m.content)}async function PO(e){let t=await mb(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:T()}}import{realpath as xm}from"node:fs/promises";import pb from"node:path";import Sm 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]="7a21ee76-ed53-57a0-9776-c787297ed7b6")}catch{}})();function bm(e,t){return t==="body"?e.body:e.metadata[t]}function pa(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((a,s)=>!r.has(s)&&pa(i,a));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)&&pa(i,n[r]))}function km(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],a=new Set;for(let c of sc(o.patch))a.add(Er(c.path)),c.from&&a.add(Er(c.from));let s=[...n].filter(c=>a.has(c));if(s.length!==0){for(let c of s)n.delete(c);r.push({index:i+1,ts:o.ts,author:o.author,op:o.op,fields:s.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function fb(e,t,n){let r=Sm.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(Er(p.path));let o=new Set([...i].filter(p=>pa(bm(t,p),bm(n,p)))),a=new Set([...i].filter(p=>!o.has(p))),s=km(e,a),c=km(e,o),d=[...i].sort((p,h)=>p.localeCompare(h)),l=[...a].sort((p,h)=>p.localeCompare(h)),u=[...o].sort((p,h)=>p.localeCompare(h)),m=[...new Set(s.map(p=>p.author))].sort((p,h)=>p.localeCompare(h)),f=[...new Set(c.map(p=>p.author))].sort((p,h)=>p.localeCompare(h));return{reconciled_field_count:i.size,reconciled_fields:d,reverted_field_count:a.size,reverted_fields:l,discarded_events:s,discarded_authors:m,preserved_field_count:o.size,preserved_fields:u,preserved_events:c,preserved_authors:f,recovery_hint:s.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 hb(e){try{return await xm(e)}catch{return null}}async function gb(e){if(e.receipt.evidence_source!=="clone_local"||await hb(pb.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(s=>s.field)])].sort((s,c)=>s.localeCompare(c)),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let i=Object.keys(r).sort((s,c)=>s.localeCompare(c));if(n.length!==i.length||n.some((s,c)=>s!==i[c]))return null;let o=e.currentItemReplay.metadata;return n.every(s=>{let c=s==="body"?e.currentItemReplay.body:o[s];return r[s]===ot(X(c))})?{receipt:e.receipt,declaredFields:n}:null}async function _b(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(a=>a.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await xm(e.itemPath),r=[];for(let a of t){let s=await gb({receipt:a,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});s&&r.push(s)}let i=new Set(r.flatMap(({declaredFields:a})=>a)),o=e.reconciliation?.reconciled_fields;return r.length>0&&(o===void 0||o.length>0&&o.every(a=>i.has(a)))?{trusted:!0,reason:"trusted_clone_local_driver_evidence",receipt_ids:r.map(({receipt:a})=>a.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function yb(e){let t=e.options.mergeReceiptProof?.receipts.filter(i=>i.item_id===e.subjectId)??[],n=e.options.mergeReceiptProof?await _b({proof:{...e.options.mergeReceiptProof,receipts:t},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(n&&!n.trusted&&e.options.dryRun!==!0&&e.options.force!==!0)throw new y(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${n.reason}).`,_.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use clone-local driver 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 r=n?.trusted?t.filter(i=>n.receipt_ids.includes(i.id)):[];return{mergeReceiptProof:n,effectiveAuditContext:r.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:r.map(di)}}:e.options.auditContext}}async function wb(e,t,n,r){let i=e.located?.itemPath??null,o=e.located?await st(e.located,{schema:t.schema}):null;if(!o)return{currentItemReplay:null,currentItemPath:i,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let a=ac(o.document),s=n[n.length-1]?.after_hash;return{currentItemReplay:a,currentItemPath:i,matchedChainBefore:Ft(a,r)===s,currentItemRawBeforeLock:o.raw,loadedItem:o}}function vb(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 bb(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:T(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Sm.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Ft(e.finalReplay,e.itemHashVersion),after_hash:Ft(n,e.itemHashVersion),message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function kb(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 xb(e){return wc({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})=>yc({historyPath:e.historyPath,nextHistoryRaw:lc(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>ne({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function fa(e,t,n){let r=L(process.cwd(),n.path);await Q(r);let i=await C(r),o=B(i,z()),a=await vc(r,e,i,o.type_to_folder);if(!await D(a.historyPath))throw new y(`No history stream exists for ${a.id}.`,_.NOT_FOUND);let s=await Y(a.historyPath),c=await Lt(a.historyPath,a.id);if(c.length===0)throw new y(`No history entries exist for ${a.id}; nothing to repair.`,_.USAGE);let d=Ji(c),l=_r(c),u=t.normalizeProvenance?Nd(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},m=cc(u.entries),f=new Set(u.entries.map(W=>W.item_hash_version).filter(W=>W!==void 0)),p=dc(u.entries,m),h=await wb(a,i,c,m),g=p.finalDocument,w=h.currentItemReplay!==null&&Ft(g,m)!==Ft(h.currentItemReplay,m),v=w&&h.currentItemReplay?fb(p.entries,g,h.currentItemReplay):void 0,{mergeReceiptProof:x,effectiveAuditContext:S}=await yb({options:t,subjectId:a.id,itemReplayContext:h,reconciliation:v}),b=[p.entriesRehashed>0,p.entriesPatchRepaired>0,w,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),R=J(t.author,i.author_default),k=!!t.dryRun,I=vb({message:t.message,entriesRehashed:p.entriesRehashed,entriesPatchRepaired:p.entriesPatchRepaired,reconcileNeeded:w}),{rewrittenEntries:A,auditEntryAdded:j}=bb({reanchorEntries:p.entries,changed:b,reconcileNeeded:w,currentItemReplay:h.currentItemReplay,finalReplay:g,author:R,message:I,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...S,provenance_normalization:u.receipt}:S,itemHashVersion:m,explicitItemHashVersion:p.explicitItemHashVersion}),q=Ji(A);if(!q.ok)throw new y(`history-repair produced an invalid rewritten chain (${q.errors.join(", ")}).`,_.GENERIC_FAILURE);let O=kb(b,p.skippedOps,v);return b&&!k&&O.push(...await xb({pmRoot:r,subject:a,settings:i,typeRegistry:o,historyRawBeforeLock:s,currentItemRawBeforeLock:h.currentItemRawBeforeLock,author:R,force:t.force,loadedItem:h.loadedItem,historyPath:a.historyPath,rewrittenEntries:A})),{id:a.id,dry_run:k,changed:b,history:{path:a.historyPath,entries_scanned:c.length,chain_drift_before:!d.ok,entries_rehashed:p.entriesRehashed,entries_patch_repaired:p.entriesPatchRepaired,converted_replace_to_add:p.convertedReplaceToAdd,skipped_ops:p.skippedOps,reconciled_with_item:w,audit_entry_added:j,verify_ok:q.ok,verify_errors:q.errors,item_hash_version_before:l.item_hash_version??null,item_hash_version_after:m,version_disposition:f.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},...v?{reconciliation:v}:{},...x?{merge_receipt_proof:x}:{},warnings:[...new Set(O)].sort((W,me)=>W.localeCompare(me)),generated_at:T()}}function aD(e,t){if(t&&e!==void 0)throw new y("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",_.USAGE);if(!t&&e===void 0)throw new y("history-repair: provide an item <id> or pass --all to repair every drifted stream.",_.USAGE)}async function sD(e,t){let n=L(process.cwd(),t.path);await Q(n);let r=await C(n),i=B(r,z()),o=[],a=await zt(n,r.item_format,i.type_to_folder,o,r.schema,{forceSourceScan:!0}),s=await Kt(n,a),c=e.normalizeProvenance?await Md(n):[],d=[...new Set([...s.driftedItems,...c])].sort((f,p)=>f.localeCompare(p)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let f of d)try{let p=await fa(f,{...e,auditContext:e.auditContextById?.[f],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[f]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=p.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...p.warnings.map(g=>`${f}:${g}`)),l.push({id:f,outcome:h,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,l.push({id:f,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await ic(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:a.length,drifted_streams:s.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...o,...u])].sort((f,p)=>f.localeCompare(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]="652d1b49-f9d1-55a7-84b5-ff3cf57648ad")}catch{}})();var Sb=new Set(qc),Am=25,on=8,qn=100,Eb=ge.join("runtime","telemetry","events.jsonl"),Ab=ge.join("runtime","telemetry","state.json"),Rb=2500,Ib=500,Rm=Wc-3,Cb=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function va(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function ba(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function an(e){return e.trim().toLowerCase()}function _a(e,t){let n=an(e),r=an(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function ka(e){try{return(await et.stat(e)).isDirectory()}catch{return!1}}async function Tb(e){let t=(await et.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>et.readdir(ge.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>hn.some(o=>i.name.endsWith(o))).map(i=>ge.parse(i.name).name)))}async function $b(e,t,n,r){let i=await Ge({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:i,overThreshold:!1,classification:"live"};let a;try{a=await et.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let s="live";if(o){let d=a.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{s=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?a.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function Ob(e,t,n){let r=ge.join(e,"history");if(!await ka(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await et.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),a=t.enabled?t.max_entries:null,s=[],c=[],d=[],l=[];for(let u of i){let m=ge.join(r,u),f=u.slice(0,-6),p=await $b(m,f,t,n);s.push(...p.warnings),p.classification==="tombstone"&&d.push(f),p.classification==="orphaned"&&l.push(f),p.overThreshold&&c.push(f)}return{count:i.length,warnings:[...s,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:a,tombstones:d,orphaned:l}}function ya(e,t){return ge.relative(e,t).replaceAll("\\","/")}async function Im(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),a=[];try{a=await et.readdir(o)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&U(s))continue;continue}for(let s of a)hn.some(c=>s.toLowerCase().endsWith(c))&&r.push(ge.join(o,s))}return r.sort((i,o)=>ya(e,i).localeCompare(ya(e,o))),r}function Db(e){return!(typeof e=="object"&&e!==null&&"code"in e&&U(e))}async function Pb(e,t,n){let r=await Im(e,t),i=[],o=[],a=[],s=[],c=Ct(z());for(let d of r){let l=ya(e,d),u;try{u=await et.readFile(d,"utf8")}catch{i.push(l);continue}let m=Nt(u);if(m){o.push({path:l,...m});continue}try{let f=Mt(u,{format:vs(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:hr(f.metadata)})}catch{a.push(l)}}return{paths:r,unreadable:i,conflictMarkers:o,parseFailures:a,formatVersions:s}}async function Nb(e){let t=ge.join(e,"history"),n=[],r=[],i=[],o=[];try{o=(await et.readdir(t)).filter(a=>a.endsWith(".jsonl")).sort((a,s)=>a.localeCompare(s))}catch(a){Db(a)&&n.push("history")}for(let a of o){let s=a.slice(0,-6),c;try{c=await et.readFile(ge.join(t,a),"utf8")}catch{n.push(s);continue}let d=Nt(c);if(d){r.push({id:s,...d});continue}c.split(/\r?\n/).forEach((l,u)=>{if(l.trim())try{JSON.parse(l)}catch{i.push({id:s,line:u+1})}})}return{files:o,unreadable:n,conflictMarkers:r,invalidJson:i}}function Cm(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 Mb(e){return e===0?[]:[`merge_receipt_evidence_invalid:${e}`]}async function Lb(e,t,n,r,i){let o=await Pb(e,t,n),a=await Nb(e),s=gr(o.formatVersions),c=$e(n),d=Cr(i,b=>rc(b,c),wn()),l=await si(e),u=await kt(e),m=u===null?null:await Hr(u),f=await Wn(u??e,{includeLossless:!0,pmRoot:e}),p=f.receipts,{pendingDecisions:h,lossless:g}=li(p),w=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}`),...a.unreadable.map(b=>`integrity_history_unreadable:${b}`),...a.conflictMarkers.map(b=>`integrity_history_conflict_marker:${b.id}:L${b.line}`),...a.invalidJson.map(b=>`integrity_history_invalid_json:${b.id}:L${b.line}`),...s.outdated.map(b=>`integrity_item_outdated_format_version:${b}`),...s.ahead.map(b=>`integrity_item_ahead_format_version:${b}`),...Cm(d),...l.tracked_path_count>0?[`tracked_runtime_cache_files:${l.tracked_path_count}`]:[],...m!==null&&m.status!=="ok"?[`merge_driver_configuration_${w?"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}`]:[],...Mb(f.invalid_evidence_count)],x=[...new Set(v)].sort((b,R)=>b.localeCompare(R)),S=x.filter(b=>!b.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:S.length===0?"ok":"warn",ok:S.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:s.outdated.length,item_ahead_format_version:s.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:f.invalid_evidence_count},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:s.outdated,item_ahead_format_version:s.ahead,hierarchy_integrity:{...d,relations:qe(d.relations,on)},history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.invalidJson,tracked_runtime_cache:{tracker_relative_root:l.tracker_relative_root,tracked_paths:l.tracked_paths,tracked_path_count:l.tracked_path_count,remediation_command:l.remediation_command},merge_driver_configuration:m===null?null:{...m,required:r},pending_merge_decision_items:[...new Set(h.map(b=>b.item_id))].sort((b,R)=>b.localeCompare(R)),lossless_merge_receipt_items:[...new Set(g.map(b=>b.item_id))].sort((b,R)=>b.localeCompare(R))}},warnings:x,gitWorkspaceRoot:u,pendingMergeReceipts:p}}function Fb(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function jb(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:Fb(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Ub(e,t){let n=Z(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function zb(e){let n=Z(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function Wb(e){return Z(e.reason)??Z(e.error)??Z(e.message)}function ha(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function qb(e){let t=[],n=[],r=[];e.forEach((o,a)=>{let s=Ub(o.definition,a),c=zb(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:s,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:s,status:c,reason:Wb(o.definition)});return}n.push({layer:o.layer,name:o.name,id:s,status:c})}),t.sort(ha),n.sort(ha),r.sort(ha);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 Tm(e,t,n,r,i,o,a,s,c){let d=[...new Set(e)].sort((g,w)=>g.localeCompare(w)),l=[...new Set(d.map(g=>ba(g)))].sort((g,w)=>g.localeCompare(w)),u=d.filter(g=>g.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=[],h=Yo(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${er.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(g=>g.startsWith("extension_capability_legacy_alias:"))&&p.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:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):a.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.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:a.length,unmanaged_loaded_extensions:a,unmanaged_expected_extension_count:s.length,unmanaged_expected_extensions:s,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function Bb(e,t,n){let r=await na(Pe(e)),i=await Ne({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),o=i.loaded.map(k=>jb(k)),a=await yd(i.loaded,Pe(e)),s=await Me({...i,loaded:i.loaded}),[c,d]=await Promise.all([he(i.roots.project),he(i.roots.global)]);await ta(e,s.registrations.migrations);let l=qb(s.registrations.migrations),u={failed:s.failed,warnings:s.warnings,hook_counts:s.hook_counts,command_override_count:s.command_override_count,command_handler_count:s.command_handler_count,parser_override_count:s.parser_override_count,preflight_override_count:s.preflight_override_count,service_override_count:s.service_override_count,renderer_override_count:s.renderer_override_count,registration_counts:s.registration_counts,registrations:s.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(k=>an(k.name))),f=new Set(d.state.entries.map(k=>an(k.name))),p=[...new Map(i.loaded.filter(k=>!(k.layer==="project"?m:f).has(an(k.name))).map(k=>[`${k.layer}:${k.name}`,{layer:k.layer,name:k.name,directory:k.directory}])).values()].sort((k,I)=>{let A=`${k.layer}:${k.name}`,j=`${I.layer}:${I.name}`;return A.localeCompare(j)}),h=p.map(k=>`${k.layer}:${k.name}`).sort((k,I)=>k.localeCompare(I)),g=p.filter(k=>_a(k.name,k.directory)).map(k=>`${k.layer}:${k.name}`).sort((k,I)=>k.localeCompare(I)),w=p.filter(k=>!_a(k.name,k.directory)).map(k=>`${k.layer}:${k.name}`).sort((k,I)=>k.localeCompare(I)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],x=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...a.warnings],S=Fn(x),b=jn(),R=Tm(x,i.failed.length,s.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,g,w);return{check:{name:"extensions",status:x.length===0?"ok":"warn",ok:x.length===0,details:{...i,loaded:o,warnings:x,activation:u,author_manifest:r,triage:R,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:b,capability_guidance:S,host_version_census:a}},warnings:x}}function Hb(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function qe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function Gb(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 ui(e,t){let n=qe(e,t);return{...n,sample:n.sample.map(r=>Gb(r))}}function K(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 Jb(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 Vb={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:K(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:K(e.missing_required,t),missing_optional:K(e.missing_optional,t),missing:K(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:K(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:ui(e.discovered,t),effective:ui(e.effective,t),loaded:ui(e.loaded,t),failed:qe(e.failed,t),warnings:K(e.warnings,t),activation:{failed:qe(n.failed,t),warnings:K(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:Jb(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:qe(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:K(n.affected_item_ids,t),samples:qe(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:K(e.item_unreadable,t),item_conflict_markers:qe(e.item_conflict_markers,t),item_parse_failures:K(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:K(n.tracked_paths,t)},history_unreadable:K(e.history_unreadable,t),history_conflict_markers:qe(e.history_conflict_markers,t),history_invalid_json:qe(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>({checked_items:e.checked_items,counts:e.counts,drifted_items:K(e.drifted_items,t),merge_receipt_attributed_items:K(e.merge_receipt_attributed_items,t),missing_streams:K(e.missing_streams,t),unreadable_streams:K(e.unreadable_streams,t),hash_mismatches:K(e.hash_mismatches,t),chain_mismatches:K(e.chain_mismatches,t),workspace_state_mismatches:K(e.workspace_state_mismatches,t),workspace_state_missing:K(e.workspace_state_missing,t),workspace_state_unreadable:K(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:K(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:K(e.stale_items_after,t),skipped:e.skipped})};function $m(e,t){let n=Vb[e.name];return n?n(e.details,t):e.details}function Kb(e){let t=K(e.warnings,on);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:$m(n,on)})),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:on},generated_at:e.generated_at}}function Em(e){return e.details.skipped===!0}function Yb(e){let t=K(e.warnings,on),n=e.checks.filter(Em).map(r=>r.name);return{ok:e.ok,checks:e.checks.filter(r=>!Em(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:on,omitted_checks:n},generated_at:e.generated_at}}function wa(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Hb(e,Am);return{values:n.values,truncated:n.truncated,total:e.length}}function rn(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Xb(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return Sb.has(e)?e:null}function mi(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 Om(e){let t=0,n=0,r=0,i=0,o=0;for(let a of e.split(`
41
- `)){let s=a.trim();if(s.length!==0){r+=1;try{let c=JSON.parse(s);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>=Rm&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:o}}function Zb(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Qb(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 ek(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await Dm(n)}}function tk(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,a=o&&(!i||o>i),s=!i,c=t.validEntries>=Ib;return(a||s||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function nk(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function rk(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>zc?[`telemetry_schema_version_behind:${t}`]:[]}function ik(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 ok(){return{telemetry_disabled:rn("PM_TELEMETRY_DISABLED")||rn("PM_NO_TELEMETRY"),pm_no_telemetry:rn("PM_NO_TELEMETRY"),telemetry_otel_disabled:rn("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:rn("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:Xb()}}function ak(e,t){return e.telemetry.enabled&&t.validEntries>0}function sk(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Dm(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(Rb)});return{probe_url:mi(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of Cb){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:mi(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function ck(e,t){let n=rr(process.cwd()),r=ge.join(n,Eb),i=ge.join(n,Ab),o=await Y(r),a=o!==null,s=o?Buffer.byteLength(o,"utf8"):0,c=o?Om(o):Zb(),d=await Y(i),{runtimeState:l,stateParseFailed:u}=Qb(d),m=e.telemetry.endpoint.trim(),f=mi(m),p=await ek(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...tk(e,c,l),...nk(p),...rk(p),...ik(e,l));let g=ak(e,c),w=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:f,global_pm_root:n,queue_path:r,queue_exists:a,queue_entries:c.validEntries,queue_draining:sk(g,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Rm,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:ok()}},warnings:h}}async function dk(e){let t;try{t=await Jd(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 lk(e,t){let n="metadata",{missingStreams:r,unreadableStreams:i,hashMismatches:o,chainMismatches:a,driftedItems:s,workspaceStateMismatches:c,workspaceStateMissing:d,workspaceStateUnreadable:l}=await Kt(e,t,{cacheHitVerification:n}),u=[...r.map(m=>`history_drift_missing_stream:${m}`),...i.map(m=>`history_drift_unreadable_stream:${m}`),...o.map(m=>`history_drift_hash_mismatch:${m}`),...a.map(m=>`history_drift_chain_mismatch:${m}`),...c.map(m=>`history_drift_workspace_state_mismatch:${m}`),...d.map(m=>`history_drift_workspace_state_missing:${m}`),...l.map(m=>`history_drift_workspace_state_unreadable:${m}`)];return{check:{name:"history_drift",status:u.length===0?"ok":"warn",ok:u.length===0,details:{checked_items:t.length,cache_hit_verification:n,drifted_items:s,counts:{drifted:s.length,missing_streams:r.length,unreadable_streams:i.length,hash_mismatches:o.length,chain_mismatches:a.length,workspace_state_mismatches:c.length,workspace_state_missing:d.length,workspace_state_unreadable:l.length},missing_streams:r,unreadable_streams:i,hash_mismatches:o,chain_mismatches:a,workspace_state_mismatches:c,workspace_state_missing:d,workspace_state_unreadable:l}},warnings:u}}function uk(e,t){let n=Ar(e),r=yn(n.settings),i=Rr(n.settings,t),o=r.active?vt(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(r.active&&i.active)}}function mk(){return{refreshed:[],skipped:[],warnings:[]}}async function pk(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?mk():jc(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function fk(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Wt(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function hk(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 gk(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Pm(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:Xi(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:Xi(r,e.vector_store?.adapter??null)}}function _k(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function yk(e,t,n){return e.enabled&&n.length>0&&t}async function wk(e,t,n,r,i){let o=uk(t,e),a=await qt(e),s=o.semanticRuntimeAvailable?eo(n,a.entries):[],c=await pk({pmRoot:e,snapshot:o,refreshPolicy:r,staleBefore:s}),d=await qt(e),l=o.semanticRuntimeAvailable?eo(n,d.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,m=fk({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:a,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),f=hk({ledgerBefore:a,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=wa(s,i),h=wa(l,i),g=yk(r,o.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.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:_k(r),...Pm(t,o),embedding_identity_changed:m,embedding_identity_before:a.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(a.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Am,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:g,refresh_skipped_reason:gk(r,o.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:f}}function vk(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 Nm(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new y("--check-only cannot be combined with --refresh-vectors",_.USAGE);if(n&&e.noRefresh===!0)throw new y("--no-refresh cannot be combined with --refresh-vectors",_.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var bk=new Set(["extensions","locks","search"]);function kk(e){let t=new Set(ps.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(fs));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of bk)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 xk(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:o}=kk(t),a=[],s=[],c=[];for(let d of[...r,...i]){let l=ge.join(e,d);c.push(...await Ge({path:l,scope:"project"})),!await ka(l)&&(o.has(d)?s.push(d):a.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:a,missingOptionalDirs:s,missingDirs:n?[...a,...s]:[...a],hookWarnings:c}}function Mm(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 Sk(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Je(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):zt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function ga(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function Ek(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 Ak(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 Rk(e){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e}}}var xa=e=>e.unknown_event_count??0,Sa=e=>e.actionable_unknown_event_count??xa(e);function Ik(e,t,n,r,i,o,a){let s=xa(r),c=Sa(r),d=s>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}:{},...a.length>0?{provenance_invalid_values:a}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Lm(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function Ck(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 Tk(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function $k(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 Fm(e){let t=new Map;for(let[i,o]of Object.entries(e.remediationSources))for(let a of o)t.has(a)||t.set(a,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let o=t.get(i)??"integrity",a=vo(i)?.code??ba(i),s=n.get(o)?.details,d=(typeof s?.remediation_map=="object"&&s.remediation_map!==null?s.remediation_map:{})[a],l=va(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:a,check:o,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function Ok(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&(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 Dk(e){for(let t of e.checks){let n=bo(e.remediationSources[t.name]);Ok({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function Pk(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(a=>typeof a=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(a=>Array.isArray(a)?a:[])),i=new Map;for(let a of e.pendingMergeReceipts){if(a.evidence_source!=="clone_local")continue;let s=i.get(a.item_id)??[];s.push(a),i.set(a.item_id,s)}let o=[];for(let a of n){if(r.has(a))continue;let s=i.get(a);if(!(!s||s.length===0))try{(await fa(a,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:s}},e.global)).merge_receipt_proof?.trusted&&o.push(a)}catch{}}return[...new Set(o)].sort((a,s)=>a.localeCompare(s))}function Nk(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 jm(e,t,n){let r=e.warning_count??e.warnings.length,i={...e,warning_count:r,warning_limit:qn,warnings_truncated:r>qn,warnings:e.warnings.slice(0,qn),findings:(e.findings??[]).filter(a=>e.warnings.slice(0,qn).includes(a.warning)||e.failed_because.includes(a.warning))},o=n?Yb(i):t.brief===!0?Kb(i):i;return{...o,warning_count:r,warning_limit:qn,warnings_truncated:r>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:r,warnings_truncated:r>o.warnings.length}}:{}}}async function Um(e,t={}){let n=L(process.cwd(),e.path);await Q(n);let r=yt(n),{settings:i,warnings:o}=await pc(n),a=[...new Set(o)],s=B(i,z()),c=t.strictDirectories===!0,d=Nm(t),l=await xk(n,s,c),u=vk(i),m=await ck(i,{checkTelemetry:t.checkTelemetry===!0}),f=await Bb(n,i,!!e.noExtensions),p=Mm(t),h=[],g=await Sk({pmRoot:n,settings:i,typeRegistry:s,skipPolicy:p,itemReadWarnings:h}),w=g,v=[...new Set(h)],x=p.skipDrift?{warnings:[]}:await fc({pmRoot:n,settings:i,itemIds:g.map(Pi=>Pi.id),commandLabel:"health"}),S=await Ob(n,i.history.compact_policy,await Tb(n)),b=await An(n,20,t.verboseAuthorEvents===!0),R=Sa(b),k=R>0?[`history_unknown_author_events:${R}`]:[],I=Lm(await Uc(n,g,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),A=await jd(n),j=A.outcomes,q=A.invalid_values,O=A.warnings,W=await dk(n),me=p.skipIntegrity?{...ga("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await Lb(n,s.type_to_folder,i.schema,t.requireMergeDrivers===!0,g),ue=p.skipDrift?ga("history_drift"):await lk(n,w),gt=await Pk({gitWorkspaceRoot:me.gitWorkspaceRoot,pendingMergeReceipts:me.pendingMergeReceipts,historyDriftCheck:ue,global:e});Nk(ue,gt);let rt=p.skipVectors?ga("vectorization"):await wk(n,i,w,d,t.verboseStaleItems===!0),_t=[Ek(r,i,a),Ak(l,c),Rk(u),m.check,f.check,Ik(g,i,S,b,I.scan,j,q),W.check,me.check,ue.check,rt.check],F=Ck({directoryState:l,normalizedSettingsReadWarnings:a,settingWarnings:u,normalizedItemReadWarnings:v,telemetryCheck:m,extensionCheck:f,historyPolicyWarnings:x.warnings,historySummary:S,authorAttributionWarnings:k,staleInProgressWarnings:I.warnings,provenanceWarnings:O,locksCheck:W,integrityCheck:me,historyDriftCheck:ue,vectorizationCheck:rt}),G=$k({directoryState:l,normalizedSettingsReadWarnings:a,settingWarnings:u,normalizedItemReadWarnings:v,telemetryCheck:m,extensionCheck:f,historyPolicyWarnings:x.warnings,historySummary:S,authorAttributionWarnings:k,staleInProgressWarnings:I.warnings,provenanceWarnings:O,locksCheck:W,integrityCheck:me,historyDriftCheck:ue,vectorizationCheck:rt});Dk({checks:_t,remediationSources:G,historyDriftedCount:Tk(ue),overThresholdCount:S.over_threshold.length});let Oi=F.filter(Pi=>!va(Pi,t.requireMergeDrivers===!0)),Di=Fm({warnings:F,checks:_t,remediationSources:G,requireMergeDrivers:t.requireMergeDrivers===!0}),Ff={ok:Oi.length===0,checks:_t,warnings:F,findings:Di,failed_because:Oi,generated_at:T()};return jm(Ff,t,p.summaryMode)}var eP={buildHierarchyIntegrityWarnings:Cm,buildExtensionHealthTriageSummary:Tm,buildHealthFindings:Fm,buildCapabilityContractMetadata:jn,buildStaleInProgressHealthSummary:Lm,buildVectorizationProviderDetails:Pm,collectUnknownCapabilityGuidance:Fn,isAdvisoryHealthWarning:va,isDirectory:ka,isExpectedUnmanagedExtension:_a,listItemDocumentPaths:Im,normalizeEndpointForDisplay:mi,normalizeExtensionNameForMatch:an,parseTelemetryQueue:Om,probeTelemetryEndpointHealth:Dm,projectHealthResult:jm,resolveActionableUnknownAuthorEventCount:Sa,resolveHealthSkipPolicy:Mm,resolveUnknownAuthorEventCount:xa,resolveVectorRefreshPolicy:Nm,selectStaleItemDetail:wa,summarizeHealthCheckDetails:$m,summarizeExtensionList:ui,summarizeRecordList:qe,summarizeStringList:K,telemetryEnvFlagEnabled:rn,warningCode:ba};import sn from"node:fs/promises";import cn 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 Mk(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let o;try{o=await sn.readdir(cn.join(e,i))}catch{return}for(let a of o)for(let s of hn)if(a.toLowerCase().endsWith(s)){r.push({relativePath:`${i}/${a}`,id:a.slice(0,-s.length)});break}})),r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath))}function Lk(e,t){let{id:n,relativePath:r,liveItemIds:i,out:o}=e,a=Nt(t);if(a){o.conflictMarkers.push({id:n,path:r,line:a.line,detail:`unresolved merge conflict marker ${a.marker}`});return}let s=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");s=l}catch{o.unparseable.push({id:n,path:r,line:d.number,detail:"history line is not a valid JSON object"});return}s!==null&&(s.op==="delete"&&i.has(n)&&o.resurrected.push({id:n,deleted_at:typeof s.ts=="string"?s.ts:"",deleted_by:typeof s.author=="string"?s.author:""}),s.op==="history_repair"&&Array.isArray(s.patch)&&s.patch.length>0&&(o.repairReconciliations+=1))}function Ea(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function Fk(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await sn.readdir(cn.join(e,"history"))}catch{return n}for(let i of r.sort((o,a)=>o.localeCompare(a))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await sn.readFile(cn.join(e,"history",i),"utf8")}catch(a){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Ea("history stream",a)});continue}Lk({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},o)}return n}function zm(e){let t=Nt(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function jk(e){let t=[],n=0,r=null;try{r=await Y(yt(e))}catch(o){n+=1,t.push({path:"settings.json",detail:Ea("configuration file",o)})}if(r!==null){n+=1;let o=zm(r);o!==null&&t.push({path:"settings.json",detail:o})}let i;try{i=await sn.readdir(cn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of i.sort((a,s)=>a.localeCompare(s))){if(!o.endsWith(".json"))continue;n+=1;let a;try{a=await sn.readFile(cn.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:Ea("configuration file",c)});continue}let s=zm(a);s!==null&&t.push({path:`schema/${o}`,detail:s})}return{scanned:n,unparseable:t}}async function Wm(e,t,n,r={}){let i=await Mk(e,n),o=new Set(i.map(u=>u.id)),a=new Map;for(let u of i){let m=a.get(u.id);m===void 0?a.set(u.id,[u.relativePath]):m.push(u.relativePath)}let s=[...a.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).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=cn.join(e,u.relativePath);return Mt(await sn.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 Fk(e,o),l=await jk(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:s,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 Uk}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 Bm(e,t){return new Promise((n,r)=>{Uk("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,o)=>{i?r(i):n(o)})})}function Hm(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 mP(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Hm(n),!n)throw new RangeError("Source line range must use start:end.");return n}function zk(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 Wk(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((a,s)=>a.localeCompare(s));n.set(i,o)}return n}async function qk(e){let t=qm.relative(e.workspaceRoot,qm.resolve(e.workspaceRoot,e.sourcePath)),n=await Bm(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Bm(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:zk(n),commitItems:Wk(r),available:!0}}function Bk(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,a=o?i.target:i.source;if((e.visitedDepth.get(a)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(a,n);let s=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,a],kinds:[...e.current.kinds,o?i.kind:s.inverse??i.kind]};e.details.get(a)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function Hk(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let o=t.shift(),a=o.kinds.length;i!==void 0&&a>=i||a>=e.maxDepth||(i=Bk({current:o,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((o,a)=>o.nodes.join("\0").localeCompare(a.nodes.join("\0"))),r}function Gk(e,t,n){let r=Hc(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=Hk({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(s=>[s.id,s]))}),o=i[0];if(!o)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let a=[...new Set(i.map(s=>s.nodes.at(-1)))];return{status:a.length===1?"found":"ambiguous",nodes:o.nodes,kinds:o.kinds,alternative_decision_ids:a.slice(1)}}async function Jk(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await qk({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function Vk(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 Kk(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Gm(e){Hm(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 Jk(e),r=Kk(n),i=new Map;for(let o of e.candidates){let a=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(o.item.id)),s=a.reduce((l,[,u])=>l+u,0),c=Gk(o.item.id,e.corpus,t),d=Vk({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:s,decisionStatus:c.status});i.set(o.item.id,{score:s*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:s,evidence:[...o.files.map(l=>({kind:"linked_file",reference:l.path})),...a.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value: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 Ja from"node:fs/promises";import{realpathSync as dS}from"node:fs";import{execFile as lS}from"node:child_process";import _e from"node:path";import{promisify as uS}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 Yk=["metadata","resolution"],Aa=["metadata","resolution","estimates","lifecycle"],Xk="completed";function Ra(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Jm(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Vm(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Jm(n.close_reason)??Xk;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Ra(r)}`,gate:"resolution"})}return t}function Km(e){let t=[];for(let n of e){let r=Jm(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 ${Ra(r)}`,gate:"metadata"})}return t}function Ym(e,t){return e.map(n=>{let r=mc(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 Xm(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 Zm(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 ${Ra(n.path)}`})}return t}function Qm(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 y(`--fix-scope values must not be empty. Supported values: ${Aa.join(", ")}.`,_.USAGE);return new Set(Yk)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Aa.includes(i)){n.add(i);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${Aa.join(", ")}.`,_.USAGE)}return n}function ep(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 Bn(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 Zk=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function Qk(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=Zk.exec(n);if(!r)return null;let i=r[1],o=i.toUpperCase(),a=i.slice(0,i.lastIndexOf("-")),s=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 a===a.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||s.has(a.toUpperCase())||l?o:null}function tp(e){return typeof e=="string"&&e.trim().length>0}function np(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||tp(i.duplicate_of))continue;let o=Qk(i.title,{...t,evidenceText:i.body});if(o===null)continue;let a=n.get(o);a||(a=[],n.set(o,a)),a.some(s=>s.id===i.id)||a.push({id:i.id,title:i.title,parent:tp(i.parent)?i.parent.trim():null})}let r=[];for(let[i,o]of n){if(o.length<2)continue;let a=new Set(o.map(d=>d.id.toLowerCase())),s=o.filter(d=>d.parent===null||!a.has(d.parent.toLowerCase()));if(s.length<2)continue;let c=[...s].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 rp(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 a of[...i.keys()].sort((s,c)=>s.localeCompare(c)))o[a]=i.get(a);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 ip=3;function op(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function ap(e,t,n=ip){let r=Number.isFinite(n)&&n>=1?Math.floor(n):ip,i=new Map;for(let o of t){let a=op(o);if(a.length===0)continue;let s=i.get(a);s?s.push(o):i.set(a,[o])}return e.map(o=>{let a=(i.get(op(o))??[]).filter(s=>s!==o).sort((s,c)=>s.localeCompare(c));return a.length===0?{path:o,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:o,classification:"moved",candidates:a.slice(0,r),candidates_truncated:a.length>r}})}function sp(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 ex=/^[a-z][a-z0-9+.-]+:\/\//i;function Hn(e){return ex.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 tx(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function cp(e){return`${e.item_id} ${e.link_kind}`}function dp(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=tx(i.classification,r.classification),i.owners.set(cp(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[cp(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 a=t(o.item_id);return{id:o.item_id,type:a?.type??"Unknown",title:a?.title??"",status:a?.status??"",field:o.link_kind}}).sort((o,a)=>{let s=o.id.localeCompare(a.id);return s!==0?s:o.field.localeCompare(a.field)})}))}function nx(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function lp(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="${nx(r.title)}"`);return t}import rx from"node:fs/promises";import Ce from"node:path";import ix 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]="1832e2b3-0ece-523d-8f38-598303d3f590")}catch{}})();var ox=["path","scope","note"],ax=["pattern","glob","path","scope","note"],sx=["path"],cx=["from","to"],dx=new Set(["note","scope"]);function mp(e){let t=e??"project";if(!Ni.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${Ni.join(", ")} (default: project).`,_.USAGE);return t}function Ca(e){if(e.startsWith("```")||e.includes(`
43
- `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf("=");return t>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(n=>n>=0&&n<t))?!1:e.includes("=")||Sc(e)}function lx(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Ca(n)||!n.includes(",")?[t]:Ir(n)})}function ux(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function mx(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Ca(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let o=e.slice(t+2,-1).trim();if(o.length>0&&ux(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 px(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let i=mx(r);if(i!==void 0)return[i]}return lx([n]).map(i=>{let o=i.trim(),a=Ca(o)?gn(i,"--add"):{path:o};if(_n(a,"--add",ox),!a.path)throw new y(`--add requires path=<value> or a bare ${t} path`,_.USAGE);return{path:a.path,scope:mp(a.scope),note:a.note?.trim()||void 0}})}):[]}function fx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",_.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=gn(n,"--add-glob");_n(r,"--add-glob",ax);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new y("--add-glob key/value form requires pattern=<glob>",_.USAGE);return{pattern:i,scope:mp(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function hx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",_.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=gn(n,"--remove"),i=Object.keys(r).filter(o=>dx.has(o.toLowerCase()));if(i.length>0)throw new y(`--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>".`,_.USAGE);if(_n(r,"--remove",sx),!r.path)throw new y("--remove key/value form requires path=<value>",_.USAGE);return r.path}return n}):[]}function gx(e){return e?e.map(t=>{let n=gn(t,"--migrate");_n(n,"--migrate",cx);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new y("--migrate requires from=<value> and to=<value>",_.USAGE);return{from:r,to:i}}):[]}function Gn(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 _x(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(o=>Gn(o.path,n))),i=[...new Set(t.map(o=>Gn(o,n)).filter(o=>r.has(o)))].sort((o,a)=>o.localeCompare(a));if(i.length!==0)throw new y(`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.`,_.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 tt(e){return e.split(Ce.sep).join("/")}function Ia(e,t,n=process.cwd()){let r=e.trim();if(Hn(r))return r;if(Ce.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return tt(r.replaceAll("\\",Ce.sep));let i=Ce.relative(t,n);return i.startsWith(`..${Ce.sep}`)||i===".."||Ce.isAbsolute(i)?tt(Ce.normalize(r)):tt(Ce.relative(t,Ce.resolve(n,r)))}async function yx(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){let o=Ce.isAbsolute(i.pattern),a=await ix(i.pattern,{cwd:n,absolute:o,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),s=[...new Set(a.map(c=>Ia(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of s)r.push({path:c,scope:i.scope,note:i.note})}return r}function wx(e,t,n){if(t===void 0)return e;if(!n)throw new y("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",_.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function vx(e){return`${e.path}::${e.scope}`}function Ta(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function $a(e){return[...new Map(e.map(t=>[vx(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function bx(e,t=process.cwd()){let n=[...new Set(e)].sort((s,c)=>s.localeCompare(c)),r=[],i=[],o=[],a=[];for(let s of n){if(Hn(s)){a.push(s.trim());continue}let c=Ce.isAbsolute(s)?s:Ce.resolve(t,s);try{(await rx.stat(c)).isFile()?r.push(s):o.push(s)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&it(d)){i.push(s);continue}o.push(s)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:o,remote_references:a}}function kx(e,t,n,r){let i=0;for(let a=0;a<e.length;a+=1){let s=Gn(e[a].path,r);s!==e[a].path&&(e[a]={...e[a],path:s},i+=1)}return{adds:t.map(a=>{let s=Gn(a.path,r);return s!==a.path&&(i+=1),{...a,path:s}}),removes:n.map(a=>Gn(a,r)),count:i}}function xx(e,t,n,r){for(let o of t)e.some(a=>a.path===o.path&&a.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=$a(e);return r?i:Ta(i)}async function up(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths?await bx(t,e.workspaceRoot):void 0}}async function pi(e,t,n,r){let{metadataKey:i}=r,o=Rc(),a=L(process.cwd(),n.path),s=Pe(a),c=process.cwd();await Q(a);let d=await C(a),l=B(d,z()),u=await o.resolveList(t.add,"--add"),m=await o.resolveList(t.addGlob,"--add-glob"),f=await o.resolveList(t.remove,"--remove"),p=await o.resolveList(t.migrate,"--migrate"),h=px(u,r.bareNoun).map(q=>({...q,path:Ia(q.path,s,c)})),g=fx(m),w=await yx(g,s,c),v=wx([...h,...w],t.note,h.length>0||g.length>0),x=hx(f).map(q=>Ia(q,s,c)),S=gx(p);if(_x(v,x,S),!(v.length>0||x.length>0||S.length>0)){let q=await jt(a,e,d.id_prefix,d.item_format,l.type_to_folder);if(!q)throw new y(`Item ${e} not found`,_.NOT_FOUND);let W=(await st(q,{schema:d.schema})).document.metadata[i]??[];return up({id:q.id,artifacts:W,changed:!1,options:t,workspaceRoot:s})}let R=J(t.author,d.author_default),k=await wt({pmRoot:a,settings:d,id:e,op:r.op,author:R,message:t.message,force:t.force,skipNoop:!0,mutate(q){let O=q.metadata,W=O[i]??[],me=[...W],ue=kx(me,v,x,S),gt=xx(me,ue.adds,ue.removes,r.supportsAppendStable&&t.appendStable===!0);gt.length>0?O[i]=gt:delete O[i];let rt=!Rs(W,gt);return{changedFields:rt?[i]:[],warnings:rt&&ue.count>0?[`path_migrations_applied:${ue.count}`]:[]}}}),I=k.item[i]??[],A=k.warnings.find(q=>q.startsWith("path_migrations_applied:")),j=A?Number(A.slice(24)):0;return up({id:k.item.id,artifacts:I,changed:k.changedFields.includes(i),migrationsApplied:j,options:t,workspaceRoot:s})}function fi(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 pp(e,t,n){let r=await pi(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return fi(r,"docs")}import fp 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]="ed504f2b-8b78-5fca-a4a7-7b0709a65533")}catch{}})();var Sx=32768;function Oa(e){return tt(Te.normalize(e))}async function hi(e){try{return await fp.realpath(e)}catch{return Te.resolve(e)}}function dn(e,t){let n=Te.isAbsolute(e.path)?Te.resolve(e.path):Te.resolve(t,e.path);return`${Oa(n)}::${e.scope}`}function gi(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)=>gi(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))gi(i,t?`${t}.${r}`:r,n)}function Ex(e){let t=[];return gi(e.metadata,"metadata",t),gi(e.body,"body",t),t}function Ax(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 Rx(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,a=i.value.slice(0,Sx);for(let[s,c]of[[n,i.value],[r,a]]){s.lastIndex=0;for(let d of c.matchAll(s)){let l=Ax(d[0]);!l||o.has(l)||(o.add(l),t.push({field:i.field,value:l}))}}}return t}async function Ix(e,t,n=t){let r=Te.isAbsolute(e)?Te.resolve(e):Te.resolve(n,e),i;try{i=await fp.stat(r)}catch{return}if(!i.isFile())return;let[o,a]=await Promise.all([hi(t),hi(r)]);if(we(o,a)){let s=Te.relative(o,a);return!s||s.startsWith("..")||Te.isAbsolute(s)?void 0:{path:Oa(s),scope:"project"}}return{path:Oa(r),scope:"global"}}async function Cx(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>dn(c,t))),i=new Map,o=Rx(Ex(e)),a=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{a.set(c,await Ix(c,t,n))}));let s=o.map(c=>({reference:c,resolved:a.get(c.value)}));for(let{reference:c,resolved:d}of s){if(!d)continue;let l=dn(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 hp(e,t,n){let r=await pi(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return fi(r,"files")}async function Tx(e,t){let n=await hi(t),r=await Promise.all(e.map(async o=>{let a=o.trim();if(!a)throw new y("Files lookup paths must not be empty.",_.USAGE);if(!Te.isAbsolute(a))return tt(a);let s=await hi(a);return we(n,s)?tt(Te.relative(n,s)):tt(s)})),i=[...new Set(r)].sort((o,a)=>o.localeCompare(a));if(i.length===0)throw new y("Files lookup requires at least one path.",_.USAGE);return i}function $x(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new y(`Files lookup ${r} must be a non-negative integer.`,_.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 gp(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function _p(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 Ox(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(tt(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(_p)}async function Dx(e){if(e.explain)return Gm({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 Px(e){if([e.strictRead,e.noTruncate,e.explain,Qs()].includes(!0))return null;let t=await xr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?gc({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function Nx(e){let t=[],n=await Ut(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=Ox({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 y(`Files lookup could not read every item: ${i.join("; ")}`,_.GENERIC_FAILURE);let o=await Dx({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),s=(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:_p(c,d)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:s.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+s.length<r.length,truncated:e.offset+s.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:s.map(c=>({item:gp(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=L(process.cwd(),t.path),r=Pe(n);await Q(n);let i=await Tx(e.paths,r);if(e.lineRange&&i.length!==1)throw new y("Files lookup line attribution requires exactly one source path.",_.USAGE);let o=await C(n),a=B(o,z()),{offset:s,limit:c}=$x(e),d=await Px({pmRoot:n,typeToFolder:a.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,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:s,limit:c,has_more:s+d.matches.length<d.total,truncated:s+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:gp(l.item),files:l.files}))}:Nx({pmRoot:n,settings:o,typeToFolder:a.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function sN(e,t,n){let r=L(process.cwd(),n.path),i=Pe(r);await Q(r);let o=await C(r),a=B(o,z()),s=await jt(r,e,o.id_prefix,o.item_format,a.type_to_folder);if(!s)throw new y(`Item ${e} not found`,_.NOT_FOUND);let c=await st(s,{schema:o.schema}),d=await Cx(c.document,i,process.cwd()),l=d.filter(I=>I.status==="addable"),u=d.filter(I=>I.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let I=c.document.metadata.files??[];return{id:s.id,files:I,changed:!1,apply:m,count:I.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let p=J(t.author,o.author_default),h=l.map(I=>({path:I.path,scope:I.scope,note:f})),g=[],w=new Set,v=await wt({pmRoot:r,settings:o,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(I){let A=[...I.metadata.files??[]],j=new Set(A.map(W=>dn(W,i)));g=[],w.clear();for(let[W,me]of h.entries()){let ue=dn(me,i);j.has(ue)||(A.push(me),j.add(ue),g.push(me),w.add(W))}let q=$a(A),O=t.appendStable?q:Ta(q);return O.length>0?I.metadata.files=O:delete I.metadata.files,{changedFields:g.length>0?["files"]:[],warnings:g.length!==h.length?[`files_discover_skipped_existing:${h.length-g.length}`]:[]}}}),x=v.item.files??[],S=new Set(g.map(I=>dn(I,i))),b=x.filter(I=>S.has(dn(I,i))),R=l.filter((I,A)=>!w.has(A)),k=[...u,...R];return{id:v.item.id,files:x,changed:b.length>0,apply:!0,count:x.length,candidate_count:d.length,addable_count:l.length,added_count:b.length,skipped_existing_count:k.length,candidates:d,added:b,skipped_existing:k}}import{readFileSync as Mx}from"node:fs";import _i 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 Lx=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Da=new Set(["--pm-path","--path","--author"]),Fx={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"])},jx=new Set(["-p","--package"]),Ux=new Set(["-c","--call"]),zx=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Wx=new Set(["-C","--prefix","--userconfig","--cache"]),uN=new Set(["--cwd"]),mN=new Set(["--cwd"]),qx=new Set(["exec","x"]),pN=new Set(["run","run-script"]),fN=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Bx(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function Hx(e,t=process.cwd()){let n=Gx(e.split(" ").filter(a=>a.length>0));if(n.length===0)return null;let[r,...i]=n;if(yp(r)||wp(r,t))return i;if(r==="node"&&i[0]&&wp(i[0],t))return i.slice(1);let o=r==="npx"||r==="bunx"?Pa(i):r==="pnpm"?Kx(i):r==="npm"?Yx(i):null;return o&&(yp(o.command)||Vx(o.command))?o.args:null}var vp=(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(),a=new Set;for(let s of Bx(o)){let c=Hx(s),d=c?Xx(c):null,l=d&&Lx.has(d.subcommand)?Zx(d.remaining,Fx[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&a.add(l)}return[...a].sort((s,c)=>s.localeCompare(c))};function Gx(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 hN(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Da.has(n)){t+=2;continue}t+=1;continue}return n}}function yp(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function Jx(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 Vx(e){let t=Jx(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function wp(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=_i.resolve(t,e);try{return JSON.parse(Mx(_i.join(_i.dirname(_i.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Pa(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(Ux.has(r)){t+=1;break}t+=jx.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function bp(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 Kx(e){let t=bp(e,zx);return t?.subcommand!=="dlx"?null:Pa(t.args)}function Yx(e){let t=bp(e,Wx);return!t||!qx.has(t.subcommand)?null:Pa(t.args)}function Xx(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Da.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Zx(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("=")&&(Da.has(r)||t.has(r))&&(n+=1)}}import{execFile as Qx}from"node:child_process";import{readFile as eS}from"node:fs/promises";import xp from"node:path";import{promisify as tS}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 nS=tS(Qx),Na=1,rS="linked-test-trust.json";function Ma(e){return xp.join(bs(e),rS)}function kp(){return{version:Na,acknowledged:{}}}async function La(e){try{let t=JSON.parse(await eS(Ma(e),"utf8"));return t.version!==Na||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?kp():{version:Na,acknowledged:t.acknowledged}}catch{return kp()}}async function Fa(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 nS("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 ja(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function iS(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&ec(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Jn(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function oS(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 EN(e,t,n){if(!e||e.length===0)return e;let r=ja();return oS(e,t,n,await Fa(r))}function Sp(e){return ot(X({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 AN(e,t,n){let r=await La(e);return Ep(t,n,r)}function Ep(e,t,n){let r=Sp(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||!iS(e.provenance)?o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Jn(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...Jn(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...Jn(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",...Jn(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...Jn(i,t)}}async function Ap(e,t,n){let r=await La(e);return t.map(i=>Ep(i,n,r))}async function RN(e,t,n){let r=await La(e),i=t.filter(o=>typeof o.command=="string"&&o.command.length>0).map(Sp);for(let o of i)r.acknowledged[o]={acknowledged_at:n};return await fn(xp.dirname(Ma(e))),await se(Ma(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 Rp(e){return e.includeBody?zt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Ut(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1261d65-222c-5c6c-8634-a4413a91aba9")}catch{}})();var aS=5;async function Ip(e,t,n){let r=await Kt(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_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),a=n?Number.POSITIVE_INFINITY:aS,s=r.driftedItems.slice(0,a);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:s,drifted_items_truncated:s.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable}},warnings: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 yi(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],o=new Set([n]),a=s=>{for(let c of(t.get(s)??[]).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),a(c))return!0;i.pop(),o.delete(c)}}return!1};return a(n)?[...i]:[...e,n]}function sS(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function cS(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 a=n.get(i.id.toLowerCase());a&&(o.hierarchyDirection==="source_parent"?t.get(a).push(e.id):t.get(e.id).push(a))}}function Ua(e,t=wn()){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,a)=>o.id.localeCompare(a.id))){let o=r.get(i.id),a=sS(i.parent,n);a&&o.push(a),cS(i,r,n,t)}for(let[i,o]of r)r.set(i,[...new Set(o)].sort());return r}function za(e,t,n=wn()){let r=Cr(e,a=>t?Ws(a,t):a==="closed"||a==="canceled",n),i=Ua(e,n),o=r.cycles.map(a=>a.item_ids);return{cycle_count:o.length,active_cycle_count:r.cycles.filter(a=>!a.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(a=>a.legacy_terminal).length,cycle_item_ids:[...new Set(o.flat())].sort(),cycle_sample_paths:o.map(a=>yi(a,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(a=>!a.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(a=>a.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(a=>`${a.child_id}:${a.parent_ids.join(",")}:${a.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(a=>!a.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(a=>a.legacy_terminal).length,parent_divergence_rows:r.divergences.map(a=>`${a.child_id}:scalar=${a.scalar_parent_id}:dependencies=${a.dependency_parent_ids.join(",")}:${a.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7a231e7-0546-5d5f-b0c8-59629ad4d731")}catch{}})();var mS=["src","tests","docs"],pS=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],fS=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),hS=["resolution","expected_result","actual_result"],gS=["default","tracked-all","tracked-all-strict"],Cp=["core","strict","custom"],bi=["off","warn","error"],Ba=["author","acceptance_criteria","estimated_minutes","close_reason"],Dp=[...Ba,"reviewer","risk","confidence","sprint","release"],Va=Array.from(new Set(Dp)),_S={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"},yS={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"},wS={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"},vS={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"},bS={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"},kS=32*1024*1024,xS=1e4,Pp=40,ht=5,SS=4096,ES=255,AS=uS(lS);function Np(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?Np(r):r);return t}function RS(e){return{...e,checks:e.checks.map(t=>({...t,details:Np(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 It(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Tp(e){return It(e).replace(/\/+$/,"")}function Be(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 xi(e,t){return nc(e,t)??e}function Vn(e,t){return t.terminal_statuses.has(xi(e,t))}function pt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function wi(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function IS(e){let t=pt(hs),n={blocked_reason:pt(nr.blocked_reason),resolution:pt(nr.resolution),actual_result:pt(nr.actual_result)},r=pt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:pt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:pt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:pt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:wi(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:wi(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:wi(i.resolution,n.resolution)?"default":"settings",actual_result:wi(i.actual_result,n.actual_result)?"default":"settings"}}}function Mp(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Cp.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${Cp.join(", ")}.`,_.USAGE)}function Lp(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(bi.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${bi.join(", ")}.`,_.USAGE)}function Fp(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(bi.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${bi.join(", ")}.`,_.USAGE)}function CS(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>_S[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function TS(e,t,n){let r=CS(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Ba],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Dp],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:[...Ba],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var $S=new Set(["acceptance_criteria","estimated_minutes"]);function jp(e,t,n,r){return!r&&$S.has(t)&&Vn(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"?xi(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 Up(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 y(`Unknown --scan-mode value "${e}". Supported values: ${gS.join(", ")}.`,_.USAGE)}function zp(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return _e.resolve(t);let n=_e.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return _e.dirname(_e.dirname(n));let i=_e.resolve(process.cwd()),o=$p(n),a=$p(i),s=_e.relative(o,a);return s.length===0||!s.startsWith("..")&&!_e.isAbsolute(s)?n:i}function $p(e){try{return dS.native(e)}catch{return _e.resolve(e)}}function OS(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Ka(e,t,n){let r=t.length>0?_e.join(e,t):e,i;try{i=await Ja.readdir(r,{withFileTypes:!0})}catch(o){if(U(o))return;throw o}for(let o of i){if(o.name.startsWith("."))continue;let a=t.length>0?_e.join(t,o.name):o.name;if(o.isDirectory()){if(fS.has(o.name))continue;await Ka(e,a,n);continue}o.isFile()&&n.push(It(a))}}async function Ha(e){let t=[];for(let n of mS)await Ka(e,n,t);for(let n of pS){let r=_e.join(e,n);try{(await Ja.stat(r)).isFile()&&t.push(It(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function Wp(e){try{let{stdout:t}=await AS("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:kS,windowsHide:!0,timeout:xS}),n=t.split("\0").map(r=>It(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function DS(e,t){let n=new Set,r=Tp(ms);r.length>0&&n.add(r);let i=Tp(_e.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((o,a)=>o.localeCompare(a))}function Op(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function PS(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await Wp(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Ha(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Ha(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function te(e,t=ht){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function ft(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=te(e,Pp);return{values:n.values,truncated:n.truncated,total:e.length}}var NS={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},MS={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function LS(e){let t=e.missing_fields.map(n=>`${NS[n]} "${MS[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function qp(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(a=>typeof a=="string"):Kd(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 Bp(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 FS="validate_metadata_duplicate_issue_codes";function Hp(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:ht,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:[`${FS}:${e.length}`]}}function jS(){return Object.fromEntries(Va.map(e=>[e,[]]))}function US(e,t,n){let r=jS();for(let i of e)for(let o of Va)jp(i,o,t,n)&&r[o].push(i.id);return r}function zS(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let o=t[i];o.length>0&&r.push(`${yS[i]}:${o.length}`)}return r.push(...n),r}function Gp(e,t){let n={};for(let r of e.required_fields){let i=t[r],o=i?i.length:0,a=wS[r];n[a]=o}return n}function Jp(e,t,n){let r=[];for(let i of e.required_fields){let o=t[i];if(o)for(let a of o){let s=n.get(a)?.type,c=typeof s=="string"&&s.length>0?s:"Unknown";r.push({item_type:c,field:i})}}return r}function WS(e,t,n,r){for(let i of t.required_fields){let o=n[i];if(!o||o.length===0)continue;let a=vS[i],s=bS[i];if(!a||!s)continue;let c=te(o,r?o.length:ht);e[a]=c.values,e[s]=c.truncated}}function Vp(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 Kp(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 qS(e,t,n,r,i){let o=new Map(e.map(w=>[w.id,w])),a=t.profile==="strict",s=US(e,n,a),c=np(e,{configuredPrefixes:i}),d=Hp(c,r),l=zS(t,s,d.warnings),u=Gp(t,s),m=Jp(t,s,o),f=rp(m),p={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:[...Va],counts:u,missing_by_type:f,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(p.configured_custom_required_fields=[...t.configured_custom_fields]),WS(p,t,s,r);let h=Vp(t,s,o),g=Kp(t,s,o);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:p},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:g}}function BS(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(xi(m.status,t))),o=[],a=[];for(let m of i){let f=hS.filter(p=>!Z(m[p]));f.length!==0&&(o.push({id:m.id,missing_fields:f}),a.push({id:m.id,missing_fields:f,close_reason:Z(m.close_reason)}))}let s=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:ht,d=te(o.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=o.map(m=>LS(m)),u=te(l,c);return{check:{name:"resolution",status:s.length===0?"ok":"warn",ok:s.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:s,resolutionBackfillRows:a}}function Yp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xp(e,t="pm",n=Ss()){let r=new Set(e.map(o=>o.id)),i=[...e].sort((o,a)=>o.id.localeCompare(a.id));return new Map(i.map(o=>{let a=new Set,s=Be(o.blocked_by);s&&r.has(s)&&a.add(s),(o.dependencies??[]).filter(d=>{let l=Be(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Be(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>a.add(d));let c=Be(o.definition_of_ready);return Qp(c??"",t).filter(d=>r.has(d)).forEach(d=>a.add(d)),[o.id,[...a].sort((d,l)=>d.localeCompare(l))]}))}function Zp(e,t,n){let r=Bc(e,n?l=>Vn(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}`),a=t?Number.POSITIVE_INFINITY:ht,s=te(i,a),c=te(o,a),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>'`),a);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+o.length,active_dangling_reference_count:i.length,dangling_reference_rows:s.values,dangling_reference_rows_truncated:s.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 Qp(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${Yp(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 ef(e){let t=0,n=new Map,r=new Map,i=[],o=new Set,a=[],s=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))):(s(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,f)=>m.localeCompare(f)),a.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||s(l);return a.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function tf(e,t="pm"){let n=Xp(e,t),r=ef(n),i=[...new Set(r.flat())].sort((a,s)=>a.localeCompare(s)),o=r.map(a=>yi(a,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:o}}function nf(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 ki(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function rf(e,t){let n=ki(e).split("/").filter(Boolean),r=ki(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function HS(e,t){let n=ki(t),r=ki(e),i=t.endsWith("/")?t:`${t}/`,o=e.startsWith(i),a=n.length>0&&n===r,s=rf(e,t);return!o&&!a&&s===0?null:o?{score:t.length+1e3,confidence:"path_prefix"}:a?{score:s+500,confidence:"same_directory"}:{score:s,confidence:"shared_directory"}}function GS(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function JS(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(o=>(r==="docs"?o.docs??[]:o.files??[]).map(a=>({item:o,link:a}))).forEach(({item:o,link:a})=>{if(a.scope!=="project")return;let s=It(a.path);if(s.length===0||s===e)return;let c=HS(e,s);c!==null&&GS(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 of(e,t){return e.map(n=>{let r=nf(n),i=r==="docs_unowned"?"docs":"files",o=JS(n,r,t),a=o?.id??"<id>";return{path:n,classification:r,owner_candidate:o,remediation_hint:`pm ${i} ${a} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function af(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function VS(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Be(e[n]);return i?r.some(o=>i.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function KS(e,t,n,r,i){let o=Be(t.parent),a=o?n.get(r.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:a?.id,grandparent_active:a!==void 0&&!Vn(a.status,i)}}function YS(e,t,n,r){let i=Be(e.blocked_by),o=Be(e.blocked_reason),a=o?.toLowerCase(),s=xi(e.status,n),c=[];return t.has(s)?(!i&&!o&&c.push("blocked_status_missing_blocker_context"),a?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),a&&r.stale_blocker_reason_patterns.some(d=>a.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function XS(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])),a=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),s={activeItems:e.filter(c=>!Vn(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of s.activeItems){let d=VS(c,r);d.length>0&&s.closureLikeRows.push({id:c.id,fields:d});let l=Be(c.parent),u=l?i.get(o.get(l.toLowerCase())??l):void 0;if(u&&Vn(u.status,n)&&(s.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),s.terminalParentFixRows.push(KS(c,u,i,o,n))),t){let m=YS(c,a,n,r);m.length>0&&s.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,p)=>f.localeCompare(p))})}}return s}function ZS(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 vi(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Wa(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function QS(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 a=vi("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),s=vi("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=vi("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=vi("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=Wa("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=Wa("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=Wa("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...o,...a?[a]:[],...s?[s]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function sf(e){let t=It(e);return t.length>SS||t.split(/[\\/]/).some(n=>n.length>ES)}async function eE(e,t){let n=_e.isAbsolute(t)?t:_e.resolve(e,t);if(sf(n))return!1;try{let r=await Ja.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return OS(r,["ENOENT","ENOTDIR"])}}async function tE(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:a}of r){if(o.scope!=="project")continue;if(Hn(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let s=It(o.path);s.length!==0&&(n.linkedProjectPaths.add(s),await eE(t,o.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:i.id,path:s,link_kind:a})))}return n}function nE(e,t,n,r,i,o){let a=r==="tracked-all-strict",s=a&&!i,c=i||a,d=c?[]:DS(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>Op(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Op(f,d)),m={};if(l.length>0){let f=ft(l,o);m.pm_internals={count:l.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:a,strictModeForcesPmInternals:s,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function cf(e,t,n,r,i,o,a,s="pm"){let c=XS(e,t,i,o);ZS(c);let d=tf(c.activeItems,s),l=za(e,i),u=QS(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),m=a?Number.POSITIVE_INFINITY:ht,f=te(c.closureLikeRows.map(k=>`${k.id}:${k.fields.join(",")}`),m),p=te(c.terminalParentRows.map(k=>`${k.id}:${k.parent_id}:${k.parent_status}`),m),h=te(c.staleBlockerRows.map(k=>`${k.id}:${k.status}:${k.reasons.join(",")}`),m),g=te(d.cycle_item_ids,m),w=te(d.cycle_sample_paths,m),v=te(l.cycle_item_ids,m),x=te(l.cycle_sample_paths,m),S=te(l.cardinality_violation_rows,m),b=te(l.parent_divergence_rows,m),R=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:R?"error":u.length===0?"ok":"warn",ok:!R&&u.length===0,details:{checked_active_items:c.activeItems.length,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:p.values,active_terminal_parent_rows_truncated:p.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:h.values,stale_blocker_rows_truncated:h.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:g.values,dependency_cycle_item_ids_truncated:g.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:v.values,parent_cycle_item_ids_truncated:v.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:b.values,hierarchy_parent_divergence_rows_truncated:b.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:u,terminalParentFixRows:c.terminalParentFixRows}}async function df(e,t,n,r,i,o){let a=await tE(e,t),s=new Map(e.map(O=>[O.id,O])),c=[...new Set(a.missingLinkedPaths)].sort((O,W)=>O.localeCompare(W)),d=await PS(t,r),l=nE(d,n,t,r,i,o),u=l.candidateFiles.filter(O=>!a.linkedProjectPaths.has(O)),m=of(u,e),f=ap(c,l.candidateFiles),p=new Map(f.map(O=>[O.path,O.classification])),h=f.filter(O=>O.classification==="moved").length,g=a.staleLinkRows.map(O=>({...O,classification:p.get(O.path)??"deleted"})).sort((O,W)=>O.item_id.localeCompare(W.item_id)||O.path.localeCompare(W.path)||O.link_kind.localeCompare(W.link_kind)),w=[];l.strictModeForcesPmInternals&&w.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&w.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&w.push(`validate_files_orphaned_paths:${u.length}`);let v=[...a.remoteLinkedPaths].sort((O,W)=>O.localeCompare(W)),x=ft(v,o),S=ft(c,o),b=ft(u,o),R=ft(m.map(O=>`${O.path}:${O.classification}:owner_candidate=${O.owner_candidate?.id??"unowned"}`),o),k=o?m:ft(af(m),!1).values,I=ft(sp(f),o),A=g.map(O=>({item_id:O.item_id,path:O.path,link_kind:O.link_kind,classification:O.classification})),j=dp(A,O=>{let W=s.get(O);return W?{type:W.type,title:W.title,status:W.status}:void 0}),q=o?j:ft(lp(j),!1).values;return{check:{name:"files",status:w.length===0?"ok":"warn",ok:w.length===0,details:{workspace_root:t,scan_mode_requested:d.requestedMode,scan_mode_applied:d.appliedMode,strict_tracked_all_mode:l.strictTrackedAllMode,strict_mode_forces_pm_internals:l.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:l.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:o?"full":"summary",file_list_summary_limit:Pp,candidate_scan_source:d.source,include_pm_internals:l.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:l.pmInternalCandidatePrefixes,pm_internal_excluded_count:l.excludedPmInternalPaths.length,excluded_total:l.excludedPmInternalPaths.length,excluded_by_reason:l.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:x.total,remote_linked_paths:x.values,remote_linked_paths_truncated:x.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:S.total,missing_linked_paths:S.values,missing_linked_paths_truncated:S.truncated,missing_linked_paths_moved_count:h,missing_linked_paths_deleted_count:c.length-h,missing_linked_path_classifications:I.values,missing_linked_path_classifications_truncated:I.truncated,missing_linked_path_rows_count:j.length,missing_linked_path_rows:q,orphaned_paths_count:u.length,orphaned_paths_total:b.total,orphaned_paths:b.values,orphaned_paths_truncated:b.truncated,orphaned_path_classifications:R.values,orphaned_path_classifications_truncated:R.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:k}},warnings:w,staleLinkPruneRows:g}}function lf(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function rE(e,t,n){return`${e}:${t}:${lf(n)}`}function iE(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},o)=>{let a=t[o];if(a.trusted)return;let s=lf(i.command??"");n.push(`${r.id}:${a.source_ref??"unknown"}->${a.current_source_ref??"unknown"}:${s}`)}),n}async function uf(e,t,n,r){let i=new Set(e.map(b=>b.id.toLowerCase())),o=0,a=0,s=new Set,c=[],d=e.flatMap(b=>(b.tests??[]).map(R=>({item:b,linkedTest:R}))),l=await Fa(ja()),u=await Ap(r,d.map(({linkedTest:b})=>b),l),m=iE(d,u);for(let{item:b,linkedTest:R}of d){if(typeof R.command!="string"||R.command.trim().length===0)continue;o+=1;let k=vp(R.command,t);if(k.length!==0){a+=k.length;for(let I of k)s.add(I),i.has(I.toLowerCase())||c.push(rE(b.id,I,R.command))}}let f=[...new Set(c)].sort((b,R)=>b.localeCompare(R)),p=[...new Set(f.map(b=>b.split(":")[1]??""))].filter(b=>b.length>0).sort((b,R)=>b.localeCompare(R)),h=[];f.length>0&&h.push(`validate_command_references_stale_pm_ids:${f.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let g=n?Number.POSITIVE_INFINITY:ht,w=te(f,g),v=te(p,g),x=te([...s].sort((b,R)=>b.localeCompare(R)),g),S=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:a,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:x.values,unique_referenced_pm_ids_truncated:x.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:S.values,untrusted_linked_tests_truncated:S.truncated,stale_pm_id_references_count:f.length,stale_pm_ids_count:p.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:h}}function oE(e,t){let n=gr(e.map(c=>({ref:c.id,version:hr(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:ht,o=te(n.outdated,i),a=te(n.ahead,i),s=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:s,ok:s==="ok",details:{checked_items:e.length,current_format_version:tc,outdated_items_count:n.outdated.length,outdated_items:o.values,outdated_items_truncated:o.truncated,ahead_items_count:n.ahead.length,ahead_items:a.values,ahead_items_truncated:a.truncated}},warnings:r}}var Ga="pm validate auto-fix";async function mf(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Ga};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 y("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",_.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 qa(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function pf(e,t,n){let r=[],i=[],o=new Map;for(let a of e.filter(s=>qa(s)===null))try{await mf(a,t,n),r.push(a)}catch(s){i.push({fix:a,error:s})}for(let a of e.filter(s=>qa(s)!==null)){let s=qa(a),c=o.get(s);c?c.push(a):o.set(s,[a])}for(let a of o.values()){let s=a[0];if(!s)continue;let c=a.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{s.kind==="prune_file_link"?await hp(s.item_id,{remove:c,message:Ga},t):await pp(s.item_id,{remove:c,message:Ga},t),r.push(...a)}catch(d){i.push(...a.map(l=>({fix:l,error:d})))}}return{applied:r,failed:i}}var SM={applyValidateFix:mf,applyValidateFixes:pf,attachValidateFixHints:qp,buildCommandReferencesCheck:uf,buildDependencyReferencesCheck:Zp,buildCloseReasonBackfillRows:Vp,buildFilesCheck:df,buildLifecycleCheck:cf,buildLifecycleDependencyGraph:Xp,buildLifecycleParentGraph:Ua,buildEstimateBackfillRows:Kp,buildMetadataCounts:Gp,buildMissingFieldOccurrences:Jp,buildOrphanedPathRows:of,classifyOrphanedPath:nf,collectDefaultProjectFileCandidates:Ha,collectTrackedGitFileCandidates:Wp,detectLifecycleDependencyCycles:tf,detectLifecycleParentCycles:za,escapeRegExp:Yp,extractItemIds:Qp,findLifecycleDependencyCycleComponents:ef,isMetadataFieldMissing:jp,linkedArtifactPathExceedsFilesystemLimits:sf,listFilesRecursive:Ka,resolveDependencyCycleSeverity:Lp,resolveParentCycleSeverity:Fp,resolveFileScanMode:Up,resolveLifecycleDependencyCycleSamplePath:yi,resolveRequestedChecks:Bp,resolveValidateMetadataProfile:Mp,resolveWorkspaceRoot:zp,sharedDirectoryPrefixLength:rf,summarizeOrphanedPathRows:af,summarizeDuplicateIssueCodes:Hp,toMeaningfulString:Be};function aE(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function sE(e,t,n,r){let i=await Wm(e,new Set(t.map(g=>g.id)),n,{schema:r.schema,extensionFieldNames:Ct(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 a=o.length,s=await si(e);s.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${s.tracked_path_count}`);let c=await ll(e,Br(r));c.status==="drift"&&o.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await kt(e),l=d===null?null:await Hr(d);l!==null&&l.status!=="ok"&&o.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await Wn(d??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:f,lossless:p}=li(m);f.length>0&&o.push(`validate_merge_decisions_unreviewed:${f.length}`),aE(o,u.invalid_evidence_count);let h=a>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:f.length,pending_merge_decision_items:[...new Set(f.map(g=>g.item_id))].sort((g,w)=>g.localeCompare(w)),lossless_merge_receipt_count:p.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,lossless_merge_receipt_items:[...new Set(p.map(g=>g.item_id))].sort((g,w)=>g.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:s.tracker_relative_root,tracked_paths:s.tracked_paths,tracked_path_count:s.tracked_path_count,remediation_command:s.remediation_command}}},warnings:o}}function nt(e,t,n){n&&qp(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function cE(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=qS(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,nt(t,i,n)}if(e.requestedChecks.has("resolution")){let i=BS(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,nt(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=cf(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,nt(t,i,n),nt(t,Zp(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await df(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=i.staleLinkPruneRows,nt(t,i,n)}return e.requestedChecks.has("command_references")&&nt(t,await uf(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&nt(t,await Ip(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&nt(t,oE(e.items,r),n),e.requestedChecks.has("storage_integrity")&&nt(t,await sE(e.pmRoot,e.items,B(e.settings,z()).type_to_folder,e.settings),n),t}function dE(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...Km(t.closeReasonBackfillRows)),r.push(...Vm(t.resolutionBackfillRows)),r.push(...Ym(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Xm(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Zm(t.staleLinkPruneRows)),r}async function lE(e,t,n,r,i,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let a=dE(e,t,n),{applicable:s,gated:c}=ep(a,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await pf(s,i,o);l.push(...m.applied.map(Bn)),u.push(...m.failed.map(({fix:f,error:p})=>({...Bn(f),error:p instanceof Error?p.message:String(p)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,f)=>m.localeCompare(f)),planned_count:a.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:a.map(Bn),applied_fixes:l,gated_fixes:c.map(m=>({...Bn(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function ff(e,t,n={}){Ys(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new y("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",_.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new y("--fix-scope requires --auto-fix.",_.USAGE);let i=Qm(e.fixScope),o=L(process.cwd(),t.path);await Q(o);let a=await C(o),s=$e(a.schema),c=B(a,z()),d=Bp(e),l=[],u=await Rp({includeBody:d.has("history_drift")||d.has("metadata"),pmRoot:o,settings:a,typeToFolder:c.type_to_folder,warnings:l});if(d.has("history_drift")){let A=await An(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",f=Mp(typeof e.metadataProfile=="string"?e.metadataProfile:a.validation.metadata_profile),p=TS(f,m,a.validation.metadata_required_fields),h=IS(a),g=Lp(e.dependencyCycleSeverity),w=Fp(e.parentCycleSeverity),v=Up(e.scanMode),x=zp(o),S=await cE({requestedChecks:d,options:e,global:t,pmRoot:o,workspaceRoot:x,settings:a,items:u,statusRegistry:s,metadataPolicy:p,lifecyclePatternPolicy:h,dependencyCycleSeverity:g,parentCycleSeverity:w,fileScanMode:v,initialWarnings:[...new Set(l)]}),b=r?await lE(e,S,a,i,t,n):void 0,R=[...new Set(S.warnings)].sort((A,j)=>A.localeCompare(j)),I={ok:!S.checks.some(A=>A.status==="error"),has_warnings:R.length>0,checks:S.checks,warnings:R,...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?I:{...RS(I),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as uE}from"node:child_process";import{promisify as mE}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 pE=mE(uE),fE=16,hE=3e4;function gE(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 _E(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(([,a])=>a.required===!0).map(([a])=>a))if(!Object.hasOwn(r,o))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${o}`);for(let[o,a]of Object.entries(r)){let s=i[o];if(!s)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${o}`);if(a===null||typeof a!==s.type)throw new TypeError(`assurance provider ${e.id} parameter ${o} must be ${s.type}`)}return{...r}}async function yE(e,t,n,r){let i=_E(e,t),o=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Zs(n)}));o.catch(()=>{});let a;try{let s=await Promise.race([o,new Promise((c,d)=>{a=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??hE),a.unref?.()})]);return gE(e,t.key,s)}finally{clearTimeout(a)}}function gf(e,t,n,r){let i=e;for(let o of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new Fe(`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 Fe(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function hf(e,t,n,r){let i=e.checks.find(a=>a.name===t);if(!i)throw new Fe(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:gf(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function wE(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await pE("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function vE(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(fE,t.length)},async()=>{for(;r<t.length;){let o=r;r+=1;let a=t[o],s=await Lt(ir(e,a.id),a.id);n[o]=s.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 Kn(e,t={}){let n=await C(e),r=B(n),i=$e(n.schema),a=(await Ut(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(f=>({...f,id:f.id,status:f.status,type:f.type})),s={path:e},c=z(),d=Object.fromEntries((c?.assurance_providers??[]).map(f=>[f.definition.id,{cost_class:f.runtime_definition.cost_class,network:f.runtime_definition.network}])),l=new Map,u,m;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await wE(e,t.tree_id),items:a,history:t.include_history===!1?[]:await vE(e,a),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async f=>{if(f.kind==="graph"){let g=X({operation:f.operation,parameters:f.parameters??{}}),w=l.get(g);w===void 0&&(w=Gc(f.operation,void 0,void 0,{...f.parameters,full:!0},s),l.set(g,w));let v=await w;return{value:gf(v,f.field,f.kind),population_size:a.length,cost:a.length}}if(f.kind==="validate"){u??=ff({counts:!0},s);let g=await u;return hf(g,f.check,f.field,f.kind)}if(f.kind==="health"){m??=Um(s,{checkOnly:!0,full:!0});let g=await m;return hf(g,f.check,f.field,f.kind)}let p=t.providers?.[f.provider];if(p)return p(f);let h=bc(c,f.provider);if(!h)throw new TypeError(`assurance provider ${f.provider} is not registered`);return yE(h.runtime_definition,f,e,t.trigger??"sdk")}}}import{createHash as bE}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 Si(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 Ai=["production_defect","nightly_regression","scanner_finding","review_caught_late"],Xa=["gate_added","gate_strengthened","explicit_waiver"],_f=256,kE=1024,Yn=new Map,xE=["files","package_names","item_ids","tags","error_codes"];function ye(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t<n?-1:1)}function yf(e){return bE("sha256").update(X(e)).digest("hex")}function Ya(e,t){if(typeof e!="string"||!e.trim())throw new TypeError(`${t} must be a non-empty string`)}function Xn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ln(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function vf(e,t){if(!Xn(e))throw new TypeError(`${t} must be an object`);for(let n of xE)if(e[n]!==void 0&&!ln(e[n]))throw new TypeError(`${t}.${n} must be an array of strings`);return e}function SE(e,t){if(!Xn(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&&!ln(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&&!ln(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>_f)throw new TypeError(`defect recurrence family ${t} file pattern exceeds ${_f} characters`)}function EE(e,t){if(Ya(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(!Ai.includes(e.escape_class))throw new TypeError(`defect recurrence family ${e.id} has an invalid escape class`);Ya(e.title,`defect recurrence family ${e.id} title`),Ya(e.owner_item_id,`defect recurrence family ${e.id} owner_item_id`)}function AE(e){if(!ln(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(SE(e.triggers,e.id),!Xn(e.checks)||!ln(e.checks.local)||!ln(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 RE(e){if(!Xn(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 IE(e){let t=vf(e.negative_control,`defect recurrence family ${e.id} negative_control`);if(Qa(e,t,{}).length===0)throw new TypeError(`defect recurrence family ${e.id} negative_control must select its own family`)}function Za(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(!Xn(n))throw new TypeError("defect recurrence family must be an object");EE(n,t),AE(n),RE(n),IE(n)}}function CE(e,t){let n=Yn.get(e);if(n===void 0){if(Yn.size>=kE){let i=Yn.keys().next().value;Yn.delete(i)}let r=e.replaceAll("**","\0").replaceAll(/[|\\{}()[\]^$+?./]/gu,"\\$&").replaceAll("*","[^/]*").replaceAll("\0",".*");n=new RegExp(`^${r}$`,"u"),Yn.set(e,n)}return n.test(t)}function TE(e,t){let n=[],r=ye(e.triggers.file_patterns??[]);for(let i of ye(t.files??[]))for(let o of r)CE(o,i)&&n.push({signal:"file",value:i,matched:o});return n}function $E(e,t){let n=[{signal:"package",values:ye(t.package_names??[]),triggers:ye(e.triggers.package_names??[])},{signal:"tag",values:ye(t.tags??[]),triggers:ye(e.triggers.tags??[])},{signal:"error_code",values:ye(t.error_codes??[]),triggers:ye(e.triggers.error_codes??[])}],r=[];for(let i of n){let o=new Set(i.triggers);for(let a of i.values)o.has(a)&&r.push({signal:i.signal,value:a,matched:a})}return r}function OE(e,t,n){let r=new Set(e.triggers.item_ids??[]);return ye(t.item_ids??[]).flatMap(i=>r.has(i)||n[i]?.includes(e.id)?[{signal:"item",value:i,matched:e.id}]:[])}function Qa(e,t,n){return[...TE(e,t),...$E(e,t),...OE(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 DE(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 PE(e){return[e.files,e.package_names,e.item_ids,e.tags,e.error_codes].reduce((t,n)=>t+(n?.length??0),0)}function bf(e,t,n={}){Za(e);let r=[...e.families].sort((l,u)=>l.id<u.id?-1:1),i=yf({...e,families:r}),o=new Set(n.changed_item_ids??[]),a=n.previous_index?.policy_fingerprint===i,s=a?Object.fromEntries(Object.entries(n.previous_index?.item_families??{}).filter(([l])=>!o.has(l))):{},c=a?Object.keys(s).length:0;for(let l of t){let u=Si(l),m=r.filter(f=>f.historical_item_ids.includes(l.id)||Qa(f,u,{}).length>0).map(f=>f.id);m.length>0?s[l.id]=m:delete s[l.id]}let d=Object.fromEntries(Object.entries(s).sort(([l],[u])=>l<u?-1:1).map(([l,u])=>[l,ye(u)]));return{version:1,policy_fingerprint:i,index_fingerprint:yf({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 kf(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=DE(n.cursor,e.index_fingerprint),o=e.families.flatMap(l=>{let u=Qa(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:ye(l.checks.local),hosted_checks:ye(l.checks.hosted),budget:l.budget}]}),a=o.slice(i,i+r),s=i+a.length,c=s<o.length?Buffer.from(JSON.stringify({index_fingerprint:e.index_fingerprint,offset:s})).toString("base64url"):void 0,d={risk_detected:o.length>0,index_fingerprint:e.index_fingerprint,items:a,total:o.length,...c?{next_cursor:c}:{},required_local_checks:ye(o.flatMap(l=>l.local_checks)),required_hosted_checks:ye(o.flatMap(l=>l.hosted_checks)),row_contract:{row_keys:["items"],jq_selector:".items[]"}};return{...d,cost:{families_evaluated:e.families.length,signals_evaluated:PE(t),families_selected:o.length,estimated_output_tokens:Math.ceil(JSON.stringify(d).length/4)}}}function NE(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 Ei(e){return typeof e=="string"&&e.trim().length>0}function wf(e){return Array.isArray(e)&&e.length>0&&e.every(Ei)}function ME(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,expired:!1};let n=e;if(!Xa.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:Ei(n.waiver_reason)&&Number.isFinite(r)&&r>=t,expired:Number.isFinite(r)&&r<t}}return{valid:Ei(n.gate_id)&&Ei(n.negative_control)&&wf(n.local_checks)&&wf(n.hosted_checks),expired:!1}}function LE(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.`}):Ai.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=ME(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 zM(e,t,n,r=new Date){Za(t);let i=Date.parse(t.evidence_epoch),o=new Set(n),a=e.filter(m=>o.has(m.status)&&NE(m)),s=a.filter(m=>{let f=Date.parse(typeof m.completed_at=="string"?m.completed_at:"");if(Number.isFinite(f))return f>=i;let p=Date.parse(typeof m.closed_at=="string"?m.closed_at:"");if(Number.isFinite(p))return p>=i;let h=Date.parse(typeof m.created_at=="string"?m.created_at:"");return!Number.isFinite(h)||h>=i}),c=Object.fromEntries(Ai.map(m=>[m,0])),d=Object.fromEntries(Xa.map(m=>[m,0])),l=a.filter(m=>typeof m.escape_class=="string"&&Ai.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 f=m.gate_evidence.disposition;typeof f=="string"&&Xa.includes(f)&&(d[f]+=1)}let u=s.flatMap(m=>LE(m,r.getTime()));return u.sort((m,f)=>m.item_id!==f.item_id?m.item_id.localeCompare(f.item_id):m.kind.localeCompare(f.kind)),{ok:u.length===0,governed_item_count:s.length,classified_item_count:l.length,class_counts:c,evidence_disposition_counts:d,findings:u}}function FE(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 Za(t),t}function xf(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=vf(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:FE(t.policy),change:n,...t.cursor===void 0?{}:{cursor:t.cursor},...t.limit===void 0?{}:{limit:t.limit}}}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]="f66a964d-1352-5523-ab91-5177d0d93ce8")}catch{}})();var es,Sf=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk"],ts=["measurement","assertion","gate"];function UE(e){if(Sf.includes(e))return e;throw Sr({command_path:"assurance",token:e,allowed:Sf,display_name:"assurance action"})}function un(e,t,n){throw new y(t,_.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function zE(e){if(!e)return un("kind",`Assurance declaration kind is required. Expected: ${ts.join(", ")}`,"pm assurance list measurement");if(ts.includes(e))return e;throw new y(`Assurance declaration kind is required. Expected: ${ts.join(", ")}`,_.USAGE)}function Ef(e){if(!e)return un("preset",`Assurance preset is required. Expected: ${xn.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(xn.includes(e))return e;throw new y(`Assurance preset is required. Expected: ${xn.join(", ")}`,_.USAGE)}function ns(e){return e.owner?.trim()?e.owner.trim():un("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function WE(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 y("assurance definition must be valid JSON",_.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new y("assurance put requires a JSON object definition",_.USAGE);return n}async function qE(e){let[t,n,r]=await Promise.all([kn(e,"measurement"),kn(e,"assertion"),kn(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Af(e,t){return t===!0?{id:e.id}:e}async function BE(e,t){let n=t.authorization_decision;if(!n)return[];let r=await Kn(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(a=>a.id===n),o=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!o.has(i.status))throw new y(`Assurance authorization ${n} must name a terminal Decision item`,_.USAGE);return[i.id]}async function HE(e,t){let n=ho(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>Ht))throw new y(`assurance verdict limit must be an integer from 1 through ${Ht}`,_.USAGE);let r=await dd(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 GE(e,t,n){if(e==="presets"){if(t.preset??t.id)return Lr(Ef(t.preset??t.id),ns(t));let i=xn.map(o=>{let a=Lr(o,"pm-owner");return{id:o,title:a.title,description:a.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return Bt(()=>ud(n,Ef(t.preset??t.id),ns(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await md(await Kn(n,{resolve_tree:!1,trigger:"derive"}),ns(t)),o=t.apply?await Bt(()=>pd(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 un("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new y("assurance promote requires --enforcement warn|block",_.USAGE);let r=await co(n,"assertion",t.id);return Bt(()=>fd(n,r,t.enforcement,{author:t.author,message:t.message}))}async function JE(e,t,n){if(!e.id)return un("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 y("assurance run requires a trigger",_.USAGE);if(!bt.includes(e.trigger))throw new y(`Unknown assurance trigger ${e.trigger}. Expected: ${bt.join(", ")}`,_.USAGE);let i=e.trigger,[o,a]=await Promise.all([qE(t),Kn(t,{...n.workspace,tree_id:e.tree,trigger:i})]),s=await Jc(()=>od(r,o,a,{trigger:i,dry_run:e.dry_run===!0}));return s.dry_run||await cd(t,s,{author:e.author,message:e.message}),s}function Rf(e){throw e instanceof y?e:new y(e instanceof Error?e.message:"assurance risk request is invalid",_.USAGE)}function VE(e){if(e.limit!==void 0)throw new y("assurance risk does not accept --limit; set limit inside the risk definition",_.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new y("assurance risk definition must be valid JSON",_.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return xf(t)}catch(n){return Rf(n)}}function KE(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 YE(e,t,n){let r=X(t.policy),i=es?.pm_root===e?es:void 0,o=new Map(n.map(d=>[d.id,jE("sha256").update(X(Si(d))).digest("hex")])),a=i?.policy_serialized===r?i:void 0,s=a?KE(a,o):new Set,c=bf(t.policy,a?n.filter(d=>s.has(d.id)):n,a?{previous_index:a.index,changed_item_ids:[...s]}:{});return es={pm_root:e,policy_serialized:r,item_fingerprints:o,index:c},c}async function XE(e,t){let n=VE(e),r=await Kn(t,{include_history:!1,resolve_tree:!1});try{return kf(YE(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit})}catch(i){return Rf(i)}}async function ZE(e,t={},n={}){let r=UE(e.action),i=L(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return GE(r,e,i);if(r==="verdicts")return HE(e,i);if(r==="run")return JE(e,i,n);if(r==="risk")return XE(e,i);let o=zE(e.kind);if(r==="list")return kn(i,o);if(!e.id)return un("id",`assurance ${r} requires an id`,`pm assurance ${r} ${o} <id>`);let a=e.id;if(r==="show")return co(i,o,a);if(r==="remove"){let l=await Bt(()=>sd(i,o,a,{author:e.author,message:e.message}));return Af(l,e.idOnly)}let s=WE(o,e.definition);if(s.id!==a)throw new y(`Assurance definition id ${s.id} does not match requested id ${a}`,_.USAGE);let c={author:e.author,message:e.message,...o==="assertion"?{authorized_decision_ids:await BE(i,s)}:{}},d=await Bt(()=>Nr(i,o,s,c));return Af(d,e.idOnly)}function rL(e,t,n){let r={...e,...t};return ZE({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:ho(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 QE}from"node:child_process";import eA from"node:path";import{promisify as tA}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 nA=tA(QE),rA="@unbrained/pm-cli",iA="latest",oA={global:["--global"],project:[]};function If(e){let t=e.project===!0||e.local===!0||e.scope==="project",n=e.global===!0||e.scope==="global";if(t&&n)throw new y('Options "--project/--local" and "--global" are mutually exclusive.',_.USAGE);return n?"global":"project"}function Ii(e){return e.trim().toLowerCase()}function Cf(e,t){let n=Ii(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"&&Ii(i)===n)}function aA(e,t){let n=L(process.cwd(),t.path),r=Tt(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function sA(e,t,n){try{let r=await nA(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 y(`Command failed: ${e} ${t.join(" ")}
45
- ${o}`,_.GENERIC_FAILURE)}}async function cA(){return _s(import.meta.url,["../../.."])}function Ci(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():iA}function Ri(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():rA}async function dA(e,t){let n=e.commandRunner??sA,r=Ri(e),i=Ci(e),o=`${r}@${i}`,a=["npm","install","-g",o];e.repair===!0&&a.push("--force");let s=await cA(),c={requested:!0,status:"planned",package:r,target:o,command:a,before_version:s,repair:e.repair===!0};if(t)return c;try{await n(a[0],a.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 lA(e){return eA.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function uA(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!lA(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 mA(e,t){let n=uA(e,t);return e.kind!=="local"||await D(n)?n:await D(e.location)?e.location:n}function pA(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 Tf(e,t){let n=aA(e,t);return(await he(n.selected_root)).state.entries.filter(i=>i.scope===e)}async function fA(e,t,n){let r=await Tf(e,t);return r.find(i=>Cf(i,n.name))??r.find(i=>Ii(i.directory)===Ii(n.directory))}async function hA(e,t,n,r,i){let o=Ci(t),a=await mA(e.source,o),s=pA(e.source,a,r,e.source.ref),c={name:e.name,directory:e.directory,scope:r,source:e.source,status:"planned",command:s,previous_version:e.manifest_version};if(i)return c;try{await aa(a,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await fA(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 gA(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 uL(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",...oA[If(t)]];throw new y('Options "--cli-only" and "--packages-only" are mutually exclusive.',_.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:pr(m),suggested_retry_args:m}})}let i=If(t),o=t.dryRun===!0;if(t.cliOnly===!0&&r)throw new y('A package target cannot be used with "--cli-only".',_.USAGE);let a=!(t.packagesOnly===!0||r),s=t.cliOnly!==!0,c=a?await dA(t,o):{requested:!1,status:"skipped",package:Ri(t),target:`${Ri(t)}@${Ci(t)}`,command:["npm","install","-g",`${Ri(t)}@${Ci(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await Tf(i,n):[];if(r&&(d=d.filter(m=>Cf(m,r)),d.length===0))throw new y(`Managed package "${r}" was not found in ${i} scope.`,_.NOT_FOUND);let l=[];for(let m of d)l.push(await hA(m,t,n,i,o));let u=gA(c,l,a,s);return{ok:u.failed===0,action:"upgrade",dry_run:o,scope:i,target:r,cli:c,packages:l,summary:u}}import mn from"node:fs/promises";import $i from"node:path";import Ti from"node:fs/promises";import rs 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 _A=864e5;function yA(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 wA(e,t){let n;try{n=await Ti.readdir(e,{withFileTypes:!0})}catch(i){if(U(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let o=rs.join(e,i.name),a;try{a=await Ti.readdir(o)}catch(s){U(s)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let s of a)s.endsWith(".json")&&r.push(`${i.name}/${s}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function $f(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*_A,a=rs.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await wA(a,s.warnings);for(let d of c){let l=rs.join(a,d),u=`checkpoints/${d}`;s.scanned+=1,r?.onRead&&s.warnings.push(...await r.onRead(l));let m;try{m=await Ti.readFile(l,"utf8")}catch(w){if(U(w)){s.scanned-=1;continue}s.warnings.push(`checkpoint_unreadable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=yA(m),p=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(p)){s.warnings.push(`checkpoint_unparseable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=i-p,g={file:u,created_at:f,age_seconds:Math.floor(h/1e3),stale:h>o,reason:h>o?"expired":"active"};if(!g.stale){s.retained.push(u),s.entries.push(g);continue}if(!n){try{await Ti.unlink(l)}catch(w){if(!U(w)){s.warnings.push(`checkpoint_remove_failed:${d}`),s.retained.push(u),s.entries.push(g);continue}}r?.onWrite&&s.warnings.push(...await r.onWrite(l))}s.removed.push(u),s.entries.push(g)}return s}import is from"node:fs/promises";import Of 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 vA=1440*60*1e3,bA=new Set(["committed","compensated"]);function kA(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 xA(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 a=r-o;return bA.has(t)?a>i?{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"active"},remove:!1}}async function SA(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],o=kA(await is.readFile(e,"utf8")),a=xA(t,o.status,o.updatedAt,r.nowMs,r.retentionMs);return a.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),a.remove&&!r.dryRun&&(await is.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:a,warnings:i}}async function Df(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*vA,a=Of.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await is.readdir(a)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(U(d))return s;throw d}for(let d of c){let l=Of.join(a,d),u=`transactions/sdk/${d}`,m=await SA(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:o});s.warnings.push(...m.warnings),s.scanned+=1;let{decision:f}=m;if(!f.remove){s.retained.push(u),s.entries.push(f.entry);continue}s.removed.push(u),s.entries.push(f.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]="76f8405f-138d-5119-a300-f068354394a5")}catch{}})();var Zn=["index","embeddings","runtime","locks","checkpoints","transactions"],EA=1440*60*1e3,AA=[{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 RA(e,t,n){let r=t.relativePath,i=$i.join(e,r),o=await Ge({path:i,scope:"project"});try{let a=await mn.stat(i);if(t.kind==="file"&&!a.isFile())return{removed:!1,warnings:[...o,`not_a_file:${r}`]};if(t.kind==="directory"&&!a.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await mn.unlink(i):await mn.rm(i,{recursive:!0,force:!0});let s=await ne({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...s]}}catch(a){if(U(a))return{removed:!1,warnings:o};throw a}}async function IA(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],o=[],a=Date.now()-EA;for(let s of n){let c=$i.join(e,s.relativePath);if(!await D(c))continue;let d=(await mn.readdir(c)).filter(l=>l.startsWith(s.prefix)).sort();for(let l of d){let u=$i.posix.join(s.relativePath,l),m=$i.join(c,l);o.push(...await Ge({path:m,scope:"project"}));let f=await mn.stat(m).catch(p=>{if(!U(p))throw p});if(f){if(f.mtimeMs>a){i.push(u);continue}r.push(u),!t&&(await mn.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 CA(e){if(!e||e.length===0)return[...Zn];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new y(`--scope requires at least one value (${Zn.join(",")})`,_.USAGE);let n=new Set;for(let r of t){if(!Zn.includes(r))throw new y(`Invalid --scope value "${r}". Expected one or more of: ${Zn.join(", ")}`,_.USAGE);n.add(r)}return Zn.filter(r=>n.has(r))}function TA(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 PL(e,t={}){let n=L(process.cwd(),e.path);await Q(n);let r=await C(n),i=t.dryRun===!0,o=CA(t.scope),a=AA.filter(p=>o.includes(p.scope)),s=[],c=[],d=[];for(let p of a){let h=await RA(n,p,i);h.removed?s.push(p.relativePath):c.push(p.relativePath),d.push(...h.warnings)}if(o.includes("runtime")){let p=await IA(n,i);s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(o.includes("locks")){let p=await Vd(n,{dryRun:i,hooks:{onRead:h=>Ge({path:h,scope:"project"}),onWrite:h=>ne({path:h,scope:"project",op:"gc:lock_remove"})}});s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),l={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(o.includes("transactions")){let p=r.checkpoints.retention_days,h=await Df(n,{dryRun:i,retentionDays:p,hooks:{onRead:g=>Ge({path:g,scope:"project"}),onWrite:g=>ne({path:g,scope:"project",op:"gc:transaction_journal_remove"})}});s.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:p}}let m;if(o.includes("checkpoints")){let p=r.checkpoints.retention_days,h=await $f(n,{dryRun:i,retentionDays:p,hooks:{onRead:g=>Ge({path:g,scope:"project"}),onWrite:g=>ne({path:g,scope:"project",op:"gc:checkpoint_remove"})}});s.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:p}}d.push(...await fr({mode:i?"gc:dry-run":"gc",total_items:a.length}));let f=TA({dryRun:i,scopes:o,removed:s});return{ok:d.length===0,dry_run:i,scope:o,removed:s,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:f,generated_at:T()}}import $A 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]="1bcd20e1-2995-56ef-8d04-f265b8282c19")}catch{}})();var os="index/manifest.json",as="search/embeddings.jsonl",OA="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function DA(e){return e.progress===!0||process.stderr.isTTY===!0}function ae(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
46
- `)}catch{}}function PA(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new y("Reindex mode must be one of keyword|semantic|hybrid",_.USAGE)}async function NA(e,t,n,r){let i=[];return{candidates:await _c(e,t,n,i,r),warnings:i}}async function cs(e,t,n,r,i){let o=Ct(z()),a=[];for(let s of t)if(!(i&&!i.has(s.metadata.id))){if(typeof s.body=="string"){a.push({metadata:s.metadata,body:s.body});continue}try{let c=await $A.readFile(s.item_path,"utf8"),d=Mt(c,{format:s.item_format,schema:n,extensionFieldNames:o,onWarning:l=>r.push(l)});a.push({metadata:s.metadata,body:d.body})}catch{r.push(`item_list_item_read_failed:${Qn.relative(e,s.item_path)}`),a.push({metadata:s.metadata,body:""})}}return a}function MA(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:Cc(e,{fields:n})}}var pn=Z;function LA(e){let t=z(),n=pn(e.search?.provider);if(!n)return null;let r=kc(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=pn(i.name)??pn(r.definition.name);if(!o)return null;let a=i.embedBatch,s=i.embed_batch,c=i.embed,d=typeof a=="function"?a:typeof s=="function"?s:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:o,embedBatch:d,embed:l}}function FA(e){let t=z(),n=pn(e.vector_store?.adapter);if(!n)return null;let r=xc(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=pn(i.name)??pn(r.definition.name);if(!o)return null;let a=i.upsert,s=i.delete;return{adapterName:o,...typeof a=="function"?{upsert:a}:{},...typeof s=="function"?{delete:s}:{}}}function ss(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new y(`Invalid vector returned by ${t}`,_.GENERIC_FAILURE);return e}async function jA(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 y(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,_.GENERIC_FAILURE);return o.map((a,s)=>ss(a,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new y(`Extension search provider "${e.name}" does not implement embed/embedBatch`,_.GENERIC_FAILURE);let i=[];for(let[o,a]of n.entries()){let s=await Promise.resolve(e.embed({input:a,settings:t,model:r}));i.push(ss(s,`extension search provider "${e.name}" embed output at index ${o}`))}return i}function Pf(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function Nf(e,t,n){let r=n?vt(n.name,Pf(e)):t?vt(t.name,t.model):null;if(!r)throw new y("No embedding identity available for semantic reindex mode",_.USAGE);return r}function UA(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function Mf(e,t,n,r,i,o,a,s){let c=r?.name??n?.name,d=Tc(c,e.search.embedding_corpus_max_characters).maxCharacters,l=Zi(e),u=i.map(p=>$c(p,{providerName:c,maxCharacters:d,fields:l})),m=[],f=null;if(r)try{m=await jA(r,e,u),f=vt(r.name,Pf(e))}catch(p){if(!n)throw new y(`Extension search provider "${r.name}" failed to generate embeddings: ${p instanceof Error?p.message:String(p)}`,_.GENERIC_FAILURE);o.push(`Extension search provider "${r.name}" failed; falling back to built-in provider (${p instanceof Error?p.message:String(p)})`)}if(m.length===0){if(!n)throw new y(`No embedding executor available for reindex mode '${t}'`,_.USAGE);let p=await Oc(n,e,u,{onProgress:h=>{h.phase==="complete"&&(a.batches_completed=h.batch_index),ae(s,`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(...p.warnings),m=p.vectors,f=vt(n.name,n.model)}if(ae(s,`embedding_complete vectors=${m.length}`),m.length!==i.length)throw new y(`Embedding output size mismatch (expected ${i.length}, received ${m.length})`,_.GENERIC_FAILURE);if(!f)throw new y(`No embedding identity available for reindex mode '${t}'`,_.USAGE);return{vectors:m,embeddingIdentity:f}}async function zA(e,t,n,r,i,o){let a=Object.keys(n);if(t){if(a.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:a.sort((s,c)=>s.localeCompare(c)),settings:r}))}catch(s){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,_.GENERIC_FAILURE)}else a.length>0&&i.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${a.length}`);if(!e)return}e&&await Nc(e,a,{},o)}async function Lf(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 y(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${o instanceof Error?o.message:String(o)}`,_.GENERIC_FAILURE)}else i.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Pc(e,n)}}function WA(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function qA(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 BA(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=yn(e.settings);if(!t.active&&!e.extensionEmbedding)throw new y(`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`,_.USAGE);let n=Rr(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new y(`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`,_.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function HA(e){let t=B(e.settings,z()),n=await NA(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 GA(e){let t=await qt(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 Nf(e.settings,yn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&Wt(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(OA))}async function JA(e){let t=await qt(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=Nf(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(d=>d.metadata.id)),i=UA(t.entries,r),o=Wt(t.embedding,n);e.forceFullSemantic&&!o&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let a=e.forceFullSemantic||o?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),s=new Set(a.map(d=>d.metadata.id)),c=s.size>0?await cs(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:i,resetRequired:o,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function VA(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await cs(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,ae(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await Mf(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:Qi(r.vectors,"Reindex embeddings")}}async function KA(e){let t=await Mf(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=Qi(n,"Reindex embeddings");if(!(!e.resetRequired&&(Wt(e.ledgerEmbedding,r)||Lc(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let a=await VA(e);return n=a.vectors,r=a.embeddingIdentity,i=a.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:a.staleDocuments,vectorDimension:i,resetRequired:!0}}async function YA(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(ae(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new y(`Extension vector adapter "${t}" does not support upserting vectors.`,_.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,ae(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof y)throw t;if(!e.activeVectorStore)throw new y(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,_.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)})`),ae(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){ae(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Dc(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,ae(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new y(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,_.USAGE)}function XA(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:ss(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 ZA(e){ae(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await KA({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?(ae(e.progressEnabled,"vector_reset_start"),await zA(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),ae(e.progressEnabled,"vector_reset_complete")):await Lf(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=XA(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await YA({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:Mc(t.embeddingIdentity,t.vectorDimension)}}async function QA(e){let t=await JA(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(ae(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 ae(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await Lf(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await ZA({...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 eR(e){let t=Qn.join(e.pmRoot,os),n=Qn.join(e.pmRoot,as),r=Zi(e.settings),i=e.documentsForKeywordArtifacts.map(a=>JSON.stringify(MA(a,e.mode,r))).join(`
33
+ `),w=My(e),x=["```ts",`import { ${Ly(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Fy(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...jy(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],S=[`# ${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,su,"- `.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:",...x,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...by[r],...du(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${At}\`. 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 \`${Jo}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${At}\`. 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":f,"manifest.json":c,"index.ts":i?Dy(e,t,r):d,"index.test.ts":i?Py(e,t,r):p,"tsconfig.json":l,".gitignore":g,"README.md":i?Ny(o,t,r):S}}async function uu(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!nu.includes(i))throw new y(`Unknown scaffold capability "${n}". Supported capabilities: ${nu.join(", ")}.`,_.USAGE);let o=i;if(r&&t!=="package")throw new y("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",_.USAGE);let a=r?"declarative":"imperative",s=e.trim(),c=Mn.resolve(process.cwd(),s),d=Vr(Mn.basename(c)).replace(/^(?:pm-)+/u,""),l=Ey(d),u=Uy(d,l,t,o,r),m=!1;if(await D(c)){if(!(await Nn.stat(c)).isDirectory())throw new y(`Scaffold target "${c}" exists and is not a directory.`,_.CONFLICT)}else await Nn.mkdir(c,{recursive:!0}),m=!0;for(let[p,h]of Object.entries(u)){let g=Mn.join(c,p);if(!await D(g))continue;if(await Nn.readFile(g,"utf8")!==h)throw new y(`Scaffold file "${p}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,_.CONFLICT)}let f=[];for(let[p,h]of Object.entries(u)){let g=Mn.join(c,p);if(await D(g)){f.push({path:p,status:"unchanged"});continue}await Nn.mkdir(Mn.dirname(g),{recursive:!0}),await Nn.writeFile(g,h,"utf8"),f.push({path:p,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:o,style:a,target_path:c,created_directory:m,files:f}}(function(){try{var e=typeof window<"u"?window:typeof 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 mu(e,t){return`${e}:${E(t)}`}function zy(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let a of i){let s=o.get(a.command)??[];o.set(a.command,[...s,a])}for(let[a,s]of o){if(t!==null&&!s.some(d=>t.has(E(d.name))))continue;let c=s.at(-1);n.push({command:a,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.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 pu(e,t,n){let r=new Set(n.failed.map(d=>mu(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(mu(d.layer,d.name))?"failed":"ok",surfaces:Yt(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:Yt(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),o=typeof e=="string"?E(e):null,a=o===null?null:new Set(t.loaded.filter(d=>E(d.name)===o||typeof d.source_package=="string"&&E(d.source_package)===o||(d.source_aliases??[]).some(l=>E(l)===o)).map(d=>E(d.name)).concat(o)),s=a===null?i:i.filter(d=>a.has(E(d.name))),c=a===null?{}:{extensionNames:[...a]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Yt(n,c),command_ownership:zy(n,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]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function Ko(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function ti(e,t,n){let r=E(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 Wy(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)ti(t,r.name,r.command),ti(n,r.name,r.action);for(let r of e.commands.handlers)ti(t,r.name,r.command);for(let r of e.commands.overrides)ti(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function fu(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function qy(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 ni(e,t,n){let r=new Set(t.loaded.map(c=>E(c.name))),i=new Set(t.failed.map(c=>E(c.name))),o=new Set(n.failed.map(c=>E(c.name))),{commandPathsByExtension:a,actionPathsByExtension:s}=Wy(n);return e.map(c=>{let d=E(c.name),l=fu(a.get(d)),u=fu(s.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},f=qy({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:i,activationFailedNames:o});return{...c,...f,...m}})}function By(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 de(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var _u=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 Hy(e){return _u.has(xu(e))}function hu(e){return e==="project"||e==="global"}function yu(e){let t=e.split(":"),n=t[0];if(!n||!_u.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),o=t.at(-2),a=t.at(-1)?.trim();return!hu(r)||!hu(o)||!i||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:o,name:a}}}function Gy(e){let t=new Set;for(let n of e){let r=yu(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Yo(e,t){let n=e.filter(Hy);if(n.length===0)return null;let r=Gy(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 Jy(e,t,n,r){let i=t.map(u=>yu(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",a=de(r,"deactivate"),s=`${de(r,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(u=>[E(u.name),u])),d=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let f=E(m);d.set(f,(d.get(f)??0)+1)}let l=[...d.entries()].map(([u,m])=>{let f=c.get(u),p=f?.name??u,h=f?.command_paths??[],g=f?.action_paths??[];return{action:"deactivate",extension:p,command:`${a} ${p} ${o}`,affected_collisions:m,feature_loss:{command_paths:[...h].sort((w,v)=>w.localeCompare(v)),action_paths:[...g].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let f=m.affected_collisions-u.affected_collisions;if(f!==0)return f;let p=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 p!==h?p-h:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:d.size,next_best_command:s,collisions:i,remediation_candidates:l}}function wu(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 vu(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 bu(e,t){let n=[];for(let r of Vs(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 Vy=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${de(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: ${Qn.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 ${de(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 ${de(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 ${de(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 ${de(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 ${de(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${de(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 Ky(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:a,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=[],m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:a};if(t.length>0){let f=Yo(t,{deactivate:`${de(n,"deactivate")} <name> ${i}`,doctor:`${de(n,"doctor")} ${i} --detail deep --trace`});f&&u.push(f);for(let p of Vy)p.matches(t,m)&&u.push(p.build(m))}return s?u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${de(n,"manage")} ${i} --fix-managed-state (or ${de(n,"adopt-all")} ${i}, ${de(n,"adopt")} <name> ${i}, or reinstall via ${de(n,"install")} ${i} <source>).`):c>0&&u.push(`Loaded unmanaged extensions are currently treated as informational. Use ${de(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 ${de(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${de(n,"manage")} ${i} after extension changes.`),u}function ri(e,t,n,r={}){let i=[...new Set(t)].sort((A,j)=>A.localeCompare(j)),o=n.filter(A=>A.managed).length,a=n.filter(A=>A.enabled).length,s=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=>gu(A)).map(A=>A.name).sort((A,j)=>A.localeCompare(j)),u=d.filter(A=>!gu(A)).map(A=>A.name).sort((A,j)=>A.localeCompare(j)),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 f=m.failed,p=m.skipped_unmanaged,h=m.skipped_non_github,g=u.length>0,w=g?"partial":"full",v=g?[`extension_update_health_partial_coverage:skipped_unmanaged:${u.length}`]:[],x=[...new Set([...i,...v])].sort((A,j)=>A.localeCompare(j)),S=[...new Set(x.map(A=>xu(A)))].sort((A,j)=>A.localeCompare(j)),b=By(x),R=e==="global"?"--global":"--project",k=Jy(e,i,n,r),I=Ky({normalizedWarnings:i,options:r,scope:e,scopeFlag:R,updateCheckFailedTotal:f,policyWarningCount:b.warning_count,updateHealthPartial:g,skippedUnmanagedTotal:p,skippedNonGithubTotal:h,updateAvailableTotal:c});return{status:x.length===0?"ok":"warn",warning_count:x.length,warning_codes:S,warnings:x,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:a,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:g,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(A=>A.name).sort((A,j)=>A.localeCompare(j)),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:f,top_warnings:x.slice(0,8),remediation:I,...k?{collision_plan:k}:{}}}function ku(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new y(`Invalid --detail value "${e}". Expected summary or deep.`,_.USAGE)}function xu(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Ln(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let o=ls(r);return o?[o]:us(r)})();for(let o of i){let a=`${o.layer}:${o.name}:${o.capability}`;t.has(a)||(t.add(a),n.push(o))}}return n}function Fn(){return{version:er.version,capabilities:[...er.capabilities],legacy_aliases:{...er.legacy_aliases}}}function gu(e){let t=E(e.name),n=E(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Su(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=>E(l.name)))].sort((l,u)=>l.localeCompare(u)),a=[...new Set(n.filter(l=>l.layer==="project").map(l=>E(l.name)))].sort((l,u)=>l.localeCompare(u)),s=new Set(r.map(l=>E(l.name))),c=o.filter(l=>!a.includes(l)&&!s.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:a.length,active_project_names:o,loaded_project_names:a,missing_active_project_names:c}}}import{randomUUID as Yy}from"node:crypto";import oe from"node:fs/promises";import Xy from"node:os";import V from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="263602a2-c000-5df7-80d2-6f095985496f")}catch{}})();var Eu=3,Zy=120,Au=250,Qy=12e4,ew=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Ru=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Iu=e=>ew.has(String(Ru(e))),ii=(e,t)=>Ru(e)===t,Cu=e=>new Promise(t=>{setTimeout(t,e)}),Tu=async e=>{let t=V.join(e,"package.json");await D(t)||await oe.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
35
+ `,"utf8")},$u=async e=>{let t=Ee(import.meta.url,["../../.."]),n=V.join(e,"node_modules","@unbrained"),r=V.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")},Xo=async e=>{let t=V.resolve(e),n=V.dirname(t),r=V.parse(n).root,i=await oe.realpath(r).catch(()=>r),o=V.relative(r,n),a=o===""?[]:o.split(V.sep);for(let[s,c]of a.entries()){let d=V.join(i,c);try{i=await oe.realpath(d)}catch{i=V.join(i,...a.slice(s));break}}return V.join(i,V.basename(t))},Ou=async(e,t,n,r=Xy.tmpdir())=>{let i=V.resolve(e),o=await oe.realpath(i).catch(()=>i),a=await Xo(t);if(o===a)return;if(!we(o,a)){await n(e,t,{recursive:!0,force:!0});return}let s=m=>{let f=V.resolve(m);if(f!==i&&!we(i,f))return!1;let p=V.resolve(o,V.relative(i,f));if(p===a||we(a,p))return!1;let g=V.relative(o,p).split(V.sep);return g.some(w=>w==="node_modules"||w.startsWith(".pm-extension-install-backup-"))?!1:g[0]!==".agents"},c=await oe.realpath(V.resolve(r)).catch(()=>Xo(r)),d=we(o,c)?V.dirname(o):c;if(we(o,d))throw new y(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,_.USAGE,{code:"extension_install_source_contains_destination"});let l=await oe.mkdtemp(V.join(d,"pm-extension-copy-")),u=V.join(l,"extension");try{await n(e,u,{recursive:!0,force:!0,filter:s}),await n(u,t,{recursive:!0,force:!0})}finally{await oe.rm(l,{recursive:!0,force:!0})}},Du=async(e,t,n=oe.cp)=>{for(let r=1;r<=Eu;r+=1)try{await oe.rm(t,{recursive:!0,force:!0}),await Ou(e,t,n);return}catch(i){if(!Iu(i)||r===Eu)throw i;await Cu(Au)}},Zo=async e=>{let t;try{t=await oe.readFile(V.join(e,"owner.json"),"utf8")}catch(i){if(!it(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},Pu=async(e,t)=>await Zo(e)!==t?!1:(await oe.rm(e,{recursive:!0,force:!0}),!0),tw=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 Zo(e);return r===null?(await oe.rm(e,{recursive:!0,force:!0}),!0):Pu(e,r)},nw=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await Zo(e)!==t)return;let o=new Date;await oe.utimes(e,o,o)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},rw=async(e,t)=>{await oe.mkdir(e);try{await oe.writeFile(V.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
36
+ `,"utf8")}catch(n){throw await oe.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},iw=async(e,t,n,r,i)=>{for(let o=1;o<=n;o+=1)try{return await rw(e,t),!0}catch(a){if(!ii(a,"EEXIST"))throw a;await tw(e,i)?o-=1:await Cu(r)}return!1},Qo=async(e,t,n,r)=>{let i=V.join(e,"runtime","extension-install-locks"),o=V.join(i,"scope.lock");await oe.mkdir(i,{recursive:!0});let{attempts:a=Zy,delay_ms:s=Au,stale_ms:c=Qy,heartbeat_ms:d}=r??{};if(![a,s,c,d].filter(w=>w!==void 0).every(Number.isFinite))throw new y("Extension install lock timings must be finite numbers.",_.USAGE);let l=Math.max(1,Math.floor(a)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),f=Math.floor(d??m/3);if(m<=0||f<=0||f>=m)throw new y("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",_.USAGE);let p={pid:process.pid,token:Yy(),created_at:T(),destination:t};if(!await iw(o,p,l,u,m))throw new y(`Timed out waiting for extension install lock for "${t}".`,_.CONFLICT);let g=nw(o,p.token,f);try{return await n()}finally{await g(),await Pu(o,p.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 Nu=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 a=i;i+=1,r[a]=await n(e[a])}});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 Mu(e,t){let n=E(e),r=t.find(i=>E(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 Lu(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${E(o.name)}`]:[])),r=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>o.passThrough!==!0).filter(o=>!n.has(`${o.layer}:${E(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,a)=>o.localeCompare(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]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var Fu=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=dr(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 ow=1e4,aw=(e,t,n)=>{let r=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),i=r.find(a=>a.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"}},ju=async(e,t=Xr)=>{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,ow);return aw(i,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import sw 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]="56290db9-933c-590d-8b9f-df62ff45e515")}catch{}})();function ea(e){return cw.join(e,"extension-migrations.json")}function Uu(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 dw(e){let t=ea(e);if(!await D(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await sw.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 ta(e,t){let n=await dw(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let a=Uu(i,o),s=r.get(zu(i,a));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function lw(e){let t=await ta(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=Uu(l,u),f=zu(l,m),p=n.get(f),h=String(l.definition.status??"pending").toLowerCase(),g=p?.status??(h==="applied"||h==="failed"?h:"pending");if(g==="applied"){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:g,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:g,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:g,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:g}));let x={key:f,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(f,x),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:f,layer:l.layer,extension:l.name,id:m,before:g,outcome:"applied"}),i=!0}catch(x){let S=x instanceof Error?x.message:String(x),b={key:f,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:S};n.set(f,b),l.definition.status="failed",l.definition.reason=S,r.push({key:f,layer:l.layer,extension:l.name,id:m,before:g,outcome:"failed",error:S}),i=!0}}if(i){let l=await C(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,f)=>m.key.localeCompare(f.key))};await vr({pmRoot:e.pmRoot,filePath:ea(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 a=r.filter(l=>l.outcome==="pending").length,s=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:ea(e.pmRoot),total:r.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function Wu(e){let t=await C(e.resolvedRoots.settings_root),n=await Ne({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Me(n);e.warnings.push(...n.warnings,...r.warnings);let i=await lw({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 uw from"node:fs/promises";import mw 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 pw(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function fw(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 na(e){let t=mw.join(e,"manifest.json"),n;try{n=await uw.readFile(t,"utf8")}catch(s){if(it(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}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=gs(i),a=pw(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:o.findings,warnings:o.findings.map(s=>fw(a,s)),remediation:o.findings.map(s=>s.message)}}function qu(e){return na(Pe(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 Bu(e,t,n){let r=typeof t=="string"?null:await Pn(e),i=r===null?null:e.trim().toLowerCase(),o=i===null?null:await Bl(i),a=Qr(r??e,{forceGithub:typeof t=="string",ref:n}),s=i===null?null:await Vl(e);return{bundledAliasName:i,bundledPackageName:o,installSource:a,sourceResolution:{requested:e,selected:{kind:i===null?a.kind:"builtin",input:i??a.input,...o===null?{}:{package:o}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...o===null?{}:{package:o},command:`pm install ${i}`}],...s===null?[]:[{kind:"npm",input:`npm:${s.package}`,package:s.package,...s.version===void 0?{}:{version:s.version},directory:s.directory,command:`pm install npm:${s.package}`}]]}}}import Rt from"node:fs/promises";import hw 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 ra=async e=>Rt.readFile(e).catch(t=>{if(ii(t,"ENOENT"))return null;throw t}),Hu=async(e,t,n,r,i)=>{let o=$n(e),a=yt(t),[s,c]=await Promise.all([ra(o),ra(a)]);return r&&await Rt.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:o,managedStateContents:s,settingsPath:a,settingsContents:c}},Gu=async e=>{await Rt.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Rt.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 Rt.rm(t,{force:!0}):(await Rt.mkdir(hw.dirname(t),{recursive:!0}),await Rt.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 gw=4,Yu=[["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=Yu.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),yw={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"},ww="__pm_native_output",vw=["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"],Xu=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],bw=["disabled","require_trusted","require_provenance"],Zu={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:[]},kw=e=>{let t=e??Zu,n={};for(let r of vw)n[r]=xe(t[r]??[]);return n},xw=(e,t)=>{for(let n of Xu)t[n].length>0&&(e[n]=t[n]);return e},Sw=(e,t)=>{for(let n of bw)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Ew=e=>{let t={};for(let n of Xu)t[n]=xe(e[n]??[]);return t},Aw=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:xw(Sw({name:t},e),Ew(e))},Rw=e=>(e??[]).map(t=>Aw(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Iw=e=>{let t=Object.assign({},Zu,e??{}),n=kw(e),r=Rw(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}},Qu=async(e,t)=>{let n=[t],r=await Hl(t);r&&n.push(r);let i=[...new Set(n.map(o=>E(o)).filter(o=>o.length>0))];for(let o of i){let a=e.find(c=>E(c.name)===o);if(a)return a;let s=e.find(c=>E(c.directory)===o);if(s)return s}},em=(e,t)=>{let n=t.trim(),r=new Set(xe(e.extensions.enabled));return new Set(xe(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},tm=(e,t)=>{let n=t.trim(),r=new Set(xe(e.extensions.enabled)),i=new Set(xe(e.extensions.disabled)),o=[...r],a=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Cw=(e,t)=>{let n=t.trim(),r=new Set(xe(e.extensions.enabled)),i=new Set(xe(e.extensions.disabled)),o=[...r],a=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Tw=(e,t)=>{let n=t.trim(),r=new Set(xe(e.extensions.enabled)),i=new Set(xe(e.extensions.disabled)),o=[...r],a=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},$w=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=Yu.map(([i,o,a])=>({action:o,flag:a,distance:ds(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},Ow=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=$w(e);if(!r)return new y(`One action flag is required. Use one of: ${_w}. Bare \`pm package\` and \`pm extension\` default to --explore.`,_.USAGE);let i=`pm ${n} ${r.flag}`;return xr({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(nm),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},Dw=[["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"]],nm={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Pw=e=>nm[e]??null,Nw=(e,t)=>{let n=[...new Set(Dw.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=Pw(e.trim().toLowerCase());if(r)return r;throw Ow(e,t)}if(n.length>1)throw new y("Extension action flags are mutually exclusive.",_.USAGE);return n[0]},Mw=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new y('Options "--project/--local" and "--global" are mutually exclusive.',_.USAGE);return n?"global":"project"},Lw=[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"}}],rm=e=>{for(let t of Lw){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},im=(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}},Fw=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),o=r?em(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:im({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:o},t,r,rm(r))}},jw=async(e,t,n,r,i,o)=>{let a=Ie.join(e,t),s=Ie.join(a,"manifest.json"),c=o.get(E(t));if(!await D(s))return Fw(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await mt.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=jo(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(E(u.name))??o.get(E(t));return{summary:im({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:em(r,u.name)},n,m,rm(m))}},We=async(e,t,n,r)=>{if(!await D(e))return{extensions:[],warnings:[]};let o=(await mt.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),a=new Map(r.entries.map(l=>[E(l.name),l])),s=new Map(r.entries.map(l=>[E(l.directory),l])),c=[],d=[];for(let l of o){let u=await jw(e,l,t,n,a,s);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))}},Uw=Xs(),zw=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Ww=(e,t,n,r)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),o=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&a.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:zw(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:a,...o?{sdk_dependency_status:"missing"}:{}}},qw=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},om=e=>e.map(t=>qw(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),am=(e,t,n)=>{let r=E(e);return t.find(i=>(n===void 0||i.layer===n)&&E(i.name)===r)},Bw=(e,t,n,r)=>n.find(o=>o.scope===t&&E(o.name)===E(e))?.activation_status??(r?"failed":"unknown"),sm=(e,t,n,r,i)=>Uw.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,a=await mt.mkdtemp(Ie.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Ee(import.meta.url,["../.."]);try{let s=await Ne({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:Li(),cache_bust:!0,module_graph_snapshot_root:a}),c=await Me({...s}),d=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...om(c.failed)],l=Object.fromEntries(s.loaded.map(u=>[E(u.name),As(Yt(c,{extensionName:u.name}))]));return{installed:ni(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await mt.rm(a,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),oa=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)}),a=r,s=[];for(let c of o){let d=Ie.join(e,c.directory),l=await tn(d),u=T(),m={kind:"local",input:c.name,location:d};a=Dn(a,{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}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return s.length>0&&await Et(e,a),{state:a,adopted_entries:s,unmanaged_candidates:o,already_managed_count:n.length-i.length}},Hw=(e,t)=>{let n=L(process.cwd(),t.path),r=Tt(n,process.cwd()),i=e==="global"?nr(process.cwd()):n,o=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:o,roots:r}},oi=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 y('Options "--gh" and "--github" must match when both are provided.',_.USAGE);return n[0]},Gw=e=>yw[e],Jw=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,o=Gw(e),a=`<${r}>`,s=`pm ${n} ${o} ${a}`;throw new y(`Action "${e}" requires ${i} input.`,_.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},ai=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new y('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',_.USAGE);return Jw(t,n)},Vw=(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}:${E(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${E(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))},Kw=(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 y(r.message,_.USAGE)},Yw=(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},Xw=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},Zw=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:Xw(e),warnings:[...new Set(e.warnings)].sort((i,o)=>i.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(r,ww,{value:!0,enumerable:!1,configurable:!1}),r},aa=async(e,t,n)=>{let r=Nw(e,t);Kw(r,t);let i=Yw(e,r,t),o=Mw(t),a=Hw(o,n),c={action:r,normalizedTarget:i,scope:o,resolvedRoots:a,warnings:[],options:t,global:n},l={...c,withResult:(u,m=!0)=>Zw(c,u,m)};return await $v(l)},Qw=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=Ks(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"`},a={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"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[o[n],...s,`Install the scaffold: ${mr(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},ev=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([oi(r),r.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new y('Action "init" does not accept --gh/--github/--ref options.',_.USAGE);let s=ai(n,t,r),c=await uu(s,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:Qw(c,r)})},tv=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:o,withResult:a}=e;if(t!==void 0)throw new y('Action "reload" does not accept a target argument.',_.USAGE);let s=await C(n.settings_root),c=Li(),d=await Ne({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await Me(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"),a(u)},nv=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 y('Action "catalog" does not accept a package target.',_.USAGE);return o(await Gl(n,i,r))},rv=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),iv=e=>({kind:"local",input:e.input,location:e.absolute_path}),ov=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),av=(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}),sv=(e,t,n,r)=>e?rv(e,t):n.kind==="local"?iv(n):n.kind==="npm"?ov(n,r):av(n,r),cv=(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},dv=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:o,destinationDirectoryName:a}=t,s=await C(r.settings_root),c=await he(r.selected_root);i.push(...c.warnings);let d=Ie.join(r.selected_root,a),l=await D(d),u=await Ql(o.directory,d);await mt.mkdir(r.selected_root,{recursive:!0});let m=await mt.mkdtemp(Ie.join(r.selected_root,".pm-extension-install-backup-")),f=Ie.join(m,"destination");try{let p=await Hu(r.selected_root,r.settings_root,d,l,f),h=sv(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),g=c.state.entries.find(S=>E(S.name)===E(o.manifest.name)),w=cv(g,o.manifest.version,h,T()),v=Dn(c.state,{name:o.manifest.name,directory:a,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,...w,source:h}),x=tm(s,o.manifest.name);try{u||await Du(o.directory,d),await Tu(d),await $u(d),await Et(r.selected_root,v),x&&await br(r.settings_root,s,"settings:write")}catch(S){try{await Gu(p)}catch(b){throw new AggregateError([S,b],`Extension install failed: ${String(S)}; rollback failed: ${String(b)}`,{cause:b})}throw S}return{settings:s,managedState:v,sourceRecord:h,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:x}}finally{await mt.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},lv=async(e,t,n)=>{let r=n.filter(i=>E(i.name)===E(t)).flatMap(i=>i.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&r.length>0&&await Cn(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},uv=(e,t,n,r,i)=>{let o=am(t,n.activation_failures,e.scope),a=Bw(t,e.scope,n.installed,o),s=[!n.extensions_disabled,a==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${a}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:a,failure:o,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:a,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},mv=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:o,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,d=await dv(e,t),l=await We(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let u=await sm(r.pm_root,Ie.dirname(r.selected_root),d.settings,l.extensions,o);i.push(...u.warnings);let m=await lv(e,s.manifest.name,u.item_type_registrations),f=Mu(s.manifest.name,u.installed),p=uv(e,s.manifest.name,u,f,m),h=u.contribution_inventories[E(s.manifest.name)];return h&&(d.managedState=await Ul(r.selected_root,d.managedState,s.manifest.name,h)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.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:p.activated,settings_changed:d.activationChanged,runtime_activation_status:p.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:h,command_discovery:Ww(s.manifest.name,d.sourceRecord,f,p.failure),verification:p.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:p.failure??null}},p.activated)},pv=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new y('Action "install all" does not accept --ref.',_.USAGE);let o=[],a=new Map;for(let c of await Yr()){let d=await Pn(c),l=Ie.resolve(d),u=a.get(l);u===void 0&&(u=await aa(c,{...t,install:!0},n),a.set(l,u)),o.push({alias:c,result:u})}r.push(...o.flatMap(c=>c.result.warnings));let s=o.every(c=>c.result.ok);return i({installed_all:s,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}})},s)},fv=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:o,installSource:a,sourceResolution:s}=await Bu(t,n,e.options.ref);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${d.package}`)}let c=await Zl(a);try{let d=await tn(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),l=Vr(d.manifest.name);return await Qo(r.settings_root,l,()=>mv(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:o,sourceResolution:s,installSource:a,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},hv=async e=>{let t=oi(e.options),n=t??ai(e.normalizedTarget,e.action,e.options);return[t===void 0,Wl(n)].every(Boolean)?pv(e):fv(e,n,t)},gv=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:a}=e;if(t!==void 0)throw new y('Action "adopt-all" does not accept a target argument.',_.USAGE);if(oi(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new y('Action "adopt-all" does not accept --gh/--github/--ref options.',_.USAGE);let c=await C(r.settings_root),d=await he(r.selected_root);i.push(...d.warnings);let l=await We(r.selected_root,n,c,d.state);i.push(...l.warnings);let u=await oa(r.selected_root,n,l.extensions,d.state),m=await We(r.selected_root,n,c,u.state);i.push(...m.warnings);let f=ri(n,i,m.extensions,o);i.push(...f.warnings);let p=new Map(m.extensions.map(w=>[`${E(w.name)}:${E(w.directory)}`,w])),h=new Map(m.extensions.map(w=>[E(w.directory),w])),g=u.adopted_entries.map(w=>{let v=E(w.directory),x=p.get(`${E(w.name)}:${v}`)??h.get(v);return{...w,...cm(x)}});return a({adopted_all:g.length>0,adopted_count:g.length,already_managed_count:u.already_managed_count,extensions:g,triage:f,warning_codes:f.warning_codes,update_health_partial:f.update_health_partial,update_health_coverage:f.update_health_coverage})},cm=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=Qr(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new y(`Invalid GitHub shorthand "${e}".`,_.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}},yv=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:a,withResult:s}=e,c=ai(n,t,a),d=oi(a),l=await C(i.settings_root),u=await he(i.selected_root);o.push(...u.warnings);let m=await We(i.selected_root,r,l,u.state);o.push(...m.warnings);let f=await Qu(m.extensions,c);if(!f)throw new y(`Installed extension "${c}" was not found in ${r} scope.`,_.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let p=Ie.join(i.selected_root,f.directory),h=await tn(p),g=T(),w=_v(d,c,p,a.ref),v=Dn(u.state,{name:h.manifest.name,directory:f.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:w});await Et(i.selected_root,v);let x=await We(i.selected_root,r,l,v);o.push(...x.warnings);let S=x.extensions.find(b=>E(b.name)===E(h.manifest.name))??x.extensions.find(b=>E(b.directory)===E(f.directory));return s({adopted:!0,extension:{name:h.manifest.name,directory:f.directory,version:h.manifest.version,entry:h.manifest.entry},source:w,...cm(S)})},dm=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:a}=e,s=ai(n,t,a),c=await C(i.settings_root),d=await he(i.selected_root);o.push(...d.warnings);let l=await We(i.selected_root,r,c,d.state);o.push(...l.warnings);let u=await Qu(l.extensions,s);if(!u)throw new y(`Installed extension "${s}" was not found in ${r} scope.`,_.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},wv=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:o}=await dm(e),a=Ie.join(t.selected_root,o.directory);await mt.rm(a,{recursive:!0,force:!0});let s={...i.state,updated_at:T(),entries:i.state.entries.filter(d=>E(d.name)!==E(o.name)&&E(d.directory)!==E(o.directory))};await Et(t.selected_root,s);let c=Tw(r,o.name);return c&&await br(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:a,settings_changed:c})},Ju=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:o}=e,{settings:a,candidate:s}=await dm(e),c=t==="activate"?tm(a,s.name):Cw(a,s.name);c&&await br(n.settings_root,a,"settings:write");let d=t==="activate"?await sm(n.pm_root,Ie.dirname(n.selected_root),a,[s],i).then(l=>(r.push(...l.warnings),am(s.name,l.activation_failures,e.scope))):void 0;return d&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),o({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},d===void 0)},vv=(e,t,n,r,i,o)=>{let a=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=i?.adopted_entries.length??0,d=[[o!==null,o??""],[t>0,`Run pm ${a} explore --project and pm ${a} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${a} ${s} --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))]},ia=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),bv=(e,t,n,r)=>{if(e!=="project"||t||!ia(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.`},kv=(e,t,n)=>{if(String(e??"").trim().length>0)throw new y('Action "doctor" does not accept a target argument.',_.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new y("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",_.USAGE);let i=ku(n.detail),o=n.trace===!0;if([o,i!=="deep"].every(Boolean))throw new y("--trace requires --detail deep with --doctor.",_.USAGE);return{isolated:r,detailMode:i,includeTrace:o}},xv=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await oa(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},Sv=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:ia(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:ia(r),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},Ev=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:a,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=kv(t,n,o),u=await C(r.settings_root),m=await he(r.selected_root);i.push(...m.warnings);let f=await We(r.selected_root,n,u,m.state);i.push(...f.warnings);let{state:p,fix:h}=await xv(e,f.extensions,m.state),g=await We(r.selected_root,n,u,p);i.push(...g.warnings);let w=await Ne({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Me({...w,loaded:w.loaded}),x=await qu(r.pm_root);i.push(...x.warnings,...w.warnings),i.push(...wu(w.failed)),i.push(...v.warnings),i.push(...vu(v.failed)),i.push(...bu(w,v)),i.push(...Lu(v,w)),i.push(...Vw(w,v)),i.push(...Fu(v));let S=ni(g.extensions,w,v),b=Su(n,S,w.loaded.map(F=>({layer:F.layer,name:F.name})),w.failed.map(F=>({name:F.name})),w.disabled_by_flag);i.push(...b.warnings);let R=S.filter(F=>F.update_check_status==="failed").map(F=>`extension_update_check_failed:${F.name}`);i.push(...R);let k=ri(n,i,S,o);i.push(...k.warnings);let I=[...k.warnings],A={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},j=Ln(I),q=Fn(),O=k.warning_codes,W=bv(n,c,o.vocabulary,w),me=vv(k.remediation,w.failed.length,v.failed.length,o.vocabulary,h,W),ue=Sv(n,c,o.vocabulary,w),gt={status:k.status,scope:n,warning_count:k.warning_count,warning_codes:O,total_extensions:S.length,managed_total:S.filter(F=>F.managed).length,enabled_total:S.filter(F=>F.enabled).length,active_total:S.filter(F=>F.active).length,unmanaged_loaded_extension_count:k.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:k.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:k.unmanaged_expected_extension_count,runtime_active_total:S.filter(F=>F.runtime_active===!0).length,activation_status_totals:{ok:S.filter(F=>F.activation_status==="ok").length,failed:S.filter(F=>F.activation_status==="failed").length,not_loaded:S.filter(F=>F.activation_status==="not_loaded").length,unknown:S.filter(F=>F.activation_status==="unknown").length},unknown_capability_count:j.length,capability_contract_version:q.version,update_available_total:S.filter(F=>F.update_available===!0).length,update_health_coverage:k.update_health_coverage,update_health_partial:k.update_health_partial,update_check_failed_total:S.filter(F=>F.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Ko(w.failed),activation_failures:Ko(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:b.warnings.length,trace_enabled:l,isolation:ue,policy:A,remediation:me},rt=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(F=>F.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:g.extensions.filter(F=>F.managed).length,adopted_extensions:[]},_t={mode:d,summary:gt,triage:k,trace_enabled:l,capability_contract:q,capability_guidance:j,managed_state_fix:rt,author_manifest:x,isolation:ue,policy:w.policy};if(d==="deep"){let F=l?v.failed:v.failed.map(G=>{let{trace:Oi,...Di}=G;return Di});_t.deep={warnings:I,warning_codes:O,capability_contract:q,capability_guidance:j,trace_enabled:l,managed_state:{path:m.path,count:p.entries.length,entries:p.entries},installed_extensions:S,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(G=>({layer:G.layer,directory:G.directory,name:G.name,version:G.version,entry:G.entry,priority:G.priority}))},activation:{failed:F,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&&(_t.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 s(_t)},Av=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:a,withResult:s}=e,c=await C(r.settings_root),d=await Ne({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),l=await Me(d);i.push(...d.warnings),i.push(...l.warnings);let u=pu(t,d,l);if(t!==void 0&&u.extensions.length===0){let m=o.vocabulary==="package"?"package":"extension",f=[...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)),p=f.length>0?` Loaded ${m} names: ${f.join(", ")}.`:"";throw new y(`No loaded ${m} named "${t}" was found in ${n} scope.${p} Run pm ${m} explore to list discovered ${m}s.`,_.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},Rv=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await oa(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let o=await Nu(r.entries,gw,async a=>{if(a.source.kind!=="github")return a;let s=await ju(a.source);return{...a,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});r={...r,updated_at:T(),entries:On(o)},await Et(e.resolvedRoots.selected_root,r)}return{state:r,fix:i}},Iv=async(e,t,n)=>{let r=await Ne({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Me({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:ni(n,r,i),failures:om(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}}},Cv=(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},Vu=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:a}=e,s=await C(r.settings_root),c=Iw(s.extensions.policy),d=await he(r.selected_root);i.push(...d.warnings);let l=await We(r.selected_root,n,s,d.state);i.push(...l.warnings);let{state:u,fix:m}=await Rv(e,l.extensions,d.state),f=await We(r.selected_root,n,s,u);if(i.push(...f.warnings),t==="manage"){let v=f.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);i.push(...v)}let p=await Iv(e,s,f.extensions),h=p.installed,g=ri(n,i,h,o);i.push(...g.warnings);let w={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 p.failures!==void 0&&(w.activation_diagnostics={failed_count:p.failures.length,failed:p.failures}),t==="explore"&&(w.runtime_probe=p.summary),t==="manage"&&(w.runtime_probe=p.summary,w.managed_state_fix=Cv(m,h)),a(w)},Ku={init:ev,install:hv,uninstall:wv,explore:Vu,manage:Vu,describe:Av,reload:tv,doctor:Ev,catalog:nv,adopt:yv,"adopt-all":gv,activate:Ju,deactivate:Ju,migrate:Wu},Tv=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),$v=e=>Tv(e)?Qo(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Ku[e.action](e)):Ku[e.action](e);import{execFile as Ov}from"node:child_process";import{realpath as Dv}from"node:fs/promises";import lm from"node:path";import{promisify as Pv}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 Nv=Pv(Ov),Mv=32*1024*1024,Lv=1e4,Fv=["search/eval-queries.json"];function sa(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function jv(e){return`'${e.replaceAll("'","'\\''")}'`}async function Uv(e,t=Dv){return t(e).catch(()=>lm.resolve(e))}async function si(e){let t=await kt(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 Uv(e),r=sa(lm.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=xo.map(o=>`${r}/${sa(o)}`);try{let{stdout:o}=await Nv("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:Mv,windowsHide:!0,timeout:Lv}),a=new Set(Fv.map(d=>`${r}/${d}`)),s=[...new Set(o.split("\0").filter(d=>d.length>0&&!a.has(sa(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>s.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:s,tracked_path_count:s.length,remediation_command:s.length===0?null:`git rm --cached -r -- ${c.map(d=>jv(`:(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 Hv}from"node:child_process";import{randomUUID as Gv}from"node:crypto";import{readdir as Jv}from"node:fs/promises";import le from"node:path";import{promisify as Vv}from"node:util";import{constants as um}from"node:fs";import{lstat as zv,open as Wv}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 qv={lstat:zv,open:Wv};function Bv(e){return e.O_NOFOLLOW??0}async function mm(e,t,n=qv){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let i=await n.open(e,um.O_RDONLY|Bv(um));try{let o=await i.stat();if(!o.isFile()||o.size>t)return null;let a=Buffer.alloc(o.size),s=0;for(;s<a.length;){let{bytesRead:d}=await i.read(a,s,a.length-s,s);if(d===0)break;s+=d}return(await i.stat()).size===o.size&&s===o.size?a.toString("utf8",0,s):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]="145a6d31-5e14-5b0b-95fb-6f837d11e2f4")}catch{}})();var Kv=Vv(Hv),Yv=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,Xv=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,da=2048,Zv=16*1024*1024,Qv=64,eb=1e5,tb=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"]),nb=new Set(["field","base","ours","theirs","retained","discarded"]);async function la(e){try{let{stdout:t}=await Kv("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 _m(e,t){let n=le.dirname(le.resolve(e,t));for(let r=0;r<12;r+=1){if(await D(le.join(n,"settings.json")))return n;let i=le.dirname(n);if(i===n)break;n=i}return null}function ua(e){return le.join(e,"merge-receipts")}function nn(e){return`${e}.json`}function Un(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ym(e,t){return Object.keys(e).every(n=>t.has(n))}function pm(e){return Array.isArray(e)&&e.length<=da&&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>eb||r.depth>Qv)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(Un(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function rb(e){return Un(e)&&ym(e,nb)&&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 ib(e){if(!Un(e))return!1;let t=Object.entries(e);return t.length<=da&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function ob(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||le.posix.isAbsolute(e))return!1;let n=le.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&le.posix.basename(n,le.posix.extname(n))===t}function ab(e){return!ym(e,tb)||e.version!==1?!1:typeof e.id=="string"&&Yv.test(e.id)&&typeof e.item_id=="string"&&Xv.test(e.item_id)&&ob(e.item_path,e.item_id)}function sb(e){return!pm(e.fields_from_theirs)||!pm(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>da||!e.decisions.every(rb)?!1:e.merged_field_hashes===void 0||ib(e.merged_field_hashes)}function cb(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 db(e){return typeof e.created_at=="string"&&Hi(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&Hi(e.reconciled_at))}function lb(e){return e.value_availability==="hash_only"&&e.decisions.every(t=>t.base===null&&t.ours===null&&t.theirs===null&&hm(t.retained)&&hm(t.discarded))}function ma(e,t){return!Un(e)||!ab(e)||!sb(e)||!cb(e)||!db(e)?!1:t!=="durable"||lb(e)}async function wm(e){return mm(e,Zv)}async function fm(e){let t;try{t=await(e.readReceipt??wm)(e.receiptPath)}catch(o){if(it(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(!ma(n,e.evidenceSource)||n.id!==e.receiptId||le.basename(e.receiptPath)!==nn(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:ci(n),content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt},null,2)}
38
+ `}}function ci(e){return ot(X({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:di(e).decisions}))}function ub(e,t){if(e.state==="reconciled"&&t.state==="reconciled")return e;let{reconciled_at:n,...r}=e;return{...r,state:"pending"}}function di(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:ca(t.retained)??ot(X(t.retained)),discarded_hash:ca(t.discarded)??ot(X(t.discarded))}))}}function ca(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 hm(e){return Un(e)&&Object.keys(e).length===1&&ca(e)!==void 0}async function OO(e){let t=await la(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=le.basename(r,le.extname(r)),o={version:1,id:Gv(),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 fn(t),await se(le.join(t,nn(o.id)),`${JSON.stringify(o,null,2)}
39
+ `);let a=await _m(e.cwd,o.item_path);if(a!==null){let s=ua(a),c=di(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 fn(s),await se(le.join(s,nn(o.id)),`${JSON.stringify(d,null,2)}
40
+ `)}return o}async function gm(e,t){if(!await D(e))return{receipts:[],invalid_evidence_count:0};let n;try{n=await Jv(e)}catch{return{receipts:[],invalid_evidence_count:1}}let r=[],i=0;for(let o of n.sort((a,s)=>a.localeCompare(s)))if(o.endsWith(".json"))try{let a=le.join(e,o),s=await wm(a);if(s===null){i+=1;continue}let c=JSON.parse(s);if(!ma(c,t)||o!==nn(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 zn(e,t={}){let n=await la(e),r=n===null?{receipts:[],invalid_evidence_count:0}:await gm(n,"clone_local"),i=t.pmRoot??le.join(e,".agents","pm"),o=await gm(ua(i),"durable"),a=new Map(o.receipts.map(c=>[c.id,c])),s=0;for(let c of r.receipts){let d=a.get(c.id);if(d!==void 0&&ci(d)!==ci(c)){a.delete(c.id),s+=1;continue}a.set(c.id,d===void 0?c:ub(c,d))}return{receipts:[...a.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+s}}async function mb(e,t={}){return(await zn(e,t)).receipts}function li(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 DO(e,t,n={}){let r=await la(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(!ma(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let o=T(),a=le.join(r,nn(t.id)),s=await _m(e,t.item_path),c=s===null?null:le.join(ua(s),nn(t.id)),l=(await Promise.all([fm({receiptPath:a,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:o}),...c===null?[]:[fm({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=ci(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 se(m.path,m.content)}async function PO(e){let t=await mb(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:T()}}import{realpath as km}from"node:fs/promises";import pb from"node:path";import xm 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]="7a21ee76-ed53-57a0-9776-c787297ed7b6")}catch{}})();function vm(e,t){return t==="body"?e.body:e.metadata[t]}function pa(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((a,s)=>!r.has(s)&&pa(i,a));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)&&pa(i,n[r]))}function bm(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],a=new Set;for(let c of sc(o.patch))a.add(Sr(c.path)),c.from&&a.add(Sr(c.from));let s=[...n].filter(c=>a.has(c));if(s.length!==0){for(let c of s)n.delete(c);r.push({index:i+1,ts:o.ts,author:o.author,op:o.op,fields:s.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function fb(e,t,n){let r=xm.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(Sr(p.path));let o=new Set([...i].filter(p=>pa(vm(t,p),vm(n,p)))),a=new Set([...i].filter(p=>!o.has(p))),s=bm(e,a),c=bm(e,o),d=[...i].sort((p,h)=>p.localeCompare(h)),l=[...a].sort((p,h)=>p.localeCompare(h)),u=[...o].sort((p,h)=>p.localeCompare(h)),m=[...new Set(s.map(p=>p.author))].sort((p,h)=>p.localeCompare(h)),f=[...new Set(c.map(p=>p.author))].sort((p,h)=>p.localeCompare(h));return{reconciled_field_count:i.size,reconciled_fields:d,reverted_field_count:a.size,reverted_fields:l,discarded_events:s,discarded_authors:m,preserved_field_count:o.size,preserved_fields:u,preserved_events:c,preserved_authors:f,recovery_hint:s.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 hb(e){try{return await km(e)}catch{return null}}async function gb(e){if(e.receipt.evidence_source!=="clone_local"||await hb(pb.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(s=>s.field)])].sort((s,c)=>s.localeCompare(c)),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let i=Object.keys(r).sort((s,c)=>s.localeCompare(c));if(n.length!==i.length||n.some((s,c)=>s!==i[c]))return null;let o=e.currentItemReplay.metadata;return n.every(s=>{let c=s==="body"?e.currentItemReplay.body:o[s];return r[s]===ot(X(c))})?{receipt:e.receipt,declaredFields:n}:null}async function _b(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(a=>a.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await km(e.itemPath),r=[];for(let a of t){let s=await gb({receipt:a,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});s&&r.push(s)}let i=new Set(r.flatMap(({declaredFields:a})=>a)),o=e.reconciliation?.reconciled_fields;return r.length>0&&(o===void 0||o.length>0&&o.every(a=>i.has(a)))?{trusted:!0,reason:"trusted_clone_local_driver_evidence",receipt_ids:r.map(({receipt:a})=>a.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function yb(e){let t=e.options.mergeReceiptProof?.receipts.filter(i=>i.item_id===e.subjectId)??[],n=e.options.mergeReceiptProof?await _b({proof:{...e.options.mergeReceiptProof,receipts:t},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(n&&!n.trusted&&e.options.dryRun!==!0&&e.options.force!==!0)throw new y(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${n.reason}).`,_.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use clone-local driver 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 r=n?.trusted?t.filter(i=>n.receipt_ids.includes(i.id)):[];return{mergeReceiptProof:n,effectiveAuditContext:r.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:r.map(di)}}:e.options.auditContext}}async function wb(e,t,n,r){let i=e.located?.itemPath??null,o=e.located?await st(e.located,{schema:t.schema}):null;if(!o)return{currentItemReplay:null,currentItemPath:i,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let a=ac(o.document),s=n[n.length-1]?.after_hash;return{currentItemReplay:a,currentItemPath:i,matchedChainBefore:Ft(a,r)===s,currentItemRawBeforeLock:o.raw,loadedItem:o}}function vb(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 bb(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:T(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?xm.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Ft(e.finalReplay,e.itemHashVersion),after_hash:Ft(n,e.itemHashVersion),message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function kb(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 xb(e){return wc({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})=>yc({historyPath:e.historyPath,nextHistoryRaw:lc(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>ne({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function fa(e,t,n){let r=L(process.cwd(),n.path);await Q(r);let i=await C(r),o=B(i,z()),a=await vc(r,e,i,o.type_to_folder);if(!await D(a.historyPath))throw new y(`No history stream exists for ${a.id}.`,_.NOT_FOUND);let s=await Y(a.historyPath),c=await Lt(a.historyPath,a.id);if(c.length===0)throw new y(`No history entries exist for ${a.id}; nothing to repair.`,_.USAGE);let d=Ji(c),l=gr(c),u=t.normalizeProvenance?Nd(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},m=cc(u.entries),f=new Set(u.entries.map(W=>W.item_hash_version).filter(W=>W!==void 0)),p=dc(u.entries,m),h=await wb(a,i,c,m),g=p.finalDocument,w=h.currentItemReplay!==null&&Ft(g,m)!==Ft(h.currentItemReplay,m),v=w&&h.currentItemReplay?fb(p.entries,g,h.currentItemReplay):void 0,{mergeReceiptProof:x,effectiveAuditContext:S}=await yb({options:t,subjectId:a.id,itemReplayContext:h,reconciliation:v}),b=[p.entriesRehashed>0,p.entriesPatchRepaired>0,w,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),R=J(t.author,i.author_default),k=!!t.dryRun,I=vb({message:t.message,entriesRehashed:p.entriesRehashed,entriesPatchRepaired:p.entriesPatchRepaired,reconcileNeeded:w}),{rewrittenEntries:A,auditEntryAdded:j}=bb({reanchorEntries:p.entries,changed:b,reconcileNeeded:w,currentItemReplay:h.currentItemReplay,finalReplay:g,author:R,message:I,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...S,provenance_normalization:u.receipt}:S,itemHashVersion:m,explicitItemHashVersion:p.explicitItemHashVersion}),q=Ji(A);if(!q.ok)throw new y(`history-repair produced an invalid rewritten chain (${q.errors.join(", ")}).`,_.GENERIC_FAILURE);let O=kb(b,p.skippedOps,v);return b&&!k&&O.push(...await xb({pmRoot:r,subject:a,settings:i,typeRegistry:o,historyRawBeforeLock:s,currentItemRawBeforeLock:h.currentItemRawBeforeLock,author:R,force:t.force,loadedItem:h.loadedItem,historyPath:a.historyPath,rewrittenEntries:A})),{id:a.id,dry_run:k,changed:b,history:{path:a.historyPath,entries_scanned:c.length,chain_drift_before:!d.ok,entries_rehashed:p.entriesRehashed,entries_patch_repaired:p.entriesPatchRepaired,converted_replace_to_add:p.convertedReplaceToAdd,skipped_ops:p.skippedOps,reconciled_with_item:w,audit_entry_added:j,verify_ok:q.ok,verify_errors:q.errors,item_hash_version_before:l.item_hash_version??null,item_hash_version_after:m,version_disposition:f.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},...v?{reconciliation:v}:{},...x?{merge_receipt_proof:x}:{},warnings:[...new Set(O)].sort((W,me)=>W.localeCompare(me)),generated_at:T()}}function aD(e,t){if(t&&e!==void 0)throw new y("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",_.USAGE);if(!t&&e===void 0)throw new y("history-repair: provide an item <id> or pass --all to repair every drifted stream.",_.USAGE)}async function sD(e,t){let n=L(process.cwd(),t.path);await Q(n);let r=await C(n),i=B(r,z()),o=[],a=await zt(n,r.item_format,i.type_to_folder,o,r.schema,{forceSourceScan:!0}),s=await Kt(n,a),c=e.normalizeProvenance?await Md(n):[],d=[...new Set([...s.driftedItems,...c])].sort((f,p)=>f.localeCompare(p)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let f of d)try{let p=await fa(f,{...e,auditContext:e.auditContextById?.[f],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[f]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=p.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...p.warnings.map(g=>`${f}:${g}`)),l.push({id:f,outcome:h,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,l.push({id:f,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await ic(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:a.length,drifted_streams:s.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...o,...u])].sort((f,p)=>f.localeCompare(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]="652d1b49-f9d1-55a7-84b5-ff3cf57648ad")}catch{}})();var Sb=new Set(qc),Em=25,on=8,Wn=100,Eb=ge.join("runtime","telemetry","events.jsonl"),Ab=ge.join("runtime","telemetry","state.json"),Rb=2500,Ib=500,Am=Wc-3,Cb=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function va(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function ba(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function an(e){return e.trim().toLowerCase()}function _a(e,t){let n=an(e),r=an(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function ka(e){try{return(await et.stat(e)).isDirectory()}catch{return!1}}async function Tb(e){let t=(await et.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>et.readdir(ge.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>hn.some(o=>i.name.endsWith(o))).map(i=>ge.parse(i.name).name)))}async function $b(e,t,n,r){let i=await Ge({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:i,overThreshold:!1,classification:"live"};let a;try{a=await et.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let s="live";if(o){let d=a.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{s=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?a.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function Ob(e,t,n){let r=ge.join(e,"history");if(!await ka(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await et.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),a=t.enabled?t.max_entries:null,s=[],c=[],d=[],l=[];for(let u of i){let m=ge.join(r,u),f=u.slice(0,-6),p=await $b(m,f,t,n);s.push(...p.warnings),p.classification==="tombstone"&&d.push(f),p.classification==="orphaned"&&l.push(f),p.overThreshold&&c.push(f)}return{count:i.length,warnings:[...s,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:a,tombstones:d,orphaned:l}}function ya(e,t){return ge.relative(e,t).replaceAll("\\","/")}async function Rm(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),a=[];try{a=await et.readdir(o)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&U(s))continue;continue}for(let s of a)hn.some(c=>s.toLowerCase().endsWith(c))&&r.push(ge.join(o,s))}return r.sort((i,o)=>ya(e,i).localeCompare(ya(e,o))),r}function Db(e){return!(typeof e=="object"&&e!==null&&"code"in e&&U(e))}async function Pb(e,t,n){let r=await Rm(e,t),i=[],o=[],a=[],s=[],c=Ct(z());for(let d of r){let l=ya(e,d),u;try{u=await et.readFile(d,"utf8")}catch{i.push(l);continue}let m=Nt(u);if(m){o.push({path:l,...m});continue}try{let f=Mt(u,{format:vs(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:fr(f.metadata)})}catch{a.push(l)}}return{paths:r,unreadable:i,conflictMarkers:o,parseFailures:a,formatVersions:s}}async function Nb(e){let t=ge.join(e,"history"),n=[],r=[],i=[],o=[];try{o=(await et.readdir(t)).filter(a=>a.endsWith(".jsonl")).sort((a,s)=>a.localeCompare(s))}catch(a){Db(a)&&n.push("history")}for(let a of o){let s=a.slice(0,-6),c;try{c=await et.readFile(ge.join(t,a),"utf8")}catch{n.push(s);continue}let d=Nt(c);if(d){r.push({id:s,...d});continue}c.split(/\r?\n/).forEach((l,u)=>{if(l.trim())try{JSON.parse(l)}catch{i.push({id:s,line:u+1})}})}return{files:o,unreadable:n,conflictMarkers:r,invalidJson:i}}function Im(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 Mb(e){return e===0?[]:[`merge_receipt_evidence_invalid:${e}`]}async function Lb(e,t,n,r,i){let o=await Pb(e,t,n),a=await Nb(e),s=hr(o.formatVersions),c=$e(n),d=Ir(i,b=>rc(b,c),wn()),l=await si(e),u=await kt(e),m=u===null?null:await Br(u),f=await zn(u??e,{includeLossless:!0,pmRoot:e}),p=f.receipts,{pendingDecisions:h,lossless:g}=li(p),w=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}`),...a.unreadable.map(b=>`integrity_history_unreadable:${b}`),...a.conflictMarkers.map(b=>`integrity_history_conflict_marker:${b.id}:L${b.line}`),...a.invalidJson.map(b=>`integrity_history_invalid_json:${b.id}:L${b.line}`),...s.outdated.map(b=>`integrity_item_outdated_format_version:${b}`),...s.ahead.map(b=>`integrity_item_ahead_format_version:${b}`),...Im(d),...l.tracked_path_count>0?[`tracked_runtime_cache_files:${l.tracked_path_count}`]:[],...m!==null&&m.status!=="ok"?[`merge_driver_configuration_${w?"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}`]:[],...Mb(f.invalid_evidence_count)],x=[...new Set(v)].sort((b,R)=>b.localeCompare(R)),S=x.filter(b=>!b.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:S.length===0?"ok":"warn",ok:S.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:s.outdated.length,item_ahead_format_version:s.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:f.invalid_evidence_count},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:s.outdated,item_ahead_format_version:s.ahead,hierarchy_integrity:{...d,relations:qe(d.relations,on)},history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.invalidJson,tracked_runtime_cache:{tracker_relative_root:l.tracker_relative_root,tracked_paths:l.tracked_paths,tracked_path_count:l.tracked_path_count,remediation_command:l.remediation_command},merge_driver_configuration:m===null?null:{...m,required:r},pending_merge_decision_items:[...new Set(h.map(b=>b.item_id))].sort((b,R)=>b.localeCompare(R)),lossless_merge_receipt_items:[...new Set(g.map(b=>b.item_id))].sort((b,R)=>b.localeCompare(R))}},warnings:x,gitWorkspaceRoot:u,pendingMergeReceipts:p}}function Fb(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function jb(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:Fb(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Ub(e,t){let n=Z(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function zb(e){let n=Z(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function Wb(e){return Z(e.reason)??Z(e.error)??Z(e.message)}function ha(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function qb(e){let t=[],n=[],r=[];e.forEach((o,a)=>{let s=Ub(o.definition,a),c=zb(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:s,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:s,status:c,reason:Wb(o.definition)});return}n.push({layer:o.layer,name:o.name,id:s,status:c})}),t.sort(ha),n.sort(ha),r.sort(ha);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 Cm(e,t,n,r,i,o,a,s,c){let d=[...new Set(e)].sort((g,w)=>g.localeCompare(w)),l=[...new Set(d.map(g=>ba(g)))].sort((g,w)=>g.localeCompare(w)),u=d.filter(g=>g.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=[],h=Yo(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${Qn.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(g=>g.startsWith("extension_capability_legacy_alias:"))&&p.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:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):a.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.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:a.length,unmanaged_loaded_extensions:a,unmanaged_expected_extension_count:s.length,unmanaged_expected_extensions:s,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function Bb(e,t,n){let r=await na(Pe(e)),i=await Ne({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),o=i.loaded.map(k=>jb(k)),a=await yd(i.loaded,Pe(e)),s=await Me({...i,loaded:i.loaded}),[c,d]=await Promise.all([he(i.roots.project),he(i.roots.global)]);await ta(e,s.registrations.migrations);let l=qb(s.registrations.migrations),u={failed:s.failed,warnings:s.warnings,hook_counts:s.hook_counts,command_override_count:s.command_override_count,command_handler_count:s.command_handler_count,parser_override_count:s.parser_override_count,preflight_override_count:s.preflight_override_count,service_override_count:s.service_override_count,renderer_override_count:s.renderer_override_count,registration_counts:s.registration_counts,registrations:s.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(k=>an(k.name))),f=new Set(d.state.entries.map(k=>an(k.name))),p=[...new Map(i.loaded.filter(k=>!(k.layer==="project"?m:f).has(an(k.name))).map(k=>[`${k.layer}:${k.name}`,{layer:k.layer,name:k.name,directory:k.directory}])).values()].sort((k,I)=>{let A=`${k.layer}:${k.name}`,j=`${I.layer}:${I.name}`;return A.localeCompare(j)}),h=p.map(k=>`${k.layer}:${k.name}`).sort((k,I)=>k.localeCompare(I)),g=p.filter(k=>_a(k.name,k.directory)).map(k=>`${k.layer}:${k.name}`).sort((k,I)=>k.localeCompare(I)),w=p.filter(k=>!_a(k.name,k.directory)).map(k=>`${k.layer}:${k.name}`).sort((k,I)=>k.localeCompare(I)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],x=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...a.warnings],S=Ln(x),b=Fn(),R=Cm(x,i.failed.length,s.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,g,w);return{check:{name:"extensions",status:x.length===0?"ok":"warn",ok:x.length===0,details:{...i,loaded:o,warnings:x,activation:u,author_manifest:r,triage:R,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:b,capability_guidance:S,host_version_census:a}},warnings:x}}function Hb(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function qe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function Gb(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 ui(e,t){let n=qe(e,t);return{...n,sample:n.sample.map(r=>Gb(r))}}function K(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 Jb(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 Vb={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:K(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:K(e.missing_required,t),missing_optional:K(e.missing_optional,t),missing:K(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:K(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:ui(e.discovered,t),effective:ui(e.effective,t),loaded:ui(e.loaded,t),failed:qe(e.failed,t),warnings:K(e.warnings,t),activation:{failed:qe(n.failed,t),warnings:K(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:Jb(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:qe(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:K(n.affected_item_ids,t),samples:qe(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:K(e.item_unreadable,t),item_conflict_markers:qe(e.item_conflict_markers,t),item_parse_failures:K(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:K(n.tracked_paths,t)},history_unreadable:K(e.history_unreadable,t),history_conflict_markers:qe(e.history_conflict_markers,t),history_invalid_json:qe(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>({checked_items:e.checked_items,counts:e.counts,drifted_items:K(e.drifted_items,t),merge_receipt_attributed_items:K(e.merge_receipt_attributed_items,t),missing_streams:K(e.missing_streams,t),unreadable_streams:K(e.unreadable_streams,t),hash_mismatches:K(e.hash_mismatches,t),chain_mismatches:K(e.chain_mismatches,t),workspace_state_mismatches:K(e.workspace_state_mismatches,t),workspace_state_missing:K(e.workspace_state_missing,t),workspace_state_unreadable:K(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:K(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:K(e.stale_items_after,t),skipped:e.skipped})};function Tm(e,t){let n=Vb[e.name];return n?n(e.details,t):e.details}function Kb(e){let t=K(e.warnings,on);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:Tm(n,on)})),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:on},generated_at:e.generated_at}}function Sm(e){return e.details.skipped===!0}function Yb(e){let t=K(e.warnings,on),n=e.checks.filter(Sm).map(r=>r.name);return{ok:e.ok,checks:e.checks.filter(r=>!Sm(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:on,omitted_checks:n},generated_at:e.generated_at}}function wa(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Hb(e,Em);return{values:n.values,truncated:n.truncated,total:e.length}}function rn(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Xb(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return Sb.has(e)?e:null}function mi(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 $m(e){let t=0,n=0,r=0,i=0,o=0;for(let a of e.split(`
41
+ `)){let s=a.trim();if(s.length!==0){r+=1;try{let c=JSON.parse(s);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>=Am&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:o}}function Zb(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Qb(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 ek(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await Om(n)}}function tk(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,a=o&&(!i||o>i),s=!i,c=t.validEntries>=Ib;return(a||s||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function nk(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function rk(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>zc?[`telemetry_schema_version_behind:${t}`]:[]}function ik(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 ok(){return{telemetry_disabled:rn("PM_TELEMETRY_DISABLED")||rn("PM_NO_TELEMETRY"),pm_no_telemetry:rn("PM_NO_TELEMETRY"),telemetry_otel_disabled:rn("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:rn("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:Xb()}}function ak(e,t){return e.telemetry.enabled&&t.validEntries>0}function sk(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Om(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(Rb)});return{probe_url:mi(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of Cb){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:mi(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function ck(e,t){let n=nr(process.cwd()),r=ge.join(n,Eb),i=ge.join(n,Ab),o=await Y(r),a=o!==null,s=o?Buffer.byteLength(o,"utf8"):0,c=o?$m(o):Zb(),d=await Y(i),{runtimeState:l,stateParseFailed:u}=Qb(d),m=e.telemetry.endpoint.trim(),f=mi(m),p=await ek(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...tk(e,c,l),...nk(p),...rk(p),...ik(e,l));let g=ak(e,c),w=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:f,global_pm_root:n,queue_path:r,queue_exists:a,queue_entries:c.validEntries,queue_draining:sk(g,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Am,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:ok()}},warnings:h}}async function dk(e){let t;try{t=await Jd(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 lk(e,t){let n="metadata",{missingStreams:r,unreadableStreams:i,hashMismatches:o,chainMismatches:a,driftedItems:s,workspaceStateMismatches:c,workspaceStateMissing:d,workspaceStateUnreadable:l}=await Kt(e,t,{cacheHitVerification:n}),u=[...r.map(m=>`history_drift_missing_stream:${m}`),...i.map(m=>`history_drift_unreadable_stream:${m}`),...o.map(m=>`history_drift_hash_mismatch:${m}`),...a.map(m=>`history_drift_chain_mismatch:${m}`),...c.map(m=>`history_drift_workspace_state_mismatch:${m}`),...d.map(m=>`history_drift_workspace_state_missing:${m}`),...l.map(m=>`history_drift_workspace_state_unreadable:${m}`)];return{check:{name:"history_drift",status:u.length===0?"ok":"warn",ok:u.length===0,details:{checked_items:t.length,cache_hit_verification:n,drifted_items:s,counts:{drifted:s.length,missing_streams:r.length,unreadable_streams:i.length,hash_mismatches:o.length,chain_mismatches:a.length,workspace_state_mismatches:c.length,workspace_state_missing:d.length,workspace_state_unreadable:l.length},missing_streams:r,unreadable_streams:i,hash_mismatches:o,chain_mismatches:a,workspace_state_mismatches:c,workspace_state_missing:d,workspace_state_unreadable:l}},warnings:u}}function uk(e,t){let n=Er(e),r=yn(n.settings),i=Ar(n.settings,t),o=r.active?vt(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(r.active&&i.active)}}function mk(){return{refreshed:[],skipped:[],warnings:[]}}async function pk(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?mk():jc(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function fk(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Wt(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function hk(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 gk(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Dm(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:Xi(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:Xi(r,e.vector_store?.adapter??null)}}function _k(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function yk(e,t,n){return e.enabled&&n.length>0&&t}async function wk(e,t,n,r,i){let o=uk(t,e),a=await qt(e),s=o.semanticRuntimeAvailable?eo(n,a.entries):[],c=await pk({pmRoot:e,snapshot:o,refreshPolicy:r,staleBefore:s}),d=await qt(e),l=o.semanticRuntimeAvailable?eo(n,d.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,m=fk({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:a,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),f=hk({ledgerBefore:a,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=wa(s,i),h=wa(l,i),g=yk(r,o.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.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:_k(r),...Dm(t,o),embedding_identity_changed:m,embedding_identity_before:a.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(a.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Em,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:g,refresh_skipped_reason:gk(r,o.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:f}}function vk(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 Pm(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new y("--check-only cannot be combined with --refresh-vectors",_.USAGE);if(n&&e.noRefresh===!0)throw new y("--no-refresh cannot be combined with --refresh-vectors",_.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var bk=new Set(["extensions","locks","search"]);function kk(e){let t=new Set(ps.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(fs));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of bk)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 xk(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:o}=kk(t),a=[],s=[],c=[];for(let d of[...r,...i]){let l=ge.join(e,d);c.push(...await Ge({path:l,scope:"project"})),!await ka(l)&&(o.has(d)?s.push(d):a.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:a,missingOptionalDirs:s,missingDirs:n?[...a,...s]:[...a],hookWarnings:c}}function Nm(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 Sk(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Je(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):zt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function ga(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function Ek(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 Ak(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 Rk(e){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e}}}var xa=e=>e.unknown_event_count??0,Sa=e=>e.actionable_unknown_event_count??xa(e);function Ik(e,t,n,r,i,o,a){let s=xa(r),c=Sa(r),d=s>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}:{},...a.length>0?{provenance_invalid_values:a}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Mm(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function Ck(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 Tk(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function $k(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 Lm(e){let t=new Map;for(let[i,o]of Object.entries(e.remediationSources))for(let a of o)t.has(a)||t.set(a,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let o=t.get(i)??"integrity",a=vo(i)?.code??ba(i),s=n.get(o)?.details,d=(typeof s?.remediation_map=="object"&&s.remediation_map!==null?s.remediation_map:{})[a],l=va(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:a,check:o,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function Ok(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&(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 Dk(e){for(let t of e.checks){let n=bo(e.remediationSources[t.name]);Ok({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function Pk(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(a=>typeof a=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(a=>Array.isArray(a)?a:[])),i=new Map;for(let a of e.pendingMergeReceipts){if(a.evidence_source!=="clone_local")continue;let s=i.get(a.item_id)??[];s.push(a),i.set(a.item_id,s)}let o=[];for(let a of n){if(r.has(a))continue;let s=i.get(a);if(!(!s||s.length===0))try{(await fa(a,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:s}},e.global)).merge_receipt_proof?.trusted&&o.push(a)}catch{}}return[...new Set(o)].sort((a,s)=>a.localeCompare(s))}function Nk(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 Fm(e,t,n){let r=e.warning_count??e.warnings.length,i={...e,warning_count:r,warning_limit:Wn,warnings_truncated:r>Wn,warnings:e.warnings.slice(0,Wn),findings:(e.findings??[]).filter(a=>e.warnings.slice(0,Wn).includes(a.warning)||e.failed_because.includes(a.warning))},o=n?Yb(i):t.brief===!0?Kb(i):i;return{...o,warning_count:r,warning_limit:Wn,warnings_truncated:r>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:r,warnings_truncated:r>o.warnings.length}}:{}}}async function jm(e,t={}){let n=L(process.cwd(),e.path);await Q(n);let r=yt(n),{settings:i,warnings:o}=await pc(n),a=[...new Set(o)],s=B(i,z()),c=t.strictDirectories===!0,d=Pm(t),l=await xk(n,s,c),u=vk(i),m=await ck(i,{checkTelemetry:t.checkTelemetry===!0}),f=await Bb(n,i,!!e.noExtensions),p=Nm(t),h=[],g=await Sk({pmRoot:n,settings:i,typeRegistry:s,skipPolicy:p,itemReadWarnings:h}),w=g,v=[...new Set(h)],x=p.skipDrift?{warnings:[]}:await fc({pmRoot:n,settings:i,itemIds:g.map(Pi=>Pi.id),commandLabel:"health"}),S=await Ob(n,i.history.compact_policy,await Tb(n)),b=await An(n,20,t.verboseAuthorEvents===!0),R=Sa(b),k=R>0?[`history_unknown_author_events:${R}`]:[],I=Mm(await Uc(n,g,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),A=await jd(n),j=A.outcomes,q=A.invalid_values,O=A.warnings,W=await dk(n),me=p.skipIntegrity?{...ga("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await Lb(n,s.type_to_folder,i.schema,t.requireMergeDrivers===!0,g),ue=p.skipDrift?ga("history_drift"):await lk(n,w),gt=await Pk({gitWorkspaceRoot:me.gitWorkspaceRoot,pendingMergeReceipts:me.pendingMergeReceipts,historyDriftCheck:ue,global:e});Nk(ue,gt);let rt=p.skipVectors?ga("vectorization"):await wk(n,i,w,d,t.verboseStaleItems===!0),_t=[Ek(r,i,a),Ak(l,c),Rk(u),m.check,f.check,Ik(g,i,S,b,I.scan,j,q),W.check,me.check,ue.check,rt.check],F=Ck({directoryState:l,normalizedSettingsReadWarnings:a,settingWarnings:u,normalizedItemReadWarnings:v,telemetryCheck:m,extensionCheck:f,historyPolicyWarnings:x.warnings,historySummary:S,authorAttributionWarnings:k,staleInProgressWarnings:I.warnings,provenanceWarnings:O,locksCheck:W,integrityCheck:me,historyDriftCheck:ue,vectorizationCheck:rt}),G=$k({directoryState:l,normalizedSettingsReadWarnings:a,settingWarnings:u,normalizedItemReadWarnings:v,telemetryCheck:m,extensionCheck:f,historyPolicyWarnings:x.warnings,historySummary:S,authorAttributionWarnings:k,staleInProgressWarnings:I.warnings,provenanceWarnings:O,locksCheck:W,integrityCheck:me,historyDriftCheck:ue,vectorizationCheck:rt});Dk({checks:_t,remediationSources:G,historyDriftedCount:Tk(ue),overThresholdCount:S.over_threshold.length});let Oi=F.filter(Pi=>!va(Pi,t.requireMergeDrivers===!0)),Di=Lm({warnings:F,checks:_t,remediationSources:G,requireMergeDrivers:t.requireMergeDrivers===!0}),Lf={ok:Oi.length===0,checks:_t,warnings:F,findings:Di,failed_because:Oi,generated_at:T()};return Fm(Lf,t,p.summaryMode)}var eP={buildHierarchyIntegrityWarnings:Im,buildExtensionHealthTriageSummary:Cm,buildHealthFindings:Lm,buildCapabilityContractMetadata:Fn,buildStaleInProgressHealthSummary:Mm,buildVectorizationProviderDetails:Dm,collectUnknownCapabilityGuidance:Ln,isAdvisoryHealthWarning:va,isDirectory:ka,isExpectedUnmanagedExtension:_a,listItemDocumentPaths:Rm,normalizeEndpointForDisplay:mi,normalizeExtensionNameForMatch:an,parseTelemetryQueue:$m,probeTelemetryEndpointHealth:Om,projectHealthResult:Fm,resolveActionableUnknownAuthorEventCount:Sa,resolveHealthSkipPolicy:Nm,resolveUnknownAuthorEventCount:xa,resolveVectorRefreshPolicy:Pm,selectStaleItemDetail:wa,summarizeHealthCheckDetails:Tm,summarizeExtensionList:ui,summarizeRecordList:qe,summarizeStringList:K,telemetryEnvFlagEnabled:rn,warningCode:ba};import sn from"node:fs/promises";import cn 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 Mk(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let o;try{o=await sn.readdir(cn.join(e,i))}catch{return}for(let a of o)for(let s of hn)if(a.toLowerCase().endsWith(s)){r.push({relativePath:`${i}/${a}`,id:a.slice(0,-s.length)});break}})),r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath))}function Lk(e,t){let{id:n,relativePath:r,liveItemIds:i,out:o}=e,a=Nt(t);if(a){o.conflictMarkers.push({id:n,path:r,line:a.line,detail:`unresolved merge conflict marker ${a.marker}`});return}let s=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");s=l}catch{o.unparseable.push({id:n,path:r,line:d.number,detail:"history line is not a valid JSON object"});return}s!==null&&(s.op==="delete"&&i.has(n)&&o.resurrected.push({id:n,deleted_at:typeof s.ts=="string"?s.ts:"",deleted_by:typeof s.author=="string"?s.author:""}),s.op==="history_repair"&&Array.isArray(s.patch)&&s.patch.length>0&&(o.repairReconciliations+=1))}function Ea(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function Fk(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await sn.readdir(cn.join(e,"history"))}catch{return n}for(let i of r.sort((o,a)=>o.localeCompare(a))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await sn.readFile(cn.join(e,"history",i),"utf8")}catch(a){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Ea("history stream",a)});continue}Lk({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},o)}return n}function Um(e){let t=Nt(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function jk(e){let t=[],n=0,r=null;try{r=await Y(yt(e))}catch(o){n+=1,t.push({path:"settings.json",detail:Ea("configuration file",o)})}if(r!==null){n+=1;let o=Um(r);o!==null&&t.push({path:"settings.json",detail:o})}let i;try{i=await sn.readdir(cn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of i.sort((a,s)=>a.localeCompare(s))){if(!o.endsWith(".json"))continue;n+=1;let a;try{a=await sn.readFile(cn.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:Ea("configuration file",c)});continue}let s=Um(a);s!==null&&t.push({path:`schema/${o}`,detail:s})}return{scanned:n,unparseable:t}}async function zm(e,t,n,r={}){let i=await Mk(e,n),o=new Set(i.map(u=>u.id)),a=new Map;for(let u of i){let m=a.get(u.id);m===void 0?a.set(u.id,[u.relativePath]):m.push(u.relativePath)}let s=[...a.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).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=cn.join(e,u.relativePath);return Mt(await sn.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 Fk(e,o),l=await jk(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:s,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 Uk}from"node:child_process";import Wm 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 qm(e,t){return new Promise((n,r)=>{Uk("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,o)=>{i?r(i):n(o)})})}function Bm(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 mP(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Bm(n),!n)throw new RangeError("Source line range must use start:end.");return n}function zk(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 Wk(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((a,s)=>a.localeCompare(s));n.set(i,o)}return n}async function qk(e){let t=Wm.relative(e.workspaceRoot,Wm.resolve(e.workspaceRoot,e.sourcePath)),n=await qm(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await qm(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:zk(n),commitItems:Wk(r),available:!0}}function Bk(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,a=o?i.target:i.source;if((e.visitedDepth.get(a)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(a,n);let s=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,a],kinds:[...e.current.kinds,o?i.kind:s.inverse??i.kind]};e.details.get(a)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function Hk(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let o=t.shift(),a=o.kinds.length;i!==void 0&&a>=i||a>=e.maxDepth||(i=Bk({current:o,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((o,a)=>o.nodes.join("\0").localeCompare(a.nodes.join("\0"))),r}function Gk(e,t,n){let r=Hc(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=Hk({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(s=>[s.id,s]))}),o=i[0];if(!o)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let a=[...new Set(i.map(s=>s.nodes.at(-1)))];return{status:a.length===1?"found":"ambiguous",nodes:o.nodes,kinds:o.kinds,alternative_decision_ids:a.slice(1)}}async function Jk(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await qk({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function Vk(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 Kk(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Hm(e){Bm(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 Jk(e),r=Kk(n),i=new Map;for(let o of e.candidates){let a=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(o.item.id)),s=a.reduce((l,[,u])=>l+u,0),c=Gk(o.item.id,e.corpus,t),d=Vk({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:s,decisionStatus:c.status});i.set(o.item.id,{score:s*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:s,evidence:[...o.files.map(l=>({kind:"linked_file",reference:l.path})),...a.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value: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 Ja from"node:fs/promises";import{realpathSync as dS}from"node:fs";import{execFile as lS}from"node:child_process";import _e from"node:path";import{promisify as uS}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 Yk=["metadata","resolution"],Aa=["metadata","resolution","estimates","lifecycle"],Xk="completed";function Ra(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Gm(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Jm(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Gm(n.close_reason)??Xk;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Ra(r)}`,gate:"resolution"})}return t}function Vm(e){let t=[];for(let n of e){let r=Gm(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 ${Ra(r)}`,gate:"metadata"})}return t}function Km(e,t){return e.map(n=>{let r=mc(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 Ym(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 Xm(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 ${Ra(n.path)}`})}return t}function Zm(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 y(`--fix-scope values must not be empty. Supported values: ${Aa.join(", ")}.`,_.USAGE);return new Set(Yk)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Aa.includes(i)){n.add(i);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${Aa.join(", ")}.`,_.USAGE)}return n}function Qm(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 qn(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 Zk=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function Qk(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=Zk.exec(n);if(!r)return null;let i=r[1],o=i.toUpperCase(),a=i.slice(0,i.lastIndexOf("-")),s=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 a===a.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||s.has(a.toUpperCase())||l?o:null}function ep(e){return typeof e=="string"&&e.trim().length>0}function tp(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||ep(i.duplicate_of))continue;let o=Qk(i.title,{...t,evidenceText:i.body});if(o===null)continue;let a=n.get(o);a||(a=[],n.set(o,a)),a.some(s=>s.id===i.id)||a.push({id:i.id,title:i.title,parent:ep(i.parent)?i.parent.trim():null})}let r=[];for(let[i,o]of n){if(o.length<2)continue;let a=new Set(o.map(d=>d.id.toLowerCase())),s=o.filter(d=>d.parent===null||!a.has(d.parent.toLowerCase()));if(s.length<2)continue;let c=[...s].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 np(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 a of[...i.keys()].sort((s,c)=>s.localeCompare(c)))o[a]=i.get(a);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 rp=3;function ip(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function op(e,t,n=rp){let r=Number.isFinite(n)&&n>=1?Math.floor(n):rp,i=new Map;for(let o of t){let a=ip(o);if(a.length===0)continue;let s=i.get(a);s?s.push(o):i.set(a,[o])}return e.map(o=>{let a=(i.get(ip(o))??[]).filter(s=>s!==o).sort((s,c)=>s.localeCompare(c));return a.length===0?{path:o,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:o,classification:"moved",candidates:a.slice(0,r),candidates_truncated:a.length>r}})}function ap(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 ex=/^[a-z][a-z0-9+.-]+:\/\//i;function Bn(e){return ex.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 tx(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function sp(e){return`${e.item_id} ${e.link_kind}`}function cp(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=tx(i.classification,r.classification),i.owners.set(sp(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[sp(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 a=t(o.item_id);return{id:o.item_id,type:a?.type??"Unknown",title:a?.title??"",status:a?.status??"",field:o.link_kind}}).sort((o,a)=>{let s=o.id.localeCompare(a.id);return s!==0?s:o.field.localeCompare(a.field)})}))}function nx(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function dp(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="${nx(r.title)}"`);return t}import rx from"node:fs/promises";import Ce from"node:path";import ix 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]="1832e2b3-0ece-523d-8f38-598303d3f590")}catch{}})();var ox=["path","scope","note"],ax=["pattern","glob","path","scope","note"],sx=["path"],cx=["from","to"],dx=new Set(["note","scope"]);function up(e){let t=e??"project";if(!Ni.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${Ni.join(", ")} (default: project).`,_.USAGE);return t}function Ca(e){if(e.startsWith("```")||e.includes(`
43
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf("=");return t>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(n=>n>=0&&n<t))?!1:e.includes("=")||Sc(e)}function lx(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Ca(n)||!n.includes(",")?[t]:Rr(n)})}function ux(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function mx(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Ca(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let o=e.slice(t+2,-1).trim();if(o.length>0&&ux(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 px(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let i=mx(r);if(i!==void 0)return[i]}return lx([n]).map(i=>{let o=i.trim(),a=Ca(o)?gn(i,"--add"):{path:o};if(_n(a,"--add",ox),!a.path)throw new y(`--add requires path=<value> or a bare ${t} path`,_.USAGE);return{path:a.path,scope:up(a.scope),note:a.note?.trim()||void 0}})}):[]}function fx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",_.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=gn(n,"--add-glob");_n(r,"--add-glob",ax);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new y("--add-glob key/value form requires pattern=<glob>",_.USAGE);return{pattern:i,scope:up(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function hx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",_.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=gn(n,"--remove"),i=Object.keys(r).filter(o=>dx.has(o.toLowerCase()));if(i.length>0)throw new y(`--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>".`,_.USAGE);if(_n(r,"--remove",sx),!r.path)throw new y("--remove key/value form requires path=<value>",_.USAGE);return r.path}return n}):[]}function gx(e){return e?e.map(t=>{let n=gn(t,"--migrate");_n(n,"--migrate",cx);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new y("--migrate requires from=<value> and to=<value>",_.USAGE);return{from:r,to:i}}):[]}function Hn(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 _x(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(o=>Hn(o.path,n))),i=[...new Set(t.map(o=>Hn(o,n)).filter(o=>r.has(o)))].sort((o,a)=>o.localeCompare(a));if(i.length!==0)throw new y(`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.`,_.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 tt(e){return e.split(Ce.sep).join("/")}function Ia(e,t,n=process.cwd()){let r=e.trim();if(Bn(r))return r;if(Ce.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return tt(r.replaceAll("\\",Ce.sep));let i=Ce.relative(t,n);return i.startsWith(`..${Ce.sep}`)||i===".."||Ce.isAbsolute(i)?tt(Ce.normalize(r)):tt(Ce.relative(t,Ce.resolve(n,r)))}async function yx(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){let o=Ce.isAbsolute(i.pattern),a=await ix(i.pattern,{cwd:n,absolute:o,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),s=[...new Set(a.map(c=>Ia(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of s)r.push({path:c,scope:i.scope,note:i.note})}return r}function wx(e,t,n){if(t===void 0)return e;if(!n)throw new y("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",_.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function vx(e){return`${e.path}::${e.scope}`}function Ta(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function $a(e){return[...new Map(e.map(t=>[vx(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function bx(e,t=process.cwd()){let n=[...new Set(e)].sort((s,c)=>s.localeCompare(c)),r=[],i=[],o=[],a=[];for(let s of n){if(Bn(s)){a.push(s.trim());continue}let c=Ce.isAbsolute(s)?s:Ce.resolve(t,s);try{(await rx.stat(c)).isFile()?r.push(s):o.push(s)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&it(d)){i.push(s);continue}o.push(s)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:o,remote_references:a}}function kx(e,t,n,r){let i=0;for(let a=0;a<e.length;a+=1){let s=Hn(e[a].path,r);s!==e[a].path&&(e[a]={...e[a],path:s},i+=1)}return{adds:t.map(a=>{let s=Hn(a.path,r);return s!==a.path&&(i+=1),{...a,path:s}}),removes:n.map(a=>Hn(a,r)),count:i}}function xx(e,t,n,r){for(let o of t)e.some(a=>a.path===o.path&&a.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=$a(e);return r?i:Ta(i)}async function lp(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths?await bx(t,e.workspaceRoot):void 0}}async function pi(e,t,n,r){let{metadataKey:i}=r,o=Rc(),a=L(process.cwd(),n.path),s=Pe(a),c=process.cwd();await Q(a);let d=await C(a),l=B(d,z()),u=await o.resolveList(t.add,"--add"),m=await o.resolveList(t.addGlob,"--add-glob"),f=await o.resolveList(t.remove,"--remove"),p=await o.resolveList(t.migrate,"--migrate"),h=px(u,r.bareNoun).map(q=>({...q,path:Ia(q.path,s,c)})),g=fx(m),w=await yx(g,s,c),v=wx([...h,...w],t.note,h.length>0||g.length>0),x=hx(f).map(q=>Ia(q,s,c)),S=gx(p);if(_x(v,x,S),!(v.length>0||x.length>0||S.length>0)){let q=await jt(a,e,d.id_prefix,d.item_format,l.type_to_folder);if(!q)throw new y(`Item ${e} not found`,_.NOT_FOUND);let W=(await st(q,{schema:d.schema})).document.metadata[i]??[];return lp({id:q.id,artifacts:W,changed:!1,options:t,workspaceRoot:s})}let R=J(t.author,d.author_default),k=await wt({pmRoot:a,settings:d,id:e,op:r.op,author:R,message:t.message,force:t.force,skipNoop:!0,mutate(q){let O=q.metadata,W=O[i]??[],me=[...W],ue=kx(me,v,x,S),gt=xx(me,ue.adds,ue.removes,r.supportsAppendStable&&t.appendStable===!0);gt.length>0?O[i]=gt:delete O[i];let rt=!Rs(W,gt);return{changedFields:rt?[i]:[],warnings:rt&&ue.count>0?[`path_migrations_applied:${ue.count}`]:[]}}}),I=k.item[i]??[],A=k.warnings.find(q=>q.startsWith("path_migrations_applied:")),j=A?Number(A.slice(24)):0;return lp({id:k.item.id,artifacts:I,changed:k.changedFields.includes(i),migrationsApplied:j,options:t,workspaceRoot:s})}function fi(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 mp(e,t,n){let r=await pi(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return fi(r,"docs")}import pp 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]="ed504f2b-8b78-5fca-a4a7-7b0709a65533")}catch{}})();var Sx=32768;function Oa(e){return tt(Te.normalize(e))}async function hi(e){try{return await pp.realpath(e)}catch{return Te.resolve(e)}}function dn(e,t){let n=Te.isAbsolute(e.path)?Te.resolve(e.path):Te.resolve(t,e.path);return`${Oa(n)}::${e.scope}`}function gi(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)=>gi(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))gi(i,t?`${t}.${r}`:r,n)}function Ex(e){let t=[];return gi(e.metadata,"metadata",t),gi(e.body,"body",t),t}function Ax(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 Rx(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,a=i.value.slice(0,Sx);for(let[s,c]of[[n,i.value],[r,a]]){s.lastIndex=0;for(let d of c.matchAll(s)){let l=Ax(d[0]);!l||o.has(l)||(o.add(l),t.push({field:i.field,value:l}))}}}return t}async function Ix(e,t,n=t){let r=Te.isAbsolute(e)?Te.resolve(e):Te.resolve(n,e),i;try{i=await pp.stat(r)}catch{return}if(!i.isFile())return;let[o,a]=await Promise.all([hi(t),hi(r)]);if(we(o,a)){let s=Te.relative(o,a);return!s||s.startsWith("..")||Te.isAbsolute(s)?void 0:{path:Oa(s),scope:"project"}}return{path:Oa(r),scope:"global"}}async function Cx(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>dn(c,t))),i=new Map,o=Rx(Ex(e)),a=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{a.set(c,await Ix(c,t,n))}));let s=o.map(c=>({reference:c,resolved:a.get(c.value)}));for(let{reference:c,resolved:d}of s){if(!d)continue;let l=dn(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 fp(e,t,n){let r=await pi(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return fi(r,"files")}async function Tx(e,t){let n=await hi(t),r=await Promise.all(e.map(async o=>{let a=o.trim();if(!a)throw new y("Files lookup paths must not be empty.",_.USAGE);if(!Te.isAbsolute(a))return tt(a);let s=await hi(a);return we(n,s)?tt(Te.relative(n,s)):tt(s)})),i=[...new Set(r)].sort((o,a)=>o.localeCompare(a));if(i.length===0)throw new y("Files lookup requires at least one path.",_.USAGE);return i}function $x(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new y(`Files lookup ${r} must be a non-negative integer.`,_.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 hp(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function gp(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 Ox(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(tt(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(gp)}async function Dx(e){if(e.explain)return Hm({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 Px(e){if([e.strictRead,e.noTruncate,e.explain,Qs()].includes(!0))return null;let t=await kr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?gc({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function Nx(e){let t=[],n=await Ut(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=Ox({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 y(`Files lookup could not read every item: ${i.join("; ")}`,_.GENERIC_FAILURE);let o=await Dx({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),s=(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:gp(c,d)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:s.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+s.length<r.length,truncated:e.offset+s.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:s.map(c=>({item:hp(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=L(process.cwd(),t.path),r=Pe(n);await Q(n);let i=await Tx(e.paths,r);if(e.lineRange&&i.length!==1)throw new y("Files lookup line attribution requires exactly one source path.",_.USAGE);let o=await C(n),a=B(o,z()),{offset:s,limit:c}=$x(e),d=await Px({pmRoot:n,typeToFolder:a.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,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:s,limit:c,has_more:s+d.matches.length<d.total,truncated:s+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:hp(l.item),files:l.files}))}:Nx({pmRoot:n,settings:o,typeToFolder:a.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function sN(e,t,n){let r=L(process.cwd(),n.path),i=Pe(r);await Q(r);let o=await C(r),a=B(o,z()),s=await jt(r,e,o.id_prefix,o.item_format,a.type_to_folder);if(!s)throw new y(`Item ${e} not found`,_.NOT_FOUND);let c=await st(s,{schema:o.schema}),d=await Cx(c.document,i,process.cwd()),l=d.filter(I=>I.status==="addable"),u=d.filter(I=>I.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let I=c.document.metadata.files??[];return{id:s.id,files:I,changed:!1,apply:m,count:I.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let p=J(t.author,o.author_default),h=l.map(I=>({path:I.path,scope:I.scope,note:f})),g=[],w=new Set,v=await wt({pmRoot:r,settings:o,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(I){let A=[...I.metadata.files??[]],j=new Set(A.map(W=>dn(W,i)));g=[],w.clear();for(let[W,me]of h.entries()){let ue=dn(me,i);j.has(ue)||(A.push(me),j.add(ue),g.push(me),w.add(W))}let q=$a(A),O=t.appendStable?q:Ta(q);return O.length>0?I.metadata.files=O:delete I.metadata.files,{changedFields:g.length>0?["files"]:[],warnings:g.length!==h.length?[`files_discover_skipped_existing:${h.length-g.length}`]:[]}}}),x=v.item.files??[],S=new Set(g.map(I=>dn(I,i))),b=x.filter(I=>S.has(dn(I,i))),R=l.filter((I,A)=>!w.has(A)),k=[...u,...R];return{id:v.item.id,files:x,changed:b.length>0,apply:!0,count:x.length,candidate_count:d.length,addable_count:l.length,added_count:b.length,skipped_existing_count:k.length,candidates:d,added:b,skipped_existing:k}}import{readFileSync as Mx}from"node:fs";import _i 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 Lx=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Da=new Set(["--pm-path","--path","--author"]),Fx={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"])},jx=new Set(["-p","--package"]),Ux=new Set(["-c","--call"]),zx=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Wx=new Set(["-C","--prefix","--userconfig","--cache"]),uN=new Set(["--cwd"]),mN=new Set(["--cwd"]),qx=new Set(["exec","x"]),pN=new Set(["run","run-script"]),fN=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Bx(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function Hx(e,t=process.cwd()){let n=Gx(e.split(" ").filter(a=>a.length>0));if(n.length===0)return null;let[r,...i]=n;if(_p(r)||yp(r,t))return i;if(r==="node"&&i[0]&&yp(i[0],t))return i.slice(1);let o=r==="npx"||r==="bunx"?Pa(i):r==="pnpm"?Kx(i):r==="npm"?Yx(i):null;return o&&(_p(o.command)||Vx(o.command))?o.args:null}var wp=(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(),a=new Set;for(let s of Bx(o)){let c=Hx(s),d=c?Xx(c):null,l=d&&Lx.has(d.subcommand)?Zx(d.remaining,Fx[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&a.add(l)}return[...a].sort((s,c)=>s.localeCompare(c))};function Gx(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 hN(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Da.has(n)){t+=2;continue}t+=1;continue}return n}}function _p(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function Jx(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 Vx(e){let t=Jx(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function yp(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=_i.resolve(t,e);try{return JSON.parse(Mx(_i.join(_i.dirname(_i.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Pa(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(Ux.has(r)){t+=1;break}t+=jx.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function vp(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 Kx(e){let t=vp(e,zx);return t?.subcommand!=="dlx"?null:Pa(t.args)}function Yx(e){let t=vp(e,Wx);return!t||!qx.has(t.subcommand)?null:Pa(t.args)}function Xx(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Da.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Zx(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("=")&&(Da.has(r)||t.has(r))&&(n+=1)}}import{execFile as Qx}from"node:child_process";import{readFile as eS}from"node:fs/promises";import kp from"node:path";import{promisify as tS}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 nS=tS(Qx),Na=1,rS="linked-test-trust.json";function Ma(e){return kp.join(bs(e),rS)}function bp(){return{version:Na,acknowledged:{}}}async function La(e){try{let t=JSON.parse(await eS(Ma(e),"utf8"));return t.version!==Na||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?bp():{version:Na,acknowledged:t.acknowledged}}catch{return bp()}}async function Fa(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 nS("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 ja(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function iS(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&ec(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Gn(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function oS(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 EN(e,t,n){if(!e||e.length===0)return e;let r=ja();return oS(e,t,n,await Fa(r))}function xp(e){return ot(X({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 AN(e,t,n){let r=await La(e);return Sp(t,n,r)}function Sp(e,t,n){let r=xp(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||!iS(e.provenance)?o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Gn(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...Gn(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...Gn(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",...Gn(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...Gn(i,t)}}async function Ep(e,t,n){let r=await La(e);return t.map(i=>Sp(i,n,r))}async function RN(e,t,n){let r=await La(e),i=t.filter(o=>typeof o.command=="string"&&o.command.length>0).map(xp);for(let o of i)r.acknowledged[o]={acknowledged_at:n};return await fn(kp.dirname(Ma(e))),await se(Ma(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 Ap(e){return e.includeBody?zt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Ut(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1261d65-222c-5c6c-8634-a4413a91aba9")}catch{}})();var aS=5;async function Rp(e,t,n){let r=await Kt(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_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),a=n?Number.POSITIVE_INFINITY:aS,s=r.driftedItems.slice(0,a);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:s,drifted_items_truncated:s.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable}},warnings: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 yi(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],o=new Set([n]),a=s=>{for(let c of(t.get(s)??[]).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),a(c))return!0;i.pop(),o.delete(c)}}return!1};return a(n)?[...i]:[...e,n]}function sS(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function cS(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 a=n.get(i.id.toLowerCase());a&&(o.hierarchyDirection==="source_parent"?t.get(a).push(e.id):t.get(e.id).push(a))}}function Ua(e,t=wn()){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,a)=>o.id.localeCompare(a.id))){let o=r.get(i.id),a=sS(i.parent,n);a&&o.push(a),cS(i,r,n,t)}for(let[i,o]of r)r.set(i,[...new Set(o)].sort());return r}function za(e,t,n=wn()){let r=Ir(e,a=>t?Ws(a,t):a==="closed"||a==="canceled",n),i=Ua(e,n),o=r.cycles.map(a=>a.item_ids);return{cycle_count:o.length,active_cycle_count:r.cycles.filter(a=>!a.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(a=>a.legacy_terminal).length,cycle_item_ids:[...new Set(o.flat())].sort(),cycle_sample_paths:o.map(a=>yi(a,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(a=>!a.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(a=>a.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(a=>`${a.child_id}:${a.parent_ids.join(",")}:${a.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(a=>!a.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(a=>a.legacy_terminal).length,parent_divergence_rows:r.divergences.map(a=>`${a.child_id}:scalar=${a.scalar_parent_id}:dependencies=${a.dependency_parent_ids.join(",")}:${a.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7a231e7-0546-5d5f-b0c8-59629ad4d731")}catch{}})();var mS=["src","tests","docs"],pS=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],fS=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),hS=["resolution","expected_result","actual_result"],gS=["default","tracked-all","tracked-all-strict"],Ip=["core","strict","custom"],bi=["off","warn","error"],Ba=["author","acceptance_criteria","estimated_minutes","close_reason"],Op=[...Ba,"reviewer","risk","confidence","sprint","release"],Va=Array.from(new Set(Op)),_S={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"},yS={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"},wS={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"},vS={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"},bS={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"},kS=32*1024*1024,xS=1e4,Dp=40,ht=5,SS=4096,ES=255,AS=uS(lS);function Pp(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?Pp(r):r);return t}function RS(e){return{...e,checks:e.checks.map(t=>({...t,details:Pp(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 It(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Cp(e){return It(e).replace(/\/+$/,"")}function Be(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 xi(e,t){return nc(e,t)??e}function Jn(e,t){return t.terminal_statuses.has(xi(e,t))}function pt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function wi(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function IS(e){let t=pt(hs),n={blocked_reason:pt(tr.blocked_reason),resolution:pt(tr.resolution),actual_result:pt(tr.actual_result)},r=pt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:pt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:pt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:pt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:wi(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:wi(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:wi(i.resolution,n.resolution)?"default":"settings",actual_result:wi(i.actual_result,n.actual_result)?"default":"settings"}}}function Np(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Ip.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${Ip.join(", ")}.`,_.USAGE)}function Mp(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(bi.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${bi.join(", ")}.`,_.USAGE)}function Lp(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(bi.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${bi.join(", ")}.`,_.USAGE)}function CS(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>_S[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function TS(e,t,n){let r=CS(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Ba],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Op],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:[...Ba],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var $S=new Set(["acceptance_criteria","estimated_minutes"]);function Fp(e,t,n,r){return!r&&$S.has(t)&&Jn(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"?xi(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 y(`Unknown --scan-mode value "${e}". Supported values: ${gS.join(", ")}.`,_.USAGE)}function Up(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return _e.resolve(t);let n=_e.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return _e.dirname(_e.dirname(n));let i=_e.resolve(process.cwd()),o=Tp(n),a=Tp(i),s=_e.relative(o,a);return s.length===0||!s.startsWith("..")&&!_e.isAbsolute(s)?n:i}function Tp(e){try{return dS.native(e)}catch{return _e.resolve(e)}}function OS(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Ka(e,t,n){let r=t.length>0?_e.join(e,t):e,i;try{i=await Ja.readdir(r,{withFileTypes:!0})}catch(o){if(U(o))return;throw o}for(let o of i){if(o.name.startsWith("."))continue;let a=t.length>0?_e.join(t,o.name):o.name;if(o.isDirectory()){if(fS.has(o.name))continue;await Ka(e,a,n);continue}o.isFile()&&n.push(It(a))}}async function Ha(e){let t=[];for(let n of mS)await Ka(e,n,t);for(let n of pS){let r=_e.join(e,n);try{(await Ja.stat(r)).isFile()&&t.push(It(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function zp(e){try{let{stdout:t}=await AS("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:kS,windowsHide:!0,timeout:xS}),n=t.split("\0").map(r=>It(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function DS(e,t){let n=new Set,r=Cp(ms);r.length>0&&n.add(r);let i=Cp(_e.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((o,a)=>o.localeCompare(a))}function $p(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function PS(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await zp(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Ha(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Ha(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function te(e,t=ht){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function ft(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=te(e,Dp);return{values:n.values,truncated:n.truncated,total:e.length}}var NS={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},MS={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function LS(e){let t=e.missing_fields.map(n=>`${NS[n]} "${MS[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Wp(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(a=>typeof a=="string"):Kd(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 FS="validate_metadata_duplicate_issue_codes";function Bp(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:ht,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:[`${FS}:${e.length}`]}}function jS(){return Object.fromEntries(Va.map(e=>[e,[]]))}function US(e,t,n){let r=jS();for(let i of e)for(let o of Va)Fp(i,o,t,n)&&r[o].push(i.id);return r}function zS(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let o=t[i];o.length>0&&r.push(`${yS[i]}:${o.length}`)}return r.push(...n),r}function Hp(e,t){let n={};for(let r of e.required_fields){let i=t[r],o=i?i.length:0,a=wS[r];n[a]=o}return n}function Gp(e,t,n){let r=[];for(let i of e.required_fields){let o=t[i];if(o)for(let a of o){let s=n.get(a)?.type,c=typeof s=="string"&&s.length>0?s:"Unknown";r.push({item_type:c,field:i})}}return r}function WS(e,t,n,r){for(let i of t.required_fields){let o=n[i];if(!o||o.length===0)continue;let a=vS[i],s=bS[i];if(!a||!s)continue;let c=te(o,r?o.length:ht);e[a]=c.values,e[s]=c.truncated}}function Jp(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 Vp(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 qS(e,t,n,r,i){let o=new Map(e.map(w=>[w.id,w])),a=t.profile==="strict",s=US(e,n,a),c=tp(e,{configuredPrefixes:i}),d=Bp(c,r),l=zS(t,s,d.warnings),u=Hp(t,s),m=Gp(t,s,o),f=np(m),p={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:[...Va],counts:u,missing_by_type:f,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(p.configured_custom_required_fields=[...t.configured_custom_fields]),WS(p,t,s,r);let h=Jp(t,s,o),g=Vp(t,s,o);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:p},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:g}}function BS(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(xi(m.status,t))),o=[],a=[];for(let m of i){let f=hS.filter(p=>!Z(m[p]));f.length!==0&&(o.push({id:m.id,missing_fields:f}),a.push({id:m.id,missing_fields:f,close_reason:Z(m.close_reason)}))}let s=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:ht,d=te(o.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=o.map(m=>LS(m)),u=te(l,c);return{check:{name:"resolution",status:s.length===0?"ok":"warn",ok:s.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:s,resolutionBackfillRows:a}}function Kp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yp(e,t="pm",n=Ss()){let r=new Set(e.map(o=>o.id)),i=[...e].sort((o,a)=>o.id.localeCompare(a.id));return new Map(i.map(o=>{let a=new Set,s=Be(o.blocked_by);s&&r.has(s)&&a.add(s),(o.dependencies??[]).filter(d=>{let l=Be(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Be(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>a.add(d));let c=Be(o.definition_of_ready);return Zp(c??"",t).filter(d=>r.has(d)).forEach(d=>a.add(d)),[o.id,[...a].sort((d,l)=>d.localeCompare(l))]}))}function Xp(e,t,n){let r=Bc(e,n?l=>Jn(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}`),a=t?Number.POSITIVE_INFINITY:ht,s=te(i,a),c=te(o,a),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>'`),a);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+o.length,active_dangling_reference_count:i.length,dangling_reference_rows:s.values,dangling_reference_rows_truncated:s.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 Zp(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${Kp(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 Qp(e){let t=0,n=new Map,r=new Map,i=[],o=new Set,a=[],s=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))):(s(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,f)=>m.localeCompare(f)),a.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||s(l);return a.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function ef(e,t="pm"){let n=Yp(e,t),r=Qp(n),i=[...new Set(r.flat())].sort((a,s)=>a.localeCompare(s)),o=r.map(a=>yi(a,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:o}}function tf(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 ki(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function nf(e,t){let n=ki(e).split("/").filter(Boolean),r=ki(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function HS(e,t){let n=ki(t),r=ki(e),i=t.endsWith("/")?t:`${t}/`,o=e.startsWith(i),a=n.length>0&&n===r,s=nf(e,t);return!o&&!a&&s===0?null:o?{score:t.length+1e3,confidence:"path_prefix"}:a?{score:s+500,confidence:"same_directory"}:{score:s,confidence:"shared_directory"}}function GS(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function JS(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(o=>(r==="docs"?o.docs??[]:o.files??[]).map(a=>({item:o,link:a}))).forEach(({item:o,link:a})=>{if(a.scope!=="project")return;let s=It(a.path);if(s.length===0||s===e)return;let c=HS(e,s);c!==null&&GS(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 rf(e,t){return e.map(n=>{let r=tf(n),i=r==="docs_unowned"?"docs":"files",o=JS(n,r,t),a=o?.id??"<id>";return{path:n,classification:r,owner_candidate:o,remediation_hint:`pm ${i} ${a} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function of(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function VS(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Be(e[n]);return i?r.some(o=>i.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function KS(e,t,n,r,i){let o=Be(t.parent),a=o?n.get(r.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:a?.id,grandparent_active:a!==void 0&&!Jn(a.status,i)}}function YS(e,t,n,r){let i=Be(e.blocked_by),o=Be(e.blocked_reason),a=o?.toLowerCase(),s=xi(e.status,n),c=[];return t.has(s)?(!i&&!o&&c.push("blocked_status_missing_blocker_context"),a?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),a&&r.stale_blocker_reason_patterns.some(d=>a.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function XS(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])),a=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),s={activeItems:e.filter(c=>!Jn(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of s.activeItems){let d=VS(c,r);d.length>0&&s.closureLikeRows.push({id:c.id,fields:d});let l=Be(c.parent),u=l?i.get(o.get(l.toLowerCase())??l):void 0;if(u&&Jn(u.status,n)&&(s.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),s.terminalParentFixRows.push(KS(c,u,i,o,n))),t){let m=YS(c,a,n,r);m.length>0&&s.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,p)=>f.localeCompare(p))})}}return s}function ZS(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 vi(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Wa(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function QS(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 a=vi("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),s=vi("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=vi("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=vi("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=Wa("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=Wa("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=Wa("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...o,...a?[a]:[],...s?[s]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function af(e){let t=It(e);return t.length>SS||t.split(/[\\/]/).some(n=>n.length>ES)}async function eE(e,t){let n=_e.isAbsolute(t)?t:_e.resolve(e,t);if(af(n))return!1;try{let r=await Ja.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return OS(r,["ENOENT","ENOTDIR"])}}async function tE(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:a}of r){if(o.scope!=="project")continue;if(Bn(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let s=It(o.path);s.length!==0&&(n.linkedProjectPaths.add(s),await eE(t,o.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:i.id,path:s,link_kind:a})))}return n}function nE(e,t,n,r,i,o){let a=r==="tracked-all-strict",s=a&&!i,c=i||a,d=c?[]:DS(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>$p(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!$p(f,d)),m={};if(l.length>0){let f=ft(l,o);m.pm_internals={count:l.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:a,strictModeForcesPmInternals:s,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function sf(e,t,n,r,i,o,a,s="pm"){let c=XS(e,t,i,o);ZS(c);let d=ef(c.activeItems,s),l=za(e,i),u=QS(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),m=a?Number.POSITIVE_INFINITY:ht,f=te(c.closureLikeRows.map(k=>`${k.id}:${k.fields.join(",")}`),m),p=te(c.terminalParentRows.map(k=>`${k.id}:${k.parent_id}:${k.parent_status}`),m),h=te(c.staleBlockerRows.map(k=>`${k.id}:${k.status}:${k.reasons.join(",")}`),m),g=te(d.cycle_item_ids,m),w=te(d.cycle_sample_paths,m),v=te(l.cycle_item_ids,m),x=te(l.cycle_sample_paths,m),S=te(l.cardinality_violation_rows,m),b=te(l.parent_divergence_rows,m),R=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:R?"error":u.length===0?"ok":"warn",ok:!R&&u.length===0,details:{checked_active_items:c.activeItems.length,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:p.values,active_terminal_parent_rows_truncated:p.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:h.values,stale_blocker_rows_truncated:h.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:g.values,dependency_cycle_item_ids_truncated:g.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:v.values,parent_cycle_item_ids_truncated:v.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:b.values,hierarchy_parent_divergence_rows_truncated:b.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:u,terminalParentFixRows:c.terminalParentFixRows}}async function cf(e,t,n,r,i,o){let a=await tE(e,t),s=new Map(e.map(O=>[O.id,O])),c=[...new Set(a.missingLinkedPaths)].sort((O,W)=>O.localeCompare(W)),d=await PS(t,r),l=nE(d,n,t,r,i,o),u=l.candidateFiles.filter(O=>!a.linkedProjectPaths.has(O)),m=rf(u,e),f=op(c,l.candidateFiles),p=new Map(f.map(O=>[O.path,O.classification])),h=f.filter(O=>O.classification==="moved").length,g=a.staleLinkRows.map(O=>({...O,classification:p.get(O.path)??"deleted"})).sort((O,W)=>O.item_id.localeCompare(W.item_id)||O.path.localeCompare(W.path)||O.link_kind.localeCompare(W.link_kind)),w=[];l.strictModeForcesPmInternals&&w.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&w.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&w.push(`validate_files_orphaned_paths:${u.length}`);let v=[...a.remoteLinkedPaths].sort((O,W)=>O.localeCompare(W)),x=ft(v,o),S=ft(c,o),b=ft(u,o),R=ft(m.map(O=>`${O.path}:${O.classification}:owner_candidate=${O.owner_candidate?.id??"unowned"}`),o),k=o?m:ft(of(m),!1).values,I=ft(ap(f),o),A=g.map(O=>({item_id:O.item_id,path:O.path,link_kind:O.link_kind,classification:O.classification})),j=cp(A,O=>{let W=s.get(O);return W?{type:W.type,title:W.title,status:W.status}:void 0}),q=o?j:ft(dp(j),!1).values;return{check:{name:"files",status:w.length===0?"ok":"warn",ok:w.length===0,details:{workspace_root:t,scan_mode_requested:d.requestedMode,scan_mode_applied:d.appliedMode,strict_tracked_all_mode:l.strictTrackedAllMode,strict_mode_forces_pm_internals:l.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:l.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:o?"full":"summary",file_list_summary_limit:Dp,candidate_scan_source:d.source,include_pm_internals:l.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:l.pmInternalCandidatePrefixes,pm_internal_excluded_count:l.excludedPmInternalPaths.length,excluded_total:l.excludedPmInternalPaths.length,excluded_by_reason:l.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:x.total,remote_linked_paths:x.values,remote_linked_paths_truncated:x.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:S.total,missing_linked_paths:S.values,missing_linked_paths_truncated:S.truncated,missing_linked_paths_moved_count:h,missing_linked_paths_deleted_count:c.length-h,missing_linked_path_classifications:I.values,missing_linked_path_classifications_truncated:I.truncated,missing_linked_path_rows_count:j.length,missing_linked_path_rows:q,orphaned_paths_count:u.length,orphaned_paths_total:b.total,orphaned_paths:b.values,orphaned_paths_truncated:b.truncated,orphaned_path_classifications:R.values,orphaned_path_classifications_truncated:R.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:k}},warnings:w,staleLinkPruneRows:g}}function df(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function rE(e,t,n){return`${e}:${t}:${df(n)}`}function iE(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},o)=>{let a=t[o];if(a.trusted)return;let s=df(i.command??"");n.push(`${r.id}:${a.source_ref??"unknown"}->${a.current_source_ref??"unknown"}:${s}`)}),n}async function lf(e,t,n,r){let i=new Set(e.map(b=>b.id.toLowerCase())),o=0,a=0,s=new Set,c=[],d=e.flatMap(b=>(b.tests??[]).map(R=>({item:b,linkedTest:R}))),l=await Fa(ja()),u=await Ep(r,d.map(({linkedTest:b})=>b),l),m=iE(d,u);for(let{item:b,linkedTest:R}of d){if(typeof R.command!="string"||R.command.trim().length===0)continue;o+=1;let k=wp(R.command,t);if(k.length!==0){a+=k.length;for(let I of k)s.add(I),i.has(I.toLowerCase())||c.push(rE(b.id,I,R.command))}}let f=[...new Set(c)].sort((b,R)=>b.localeCompare(R)),p=[...new Set(f.map(b=>b.split(":")[1]??""))].filter(b=>b.length>0).sort((b,R)=>b.localeCompare(R)),h=[];f.length>0&&h.push(`validate_command_references_stale_pm_ids:${f.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let g=n?Number.POSITIVE_INFINITY:ht,w=te(f,g),v=te(p,g),x=te([...s].sort((b,R)=>b.localeCompare(R)),g),S=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:a,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:x.values,unique_referenced_pm_ids_truncated:x.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:S.values,untrusted_linked_tests_truncated:S.truncated,stale_pm_id_references_count:f.length,stale_pm_ids_count:p.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:h}}function oE(e,t){let n=hr(e.map(c=>({ref:c.id,version:fr(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:ht,o=te(n.outdated,i),a=te(n.ahead,i),s=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:s,ok:s==="ok",details:{checked_items:e.length,current_format_version:tc,outdated_items_count:n.outdated.length,outdated_items:o.values,outdated_items_truncated:o.truncated,ahead_items_count:n.ahead.length,ahead_items:a.values,ahead_items_truncated:a.truncated}},warnings:r}}var Ga="pm validate auto-fix";async function uf(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Ga};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 y("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",_.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 qa(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function mf(e,t,n){let r=[],i=[],o=new Map;for(let a of e.filter(s=>qa(s)===null))try{await uf(a,t,n),r.push(a)}catch(s){i.push({fix:a,error:s})}for(let a of e.filter(s=>qa(s)!==null)){let s=qa(a),c=o.get(s);c?c.push(a):o.set(s,[a])}for(let a of o.values()){let s=a[0];if(!s)continue;let c=a.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{s.kind==="prune_file_link"?await fp(s.item_id,{remove:c,message:Ga},t):await mp(s.item_id,{remove:c,message:Ga},t),r.push(...a)}catch(d){i.push(...a.map(l=>({fix:l,error:d})))}}return{applied:r,failed:i}}var SM={applyValidateFix:uf,applyValidateFixes:mf,attachValidateFixHints:Wp,buildCommandReferencesCheck:lf,buildDependencyReferencesCheck:Xp,buildCloseReasonBackfillRows:Jp,buildFilesCheck:cf,buildLifecycleCheck:sf,buildLifecycleDependencyGraph:Yp,buildLifecycleParentGraph:Ua,buildEstimateBackfillRows:Vp,buildMetadataCounts:Hp,buildMissingFieldOccurrences:Gp,buildOrphanedPathRows:rf,classifyOrphanedPath:tf,collectDefaultProjectFileCandidates:Ha,collectTrackedGitFileCandidates:zp,detectLifecycleDependencyCycles:ef,detectLifecycleParentCycles:za,escapeRegExp:Kp,extractItemIds:Zp,findLifecycleDependencyCycleComponents:Qp,isMetadataFieldMissing:Fp,linkedArtifactPathExceedsFilesystemLimits:af,listFilesRecursive:Ka,resolveDependencyCycleSeverity:Mp,resolveParentCycleSeverity:Lp,resolveFileScanMode:jp,resolveLifecycleDependencyCycleSamplePath:yi,resolveRequestedChecks:qp,resolveValidateMetadataProfile:Np,resolveWorkspaceRoot:Up,sharedDirectoryPrefixLength:nf,summarizeOrphanedPathRows:of,summarizeDuplicateIssueCodes:Bp,toMeaningfulString:Be};function aE(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function sE(e,t,n,r){let i=await zm(e,new Set(t.map(g=>g.id)),n,{schema:r.schema,extensionFieldNames:Ct(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 a=o.length,s=await si(e);s.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${s.tracked_path_count}`);let c=await ll(e,qr(r));c.status==="drift"&&o.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await kt(e),l=d===null?null:await Br(d);l!==null&&l.status!=="ok"&&o.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await zn(d??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:f,lossless:p}=li(m);f.length>0&&o.push(`validate_merge_decisions_unreviewed:${f.length}`),aE(o,u.invalid_evidence_count);let h=a>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:f.length,pending_merge_decision_items:[...new Set(f.map(g=>g.item_id))].sort((g,w)=>g.localeCompare(w)),lossless_merge_receipt_count:p.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,lossless_merge_receipt_items:[...new Set(p.map(g=>g.item_id))].sort((g,w)=>g.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:s.tracker_relative_root,tracked_paths:s.tracked_paths,tracked_path_count:s.tracked_path_count,remediation_command:s.remediation_command}}},warnings:o}}function nt(e,t,n){n&&Wp(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function cE(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=qS(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,nt(t,i,n)}if(e.requestedChecks.has("resolution")){let i=BS(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,nt(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=sf(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,nt(t,i,n),nt(t,Xp(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await cf(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=i.staleLinkPruneRows,nt(t,i,n)}return e.requestedChecks.has("command_references")&&nt(t,await lf(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&nt(t,await Rp(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&nt(t,oE(e.items,r),n),e.requestedChecks.has("storage_integrity")&&nt(t,await sE(e.pmRoot,e.items,B(e.settings,z()).type_to_folder,e.settings),n),t}function dE(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...Vm(t.closeReasonBackfillRows)),r.push(...Jm(t.resolutionBackfillRows)),r.push(...Km(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Ym(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Xm(t.staleLinkPruneRows)),r}async function lE(e,t,n,r,i,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let a=dE(e,t,n),{applicable:s,gated:c}=Qm(a,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await mf(s,i,o);l.push(...m.applied.map(qn)),u.push(...m.failed.map(({fix:f,error:p})=>({...qn(f),error:p instanceof Error?p.message:String(p)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,f)=>m.localeCompare(f)),planned_count:a.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:a.map(qn),applied_fixes:l,gated_fixes:c.map(m=>({...qn(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function pf(e,t,n={}){Ys(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new y("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",_.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new y("--fix-scope requires --auto-fix.",_.USAGE);let i=Zm(e.fixScope),o=L(process.cwd(),t.path);await Q(o);let a=await C(o),s=$e(a.schema),c=B(a,z()),d=qp(e),l=[],u=await Ap({includeBody:d.has("history_drift")||d.has("metadata"),pmRoot:o,settings:a,typeToFolder:c.type_to_folder,warnings:l});if(d.has("history_drift")){let A=await An(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",f=Np(typeof e.metadataProfile=="string"?e.metadataProfile:a.validation.metadata_profile),p=TS(f,m,a.validation.metadata_required_fields),h=IS(a),g=Mp(e.dependencyCycleSeverity),w=Lp(e.parentCycleSeverity),v=jp(e.scanMode),x=Up(o),S=await cE({requestedChecks:d,options:e,global:t,pmRoot:o,workspaceRoot:x,settings:a,items:u,statusRegistry:s,metadataPolicy:p,lifecyclePatternPolicy:h,dependencyCycleSeverity:g,parentCycleSeverity:w,fileScanMode:v,initialWarnings:[...new Set(l)]}),b=r?await lE(e,S,a,i,t,n):void 0,R=[...new Set(S.warnings)].sort((A,j)=>A.localeCompare(j)),I={ok:!S.checks.some(A=>A.status==="error"),has_warnings:R.length>0,checks:S.checks,warnings:R,...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?I:{...RS(I),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as uE}from"node:child_process";import{promisify as mE}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 pE=mE(uE),fE=16,hE=3e4;function gE(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 _E(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(([,a])=>a.required===!0).map(([a])=>a))if(!Object.hasOwn(r,o))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${o}`);for(let[o,a]of Object.entries(r)){let s=i[o];if(!s)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${o}`);if(a===null||typeof a!==s.type)throw new TypeError(`assurance provider ${e.id} parameter ${o} must be ${s.type}`)}return{...r}}async function yE(e,t,n,r){let i=_E(e,t),o=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Zs(n)}));o.catch(()=>{});let a;try{let s=await Promise.race([o,new Promise((c,d)=>{a=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??hE),a.unref?.()})]);return gE(e,t.key,s)}finally{clearTimeout(a)}}function hf(e,t,n,r){let i=e;for(let o of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new Fe(`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 Fe(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function ff(e,t,n,r){let i=e.checks.find(a=>a.name===t);if(!i)throw new Fe(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:hf(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function wE(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await pE("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function vE(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(fE,t.length)},async()=>{for(;r<t.length;){let o=r;r+=1;let a=t[o],s=await Lt(rr(e,a.id),a.id);n[o]=s.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 Vn(e,t={}){let n=await C(e),r=B(n),i=$e(n.schema),a=(await Ut(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(f=>({...f,id:f.id,status:f.status,type:f.type})),s={path:e},c=z(),d=Object.fromEntries((c?.assurance_providers??[]).map(f=>[f.definition.id,{cost_class:f.runtime_definition.cost_class,network:f.runtime_definition.network}])),l=new Map,u,m;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await wE(e,t.tree_id),items:a,history:t.include_history===!1?[]:await vE(e,a),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async f=>{if(f.kind==="graph"){let g=X({operation:f.operation,parameters:f.parameters??{}}),w=l.get(g);w===void 0&&(w=Gc(f.operation,void 0,void 0,{...f.parameters,full:!0},s),l.set(g,w));let v=await w;return{value:hf(v,f.field,f.kind),population_size:a.length,cost:a.length}}if(f.kind==="validate"){u??=pf({counts:!0},s);let g=await u;return ff(g,f.check,f.field,f.kind)}if(f.kind==="health"){m??=jm(s,{checkOnly:!0,full:!0});let g=await m;return ff(g,f.check,f.field,f.kind)}let p=t.providers?.[f.provider];if(p)return p(f);let h=bc(c,f.provider);if(!h)throw new TypeError(`assurance provider ${f.provider} is not registered`);return yE(h.runtime_definition,f,e,t.trigger??"sdk")}}}import{createHash as bE}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 Si(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 Ai=["production_defect","nightly_regression","scanner_finding","review_caught_late"],Xa=["gate_added","gate_strengthened","explicit_waiver"],gf=256,kE=1024,Kn=new Map,xE=["files","package_names","item_ids","tags","error_codes"];function ye(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t<n?-1:1)}function _f(e){return bE("sha256").update(X(e)).digest("hex")}function Ya(e,t){if(typeof e!="string"||!e.trim())throw new TypeError(`${t} must be a non-empty string`)}function Yn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ln(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function wf(e,t){if(!Yn(e))throw new TypeError(`${t} must be an object`);for(let n of xE)if(e[n]!==void 0&&!ln(e[n]))throw new TypeError(`${t}.${n} must be an array of strings`);return e}function SE(e,t){if(!Yn(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&&!ln(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&&!ln(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>gf)throw new TypeError(`defect recurrence family ${t} file pattern exceeds ${gf} characters`)}function EE(e,t){if(Ya(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(!Ai.includes(e.escape_class))throw new TypeError(`defect recurrence family ${e.id} has an invalid escape class`);Ya(e.title,`defect recurrence family ${e.id} title`),Ya(e.owner_item_id,`defect recurrence family ${e.id} owner_item_id`)}function AE(e){if(!ln(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(SE(e.triggers,e.id),!Yn(e.checks)||!ln(e.checks.local)||!ln(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 RE(e){if(!Yn(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 IE(e){let t=wf(e.negative_control,`defect recurrence family ${e.id} negative_control`);if(Qa(e,t,{}).length===0)throw new TypeError(`defect recurrence family ${e.id} negative_control must select its own family`)}function Za(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(!Yn(n))throw new TypeError("defect recurrence family must be an object");EE(n,t),AE(n),RE(n),IE(n)}}function CE(e,t){let n=Kn.get(e);if(n===void 0){if(Kn.size>=kE){let i=Kn.keys().next().value;Kn.delete(i)}let r=e.replaceAll("**","\0").replaceAll(/[|\\{}()[\]^$+?./]/gu,"\\$&").replaceAll("*","[^/]*").replaceAll("\0",".*");n=new RegExp(`^${r}$`,"u"),Kn.set(e,n)}return n.test(t)}function TE(e,t){let n=[],r=ye(e.triggers.file_patterns??[]);for(let i of ye(t.files??[]))for(let o of r)CE(o,i)&&n.push({signal:"file",value:i,matched:o});return n}function $E(e,t){let n=[{signal:"package",values:ye(t.package_names??[]),triggers:ye(e.triggers.package_names??[])},{signal:"tag",values:ye(t.tags??[]),triggers:ye(e.triggers.tags??[])},{signal:"error_code",values:ye(t.error_codes??[]),triggers:ye(e.triggers.error_codes??[])}],r=[];for(let i of n){let o=new Set(i.triggers);for(let a of i.values)o.has(a)&&r.push({signal:i.signal,value:a,matched:a})}return r}function OE(e,t,n){let r=new Set(e.triggers.item_ids??[]);return ye(t.item_ids??[]).flatMap(i=>r.has(i)||n[i]?.includes(e.id)?[{signal:"item",value:i,matched:e.id}]:[])}function Qa(e,t,n){return[...TE(e,t),...$E(e,t),...OE(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 DE(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 PE(e){return[e.files,e.package_names,e.item_ids,e.tags,e.error_codes].reduce((t,n)=>t+(n?.length??0),0)}function vf(e,t,n={}){Za(e);let r=[...e.families].sort((l,u)=>l.id<u.id?-1:1),i=_f({...e,families:r}),o=new Set(n.changed_item_ids??[]),a=n.previous_index?.policy_fingerprint===i,s=a?Object.fromEntries(Object.entries(n.previous_index?.item_families??{}).filter(([l])=>!o.has(l))):{},c=a?Object.keys(s).length:0;for(let l of t){let u=Si(l),m=r.filter(f=>f.historical_item_ids.includes(l.id)||Qa(f,u,{}).length>0).map(f=>f.id);m.length>0?s[l.id]=m:delete s[l.id]}let d=Object.fromEntries(Object.entries(s).sort(([l],[u])=>l<u?-1:1).map(([l,u])=>[l,ye(u)]));return{version:1,policy_fingerprint:i,index_fingerprint:_f({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 bf(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=DE(n.cursor,e.index_fingerprint),o=e.families.flatMap(l=>{let u=Qa(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:ye(l.checks.local),hosted_checks:ye(l.checks.hosted),budget:l.budget}]}),a=o.slice(i,i+r),s=i+a.length,c=s<o.length?Buffer.from(JSON.stringify({index_fingerprint:e.index_fingerprint,offset:s})).toString("base64url"):void 0,d={risk_detected:o.length>0,index_fingerprint:e.index_fingerprint,items:a,total:o.length,...c?{next_cursor:c}:{},required_local_checks:ye(o.flatMap(l=>l.local_checks)),required_hosted_checks:ye(o.flatMap(l=>l.hosted_checks)),row_contract:{row_keys:["items"],jq_selector:".items[]"}};return{...d,cost:{families_evaluated:e.families.length,signals_evaluated:PE(t),families_selected:o.length,estimated_output_tokens:Math.ceil(JSON.stringify(d).length/4)}}}function NE(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 Ei(e){return typeof e=="string"&&e.trim().length>0}function yf(e){return Array.isArray(e)&&e.length>0&&e.every(Ei)}function ME(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,expired:!1};let n=e;if(!Xa.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:Ei(n.waiver_reason)&&Number.isFinite(r)&&r>=t,expired:Number.isFinite(r)&&r<t}}return{valid:Ei(n.gate_id)&&Ei(n.negative_control)&&yf(n.local_checks)&&yf(n.hosted_checks),expired:!1}}function LE(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.`}):Ai.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=ME(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 zM(e,t,n,r=new Date){Za(t);let i=Date.parse(t.evidence_epoch),o=new Set(n),a=e.filter(m=>o.has(m.status)&&NE(m)),s=a.filter(m=>{let f=Date.parse(typeof m.completed_at=="string"?m.completed_at:"");if(Number.isFinite(f))return f>=i;let p=Date.parse(typeof m.closed_at=="string"?m.closed_at:"");if(Number.isFinite(p))return p>=i;let h=Date.parse(typeof m.created_at=="string"?m.created_at:"");return!Number.isFinite(h)||h>=i}),c=Object.fromEntries(Ai.map(m=>[m,0])),d=Object.fromEntries(Xa.map(m=>[m,0])),l=a.filter(m=>typeof m.escape_class=="string"&&Ai.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 f=m.gate_evidence.disposition;typeof f=="string"&&Xa.includes(f)&&(d[f]+=1)}let u=s.flatMap(m=>LE(m,r.getTime()));return u.sort((m,f)=>m.item_id!==f.item_id?m.item_id.localeCompare(f.item_id):m.kind.localeCompare(f.kind)),{ok:u.length===0,governed_item_count:s.length,classified_item_count:l.length,class_counts:c,evidence_disposition_counts:d,findings:u}}function FE(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 Za(t),t}function kf(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=wf(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:FE(t.policy),change:n,...t.cursor===void 0?{}:{cursor:t.cursor},...t.limit===void 0?{}:{limit:t.limit}}}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]="f66a964d-1352-5523-ab91-5177d0d93ce8")}catch{}})();var es,xf=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk"],ts=["measurement","assertion","gate"];function UE(e){if(xf.includes(e))return e;throw xr({command_path:"assurance",token:e,allowed:xf,display_name:"assurance action"})}function un(e,t,n){throw new y(t,_.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function zE(e){if(!e)return un("kind",`Assurance declaration kind is required. Expected: ${ts.join(", ")}`,"pm assurance list measurement");if(ts.includes(e))return e;throw new y(`Assurance declaration kind is required. Expected: ${ts.join(", ")}`,_.USAGE)}function Sf(e){if(!e)return un("preset",`Assurance preset is required. Expected: ${xn.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(xn.includes(e))return e;throw new y(`Assurance preset is required. Expected: ${xn.join(", ")}`,_.USAGE)}function ns(e){return e.owner?.trim()?e.owner.trim():un("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function WE(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 y("assurance definition must be valid JSON",_.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new y("assurance put requires a JSON object definition",_.USAGE);return n}async function qE(e){let[t,n,r]=await Promise.all([kn(e,"measurement"),kn(e,"assertion"),kn(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Ef(e,t){return t===!0?{id:e.id}:e}async function BE(e,t){let n=t.authorization_decision;if(!n)return[];let r=await Vn(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(a=>a.id===n),o=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!o.has(i.status))throw new y(`Assurance authorization ${n} must name a terminal Decision item`,_.USAGE);return[i.id]}async function HE(e,t){let n=ho(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>Ht))throw new y(`assurance verdict limit must be an integer from 1 through ${Ht}`,_.USAGE);let r=await dd(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 GE(e,t,n){if(e==="presets"){if(t.preset??t.id)return Mr(Sf(t.preset??t.id),ns(t));let i=xn.map(o=>{let a=Mr(o,"pm-owner");return{id:o,title:a.title,description:a.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return Bt(()=>ud(n,Sf(t.preset??t.id),ns(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await md(await Vn(n,{resolve_tree:!1,trigger:"derive"}),ns(t)),o=t.apply?await Bt(()=>pd(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 un("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new y("assurance promote requires --enforcement warn|block",_.USAGE);let r=await co(n,"assertion",t.id);return Bt(()=>fd(n,r,t.enforcement,{author:t.author,message:t.message}))}async function JE(e,t,n){if(!e.id)return un("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 y("assurance run requires a trigger",_.USAGE);if(!bt.includes(e.trigger))throw new y(`Unknown assurance trigger ${e.trigger}. Expected: ${bt.join(", ")}`,_.USAGE);let i=e.trigger,[o,a]=await Promise.all([qE(t),Vn(t,{...n.workspace,tree_id:e.tree,trigger:i})]),s=await Jc(()=>od(r,o,a,{trigger:i,dry_run:e.dry_run===!0}));return s.dry_run||await cd(t,s,{author:e.author,message:e.message}),s}function Af(e){throw e instanceof y?e:new y(e instanceof Error?e.message:"assurance risk request is invalid",_.USAGE)}function VE(e){if(e.limit!==void 0)throw new y("assurance risk does not accept --limit; set limit inside the risk definition",_.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new y("assurance risk definition must be valid JSON",_.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return kf(t)}catch(n){return Af(n)}}function KE(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 YE(e,t,n){let r=X(t.policy),i=es?.pm_root===e?es:void 0,o=new Map(n.map(d=>[d.id,jE("sha256").update(X(Si(d))).digest("hex")])),a=i?.policy_serialized===r?i:void 0,s=a?KE(a,o):new Set,c=vf(t.policy,a?n.filter(d=>s.has(d.id)):n,a?{previous_index:a.index,changed_item_ids:[...s]}:{});return es={pm_root:e,policy_serialized:r,item_fingerprints:o,index:c},c}async function XE(e,t){let n=VE(e),r=await Vn(t,{include_history:!1,resolve_tree:!1});try{return bf(YE(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit})}catch(i){return Af(i)}}async function ZE(e,t={},n={}){let r=UE(e.action),i=L(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return GE(r,e,i);if(r==="verdicts")return HE(e,i);if(r==="run")return JE(e,i,n);if(r==="risk")return XE(e,i);let o=zE(e.kind);if(r==="list")return kn(i,o);if(!e.id)return un("id",`assurance ${r} requires an id`,`pm assurance ${r} ${o} <id>`);let a=e.id;if(r==="show")return co(i,o,a);if(r==="remove"){let l=await Bt(()=>sd(i,o,a,{author:e.author,message:e.message}));return Ef(l,e.idOnly)}let s=WE(o,e.definition);if(s.id!==a)throw new y(`Assurance definition id ${s.id} does not match requested id ${a}`,_.USAGE);let c={author:e.author,message:e.message,...o==="assertion"?{authorized_decision_ids:await BE(i,s)}:{}},d=await Bt(()=>Pr(i,o,s,c));return Ef(d,e.idOnly)}function rL(e,t,n){let r={...e,...t};return ZE({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:ho(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 QE}from"node:child_process";import eA from"node:path";import{promisify as tA}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 nA=tA(QE),rA="@unbrained/pm-cli",iA="latest",oA={global:["--global"],project:[]};function Rf(e){let t=e.project===!0||e.local===!0||e.scope==="project",n=e.global===!0||e.scope==="global";if(t&&n)throw new y('Options "--project/--local" and "--global" are mutually exclusive.',_.USAGE);return n?"global":"project"}function Ii(e){return e.trim().toLowerCase()}function If(e,t){let n=Ii(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"&&Ii(i)===n)}function aA(e,t){let n=L(process.cwd(),t.path),r=Tt(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function sA(e,t,n){try{let r=await nA(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 y(`Command failed: ${e} ${t.join(" ")}
45
+ ${o}`,_.GENERIC_FAILURE)}}async function cA(){return _s(import.meta.url,["../../.."])}function Ci(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():iA}function Ri(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():rA}async function dA(e,t){let n=e.commandRunner??sA,r=Ri(e),i=Ci(e),o=`${r}@${i}`,a=["npm","install","-g",o];e.repair===!0&&a.push("--force");let s=await cA(),c={requested:!0,status:"planned",package:r,target:o,command:a,before_version:s,repair:e.repair===!0};if(t)return c;try{await n(a[0],a.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 lA(e){return eA.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function uA(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!lA(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 mA(e,t){let n=uA(e,t);return e.kind!=="local"||await D(n)?n:await D(e.location)?e.location:n}function pA(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 Cf(e,t){let n=aA(e,t);return(await he(n.selected_root)).state.entries.filter(i=>i.scope===e)}async function fA(e,t,n){let r=await Cf(e,t);return r.find(i=>If(i,n.name))??r.find(i=>Ii(i.directory)===Ii(n.directory))}async function hA(e,t,n,r,i){let o=Ci(t),a=await mA(e.source,o),s=pA(e.source,a,r,e.source.ref),c={name:e.name,directory:e.directory,scope:r,source:e.source,status:"planned",command:s,previous_version:e.manifest_version};if(i)return c;try{await aa(a,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await fA(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 gA(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 uL(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",...oA[Rf(t)]];throw new y('Options "--cli-only" and "--packages-only" are mutually exclusive.',_.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:mr(m),suggested_retry_args:m}})}let i=Rf(t),o=t.dryRun===!0;if(t.cliOnly===!0&&r)throw new y('A package target cannot be used with "--cli-only".',_.USAGE);let a=!(t.packagesOnly===!0||r),s=t.cliOnly!==!0,c=a?await dA(t,o):{requested:!1,status:"skipped",package:Ri(t),target:`${Ri(t)}@${Ci(t)}`,command:["npm","install","-g",`${Ri(t)}@${Ci(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await Cf(i,n):[];if(r&&(d=d.filter(m=>If(m,r)),d.length===0))throw new y(`Managed package "${r}" was not found in ${i} scope.`,_.NOT_FOUND);let l=[];for(let m of d)l.push(await hA(m,t,n,i,o));let u=gA(c,l,a,s);return{ok:u.failed===0,action:"upgrade",dry_run:o,scope:i,target:r,cli:c,packages:l,summary:u}}import mn from"node:fs/promises";import $i from"node:path";import Ti from"node:fs/promises";import rs 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 _A=864e5;function yA(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 wA(e,t){let n;try{n=await Ti.readdir(e,{withFileTypes:!0})}catch(i){if(U(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let o=rs.join(e,i.name),a;try{a=await Ti.readdir(o)}catch(s){U(s)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let s of a)s.endsWith(".json")&&r.push(`${i.name}/${s}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function Tf(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*_A,a=rs.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await wA(a,s.warnings);for(let d of c){let l=rs.join(a,d),u=`checkpoints/${d}`;s.scanned+=1,r?.onRead&&s.warnings.push(...await r.onRead(l));let m;try{m=await Ti.readFile(l,"utf8")}catch(w){if(U(w)){s.scanned-=1;continue}s.warnings.push(`checkpoint_unreadable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=yA(m),p=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(p)){s.warnings.push(`checkpoint_unparseable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=i-p,g={file:u,created_at:f,age_seconds:Math.floor(h/1e3),stale:h>o,reason:h>o?"expired":"active"};if(!g.stale){s.retained.push(u),s.entries.push(g);continue}if(!n){try{await Ti.unlink(l)}catch(w){if(!U(w)){s.warnings.push(`checkpoint_remove_failed:${d}`),s.retained.push(u),s.entries.push(g);continue}}r?.onWrite&&s.warnings.push(...await r.onWrite(l))}s.removed.push(u),s.entries.push(g)}return s}import is from"node:fs/promises";import $f 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 vA=1440*60*1e3,bA=new Set(["committed","compensated"]);function kA(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 xA(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 a=r-o;return bA.has(t)?a>i?{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"active"},remove:!1}}async function SA(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],o=kA(await is.readFile(e,"utf8")),a=xA(t,o.status,o.updatedAt,r.nowMs,r.retentionMs);return a.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),a.remove&&!r.dryRun&&(await is.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:a,warnings:i}}async function Of(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*vA,a=$f.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await is.readdir(a)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(U(d))return s;throw d}for(let d of c){let l=$f.join(a,d),u=`transactions/sdk/${d}`,m=await SA(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:o});s.warnings.push(...m.warnings),s.scanned+=1;let{decision:f}=m;if(!f.remove){s.retained.push(u),s.entries.push(f.entry);continue}s.removed.push(u),s.entries.push(f.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]="76f8405f-138d-5119-a300-f068354394a5")}catch{}})();var Xn=["index","embeddings","runtime","locks","checkpoints","transactions"],EA=1440*60*1e3,AA=[{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 RA(e,t,n){let r=t.relativePath,i=$i.join(e,r),o=await Ge({path:i,scope:"project"});try{let a=await mn.stat(i);if(t.kind==="file"&&!a.isFile())return{removed:!1,warnings:[...o,`not_a_file:${r}`]};if(t.kind==="directory"&&!a.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await mn.unlink(i):await mn.rm(i,{recursive:!0,force:!0});let s=await ne({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...s]}}catch(a){if(U(a))return{removed:!1,warnings:o};throw a}}async function IA(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],o=[],a=Date.now()-EA;for(let s of n){let c=$i.join(e,s.relativePath);if(!await D(c))continue;let d=(await mn.readdir(c)).filter(l=>l.startsWith(s.prefix)).sort();for(let l of d){let u=$i.posix.join(s.relativePath,l),m=$i.join(c,l);o.push(...await Ge({path:m,scope:"project"}));let f=await mn.stat(m).catch(p=>{if(!U(p))throw p});if(f){if(f.mtimeMs>a){i.push(u);continue}r.push(u),!t&&(await mn.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 CA(e){if(!e||e.length===0)return[...Xn];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new y(`--scope requires at least one value (${Xn.join(",")})`,_.USAGE);let n=new Set;for(let r of t){if(!Xn.includes(r))throw new y(`Invalid --scope value "${r}". Expected one or more of: ${Xn.join(", ")}`,_.USAGE);n.add(r)}return Xn.filter(r=>n.has(r))}function TA(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 PL(e,t={}){let n=L(process.cwd(),e.path);await Q(n);let r=await C(n),i=t.dryRun===!0,o=CA(t.scope),a=AA.filter(p=>o.includes(p.scope)),s=[],c=[],d=[];for(let p of a){let h=await RA(n,p,i);h.removed?s.push(p.relativePath):c.push(p.relativePath),d.push(...h.warnings)}if(o.includes("runtime")){let p=await IA(n,i);s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(o.includes("locks")){let p=await Vd(n,{dryRun:i,hooks:{onRead:h=>Ge({path:h,scope:"project"}),onWrite:h=>ne({path:h,scope:"project",op:"gc:lock_remove"})}});s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),l={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(o.includes("transactions")){let p=r.checkpoints.retention_days,h=await Of(n,{dryRun:i,retentionDays:p,hooks:{onRead:g=>Ge({path:g,scope:"project"}),onWrite:g=>ne({path:g,scope:"project",op:"gc:transaction_journal_remove"})}});s.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:p}}let m;if(o.includes("checkpoints")){let p=r.checkpoints.retention_days,h=await Tf(n,{dryRun:i,retentionDays:p,hooks:{onRead:g=>Ge({path:g,scope:"project"}),onWrite:g=>ne({path:g,scope:"project",op:"gc:checkpoint_remove"})}});s.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:p}}d.push(...await pr({mode:i?"gc:dry-run":"gc",total_items:a.length}));let f=TA({dryRun:i,scopes:o,removed:s});return{ok:d.length===0,dry_run:i,scope:o,removed:s,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:f,generated_at:T()}}import $A from"node:fs/promises";import Zn 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 os="index/manifest.json",as="search/embeddings.jsonl",OA="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function DA(e){return e.progress===!0||process.stderr.isTTY===!0}function ae(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
46
+ `)}catch{}}function PA(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new y("Reindex mode must be one of keyword|semantic|hybrid",_.USAGE)}async function NA(e,t,n,r){let i=[];return{candidates:await _c(e,t,n,i,r),warnings:i}}async function cs(e,t,n,r,i){let o=Ct(z()),a=[];for(let s of t)if(!(i&&!i.has(s.metadata.id))){if(typeof s.body=="string"){a.push({metadata:s.metadata,body:s.body});continue}try{let c=await $A.readFile(s.item_path,"utf8"),d=Mt(c,{format:s.item_format,schema:n,extensionFieldNames:o,onWarning:l=>r.push(l)});a.push({metadata:s.metadata,body:d.body})}catch{r.push(`item_list_item_read_failed:${Zn.relative(e,s.item_path)}`),a.push({metadata:s.metadata,body:""})}}return a}function MA(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:Cc(e,{fields:n})}}var pn=Z;function LA(e){let t=z(),n=pn(e.search?.provider);if(!n)return null;let r=kc(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=pn(i.name)??pn(r.definition.name);if(!o)return null;let a=i.embedBatch,s=i.embed_batch,c=i.embed,d=typeof a=="function"?a:typeof s=="function"?s:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:o,embedBatch:d,embed:l}}function FA(e){let t=z(),n=pn(e.vector_store?.adapter);if(!n)return null;let r=xc(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=pn(i.name)??pn(r.definition.name);if(!o)return null;let a=i.upsert,s=i.delete;return{adapterName:o,...typeof a=="function"?{upsert:a}:{},...typeof s=="function"?{delete:s}:{}}}function ss(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new y(`Invalid vector returned by ${t}`,_.GENERIC_FAILURE);return e}async function jA(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 y(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,_.GENERIC_FAILURE);return o.map((a,s)=>ss(a,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new y(`Extension search provider "${e.name}" does not implement embed/embedBatch`,_.GENERIC_FAILURE);let i=[];for(let[o,a]of n.entries()){let s=await Promise.resolve(e.embed({input:a,settings:t,model:r}));i.push(ss(s,`extension search provider "${e.name}" embed output at index ${o}`))}return i}function Df(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function Pf(e,t,n){let r=n?vt(n.name,Df(e)):t?vt(t.name,t.model):null;if(!r)throw new y("No embedding identity available for semantic reindex mode",_.USAGE);return r}function UA(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function Nf(e,t,n,r,i,o,a,s){let c=r?.name??n?.name,d=Tc(c,e.search.embedding_corpus_max_characters).maxCharacters,l=Zi(e),u=i.map(p=>$c(p,{providerName:c,maxCharacters:d,fields:l})),m=[],f=null;if(r)try{m=await jA(r,e,u),f=vt(r.name,Df(e))}catch(p){if(!n)throw new y(`Extension search provider "${r.name}" failed to generate embeddings: ${p instanceof Error?p.message:String(p)}`,_.GENERIC_FAILURE);o.push(`Extension search provider "${r.name}" failed; falling back to built-in provider (${p instanceof Error?p.message:String(p)})`)}if(m.length===0){if(!n)throw new y(`No embedding executor available for reindex mode '${t}'`,_.USAGE);let p=await Oc(n,e,u,{onProgress:h=>{h.phase==="complete"&&(a.batches_completed=h.batch_index),ae(s,`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(...p.warnings),m=p.vectors,f=vt(n.name,n.model)}if(ae(s,`embedding_complete vectors=${m.length}`),m.length!==i.length)throw new y(`Embedding output size mismatch (expected ${i.length}, received ${m.length})`,_.GENERIC_FAILURE);if(!f)throw new y(`No embedding identity available for reindex mode '${t}'`,_.USAGE);return{vectors:m,embeddingIdentity:f}}async function zA(e,t,n,r,i,o){let a=Object.keys(n);if(t){if(a.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:a.sort((s,c)=>s.localeCompare(c)),settings:r}))}catch(s){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,_.GENERIC_FAILURE)}else a.length>0&&i.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${a.length}`);if(!e)return}e&&await Nc(e,a,{},o)}async function Mf(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 y(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${o instanceof Error?o.message:String(o)}`,_.GENERIC_FAILURE)}else i.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Pc(e,n)}}function WA(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function qA(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 BA(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=yn(e.settings);if(!t.active&&!e.extensionEmbedding)throw new y(`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`,_.USAGE);let n=Ar(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new y(`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`,_.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function HA(e){let t=B(e.settings,z()),n=await NA(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 GA(e){let t=await qt(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 Pf(e.settings,yn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&Wt(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(OA))}async function JA(e){let t=await qt(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=Pf(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(d=>d.metadata.id)),i=UA(t.entries,r),o=Wt(t.embedding,n);e.forceFullSemantic&&!o&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let a=e.forceFullSemantic||o?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),s=new Set(a.map(d=>d.metadata.id)),c=s.size>0?await cs(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:i,resetRequired:o,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function VA(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await cs(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,ae(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await Nf(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:Qi(r.vectors,"Reindex embeddings")}}async function KA(e){let t=await Nf(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=Qi(n,"Reindex embeddings");if(!(!e.resetRequired&&(Wt(e.ledgerEmbedding,r)||Lc(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let a=await VA(e);return n=a.vectors,r=a.embeddingIdentity,i=a.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:a.staleDocuments,vectorDimension:i,resetRequired:!0}}async function YA(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(ae(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new y(`Extension vector adapter "${t}" does not support upserting vectors.`,_.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,ae(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof y)throw t;if(!e.activeVectorStore)throw new y(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,_.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)})`),ae(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){ae(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Dc(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,ae(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new y(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,_.USAGE)}function XA(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:ss(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 ZA(e){ae(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await KA({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?(ae(e.progressEnabled,"vector_reset_start"),await zA(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),ae(e.progressEnabled,"vector_reset_complete")):await Mf(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=XA(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await YA({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:Mc(t.embeddingIdentity,t.vectorDimension)}}async function QA(e){let t=await JA(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(ae(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 ae(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await Mf(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await ZA({...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 eR(e){let t=Zn.join(e.pmRoot,os),n=Zn.join(e.pmRoot,as),r=Zi(e.settings),i=e.documentsForKeywordArtifacts.map(a=>JSON.stringify(MA(a,e.mode,r))).join(`
47
47
  `);ae(e.progressEnabled,"writing keyword artifacts"),await se(t,`${JSON.stringify(e.manifest,null,2)}
48
48
  `),await se(n,`${i}
49
- `);let o=[];if(e.mode!=="keyword")try{ae(e.progressEnabled,"writing vectorization status ledger"),await Fc(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(a){o.push(`search_vectorization_status_ledger_write_failed:${a instanceof Error?a.message:String(a)}`)}return o}async function UL(e,t){let n=PA(e.mode),r=DA(e),i=e.full===!0;ae(r,`start mode=${n}`);let o=L(process.cwd(),t.path);await Q(o);let a=Ar(await C(o)).settings,s=null;try{s=await pe(o,Ic,a.locks.ttl_seconds,J(void 0,"pm-reindex"),!1,a.governance.force_required_for_stale_lock,a.locks.wait_ms)}catch(c){throw c instanceof y&&c.exitCode===_.CONFLICT?new y("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",_.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=LA(a),d=FA(a),l=BA({requestedMode:n,pmRoot:o,settings:a,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;ae(r,"loading item corpus");let m=await HA({pmRoot:o,settings:a}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;ae(r,`loaded_items=${h.length}`);let g=T(),w=qA(u,g,h),v=Qn.join(o,os),x=Qn.join(o,as),S=u==="keyword"?await cs(o,p,a.schema,f):h,b=[],R={},k=null,I=WA(u);if(u==="keyword"&&await GA({pmRoot:o,settings:a,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let q=await QA({pmRoot:o,settings:a,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:p,metadataDocuments:h,documentsForKeywordArtifacts:S,forceFullSemantic:i,reindexWarnings:f,semanticWarnings:b,semanticSummary:I,progressEnabled:r});S=q.documentsForKeywordArtifacts,R=q.vectorizationLedgerEntries,k=q.vectorizationEmbeddingMetadata}let A=await eR({pmRoot:o,mode:u,manifest:w,documentsForKeywordArtifacts:S,settings:a,vectorizationLedgerEntries:R,vectorizationEmbeddingMetadata:k,progressEnabled:r}),j=[...await ne({path:v,scope:"project",op:"reindex:manifest"}),...await ne({path:x,scope:"project",op:"reindex:embeddings"}),...await fr({mode:u,total_items:h.length})];return ae(r,"done"),{ok:!0,mode:u,total_items:h.length,semantic:I,artifacts:{manifest:os,embeddings:as},warnings:[...f,...b,...A,...j],generated_at:g}}finally{await s?.()}}export{BI as a,bl as b,P as c,be as d,Fe as e,Bt as f,Jc as g,Kc as h,bt as i,to as j,Gf as k,io as l,oo as m,Qc as n,Gt as o,bn as p,so as q,uh as r,od as s,kn as t,co as u,Nr as v,lo as w,sd as x,cd as y,dd as z,xn as A,Lr as B,ud as C,md as D,pd as E,fd as F,yd as G,JR as H,$ as I,re as J,VR as K,ho as L,KR as M,YR as N,Ad as O,XR as P,ZR as Q,QR as R,eI as S,tI as T,go as U,nI as V,rI as W,fo as X,iI as Y,oI as Z,Id as _,aI as $,Ch as aa,$d as ba,gI as ca,An as da,_I as ea,Mh as fa,Lh as ga,yI as ha,Fh as ia,sg as ja,cg as ka,kt as la,uC as ma,hg as na,n_ as oa,hT as pa,gT as qa,_T as ra,Cn as sa,yT as ta,wT as ua,vT as va,bT as wa,kT as xa,xT as ya,ST as za,ET as Aa,AT as Ba,RT as Ca,IT as Da,Mu as Ea,aa as Fa,Nd as Ga,Md as Ha,jd as Ia,di as Ja,OO as Ka,Wn as La,li as Ma,DO as Na,PO as Oa,fa as Pa,aD as Qa,sD as Ra,Um as Sa,eP as Ta,Wm as Ua,pp as Va,mP as Wa,Gm as Xa,hp as Ya,aN as Za,sN as _a,zx as $a,Wx as ab,uN as bb,mN as cb,pN as db,fN as eb,Bx as fb,Hx as gb,Gx as hb,hN as ib,yp as jb,Vx as kb,wp as lb,Pa as mb,bp as nb,Kx as ob,Yx as pb,Xx as qb,Fa as rb,ja as sb,EN as tb,AN as ub,RN as vb,RS as wb,SM as xb,ff as yb,Kn as zb,Ai as Ab,Xa as Bb,bf as Cb,kf as Db,zM as Eb,FE as Fb,xf as Gb,Sf as Hb,ts as Ib,ZE as Jb,rL as Kb,uL as Lb,PL as Mb,UL as Nb};
50
- //# sourceMappingURL=chunk-4BR5UU52.js.map
49
+ `);let o=[];if(e.mode!=="keyword")try{ae(e.progressEnabled,"writing vectorization status ledger"),await Fc(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(a){o.push(`search_vectorization_status_ledger_write_failed:${a instanceof Error?a.message:String(a)}`)}return o}async function UL(e,t){let n=PA(e.mode),r=DA(e),i=e.full===!0;ae(r,`start mode=${n}`);let o=L(process.cwd(),t.path);await Q(o);let a=Er(await C(o)).settings,s=null;try{s=await pe(o,Ic,a.locks.ttl_seconds,J(void 0,"pm-reindex"),!1,a.governance.force_required_for_stale_lock,a.locks.wait_ms)}catch(c){throw c instanceof y&&c.exitCode===_.CONFLICT?new y("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",_.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=LA(a),d=FA(a),l=BA({requestedMode:n,pmRoot:o,settings:a,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;ae(r,"loading item corpus");let m=await HA({pmRoot:o,settings:a}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;ae(r,`loaded_items=${h.length}`);let g=T(),w=qA(u,g,h),v=Zn.join(o,os),x=Zn.join(o,as),S=u==="keyword"?await cs(o,p,a.schema,f):h,b=[],R={},k=null,I=WA(u);if(u==="keyword"&&await GA({pmRoot:o,settings:a,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let q=await QA({pmRoot:o,settings:a,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:p,metadataDocuments:h,documentsForKeywordArtifacts:S,forceFullSemantic:i,reindexWarnings:f,semanticWarnings:b,semanticSummary:I,progressEnabled:r});S=q.documentsForKeywordArtifacts,R=q.vectorizationLedgerEntries,k=q.vectorizationEmbeddingMetadata}let A=await eR({pmRoot:o,mode:u,manifest:w,documentsForKeywordArtifacts:S,settings:a,vectorizationLedgerEntries:R,vectorizationEmbeddingMetadata:k,progressEnabled:r}),j=[...await ne({path:v,scope:"project",op:"reindex:manifest"}),...await ne({path:x,scope:"project",op:"reindex:embeddings"}),...await pr({mode:u,total_items:h.length})];return ae(r,"done"),{ok:!0,mode:u,total_items:h.length,semantic:I,artifacts:{manifest:os,embeddings:as},warnings:[...f,...b,...A,...j],generated_at:g}}finally{await s?.()}}export{BI as a,bl as b,P as c,be as d,Fe as e,Bt as f,Jc as g,Kc as h,bt as i,to as j,Hf as k,io as l,oo as m,Qc as n,Gt as o,bn as p,so as q,lh as r,od as s,kn as t,co as u,Pr as v,lo as w,sd as x,cd as y,dd as z,xn as A,Mr as B,ud as C,md as D,pd as E,fd as F,yd as G,JR as H,$ as I,re as J,VR as K,ho as L,KR as M,YR as N,Ad as O,XR as P,ZR as Q,QR as R,eI as S,tI as T,go as U,nI as V,rI as W,fo as X,iI as Y,oI as Z,Id as _,aI as $,Ih as aa,$d as ba,gI as ca,An as da,_I as ea,Nh as fa,Mh as ga,yI as ha,Lh as ia,ag as ja,sg as ka,kt as la,uC as ma,fg as na,t_ as oa,hT as pa,gT as qa,_T as ra,Cn as sa,yT as ta,wT as ua,vT as va,bT as wa,kT as xa,xT as ya,ST as za,ET as Aa,AT as Ba,RT as Ca,IT as Da,Nu as Ea,aa as Fa,Nd as Ga,Md as Ha,jd as Ia,di as Ja,OO as Ka,zn as La,li as Ma,DO as Na,PO as Oa,fa as Pa,aD as Qa,sD as Ra,jm as Sa,eP as Ta,zm as Ua,mp as Va,mP as Wa,Hm as Xa,fp as Ya,aN as Za,sN as _a,zx as $a,Wx as ab,uN as bb,mN as cb,pN as db,fN as eb,Bx as fb,Hx as gb,Gx as hb,hN as ib,_p as jb,Vx as kb,yp as lb,Pa as mb,vp as nb,Kx as ob,Yx as pb,Xx as qb,Fa as rb,ja as sb,EN as tb,AN as ub,RN as vb,RS as wb,SM as xb,pf as yb,Vn as zb,Ai as Ab,Xa as Bb,vf as Cb,bf as Db,zM as Eb,FE as Fb,kf as Gb,xf as Hb,ts as Ib,ZE as Jb,rL as Kb,uL as Lb,PL as Mb,UL as Nb};
50
+ //# sourceMappingURL=chunk-4ZDRZYYJ.js.map