@unbrained/pm-cli 2026.8.8 → 2026.8.10

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 (222) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +59 -0
  3. package/dist/cli/commander-usage.js +17 -12
  4. package/dist/cli/help-json-payload.js +51 -16
  5. package/dist/cli/main.js +7 -6
  6. package/dist/cli-bundle/bundle-manifest.json +162 -162
  7. package/dist/cli-bundle/chunks/chunk-2QYH4QMI.js +30 -0
  8. package/dist/cli-bundle/chunks/{chunk-2ZMXX3Q6.js → chunk-EBO7OUUE.js} +70 -70
  9. package/dist/cli-bundle/chunks/{chunk-NUXRRNAB.js → chunk-ETML5C6H.js} +48 -48
  10. package/dist/cli-bundle/chunks/chunk-JUDU4RO4.js +194 -0
  11. package/dist/cli-bundle/chunks/chunk-JZSNADRR.js +5 -0
  12. package/dist/cli-bundle/chunks/chunk-MENWVGJW.js +2 -0
  13. package/dist/cli-bundle/chunks/{chunk-ALDHXLPS.js → chunk-S4EITGLA.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-TIGKWVLA.js +13 -0
  15. package/dist/cli-bundle/chunks/{chunk-CBLA33YK.js → chunk-TRWXF476.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-TSLDTJLQ.js +2 -0
  17. package/dist/cli-bundle/chunks/{register-list-query-WFZAMJHZ.js → register-list-query-OJ6ZXKV4.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-mutation-SOKKOTHQ.js → register-mutation-DKI7QC7O.js} +2 -2
  19. package/dist/cli-bundle/chunks/register-operations-P5OGMT6I.js +2 -0
  20. package/dist/cli-bundle/chunks/{register-setup-2HL5ZHMK.js → register-setup-S3KT2LTH.js} +2 -2
  21. package/dist/cli-bundle/focused-chunks/{chunk-ANTMGYLI.js → chunk-2COZ67XT.js} +2 -2
  22. package/dist/cli-bundle/focused-chunks/chunk-2EXI2DKR.js +4 -0
  23. package/dist/cli-bundle/focused-chunks/{chunk-YSAHYUXX.js → chunk-34SX654S.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/chunk-36FTZ2NT.js +2 -0
  25. package/dist/cli-bundle/focused-chunks/chunk-3CQECMKR.js +16 -0
  26. package/dist/cli-bundle/focused-chunks/chunk-75774JWP.js +6 -0
  27. package/dist/cli-bundle/focused-chunks/chunk-7UN6BHHO.js +2 -0
  28. package/dist/cli-bundle/focused-chunks/{chunk-TCSAPH33.js → chunk-CHIBMEZR.js} +6 -6
  29. package/dist/cli-bundle/focused-chunks/chunk-DZGAHZZV.js +3 -0
  30. package/dist/cli-bundle/focused-chunks/chunk-FF4MNAYB.js +153 -0
  31. package/dist/cli-bundle/focused-chunks/chunk-GHTN2ILR.js +2 -0
  32. package/dist/cli-bundle/focused-chunks/chunk-I4YM2I7S.js +2 -0
  33. package/dist/cli-bundle/focused-chunks/chunk-IMDTEN7K.js +2 -0
  34. package/dist/cli-bundle/focused-chunks/chunk-IW43E4XL.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/chunk-JMVA4HKR.js +5 -0
  36. package/dist/cli-bundle/focused-chunks/{chunk-PL2EYDJK.js → chunk-KR5RVXLQ.js} +31 -29
  37. package/dist/cli-bundle/focused-chunks/chunk-KSNJG4KI.js +16 -0
  38. package/dist/cli-bundle/focused-chunks/chunk-M6RPIXKC.js +2 -0
  39. package/dist/cli-bundle/focused-chunks/chunk-MXYSIQ56.js +18 -0
  40. package/dist/cli-bundle/focused-chunks/chunk-RIIN5V4N.js +2 -0
  41. package/dist/cli-bundle/focused-chunks/chunk-RKWSCYYN.js +2 -0
  42. package/dist/cli-bundle/main.js +13 -13
  43. package/dist/cli-bundle/sdk-authoring.js +1 -1
  44. package/dist/cli-bundle/sdk-contracts.js +1 -1
  45. package/dist/cli-bundle/sdk-core.js +38 -38
  46. package/dist/cli-bundle/sdk-governance.js +1 -1
  47. package/dist/cli-bundle/sdk-graph.js +1 -1
  48. package/dist/cli-bundle/sdk-merge.js +1 -1
  49. package/dist/cli-bundle/sdk-query.js +1 -1
  50. package/dist/cli-bundle/sdk-runtime.js +1 -1
  51. package/dist/cli-bundle/sdk-testing.js +1 -1
  52. package/dist/cli-bundle/sdk.js +2 -2
  53. package/dist/core/diagnostics/remediation.js +19 -9
  54. package/dist/core/fs/fs-utils.d.ts +10 -0
  55. package/dist/core/fs/fs-utils.js +16 -4
  56. package/dist/core/history/history.js +13 -4
  57. package/dist/core/item/actionability.d.ts +7 -1
  58. package/dist/core/item/actionability.js +71 -15
  59. package/dist/core/item/item-format.js +3 -32
  60. package/dist/core/schema/fields-file.d.ts +1 -2
  61. package/dist/core/schema/fields-file.js +4 -11
  62. package/dist/core/schema/runtime-schema.js +3 -10
  63. package/dist/core/schema/status-defs-file.d.ts +1 -2
  64. package/dist/core/schema/status-defs-file.js +4 -32
  65. package/dist/core/schema/status-token.d.ts +2 -0
  66. package/dist/core/schema/status-token.js +32 -0
  67. package/dist/core/schema/type-workflows.d.ts +1 -2
  68. package/dist/core/schema/type-workflows.js +4 -11
  69. package/dist/core/shared/author.d.ts +25 -0
  70. package/dist/core/shared/author.js +128 -10
  71. package/dist/core/shared/errors.d.ts +4 -0
  72. package/dist/core/shared/errors.js +2 -2
  73. package/dist/core/shared/text-normalization.d.ts +1 -1
  74. package/dist/core/shared/text-normalization.js +2 -2
  75. package/dist/sdk/actionability.d.ts +1 -1
  76. package/dist/sdk/actionability.js +3 -3
  77. package/dist/sdk/agent/command-recovery.d.ts +4 -0
  78. package/dist/sdk/agent/command-recovery.js +52 -0
  79. package/dist/sdk/agent/command-suggestions.d.ts +4 -0
  80. package/dist/sdk/agent/command-suggestions.js +67 -0
  81. package/dist/sdk/agent/create-option-policy.d.ts +12 -0
  82. package/dist/sdk/agent/create-option-policy.js +32 -0
  83. package/dist/sdk/agent/item-addressing.d.ts +19 -0
  84. package/dist/sdk/agent/item-addressing.js +208 -0
  85. package/dist/sdk/cli-bootstrap.d.ts +1 -1
  86. package/dist/sdk/cli-bootstrap.js +20 -5
  87. package/dist/sdk/cli-contracts/commander-mutation-options.js +16 -4
  88. package/dist/sdk/cli-contracts/flag-contracts.js +62 -21
  89. package/dist/sdk/cli-contracts/registration-helpers.js +10 -2
  90. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +8 -0
  91. package/dist/sdk/cli-contracts/runtime-contracts.js +20 -3
  92. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +6 -0
  93. package/dist/sdk/cli-contracts/tool-option-contracts.js +4 -2
  94. package/dist/sdk/cli-contracts/tool-parameter-tables.js +19 -4
  95. package/dist/sdk/cli-contracts/tool-schema.js +17 -4
  96. package/dist/sdk/context-intent-runtime.js +8 -5
  97. package/dist/sdk/context-signal-store.d.ts +34 -0
  98. package/dist/sdk/context-signal-store.js +24 -2
  99. package/dist/sdk/core-governance.d.ts +1 -1
  100. package/dist/sdk/core-governance.js +3 -3
  101. package/dist/sdk/dependencies.d.ts +2 -0
  102. package/dist/sdk/dependencies.js +7 -6
  103. package/dist/sdk/dependency-flag-validation.d.ts +15 -1
  104. package/dist/sdk/dependency-flag-validation.js +54 -2
  105. package/dist/sdk/extension/bundled-catalog.js +19 -6
  106. package/dist/sdk/generated-error-code-catalog.js +110 -2
  107. package/dist/sdk/governance/health.js +38 -12
  108. package/dist/sdk/governance/provenance-health.d.ts +39 -0
  109. package/dist/sdk/governance/provenance-health.js +185 -0
  110. package/dist/sdk/governance/validate-item-reader.d.ts +13 -0
  111. package/dist/sdk/governance/validate-item-reader.js +18 -0
  112. package/dist/sdk/governance/validate.d.ts +2 -2
  113. package/dist/sdk/governance/validate.js +25 -11
  114. package/dist/sdk/governance.d.ts +1 -0
  115. package/dist/sdk/governance.js +3 -2
  116. package/dist/sdk/graph/assembly.d.ts +4 -0
  117. package/dist/sdk/graph/assembly.js +22 -2
  118. package/dist/sdk/graph/run.d.ts +2 -0
  119. package/dist/sdk/graph/run.js +3 -2
  120. package/dist/sdk/index.d.ts +4 -0
  121. package/dist/sdk/index.js +6 -2
  122. package/dist/sdk/lifecycle/close.js +27 -19
  123. package/dist/sdk/lifecycle/create.d.ts +2 -0
  124. package/dist/sdk/lifecycle/create.js +66 -19
  125. package/dist/sdk/lifecycle/plan.js +6 -3
  126. package/dist/sdk/lifecycle/update-many.js +39 -27
  127. package/dist/sdk/lifecycle/update.d.ts +6 -1
  128. package/dist/sdk/lifecycle/update.js +51 -28
  129. package/dist/sdk/merge/driver.d.ts +2 -1
  130. package/dist/sdk/merge/driver.js +7 -4
  131. package/dist/sdk/merge/index.d.ts +1 -1
  132. package/dist/sdk/merge/index.js +3 -3
  133. package/dist/sdk/merge/install.d.ts +4 -0
  134. package/dist/sdk/merge/install.js +29 -17
  135. package/dist/sdk/merge/receipts.d.ts +17 -1
  136. package/dist/sdk/merge/receipts.js +112 -20
  137. package/dist/sdk/merge/reconcile.js +21 -4
  138. package/dist/sdk/merge/three-way.d.ts +6 -2
  139. package/dist/sdk/merge/three-way.js +24 -10
  140. package/dist/sdk/output-projection.js +24 -4
  141. package/dist/sdk/query/context.d.ts +2 -0
  142. package/dist/sdk/query/context.js +7 -4
  143. package/dist/sdk/query/get.d.ts +11 -0
  144. package/dist/sdk/query/get.js +37 -3
  145. package/dist/sdk/query/light-metadata.d.ts +3 -0
  146. package/dist/sdk/query/light-metadata.js +19 -0
  147. package/dist/sdk/read-output-contracts.d.ts +1 -1
  148. package/dist/sdk/read-output-contracts.js +23 -4
  149. package/dist/sdk/relationship-kinds/contract.d.ts +48 -0
  150. package/dist/sdk/relationship-kinds/contract.js +22 -0
  151. package/dist/sdk/relationships.d.ts +6 -41
  152. package/dist/sdk/relationships.js +12 -126
  153. package/dist/sdk/runtime-primitives.d.ts +1 -1
  154. package/dist/sdk/runtime-primitives.js +3 -3
  155. package/dist/sdk/runtime.d.ts +4 -1
  156. package/dist/sdk/runtime.js +8 -3
  157. package/dist/sdk/schema-migration.js +7 -9
  158. package/dist/sdk/similarity-scoring.d.ts +1 -2
  159. package/dist/sdk/similarity-scoring.js +4 -16
  160. package/dist/sdk/similarity.d.ts +5 -0
  161. package/dist/sdk/similarity.js +40 -10
  162. package/dist/sdk/structured-mutations.js +5 -2
  163. package/dist/sdk/test/linked-command-detection.d.ts +2 -7
  164. package/dist/sdk/test/linked-command-detection.js +22 -9
  165. package/dist/sdk/workspace-snapshot.d.ts +4 -0
  166. package/dist/sdk/workspace-snapshot.js +24 -11
  167. package/docs/AGENT_GUIDE.md +5 -2
  168. package/docs/COMMANDS.md +27 -6
  169. package/docs/DEPENDENCY_KIND_CONTRACT.md +29 -0
  170. package/docs/ITEM_READ_PROJECTIONS.md +26 -0
  171. package/docs/MERGE_SAFETY.md +17 -8
  172. package/docs/README.md +2 -5
  173. package/docs/READ_OUTPUT_CONTRACTS.md +2 -2
  174. package/docs/RELATIONSHIP_GRAPH.md +1 -1
  175. package/docs/SDK.md +33 -8
  176. package/docs/SDK_AGENT_SESSION_CONTEXT.md +36 -2
  177. package/docs/SDK_CONTEXT.md +97 -0
  178. package/docs/SDK_CONTEXT_INTEGRITY.md +33 -3
  179. package/docs/SENTRY_CONTRACT_EPOCHS.md +20 -0
  180. package/docs/agent-task-token-baseline.json +2 -2
  181. package/marketplace.json +2 -2
  182. package/package.json +5 -4
  183. package/packages/pm-beads/package.json +1 -1
  184. package/packages/pm-calendar/package.json +1 -1
  185. package/packages/pm-command-kit/package.json +1 -1
  186. package/packages/pm-digital-twin/package.json +1 -1
  187. package/packages/pm-governance-audit/package.json +1 -1
  188. package/packages/pm-guide-shell/package.json +1 -1
  189. package/packages/pm-kanban/package.json +1 -1
  190. package/packages/pm-lifecycle-hooks/package.json +1 -1
  191. package/packages/pm-linked-test-adapters/package.json +1 -1
  192. package/packages/pm-search-advanced/package.json +1 -1
  193. package/packages/pm-templates/package.json +1 -1
  194. package/packages/pm-todos/package.json +1 -1
  195. package/packages/pm-vcs/package.json +1 -1
  196. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  197. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  198. package/sdk/public-surface.json +415 -43
  199. package/dist/cli-bundle/chunks/chunk-GKA54IJM.js +0 -5
  200. package/dist/cli-bundle/chunks/chunk-KRY7SRUO.js +0 -2
  201. package/dist/cli-bundle/chunks/chunk-MNJ4NNSY.js +0 -26
  202. package/dist/cli-bundle/chunks/chunk-OJPCFDDY.js +0 -13
  203. package/dist/cli-bundle/chunks/chunk-PFSD3DAN.js +0 -194
  204. package/dist/cli-bundle/chunks/chunk-SQ7QZFQ6.js +0 -2
  205. package/dist/cli-bundle/chunks/register-operations-5XQETS6E.js +0 -2
  206. package/dist/cli-bundle/focused-chunks/chunk-54EU2UVO.js +0 -2
  207. package/dist/cli-bundle/focused-chunks/chunk-5FLBTZJQ.js +0 -2
  208. package/dist/cli-bundle/focused-chunks/chunk-5GJ57YKN.js +0 -2
  209. package/dist/cli-bundle/focused-chunks/chunk-CMDS3KYT.js +0 -14
  210. package/dist/cli-bundle/focused-chunks/chunk-DMKOMTTY.js +0 -6
  211. package/dist/cli-bundle/focused-chunks/chunk-F5B3HBEZ.js +0 -5
  212. package/dist/cli-bundle/focused-chunks/chunk-FI6DWU2M.js +0 -2
  213. package/dist/cli-bundle/focused-chunks/chunk-FNOKJG6N.js +0 -16
  214. package/dist/cli-bundle/focused-chunks/chunk-FPDYXZBK.js +0 -4
  215. package/dist/cli-bundle/focused-chunks/chunk-GWI6YIKJ.js +0 -3
  216. package/dist/cli-bundle/focused-chunks/chunk-HCUC62AB.js +0 -2
  217. package/dist/cli-bundle/focused-chunks/chunk-HGNKPSCB.js +0 -153
  218. package/dist/cli-bundle/focused-chunks/chunk-IAS7PMLG.js +0 -2
  219. package/dist/cli-bundle/focused-chunks/chunk-SM2PJGP3.js +0 -2
  220. package/dist/cli-bundle/focused-chunks/chunk-U646T7Z6.js +0 -18
  221. package/dist/cli-bundle/focused-chunks/chunk-YKPE4PPY.js +0 -2
  222. package/dist/cli-bundle/focused-chunks/chunk-ZOLDTUU7.js +0 -2
@@ -1,29 +1,31 @@
1
- import{a as pn,c as $t,d as Tt,e as Pa,g as ja,h as hn,i as Ct,j as La,k as Me,l as Fe,m as Ma,n as Fa,o as gn,p as pe,q as Ua,r as Ue,s as ze,t as za,u as Ja,v as _n}from"./chunk-DMKOMTTY.js";import{N as Ar,S as Cr,V as Rr,g as Sr,k as Er,l as $r,o as Tr,p as Ir}from"./chunk-CMDS3KYT.js";import{a as Ha}from"./chunk-IAS7PMLG.js";import{B as Ot}from"./chunk-ZOLDTUU7.js";import{f as Sn}from"./chunk-5GJ57YKN.js";import{$ as Je,Aa as br,Ba as kr,Ca as xr,H as Mt,I as sr,J as bn,K as at,M as kn,Q as cr,R as dr,S as lr,T as ur,U as Ft,W as mr,X as pr,Y as fr,Z as Re,_ as hr,aa as gr,ba as xn,ca as We,da as _r,e as or,ea as yr,f as ir,va as wr,wa as vr}from"./chunk-U646T7Z6.js";import{a as Ra,b as It,c as fn,d as Oa,e as Na,f as me,g as At,h as Da,i as xe}from"./chunk-GWI6YIKJ.js";import{$a as er,Ea as wn,Ha as jt,Ja as he,K as Y,Ka as Ya,L as A,La as R,Ma as Lt,Oa as Xa,P as X,Ta as Qa,W as Va,Z as Ka,Za,ab as tr,b as Ba,ba as yn,bb as nr,cb as ar,da as Pt,db as Ce,eb as rr,hb as vn,k as M,n as U,p as fe,r as Dt}from"./chunk-HGNKPSCB.js";import{Aa as ie,B as xa,C as Sa,Ca as se,D as H,Da as te,Fa as K,Ga as ce,I as un,J as D,Ka as nt,L as Et,M as ee,Ma as Rt,O as Ea,Ra as Nt,Sa as qa,T as ke,Ta as Ga,W as $a,a as _a,d as ya,e as wa,h as St,ma as Ta,na as Ia,p as E,q,r as re,u as oe,v as be,va as mn,w as ka,wa as Aa,xa as Ca,ya as Le}from"./chunk-FPDYXZBK.js";import{P as va,R as ba,Y as _,Z as g,a as kt,d as xt,ka as Wa}from"./chunk-54EU2UVO.js";import{execFile as ku}from"node:child_process";import xu from"node:path";import{promisify as Su}from"node:util";import Ie from"node:fs/promises";import ne from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1d184acd-e639-5b28-a294-98d22de2ebc7")}catch{}})();var cs=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function qe(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Nt(t.extensionName));for(let m of t.extensionNames??[])n.add(Nt(m));let a=m=>n.size===0||n.has(Nt(m)),r=(m,w)=>Or(m.filter(y=>a(y.name)).map(w)),o=(m,w)=>Or(m.filter(y=>a(y.name)).flatMap(w)),{registrations:i,commands:s,parsers:c,preflight:d,services:l,renderers:u,hooks:f}=e,h=o(i.relationship_kinds??[],m=>m.definitions.map(w=>w.kind)),p=u.overrides.filter(m=>a(m.name)&&((m.commands?.length??0)>0||m.resultDiscriminator!==void 0)).map(m=>({format:m.format,commands:[...m.commands??[]],result_discriminator:m.resultDiscriminator!==void 0})).sort((m,w)=>m.format.localeCompare(w.format));return{capabilities:qa(e,t),commands:r(i.commands,m=>m.command),command_overrides:r(s.overrides,m=>m.command),command_handlers:r(s.handlers,m=>m.command),hooks:cs.filter(([m])=>f[m].some(w=>a(w.name))).map(([,m])=>m),flag_commands:r(i.flags,m=>m.target_command),item_types:o(i.item_types,m=>m.types.map(w=>w.name)),item_fields:o(i.item_fields,m=>m.fields.map(w=>w.name)),...h.length>0?{relationship_kinds:h}:{},migrations:o(i.migrations,m=>typeof m.definition.id=="string"?[m.definition.id]:[]),profiles:r(i.profiles,m=>m.profile.name),importers:r(i.importers,m=>m.importer),exporters:r(i.exporters,m=>m.exporter),search_providers:r(i.search_providers,m=>m.definition.name),vector_store_adapters:r(i.vector_store_adapters,m=>m.definition.name),parser_overrides:r(c.overrides,m=>m.command),service_overrides:r(l.overrides,m=>m.service),renderer_overrides:r(u.overrides,m=>m.format),...p.length>0?{renderer_ownership:p}:{},preflight_overrides:d.overrides.filter(m=>a(m.name)).length,preflight_ownership:d.overrides.filter(m=>a(m.name)).map(m=>({commands:[...m.commands??[]]}))}}function Or(e){return[...new Set(e)].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]="288a7da9-888b-527d-88fb-4711917cec5b")}catch{}})();var ds=e=>{let t='"',n=0;for(let a of e){if(a==="\\"){n+=1;continue}t+="\\".repeat(a==='"'?n*2+1:n),t+=a,n=0}return`${t}${"\\".repeat(n*2)}"`},En=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?ds(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,Nr=(e,t=process.platform)=>{let n=e.map(a=>En(a,t)).join(" ");return n.length>0?`pm ${n}`:"pm"};import Xs from"node:path";import{mkdir as Qs}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]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();var ls=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function us(e){let t=ls.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function ms(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Dr(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,a=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,r=new Map;for(let i of e){let s=typeof i=="string"?i.trim():"";if(s.length===0)continue;let c=us(s);if(c===void 0)continue;let d=r.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<a&&d.examples.push(s),r.set(c,d)}let o=[];for(let[i,s]of r.entries()){if(s.count<n)continue;let c=ms(i);o.push({name:c,prefix:i,count:s.count,examples:s.examples,shadows_builtin:Ra(c)!==void 0})}return o.sort((i,s)=>s.count-i.count||i.name.localeCompare(s.name)),o}import{createHash as Hr}from"node:crypto";import Ne from"node:fs/promises";import Be from"node:path";import{mkdir as ps,readFile as fs}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]="d49ec604-c10c-5706-9d87-510845e55e1a")}catch{}})();var $n=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},hs="sdk-workspace-transaction",gs=/^[a-zA-Z0-9._-]+$/,_s=30,ys=3e3;function Pr(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!gs.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function jr(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 Lr(e,t,n){let a=e??t;if(!Number.isInteger(a)||a<=0)throw new TypeError(`${n} must be a positive integer`);return a}function zr(e,t){return Ur.join(e,"transactions","sdk",`${t}.json`)}async function Se(e,t){t.updatedAt=A();let n=zr(e,t.transactionId);await ps(Ur.dirname(n),{recursive:!0}),await re(n,`${JSON.stringify(t,null,2)}
2
- `)}function ws(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Oe(e){return Object.assign(Object.create(null),e)}function vs(e,t){try{let n=JSON.stringify(e,(a,r)=>{if(typeof r=="number"&&!Number.isFinite(r))throw new TypeError(`${t} contains a non-finite number`);if(r===void 0||typeof r=="function"||typeof r=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return r});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function Tn(e,t){return e===void 0?void 0:vs(e,t)}function In(e,t,n,a){let r=Tn(n,a);r===void 0?delete e[t]:e[t]=r}function Mr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Fr(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function bs(e,t){if(!Fr(e.startedStepIds,t)||!Fr(e.completedStepIds,t)||!Mr(e.results)||!Mr(e.compensationData))return!1;let n=e.startedStepIds,a=new Set(n),r=e.completedStepIds,o=new Set(r);return Object.keys(e.compensationData).some(i=>!a.has(i))||Object.keys(e.results).some(i=>!o.has(i))?!1:e.status==="committed"?t.every(i=>o.has(i)):e.status!=="compensated"||o.size===0&&a.size===0}function ks(e,t,n){let a;try{a=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!a||typeof a!="object"||Array.isArray(a))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let r=a,o=r.schemaVersion===1&&r.transactionId===t,i=Array.isArray(r.stepIds)&&r.stepIds.length===n.length&&r.stepIds.every((l,u)=>l===n[u]),s=bs(r,n),c=ws(r),d=["applying","compensating","compensated","committed"].includes(String(r.status));if(!o||!i||!s||!c||!d)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...r,results:Oe(r.results),compensationData:Oe(r.compensationData)}}async function xs(e,t,n,a,r){let o=r,i=o!==void 0;if(o?.status==="compensating"&&await Jr(e,o),o===void 0||o.status==="compensated"){let s=A();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??s,updatedAt:s,stepIds:a,startedStepIds:[],completedStepIds:[],results:Oe(),compensationData:Oe()},await Se(e.pmRoot,o),await ge(e,o,"prepared")}return{journal:o,recovered:i}}async function Ss(e,t,n){try{await $s(t,e.steps),await Se(e.pmRoot,t);let a=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let o of e.steps){if(a.has(o.id))continue;let i=await o.inspect(),s=Tn(i.result,`Step ${o.id} result`);if(i.state!=="applied"){let c=await o.prepareCompensation?.();In(t.compensationData,o.id,c,`Step ${o.id} compensation data`),r.add(o.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>r.has(l)),await Se(e.pmRoot,t);let d=await o.apply();s=Tn(d,`Step ${o.id} result`)}await ge(e,t,"step_applied",o.id),a.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>a.has(c)),In(t.results,o.id,s,`Step ${o.id} result`),await Se(e.pmRoot,t),await ge(e,t,"step_recorded",o.id)}return await ge(e,t,"committing"),t.status="committed",await Se(e.pmRoot,t),await ge(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Oe(t.results)}}catch(a){if(a instanceof $n||t.status==="committed")throw a;try{await Jr(e,t)}catch(r){throw new AggregateError([a,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw a}}async function Es(e,t,n){try{return ks(await fs(zr(e,t),"utf8"),t,n)}catch(a){if(a!==null&&typeof a=="object"&&"code"in a&&a.code==="ENOENT")return;throw a}}async function ge(e,t,n,a){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...a===void 0?{}:{stepId:a}})}async function $s(e,t){let n=new Set,a=Oe();for(let r of t){let o=await r.inspect();o.state==="applied"&&(n.add(r.id),In(a,r.id,o.result,`Step ${r.id} result`))}e.results=a,e.completedStepIds=t.map(r=>r.id).filter(r=>n.has(r))}async function Jr(e,t){t.status="compensating",await Se(e.pmRoot,t),await ge(e,t,"compensating");let n=new Set(t.completedStepIds),a=new Set(t.startedStepIds);for(let r of[...e.steps].reverse()){if(!a.has(r.id)&&!n.has(r.id))continue;let o;try{o=a.has(r.id)&&(await r.inspect()).state==="applied"}catch{o=a.has(r.id)}o&&(await ge(e,t,"step_compensating",r.id),await r.compensate(t.compensationData[r.id])),n.delete(r.id),a.delete(r.id),t.completedStepIds=e.steps.map(i=>i.id).filter(i=>n.has(i)),t.startedStepIds=e.steps.map(i=>i.id).filter(i=>a.has(i)),delete t.results[r.id],delete t.compensationData[r.id],await Se(e.pmRoot,t),await ge(e,t,"step_compensated",r.id)}t.status="compensated",await Se(e.pmRoot,t),await ge(e,t,"compensated")}async function Wr(e){let t=jr(e.pmRoot,"Transaction pmRoot"),n=Pr(e.transactionId,"Transaction id"),a=jr(e.author,"Transaction author"),r=Lr(e.lockTtlSeconds,_s,"Transaction lock TTL"),o=Lr(e.lockWaitMs,ys,"Transaction lock wait"),i=[...e.steps];if(i.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=i.map(l=>{let u=Pr(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:a,steps:i,lockTtlSeconds:r,lockWaitMs:o},d=await X(t,hs,r,a,!1,!1,o);try{let l=await Es(t,n,s),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Oe(l.results)};let f=await xs(c,n,a,s,l);return await Ss(c,f.journal,u||f.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]="c4b4af3b-6ce6-56f7-9665-9e6b2f3d9630")}catch{}})();function Ge(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Br(e){let t=Ge(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Vr(e,t){let n=Cn(e),a=Ge(t,"migrationScope");return`auto-${Hr("sha256").update(JSON.stringify({scope:a,request:n})).digest("hex").slice(0,20)}`}function Cn(e){let t=a=>Ge(a,"source or target").toLowerCase().replaceAll(/[\s-]+/g,"_"),n=e.kind==="rename-type"?{kind:e.kind,from:Ge(e.from,"source"),to:Ge(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:t(e.from),to:t(e.to),...e.type===void 0?{}:{type:Ge(e.type,"type")}}:{kind:e.kind,from:t(e.from),to:t(e.to)};if(n.from.toLowerCase()===n.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return n}function Ts(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Is(e,t,n){let a=K(t.schema),r=Ts(n);return ce(e,a.files[r],te[r])}function Kr(e,t){return Be.join(e,"transactions","schema",`${t}-plan.json`)}function Ut(e){return e.length===0?null:JSON.parse(e)}async function He(e){let t=await q(e);return{exists:t!==null,raw:t??""}}async function Yr(e,t){t.exists?await re(e,t.raw):await Ne.rm(e,{force:!0})}function As(e,t,n){let a=me(e),r=a.definitions.findIndex(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),o=a.definitions.findIndex(i=>i.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return xe(a);if(r<0)throw new TypeError(`Unknown custom type "${t.from}".`);a.definitions.push({...a.definitions[r],name:t.to})}else r>=0&&a.definitions.splice(r,1);return xe(a)}function Cs(e,t,n){let a=Me(e),r=a.fields.findIndex(i=>i.key===t.from),o=a.fields.findIndex(i=>i.key===t.to);if(n==="stage"){if(o>=0)return Fe(a);if(r<0)throw new TypeError(`Unknown custom field "${t.from}".`);let i=a.fields[r];a.fields.push({...i,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else r>=0&&a.fields.splice(r,1);return Fe(a)}function Rs(e,t,n){let a=Ue(e),r=a.statuses.findIndex(i=>i.id===t.from),o=a.statuses.findIndex(i=>i.id===t.to);if(n==="stage"){if(o>=0)return ze(a);if(r<0)throw new TypeError(`Unknown custom status "${t.from}".`);a.statuses.push({...a.statuses[r],id:t.to})}else r>=0&&a.statuses.splice(r,1);return ze(a)}function Os(e,t,n){return t.kind==="rename-type"?As(e,t,n):t.kind==="rename-field"?Cs(e,t,n):Rs(e,t,n)}function Ee(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Rn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Ve(e){return Array.isArray(e)?e.map(t=>Rn(t)).filter(t=>t!==void 0):[]}function Ns(e,t){for(let n of Ve(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(a=>Ee(a,t)));for(let n of Ve(e.type_workflows))n.type=Ee(n.type,t)}function Ds(e,t){for(let a of Ve(e.definitions))a.default_status=Ee(a.default_status,t);let n=Rn(e.workflow);if(n)for(let[a,r]of Object.entries(n))n[a]=Ee(r,t);for(let a of Ve(e.type_workflows))Array.isArray(a.allowed_transitions)&&(a.allowed_transitions=a.allowed_transitions.map(r=>Array.isArray(r)?r.map(o=>Ee(o,t)):r))}function Ps(e,t){for(let n of Ve(e.definitions)){for(let a of["required_create_fields","required_create_repeatables"])Array.isArray(n[a])&&(n[a]=n[a].map(r=>Ee(r,t)));for(let a of["options","command_option_policies"])for(let r of Ve(n[a])){let o=a==="options"?"key":"option";r[o]=Ee(r[o],t)}}}function js(e,t){let n=Rn(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 a=t.kind==="rename-type"?"type":"status";n[a]=Ee(n[a],t)}function An(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let a=n;return t.kind==="rename-type"?Ns(a,t):t.kind==="rename-field"?Ps(a,t):Ds(a,t),js(a,t),`${JSON.stringify(a,null,2)}
3
- `}function Xr(e,t){if(t.kind==="rename-type"){let a=me(e).definitions;return{source:a.some(r=>r.name.trim().toLowerCase()===t.from.toLowerCase()),target:a.some(r=>r.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let a=Me(e).fields;return{source:a.some(r=>r.key===t.from),target:a.some(r=>r.key===t.to)}}let n=Ue(e).statuses;return{source:n.some(a=>a.id===t.from),target:n.some(a=>a.id===t.to)}}function Ls(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 Ms(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 Qr(e,t){let n=Cn(t.request),a=t.migrationId===void 0?Vr(n,t.migrationScope??"plan"):Br(t.migrationId),r=e.map(c=>Ms(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),o=Hr("sha256").update(JSON.stringify({migrationId:a,request:n,items:r})).digest("hex"),i=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=r.filter(c=>!i.has(c.id));return Object.freeze({migration_id:a,request:n,fingerprint:o,affected_item_count:r.length,pending_item_count:s.length,skipped_completed_count:r.length-s.length,items:Object.freeze(s)})}async function Fs(e){let t=H(e.settings,M()),n=[...new Set(Object.values(t.type_to_folder))],a=await Za(e.pmRoot,n),r=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=a?await Qa({pmRoot:e.pmRoot,expectedSourceCursor:a.source_cursor,query:r}):null;return o?{items:o.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Ce(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Us(e,t){let n=await q(Kr(e,t));if(n===null)return null;try{let a=JSON.parse(n);if(a.schema_version!==1||a.plan.migration_id!==t||!Array.isArray(a.plan.items))throw new TypeError("invalid plan envelope");return a.plan}catch(a){throw new g(`Stored schema migration plan "${t}" is invalid: ${$a(a)}`,_.GENERIC_FAILURE)}}async function zs(e,t){let n=Kr(e,t.migration_id);await Ne.mkdir(Be.dirname(n),{recursive:!0});let a={schema_version:1,plan:t,created_at:new Date().toISOString()};await re(n,`${JSON.stringify(a,null,2)}
4
- `)}function Js(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Ws(e){let t=await tr(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new g(`Schema migration item "${e.id}" no longer exists.`,_.NOT_FOUND);return(await nr(t,{schema:e.settings.schema})).document.metadata}function qr(e,t,n){let a=n==="forward"?t.from:t.to,r=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===r.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==a.toLowerCase())throw new TypeError(`Schema migration expected type "${a}" on item "${e.metadata.id}".`);return e.metadata.type=r,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===r.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==a.toLowerCase())throw new TypeError(`Schema migration expected status "${a}" on item "${e.metadata.id}".`);return e.metadata.status=r,["status"]}let o=e.metadata;if(Object.prototype.hasOwnProperty.call(o,r)&&!Object.prototype.hasOwnProperty.call(o,a))return[];if(!Object.prototype.hasOwnProperty.call(o,a)||Object.prototype.hasOwnProperty.call(o,r))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return o[r]=o[a],delete o[a],[a,r]}function Gr(e){return{id:e.id,inspect:async()=>{let t=await He(e.filePath),n=Xr(t.raw,e.request),a=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:a?"applied":"pending",...a?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await He(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await He(e.filePath);return await re(e.filePath,Os(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 Yr(e.filePath,{exists:t.exists,raw:t.raw})}}}function qs(e){return{id:e.stepId,inspect:async()=>{let t=await He(e.filePath);return{state:An(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await He(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await He(e.filePath);return await re(e.filePath,An(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 Yr(e.filePath,{exists:t.exists,raw:t.raw})}}}function Gs(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await R(e.pmRoot),n=H(t,M()).type_to_folder,a=await Ws({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),r=Ls(a,e.request).length===0;return{state:r?"applied":"pending",...r?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await R(e.pmRoot),n=H(t,M()).type_to_folder,a=await vn({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(r){return{changedFields:qr(r,e.request,"forward")}}});return{item_id:e.id,changed_fields:a.changedFields}},compensate:async()=>{let t=await R(e.pmRoot),n=H(t,M()).type_to_folder;await vn({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(a){return{changedFields:qr(a,e.request,"reverse")}}})}}}async function Hs(e){let t=await Us(e.pmRoot,e.migrationId);if(t){if(!Js(t.request,e.request))throw new g(`Schema migration id "${e.migrationId}" already belongs to a different request.`,_.CONFLICT);return{plan:t,stored:!0}}let n=await Fs({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Qr(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Bs(e){let t=Xr(await q(e.schemaPath)??"",e.request);if(!t.source)throw new g(`Schema migration source "${e.request.from}" is not a custom definition.`,_.NOT_FOUND);if(t.target)throw new g(`Schema migration target "${e.request.to}" already exists.`,_.CONFLICT);await zs(e.pmRoot,e.plan)}async function Vs(e){let t=K(e.settings.schema),n=[...new Set([["types",te.types],["fields",te.fields],["workflows",te.workflows]].map(([r,o])=>ce(e.pmRoot,t.files[r],o)).filter(r=>r!==e.schemaPath))];try{let r=Be.join(e.pmRoot,"templates"),o=await Ne.readdir(r,{withFileTypes:!0});n.push(...o.filter(i=>i.isFile()&&i.name.toLowerCase().endsWith(".json")).map(i=>Be.join(r,i.name)))}catch(r){if(typeof r!="object"||r===null||!("code"in r)||r.code!=="ENOENT")throw r}n.sort((r,o)=>r.localeCompare(o));let a=[];for(let r of n){let o=await q(r);o!==null&&An(o,e.request)!==o&&a.push({filePath:r,beforeRaw:o})}return{paths:n,snapshots:a}}async function Ks(e){for(let t of e.snapshots){let n=await Ne.readFile(t.filePath,"utf8"),a=Be.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await wn({pmRoot:e.pmRoot,author:e.author,documentPath:a,before:Ut(t.beforeRaw),after:Ut(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${a}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function Ys(e,t,n){let a=Cn(e),r=D(process.cwd(),n.path);if(!await E(ee(r)))throw new g(`Tracker is not initialized at ${r}. Run pm init first.`,_.NOT_FOUND);let o=t.migrationId===void 0?Vr(a,await Ne.realpath(r)):Br(t.migrationId),i=await R(r),s=Y(t.author,i.author_default),c=await Hs({pmRoot:r,settings:i,migrationId:o,request:a}),d=c.plan;if(t.dryRun===!0)return{...d,action:a.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Is(r,i,a),u=await Ne.readFile(l,"utf8");c.stored||await Bs({pmRoot:r,schemaPath:l,request:a,plan:d});let f=await Vs({pmRoot:r,schemaPath:l,settings:i,request:a}),h=[Gr({id:"stage-schema",filePath:l,request:a,phase:"stage"}),...f.paths.map((y,v)=>qs({filePath:y,request:a,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(y=>Gs({pmRoot:r,id:y.id,request:a,author:s,force:t.force===!0})),Gr({id:"retire-source",filePath:l,request:a,phase:"retire"})],p=await Wr({pmRoot:r,transactionId:`schema-${o}`,author:s,steps:h,lockTtlSeconds:Math.max(i.locks.ttl_seconds,300),lockWaitMs:i.locks.wait_ms}),m=await Ne.readFile(l,"utf8"),{historyPath:w}=await wn({pmRoot:r,author:s,documentPath:Be.relative(r,l).replaceAll("\\","/"),before:Ut(u),after:Ut(m),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${a.kind}: ${a.from} -> ${a.to}; affected=${d.affected_item_count}`,lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms});return await Ks({pmRoot:r,author:s,settings:i,request:a,plan:d,snapshots:f.snapshots}),{...d,action:a.kind,applied:!0,recovered:p.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:w}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a035e10-b8fe-52cd-a9c7-0762dd0ab160")}catch{}})();var zt="schema-types",Zr="schema-statuses",eo="schema-fields";function $e(e){return jt({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 Ff(e,t,n){let a=D(process.cwd(),n.path);await _e(a);let r;try{r=fn({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(h){throw new g(h instanceof Error?h.message:String(h),_.USAGE)}let o=await R(a),i=K(o.schema),s=ce(a,i.files.types,te.types),c=[],d=Y(t.author,o.author_default),l=he(o),u=await X(a,zt,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms),f;try{let h=await q(s),p;try{p=me(h)}catch(m){throw new g(m instanceof Error?m.message:String(m),_.GENERIC_FAILURE)}try{Oa(r,p);let m=new Map,w=H(o,M());for(let[y,v]of Object.entries(w.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!m.has(x)&&m.set(x,y)}Na(r,p,m)}catch(m){throw new g(m instanceof Error?m.message:String(m),_.USAGE)}f=At(p,r),f.replaced&&f.previousName!==void 0&&f.previousName!==f.definition.name&&c.push(`type_recased:${f.previousName}->${f.definition.name}`),await $e({pmRoot:a,filePath:s,raw:xe(f.file),op:"schema:add-type",author:d,settings:o}),await rt(a,[f.definition],c,"schema:add-type-folder"),c.push(...await U({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await to(a,c),{action:"add-type",registered:!0,replaced:f.replaced,type:f.definition,file:{path:s,definitions:f.file.definitions.length},warnings:Te(c),generated_at:A()}}async function _e(e){if(!await E(ee(e)))throw new g(`Tracker is not initialized at ${e}. Run pm init first.`,_.NOT_FOUND)}async function to(e,t){try{let n=await $r(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 Te(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Zs(e,t,n,a){let r=H(t,M()),o=a.trim().toLowerCase();return(await Ce(e,t.item_format,r.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===o).length}async function ec(e,t,n,a){let r=H(t,M()),o=nt(n),i=pe(a);return(await Ce(e,t.item_format,r.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(o.alias_to_id.get(pe(d))??pe(d))===i}).length}async function tc(e,t,n,a,r){if(r.length===0||gn.has(r))return;let o=await ec(t,n,a,r);o>0&&e.push(`items_using_status:${o}`);let i=nc(a.workflow,r);i.length>0&&e.push(`status_referenced_by_workflow:${i.join(",")}`)}function nc(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(([,a])=>a!==void 0&&pe(a)===t).map(([a])=>a)}async function Uf(e,t,n){let a=D(process.cwd(),n.path);await _e(a);let r=await R(a),o=K(r.schema),i=ce(a,o.files.types,te.types),s=[],c=Y(t.author,r.author_default),d=he(r),l=await X(a,zt,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let f=await q(i),h;try{h=me(f)}catch(p){throw new g(p instanceof Error?p.message:String(p),_.GENERIC_FAILURE)}try{u=Da(h,e)}catch(p){throw new g(p instanceof Error?p.message:String(p),_.USAGE)}if(u.removed){let p=(u.definition?.name??e??"").trim();if(p.length>0){let m=await Zs(a,r,o,p);m>0&&s.push(`items_using_type:${m}`)}await $e({pmRoot:a,filePath:i,raw:xe(u.file),op:"schema:remove-type",author:c,settings:r}),s.push(...await U({path:i,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await to(a,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:i,definitions:u.file.definitions.length},warnings:Te(s),generated_at:A()}}function On(e,t){return ce(e,t.files.statuses,te.statuses)}function Jt(e,t){return ce(e,t.files.fields,te.fields)}function no(e,t){return ce(e,t.files.types,te.types)}async function rt(e,t,n,a){for(let r of t){let o=Sa(r.folder??xa(r.name)),i=Xs.join(e,o);await E(i)||(await Qs(i,{recursive:!0}),n.push(...await U({path:i,scope:"project",op:a})))}}function Nn(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 ac(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 rc(e){let t=new Map;for(let n of e){let a=pe(n.id);if(a.length!==0){t.set(a,a);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let o=pe(r);o.length>0&&!t.has(o)&&t.set(o,a)}}}return t}async function zf(e,t,n){let a=D(process.cwd(),n.path);await _e(a);let r;try{r=Ua({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(m){throw new g(m instanceof Error?m.message:String(m),_.USAGE)}let o=await R(a),i=K(o.schema),s=On(a,i),c=nt(i);try{_n(r,c.alias_to_id)}catch(m){throw new g(m instanceof Error?m.message:String(m),_.USAGE)}let d=ac(c.by_id.get(r.id)),l=[],u=Y(t.author,o.author_default),f=he(o),h=await X(a,Zr,o.locks.ttl_seconds,u,!!t.force,f.force_required_for_stale_lock,o.locks.wait_ms),p;try{let m=await q(s),w;try{w=Ue(m)}catch(v){throw new g(v instanceof Error?v.message:String(v),_.GENERIC_FAILURE)}let y=rc(w.statuses);try{_n(r,y)}catch(v){throw new g(v instanceof Error?v.message:String(v),_.USAGE)}p=za(w,r,d),await $e({pmRoot:a,filePath:s,raw:ze(p.file),op:"schema:add-status",author:u,settings:o}),l.push(...await U({path:s,scope:"project",op:"schema:add-status"}))}finally{await h()}return{action:"add-status",registered:!0,replaced:p.replaced,status:p.definition,file:{path:s,statuses:p.file.statuses.length},warnings:Te(l),generated_at:A()}}async function Jf(e,t,n){let a=D(process.cwd(),n.path);await _e(a);let r=await R(a),o=K(r.schema),i=On(a,o),s=[],c=Y(t.author,r.author_default),d=he(r),l=await X(a,Zr,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let f=await q(i),h;try{h=Ue(f)}catch(p){throw new g(p instanceof Error?p.message:String(p),_.GENERIC_FAILURE)}try{u=Ja(h,e)}catch(p){throw new g(p instanceof Error?p.message:String(p),_.USAGE)}if(u.removed){let p=pe(u.definition?.id??e);await tc(s,a,r,o,p),await $e({pmRoot:a,filePath:i,raw:ze(u.file),op:"schema:remove-status",author:c,settings:r}),s.push(...await U({path:i,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:i,statuses:u.file.statuses.length},warnings:Te(s),generated_at:A()}}function ao(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 oc(e,t,n){return{...ao(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 ro(e){return{id:e.id,source:gn.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 oo(e,t,n){let a=e.toLowerCase();return n.has(a)?"extension":t.has(a)?"custom":"builtin"}function ic(){let e=new Map,t=M();for(let n of t?.item_types??[]){let a=n.types;if(Array.isArray(a))for(let r of a){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r.name;typeof o=="string"&&o.trim().length>0&&e.set(o.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function sc(e){let t=nt(e),n=[],a=[];for(let r of t.definitions){let o=ro(r);o.source==="builtin"?n.push(o):a.push(o)}return{builtin:n,custom:a}}async function ot(e){let t=D(process.cwd(),e.path);await _e(t);let n=await R(t),a=K(n.schema),r=ce(t,a.files.types,te.types),o=On(t,a),i=H(n,M()),s=ic(),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:r,statusesPath:o,byType:i.by_type,customNames:c,extensionProvenance:s,schema:a}}async function Wf(e){let t=await ot(e),n=[],a=[],r=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=oo(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=ao(s);c==="extension"?r.push(d):c==="custom"?a.push(d):n.push(d)}let o=sc(t.schema),i=Rt(t.schema).definitions.map(Nn);return{action:"list",builtin:n,custom:a,extension:r,counts:{builtin:n.length,custom:a.length,extension:r.length,total:n.length+a.length+r.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:i,counts:{total:i.length}},file:{path:t.typesPath},generated_at:A()}}async function qf(e,t){let n=(e??"").trim();if(n.length===0)throw new g("Type name must not be empty.",_.USAGE);let a=await ot(t),r=Object.values(a.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(i=>i.toLowerCase()===n.toLowerCase()));if(!r)throw new g(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${It(n)}" to register it.`,_.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:oc(r,oo(r.name,a.customNames,new Set(a.extensionProvenance.keys())),a.extensionProvenance.get(r.name.toLowerCase())),file:{path:a.typesPath},generated_at:A()}}async function Gf(e,t){let n=pe(e);if(n.length===0)throw new g("Status id must not be empty.",_.USAGE);let a=await ot(t),r=nt(a.schema),o=r.alias_to_id.get(n)??n,i=r.by_id.get(o);if(!i)throw new g(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${It(e??"")}" to register it.`,_.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:ro(i),file:{path:a.statusesPath},generated_at:A()}}async function Hf(e,t,n){let a=D(process.cwd(),n.path);await _e(a);let r;try{r=La({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 g(p instanceof Error?p.message:String(p),_.USAGE)}let o=await R(a),i=K(o.schema),s=Jt(a,i),c=[],d=Ot(r.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=Y(t.author,o.author_default),u=he(o),f=await X(a,eo,o.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,o.locks.wait_ms),h;try{let p=await q(s),m;try{m=Me(p)}catch(w){throw new g(w instanceof Error?w.message:String(w),_.GENERIC_FAILURE)}h=Ma(m,r),await $e({pmRoot:a,filePath:s,raw:Fe(h.file),op:"schema:add-field",author:l,settings:o}),c.push(...await U({path:s,scope:"project",op:"schema:add-field"}))}finally{await f()}return{action:"add-field",registered:!0,replaced:h.replaced,field:h.definition,file:{path:s,fields:h.file.fields.length},warnings:Te(c),generated_at:A()}}async function cc(e,t,n,a){let r=H(t,M());return(await Ce(e,t.item_format,r.type_to_folder,[],n)).filter(i=>{let s=i[a];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function Bf(e,t,n){let a=D(process.cwd(),n.path);await _e(a);let r=await R(a),o=K(r.schema),i=Jt(a,o),s=[],c=Y(t.author,r.author_default),d=he(r),l=await X(a,eo,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let f=await q(i),h;try{h=Me(f)}catch(p){throw new g(p instanceof Error?p.message:String(p),_.GENERIC_FAILURE)}try{u=Fa(h,e)}catch(p){throw new g(p instanceof Error?p.message:String(p),_.USAGE)}if(u.removed){let p=Ct(u.definition?.key??e),m=Ct(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(m.length>0){let w=await cc(a,r,o,m);w>0&&s.push(`items_using_field:${w}`)}await $e({pmRoot:a,filePath:i,raw:Fe(u.file),op:"schema:remove-field",author:c,settings:r}),s.push(...await U({path:i,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:i,fields:u.file.fields.length},warnings:Te(s),generated_at:A()}}async function Vf(e){let t=await ot(e),n=Rt(t.schema).definitions.map(Nn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Jt(t.pmRoot,t.schema)},generated_at:A()}}async function Kf(e,t){let n=Ct(e);if(n.length===0)throw new g("Field key must not be empty.",_.USAGE);let a=await ot(t),r=Rt(a.schema).by_key.get(n);if(!r)throw new g(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${It(e??"")}" to register it.`,_.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Nn(r),file:{path:Jt(a.pmRoot,a.schema)},generated_at:A()}}async function Yf(e,t,n){let a=D(process.cwd(),n.path);await _e(a);let r;try{let m=ja(e);if(m===void 0)throw new Error(`Type preset name is required. Allowed: ${Pa.join(", ")}.`);r=m}catch(m){throw new g(m instanceof Error?m.message:String(m),_.USAGE)}let o=await R(a),i=K(o.schema),s=no(a,i),c=[],d=Y(t.author,o.author_default),l=he(o),u=[],f=[],h,p=await X(a,zt,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms);try{let m=await q(s),w;try{w=me(m)}catch(v){throw new g(v instanceof Error?v.message:String(v),_.GENERIC_FAILURE)}let y=w;for(let v of hn(r)){let x=At(y,v);y=x.file,(x.replaced?f:u).push(x.definition.name)}h=y.definitions.length,await $e({pmRoot:a,filePath:s,raw:xe(y),op:"schema:apply-preset",author:d,settings:o}),await rt(a,hn(r),c,"schema:apply-preset-folder"),c.push(...await U({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await p()}return{action:"apply-preset",preset:r,registered:u,replaced:f,file:{path:s,definitions:h},warnings:Te(c),generated_at:A()}}function dc(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new g("--min-count must be a positive integer (>= 1).",_.USAGE);return e}async function Xf(e,t){let n=D(process.cwd(),t.path);await _e(n);let a=await R(n),r=K(a.schema),o=no(n,r),i=dc(e.minCount),s=H(a,M()),d=(await Ce(n,a.item_format,s.type_to_folder,[],r)).map(x=>typeof x.title=="string"?x.title:""),l=Dr(d,{minCount:i}),u=[],f=[],h=[],p=[],m;if(!e.apply){let x;try{x=me(await q(o))}catch(I){throw new g(I instanceof Error?I.message:String(I),_.GENERIC_FAILURE)}return m=x.definitions.length,{action:"infer-types",applied:!1,min_count:i,candidates:l,registered:f,replaced:h,skipped:p,file:{path:o,definitions:m},warnings:u,generated_at:A()}}let w=Y(e.author,a.author_default),y=he(a),v=await X(n,zt,a.locks.ttl_seconds,w,!!e.force,y.force_required_for_stale_lock,a.locks.wait_ms);try{let x=await q(o),I;try{I=me(x)}catch(T){throw new g(T instanceof Error?T.message:String(T),_.GENERIC_FAILURE)}let b=I;for(let T of l){if(T.shadows_builtin){p.push({name:T.name,reason:"shadows_builtin"});continue}let J;try{J=fn({name:T.name})}catch{p.push({name:T.name,reason:"invalid_type_token"});continue}let W=At(b,J);b=W.file,(W.replaced?h:f).push(W.definition.name)}m=b.definitions.length,await $e({pmRoot:n,filePath:o,raw:xe(b),op:"schema:infer-types",author:w,settings:a}),await rt(n,b.definitions.filter(T=>f.includes(T.name)||h.includes(T.name)),u,"schema:infer-types-folder"),u.push(...await U({path:o,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:i,candidates:l,registered:f,replaced:h,skipped:p,file:{path:o,definitions:m},warnings:Te(u),generated_at:A()}}import io from"node:fs/promises";import Dn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af718efb-d1cf-5adc-9518-c858627e1b54")}catch{}})();function Q(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function k(e){return e.trim().toLowerCase()}function Wt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let a=t.length;for(;a>n&&t[a-1]==="-";)a-=1;let r=t.slice(n,a);if(r.length===0)throw new g("Extension manifest name must resolve to a non-empty directory name.",_.USAGE);if(r==="."||r==="..")throw new g('Extension manifest name must not resolve to "." or "..".',_.USAGE);return r}function Pn(e){return Aa(e)}async function lc(e){try{let t=JSON.parse(await io.readFile(Dn.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(a=>typeof t.scripts?.[a]=="string")}}catch{return{has_build_script:!1}}}async function uc(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new g(`Extension entry file is missing at "${t}".`,_.USAGE);let a=await lc(n.source_root),r=a.package_name?`pm install npm:${a.package_name}`:void 0,o=n.source_input??n.source_root;return new g(`Extension entry "${e.entry}" is absent from GitHub source "${o}". pm install copies GitHub repositories without running package scripts${a.has_build_script?", and this package declares a build or publish script":""}. ${r?`Try "${r}" 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:r?[r,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:r?[`Retry with ${r}.`,"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],...r?{next_best_command:r}:{}}})}async function Ke(e,t={}){let n=Dn.join(e,"manifest.json");if(!await E(n))throw new g(`Extension manifest is missing at "${n}".`,_.USAGE);let a;try{a=JSON.parse(await io.readFile(n,"utf8"))}catch(i){throw new g(`Failed to parse extension manifest at "${n}": ${mc(i)}`,_.USAGE)}let r=Pn(a);if(!r)throw new g(`Extension manifest at "${n}" is invalid.`,_.USAGE);let o=Dn.resolve(e,r.entry);if(!oe(e,o))throw new g(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,_.USAGE);if(!await E(o))throw await uc(r,o,t);if(!await Ca(e,o))throw new g(`Extension entry "${r.entry}" resolves outside extension directory after symlink resolution.`,_.USAGE);return{directory:e,manifest_path:n,entry_path:o,manifest:r}}function mc(e){return e instanceof Error?e.message:String(e)}import jn from"node:fs/promises";import pc 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]="5d60cd29-09fb-515c-acaa-b5a2b136d8ab")}catch{}})();var fc=".managed-extensions.json",qt=1;function it(e){return pc.join(e,fc)}function hc(){return{version:qt,updated_at:A(),entries:[]}}function st(e){return[...e].sort((t,n)=>{let a=t.scope.localeCompare(n.scope);if(a!==0)return a;let r=t.name.localeCompare(n.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function so(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 Z(e){return typeof e=="string"?e:void 0}function gc(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 _c(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:Z(t.name),package:Z(t.package),version:Z(t.version),repository:Z(t.repository),owner:Z(t.owner),repo:Z(t.repo),ref:Z(t.ref),subpath:Z(t.subpath),commit:Z(t.commit)}}function yc(e){if(typeof e!="object"||e===null)return null;let t=e;if(!gc(t))return null;let n=_c(t.source);if(!n)return null;let a=Ta(t.contributions);return a===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Q(t.capabilities),contributions:a,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Z(t.last_update_check_at),last_update_remote_commit:Z(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Z(t.update_error)}}function wc(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==qt||!Array.isArray(t.entries))return null;let n=[];for(let a of t.entries){let r=yc(a);r&&n.push(r)}return{version:qt,updated_at:Z(t.updated_at)??A(),entries:st(n)}}async function B(e){let t=it(e),n=hc();try{let a=await jn.readFile(t,"utf8"),r=JSON.parse(a),o=wc(r);if(!o)throw new g(`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(a){if(a instanceof g)throw a;if(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT")return{path:t,state:n,warnings:[]};throw new g(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,_.GENERIC_FAILURE)}}async function De(e,t){let n=it(e),a={version:qt,updated_at:A(),entries:st(t.entries)};await jn.mkdir(e,{recursive:!0}),await jn.writeFile(n,`${JSON.stringify(a,null,2)}
5
- `,"utf8")}function ct(e,t){let n=e.entries.filter(a=>k(a.name)!==k(t.name)&&k(a.directory)!==k(t.directory));return n.push(t),{...e,updated_at:A(),entries:st(n)}}async function co(e,t,n,a){let r=t.entries.find(i=>k(i.name)===k(n));if(!r)return t;let o=ct(t,{...r,contributions:a});return await De(e,o),o}import{execFile as Cc}from"node:child_process";import O from"node:fs/promises";import zn from"node:os";import $ from"node:path";import{fileURLToPath as Rc}from"node:url";import{promisify as Oc}from"node:util";import Nc from"npm-package-arg";import{extract as Dc,list as Pc}from"tar";import vc 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]="27a2b542-853e-52e1-ad80-11bab01b07a2")}catch{}})();var bc="PM_CLI_PACKAGE_ROOT",lo={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},kc=new Set(["*","all"]);function Ln(){let e=[],t=process.env[bc];return typeof t=="string"&&t.trim().length>0&&e.push(de.resolve(t.trim())),e.push(be(import.meta.url,["../../.."])),[...new Set(e)]}async function dt(e){let t=e.trim().toLowerCase(),n=await mo(t);if(n)return n;let a=lo[t];if(!a)return null;for(let r of Ln()){let o=de.join(r,".agents","pm","extensions",a.legacy_extension_directory);if(await E(de.join(o,"manifest.json")))return o}return null}function uo(e){return kc.has(e.trim().toLowerCase())}function xc(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Sc(e,t){let n=await vc.readdir(e,{withFileTypes:!0});for(let a of n){if(!a.isDirectory()||!a.name.startsWith("pm-"))continue;let r=de.join(e,a.name);if(!await E(de.join(r,"package.json")))continue;let o=await $t(r),i=o.aliases&&o.aliases.length>0?o.aliases:[xc(a.name)];for(let s of i){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:a.name,package_root:r,package_name:o.package_name??null})}}}async function Mn(){let e=new Map;for(let t of Ln()){let n=de.join(t,"packages");await E(n)&&await Sc(n,e)}for(let[t,n]of Object.entries(lo))if(!e.has(t))for(let a of Ln()){let r=de.join(a,"packages",n.package_directory);if(await E(de.join(r,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:r,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Gt(){return(await Mn()).map(e=>e.alias)}async function mo(e){let t=e.trim().toLowerCase();return(await Mn()).find(a=>a.alias===t||a.package_directory.toLowerCase()===t||a.package_name?.toLowerCase()===t)?.package_root??null}async function po(e){let t=await mo(e);return t?(await $t(t)).package_name??null:null}async function fo(e){let t=await dt(e);if(!t)return null;try{let n=await Tt(t);return n.length!==1?null:(await Ke(n[0])).manifest.name}catch{return null}}function Ec(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 $c(e,t,n,a,r){let o=n==="global"?"--global":"--project",i=Object.fromEntries(pn.filter(s=>s!=="extensions").map(s=>[s,e.resources[s]??[]]).filter(([,s])=>Array.isArray(s)&&s.length>0));return{alias:t.alias,bundled:!0,available:!0,installed:a.has(t.alias)||r.has(de.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,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:i,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:Ec(e),media:e.catalog?.media}}}async function ho(e,t,n={}){let a=Le(D(process.cwd(),t.path),process.cwd()),r=e==="global"?a.global:a.project,o=await B(r),i=new Set(o.state.entries.filter(u=>u.scope===e).filter(u=>u.source.kind!=="builtin").map(u=>de.resolve(u.source.location))),s=new Set(o.state.entries.filter(u=>u.scope===e&&u.source.kind==="builtin").flatMap(u=>[u.source.name,u.source.input,u.source.location]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toLowerCase())),c=[];for(let u of await Mn()){let f=await $t(u.package_root);c.push($c(f,u,e,s,i))}let d=Ic(n.fields),l=d?c.map(u=>Ac(u,d)):c;return{total:l.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:pn.filter(u=>u!=="extensions"),packages:l}}var Tc=new Set(["alias","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function Ic(e){if(e===void 0)return;let t=vr(e);if(t.length===0)throw new g("Package catalog --fields requires a comma-separated list of field names",_.USAGE);let n=t.filter(a=>!Tc.has(a));if(n.length>0)throw new g(`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 Ac(e,t){let n={};for(let a of t)a==="category"?n[a]=e.catalog?.category??null:a==="display_name"?n[a]=e.catalog?.display_name??null:n[a]=e[a]??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]="8994c8e2-8e3a-5e00-a3ca-7bd553c045d7")}catch{}})();var Jn=Oc(Cc),Bt="@unbrained/pm-cli",jc={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},Fn;async function go(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let a=$.resolve(t);for(;;){let r=$.join(a,"node_modules",...n.split("/")),o=$.join(r,"package.json");if(await E(o))try{let s=JSON.parse(await O.readFile(o,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:r}}catch{return null}let i=$.dirname(a);if(i===a)return null;a=i}}function Un(e,t,n){let a=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(a.length<2)return null;let r=a[0],o=a[1].replace(/\.git$/i,"");if(r.length===0||o.length===0)return null;let i=a.slice(2),s,c;return i[0]==="tree"&&i.length>=2?(s=i[1],c=i.slice(2).join("/")):i.length>0&&(c=i.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:r,repo:o,repository:`https://github.com/${r}/${o}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function Lc(e,t,n){let a=e.slice(4).trim();if(a.length===0)throw new g('npm package source must include a package spec after "npm:".',_.USAGE);if(t)throw new g('Options "--gh/--github" cannot be combined with npm: package sources.',_.USAGE);if(n)throw new g('Option "--ref" cannot be combined with npm: package sources.',_.USAGE);return{kind:"npm",input:e,spec:a}}function Vt(e,t={}){let n=e.trim();if(n.length===0)throw new g("Extension source is required for --install.",_.USAGE);let a=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Lc(n,t.forceGithub===!0,a);let r=(()=>{try{let i=new URL(n);if(i.hostname!=="github.com")return null;let s=i.pathname.replace(/^\/+/,"");return Un(s,n,a)}catch{return null}})();if(r)return r;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let i=Un(o,n,a);if(!i)throw new g(`Invalid GitHub source "${n}".`,_.USAGE);return i}if(t.forceGithub){let i=Un(n,n,a);if(!i)throw new g(`Invalid GitHub shorthand "${n}".`,_.USAGE);return i}if(/^https?:\/\//i.test(n))throw new g(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,_.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function Ht(e,t=Jn,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(a){let r=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr):"",o=r.trim().length>0?r.trim():a instanceof Error?a.message:String(a);throw new g(`Git command failed: git ${e.join(" ")}
6
- ${o}`,_.GENERIC_FAILURE)}}function Mc(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Fc(e=process.platform){return e==="win32"}async function _o(e,t,n=Jn,a=process.platform){let r=Mc(a);try{return((await n(r,e,{cwd:t,encoding:"utf8",shell:Fc(a)})).stdout??"").trim()}catch(o){let i=typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr):"",s=i.trim().length>0?i.trim():o instanceof Error?o.message:String(o);throw new g(`npm command failed: ${r} ${e.join(" ")}
7
- ${s}`,_.GENERIC_FAILURE)}}function Uc(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 zc(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 Jc(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return zc(e)||n.includes("not found")}function Wc(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function qc(e){let t=Uc(e),n=Wc(t),a=t.replace(/^.*\//,""),r=n?`github.com/unbraind/${a}`:void 0,o=r?`pm install --project ${r}`: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}`],...r&&o?{fallback_candidates:[{source:r,command:o,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:o}:{}}}}}function Gc(e,t){if(!Jc(t))return null;let n=qc(e);return new g(n.message,_.NOT_FOUND,n.context)}async function yo(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await E(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=Rc(t);return await E(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await E(t))return t}return null}async function Hc(e){let t=await yo(e);if(t)return t;let n=Bc(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Bc(e,t=process.cwd()){let n="@file:",a=e.lastIndexOf(n);if(a<=0)return e;let r=e.slice(0,a),o=e.slice(a+n.length);if(r.trim().length===0||o.trim().length===0||o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${r}@${$.resolve(t,o)}`;let i;try{i=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(i)?i.slice(1):i;return`${r}@${s}`}function Vc(e,t){try{let a=JSON.parse(e),r=Array.isArray(a)?a[0]:void 0;if(r&&typeof r.filename=="string"&&r.filename.trim().length>0)return{tarball:$.resolve(t,r.filename),package:typeof r.name=="string"?r.name:void 0,version:typeof r.version=="string"?r.version:void 0}}catch{}let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0).at(-1);if(!n)throw new g("npm pack did not report a tarball filename.",_.GENERIC_FAILURE);return{tarball:$.resolve(t,n)}}async function Kc(e){return Yc(e,_o)}async function Yc(e,t){let n=await yo(e.spec);if(n){if((await O.stat(n)).isFile()&&wo(n))return vo(n);let s=$.join(n,"package.json"),c=await E(s)?JSON.parse(await O.readFile(s,"utf8")):{};return{directory:await lt(n,e.input),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{}}}let a=await O.mkdtemp($.join(zn.tmpdir(),"pm-npm-package-source-")),r=$.join(a,"pack"),o=$.join(a,"extract");await O.mkdir(r,{recursive:!0}),await O.mkdir(o,{recursive:!0});try{let i=await Hc(e.spec),s=await t(["pack",i,"--json","--pack-destination",r]),c=Vc(s,r);await Jn("tar",["-xzf",c.tarball,"-C",o],{encoding:"utf8"});let d=$.join(o,"package");return await bo(d),{directory:await lt(d,e.input),package:c.package,version:c.version,cleanup:async()=>{await O.rm(a,{recursive:!0,force:!0})}}}catch(i){await O.rm(a,{recursive:!0,force:!0});let s=Gc(e.spec,i);throw s||i}}function wo(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ye(e){throw new g(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 Xc(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&ye(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let a=e.path,r=a.split("/");(a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||r.some(o=>o===".."))&&ye(`Local package archive contains an escaping path: "${a}".`),r[0]!=="package"&&ye(`Local package archive entry "${a}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ye(`Local package archive link "${a}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ye(`Local package archive entry "${a}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ye(`Local package archive entry "${a}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&ye(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),a==="package/package.json"&&(n.packageJsonEntries+=1)}async function vo(e,t=jc){(await O.stat(e)).size>t.maxArchiveBytes&&ye(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let a=await O.mkdtemp($.join(zn.tmpdir(),"pm-local-package-archive-")),r=$.join(a,"extract");await O.mkdir(r,{recursive:!0});let o={entries:0,expandedBytes:0,packageJsonEntries:0},i;try{if(await Pc({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(i===void 0)try{Xc(l,t,o)}catch(u){i=u}}}),i!==void 0)throw i;o.packageJsonEntries!==1&&ye(`Local package archive must contain exactly one package/package.json entry; found ${o.packageJsonEntries}.`),await Dc({file:e,cwd:r,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=$.join(r,"package"),c=$.join(s,"package.json"),d=JSON.parse(await O.readFile(c,"utf8"));return await bo(s),{directory:await lt(s,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await O.rm(a,{recursive:!0,force:!0})}}}catch(s){throw await O.rm(a,{recursive:!0,force:!0}),s}}async function bo(e,t=_o){let n=$.join(e,"package.json");if(!await E(n))return;let a;try{a=JSON.parse(await O.readFile(n,"utf8"))}catch{return}if(typeof a!="object"||a===null)return;let r=a,o=ad(r),i=Qc(r);if(o.length===0&&!i)return;let s={...a};delete s.devDependencies;let c={...s};Zc(c),await O.writeFile(n,`${JSON.stringify(c,null,2)}
8
- `,"utf8");try{await Promise.all([O.rm($.join(e,"package-lock.json"),{force:!0}),O.rm($.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),i&&await ed(e)}finally{await O.writeFile(n,`${JSON.stringify(s,null,2)}
9
- `,"utf8")}}function Qc(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Bt in t)return!0;return!1}function Zc(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let a={...n};delete a[Bt],Object.keys(a).length===0?delete e[t]:e[t]=a}}async function ed(e){let t=be(import.meta.url,["../../.."]),[n,a]=Bt.split("/"),r=$.join(e,"node_modules",n),o=$.join(r,a);await O.mkdir(r,{recursive:!0}),await O.rm(o,{recursive:!0,force:!0}),await O.symlink(t,o,td(process.platform))}function td(e){return e==="win32"?"junction":"dir"}function nd(e,t){if(e.startsWith("-"))throw new g(`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(a=>{let r=a.charCodeAt(0);return r<=31||r===127||"&|;()`\"'".includes(a)}))throw new g(`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{Nc.resolve(e,t)}catch{throw new g(`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 ad(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[a,r]of Object.entries(n)){if(a===Bt||typeof r!="string"||r.trim().length===0||t.has(a))continue;let o=r.trim();t.set(a,nd(a,o))}return[...t.values()]}async function lt(e,t){let n=await Tt(e);if(n.length===1)return n[0];if(n.length>1){let a=n.map(r=>$.relative(e,r).replaceAll($.sep,"/")).sort((r,o)=>r.localeCompare(o));throw new g(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${a.join(", ")}`,_.USAGE)}throw new g(`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 rd(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push($.posix.join(".agents/pm/extensions",t.subpath)),n.push($.posix.join(".custom/pm-extensions",t.subpath)),n.push($.posix.join(".custom/pm-extension",t.subpath)));for(let r of n){let o=$.resolve(e,r);if(oe(e,o)&&await E($.join(o,"manifest.json")))return{directory:o,resolved_subpath:r}}if(await E($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let a=await lt(e,t.input);return{directory:a,resolved_subpath:$.relative(e,a).replaceAll($.sep,"/")}}function od(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 id(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!od(n))return new g(t,_.NOT_FOUND);let a=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,i=typeof o=="string"&&o.trim().length>0?$.resolve(o.trim()):"";Fn?.key!==i&&(Fn={key:i,aliases:await Gt()}),a=Fn.aliases}catch{}let r=[`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): ${a.join(", ")}`];return new g(`${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:r,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function ko(e){if(e.kind==="local"){let a;try{a=await O.stat(e.absolute_path)}catch{throw await id(e)}if(a.isFile()&&wo(e.absolute_path)){let o=await vo(e.absolute_path);return{source:e,directory:o.directory,source_root:$.dirname(o.directory),resolved_subpath:$.relative($.dirname(o.directory),o.directory).replaceAll($.sep,"/"),npm_package:o.package,npm_version:o.version,cleanup:o.cleanup}}if(!a.isDirectory())throw new g(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,_.USAGE);let r=await lt(e.absolute_path,e.input);return{source:e,directory:r,source_root:e.absolute_path}}if(e.kind==="npm"){let a=await Kc(e);return{source:e,directory:a.directory,source_root:$.dirname(a.directory),cleanup:a.cleanup,resolved_subpath:$.relative($.dirname(a.directory),a.directory).replaceAll($.sep,"/"),npm_package:a.package,npm_version:a.version}}let t=await O.mkdtemp($.join(zn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Ht(n);let a=await Ht(["-C",t,"rev-parse","HEAD"]),r=await rd(t,e);return{source:e,directory:r.directory,source_root:t,resolved_subpath:r.resolved_subpath,commit:a,cleanup:async()=>{await O.rm(t,{recursive:!0,force:!0})}}}catch(a){throw await O.rm(t,{recursive:!0,force:!0}),a}}async function xo(e,t){if(!await E(e)||!await E(t))return!1;let[n,a]=await Promise.all([O.realpath(e),O.realpath(t)]);return n===a}import ut from"node:fs/promises";import mt 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]="30dfc6e4-27c5-56c0-981b-94e85b780f1f")}catch{}})();var Wn=1,Pe="2026.6.24",sd=">=22.18.0",cd={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},So=new Set([...Wa.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Ha).map(e=>e.toLowerCase()),"scaffold"]),dd="^6.0.0",ld="^22.0.0",To=["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."," }"," }","}",""],le=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Eo(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Io(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 Ao(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 ud={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},$o=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Co={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"]},md={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"]'},pd={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."},fd={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."},Ro="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",hd={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."]},gd={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."]},_d={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`."]},yd={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 Oo(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 No(e,t){return e==="schema"?_d[t]:e==="profile"?yd[t]:gd[t]}function wd(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(),a=0;for(;t[a]?.toLowerCase()==="starter";)a+=1;let r=t[a]?.toLowerCase(),o=a>0&&(a===t.length||r!==void 0&&So.has(r));return`${(So.has(n)||o?["starter",...t]:t).join(" ")} ping`}function Do(e){let t=e,n=`${e}s`,a=e.replace(/-/g,""),r=a===t?[]:[a],o=`${e.replace(/-/g,"_")}_owner`,i="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(r)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(i)},`,' 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(i)}],`,` [${JSON.stringify(i)}, "in_progress"],`,` [${JSON.stringify(i)}, "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 vd(e,t,n){let a=`${e}-search`,r=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,i=[" 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 i;if(n==="search")return[...i,""," // 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(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."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(r)},`,' 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`,f=`${e}-0001-init`;return[...i,""," // 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(f)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...i,""," // 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({",...Do(e).map(s=>` ${s}`)," });"]:n==="importers"?[...i,""," // 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"?[...i,""," // 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"?[...i,""," // 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"?[...i,""," // 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 };`," });"]:[...i,""," // 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 bd(e,t,n){let a=n==="hooks",r=n==="search",o=n==="importers",i=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",f=md[n],h=e,p=`${e}s`,m=`${e.replace(/-/g,"_")}_note`,w=`${e}-0001-init`,y=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=a?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${f},`," });"," 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;",...le,"});",""]:[],x=r?qn(e,t,"search",f):[],I=o?qn(e,t,"importers",f):[],b=i?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${f},`," });"," let deactivated = false;"," try {",...Eo(Io({extensionName:e,itemTypeName:h,itemTypeFolder:p,fieldName:m,migrationId:w,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...le,"});",""]:[],T=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${f},`," });"," let deactivated = false;"," try {",...Eo(Ao(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...le,"});",""]:[],J=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${f},`," });"," 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;",...le,"});",""]:[],W=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${f},`," });"," 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;",...le,"});",""]:[],S=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${f},`," });"," 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;",...le,"});",""]:[],P=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${f},`," });"," 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;",...le,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...y,'} from "@unbrained/pm-cli/sdk/testing";',...r?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...To,`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: ${f},`," });"," 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;",...le,"});","",...v,...x,...I,...b,...T,...J,...W,...S,...P,`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: ${f},`," });"," 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(`
10
- `)}function kd(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let a=`${e.replace(/-/g," ")} items`;return[t,`${a} import`,`${a} export`]}return[t]}var xd={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"},Sd={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 Ed(e,t,n){let a=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.",',...a?[" 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,",...a?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function $d(e,t,n){let a=[],r=[...Ed(e,t,n)],o=[" commands: [pingCommand],"],i=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),f=u===d?[]:[u],h=`${e.replace(/-/g,"_")}_note`,p=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":a.push("defineAfterCommandHook"),r.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":a.push("defineSearchProvider","defineVectorStoreAdapter"),r.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(i)},`," 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":a.push("defineExporter","defineImporter"),r.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":a.push("defineItemField","defineItemType","defineMigration"),r.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(h)},`,' 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(f)},`," // 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":a.push("defineProjectProfile"),r.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({",...Do(e),"});"),o.push(" profiles: [starterProfile],");break;case"renderers":a.push("defineRendererOverride"),r.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":a.push("defineParserOverride"),r.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":a.push("definePreflightOverride"),r.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":a.push("defineServiceOverride"),r.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:a,definitions:r,blueprintFields:o}}function Td(e,t,n){let a=$d(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...a.builderImports].sort((o,i)=>o.localeCompare(i)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...a.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({",...a.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(`
11
- `)}function qn(e,t,n,a){if(n==="commands")return[];let r=`${e}-search`,o=`${e}-vector`,i=`${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: ${a},`," });"],f=h=>[...u," let deactivated = false;"," try {",...h.map(p=>p===""?p:` ${p}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...le];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...f([" // 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 () => {`,...f([` ext.assertSearchProvider({ name: ${JSON.stringify(r)}, 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 query = await ext.runSearchProvider({",` provider: ${JSON.stringify(r)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings: {} as PmSettings,"," 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(r)},`,' operation: "embed",',' context: { input: "abc", settings: {} as PmSettings, 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: {} as PmSettings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...f([` ext.assertImporter({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(i)},`,' 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(i)},`,' 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 () => {`,...f(Io({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...f(Ao(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...f([" // 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 () => {`,...f([" // 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 () => {`,...f([" // 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 () => {`,...f([" // 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 Id(e,t,n){let a=n==="parser",r=JSON.stringify([...Co[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" };',"",...To,`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(Pe)},`," },",` target: { pmVersion: ${JSON.stringify(Pe)} },`," });"," // 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, ${r});`,` assert.deepEqual(report.manifest?.capabilities, ${r});`,"});","",`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: ${r},`," });"," 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)},`,...a?[" 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;",...le,"});","",...qn(e,t,n,r)].join(`
12
- `)}function Ad(e,t,n){let a=Oo(n,"package"),r=No(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",a,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${xd[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`.",Ro,"- `.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 ${Sd[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.",...r,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Wn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Pe}\`. 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(`
13
- `)}function Cd(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 Rd(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 Od(e,t,n,a){let r=["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"&&r.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&r.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(a.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(a.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"&&r.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"&&r.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(a.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(a.itemTypeName)},`,` folder: ${JSON.stringify(a.itemTypeFolder)},`,` aliases: ${JSON.stringify(a.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(a.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&r.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(a.itemTypeName)}, folder: ${JSON.stringify(a.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&r.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&r.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&r.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"&&r.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),r}function Nd(e,t,n){let a=[];return t==="renderers"&&a.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&a.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&a.push(" api.registerPreflight(preflightOverride);"),t==="services"&&a.push(' api.registerService("output_format", outputService);'),t==="hooks"&&a.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&a.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&a.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&a.push(" api.registerProfile(starterProfile);"),t==="importers"&&a.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.",'," },"," ],"," });"),a}function Dd(e,t,n,a="commands",r=!1){let o=`pm-${e}`,i=Co[a],s=kd(e,t,a),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Wn,pm_min_version:Pe,trusted:!0,sandbox_profile:"strict",permissions:{...cd},capabilities:i,...s.length>0?{activation:{commands:s}}:{}},null,2)}
14
- `,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...vd(e,t,a),"}","","// `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(`
15
- `),l=`${JSON.stringify(ud,null,2)}
16
- `,u=pd[a],f=Oo(a,"package"),h=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:sd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Pe}`},devDependencies:{"@types/node":ld,typescript:dd},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)}
17
- `,p=bd(e,t,a),m=fd[a],w=["node_modules/","*.log","*.tsbuildinfo",""].join(`
18
- `),y=Cd(e),x=["```ts",`import { ${Rd(a)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Od(e,t,a,y),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Nd(t,a,y),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],I=[`# ${o}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",f,u,m,Ro,"- `.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`.",...hd[a],...No(a,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Pe}\`. 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 \`${Wn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Pe}\`. 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(`
19
- `);return{"package.json":h,"manifest.json":c,"index.ts":r?Td(e,t,a):d,"index.test.ts":r?Id(e,t,a):p,"tsconfig.json":l,".gitignore":w,"README.md":r?Ad(o,t,a):I}}async function Po(e,t="extension",n="commands",a=!1){let r=n.trim().toLowerCase();if(!$o.includes(r))throw new g(`Unknown scaffold capability "${n}". Supported capabilities: ${$o.join(", ")}.`,_.USAGE);let o=r;if(a&&t!=="package")throw new g("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",_.USAGE);let i=a?"declarative":"imperative",s=e.trim(),c=mt.resolve(process.cwd(),s),d=Wt(mt.basename(c)).replace(/^(?:pm-)+/u,""),l=wd(d),u=Dd(d,l,t,o,a),f=!1;if(await E(c)){if(!(await ut.stat(c)).isDirectory())throw new g(`Scaffold target "${c}" exists and is not a directory.`,_.CONFLICT)}else await ut.mkdir(c,{recursive:!0}),f=!0;for(let[p,m]of Object.entries(u)){let w=mt.join(c,p);if(!await E(w))continue;if(await ut.readFile(w,"utf8")!==m)throw new g(`Scaffold file "${p}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,_.CONFLICT)}let h=[];for(let[p,m]of Object.entries(u)){let w=mt.join(c,p);if(await E(w)){h.push({path:p,status:"unchanged"});continue}await ut.mkdir(mt.dirname(w),{recursive:!0}),await ut.writeFile(w,m,"utf8"),h.push({path:p,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:o,style:i,target_path:c,created_directory:f,files:h}}(function(){try{var e=typeof window<"u"?window:typeof 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 jo(e,t){return`${e}:${k(t)}`}function Pd(e,t){let n=[];for(let[a,r]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let i of r){let s=o.get(i.command)??[];o.set(i.command,[...s,i])}for(let[i,s]of o){if(t!==null&&!s.some(d=>t.has(k(d.name))))continue;let c=s.at(-1);n.push({command:i,surface:a,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((a,r)=>a.command.localeCompare(r.command)||a.surface.localeCompare(r.surface))}function Lo(e,t,n){let a=new Set(n.failed.map(d=>jo(d.layer,d.name))),r=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:a.has(jo(d.layer,d.name))?"failed":"ok",surfaces:qe(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:qe(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),o=typeof e=="string"?k(e):null,i=o===null?null:new Set(t.loaded.filter(d=>k(d.name)===o||typeof d.source_package=="string"&&k(d.source_package)===o||(d.source_aliases??[]).some(l=>k(l)===o)).map(d=>k(d.name)).concat(o)),s=i===null?r:r.filter(d=>i.has(k(d.name))),c=i===null?{}:{extensionNames:[...i]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:qe(n,c),command_ownership:Pd(n,i)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function Gn(e){return e.map(({layer:t,name:n,error:a})=>({layer:t,name:n,error:a}))}function Kt(e,t,n){let a=k(t),r=n.trim();if(a.length===0||r.length===0)return;let o=e.get(a)??new Set;o.add(r),e.set(a,o)}function jd(e){let t=new Map,n=new Map;for(let a of e.registrations.commands)Kt(t,a.name,a.command),Kt(n,a.name,a.action);for(let a of e.commands.handlers)Kt(t,a.name,a.command);for(let a of e.commands.overrides)Kt(t,a.name,a.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Mo(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Ld(e){let{enabled:t,normalizedName:n,loadedNames:a,loadFailedNames:r,activationFailedNames:o}=e;return t?r.has(n)||o.has(n)?{runtime_active:!1,activation_status:"failed"}:a.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function Yt(e,t,n){let a=new Set(t.loaded.map(c=>k(c.name))),r=new Set(t.failed.map(c=>k(c.name))),o=new Set(n.failed.map(c=>k(c.name))),{commandPathsByExtension:i,actionPathsByExtension:s}=jd(n);return e.map(c=>{let d=k(c.name),l=Mo(i.get(d)),u=Mo(s.get(d)),f={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},h=Ld({enabled:c.enabled,normalizedName:d,loadedNames:a,loadFailedNames:r,activationFailedNames:o});return{...c,...h,...f}})}function Md(e){let t=0,n=0,a=0;for(let r of e)if(r.startsWith("extension_policy_")){if(t+=1,r.startsWith("extension_policy_violation_")){n+=1;continue}r.startsWith("extension_policy_blocked_")&&(a+=1)}return{warning_count:t,violation_count:n,blocked_count:a}}function G(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var zo=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 Fd(e){return zo.has(Bo(e))}function Fo(e){return e==="project"||e==="global"}function Jo(e){let t=e.split(":"),n=t[0];if(!n||!zo.has(n))return null;let a=t.at(-4),r=t.at(-3)?.trim(),o=t.at(-2),i=t.at(-1)?.trim();return!Fo(a)||!Fo(o)||!r||!i?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:a,name:r},displaced:{layer:o,name:i}}}function Ud(e){let t=new Set;for(let n of e){let a=Jo(n);a&&(t.add(a.winner.name),t.add(a.displaced.name))}return[...t].sort((n,a)=>n.localeCompare(a))}function Hn(e,t){let n=e.filter(Fd);if(n.length===0)return null;let a=Ud(n);return`Extension registration collisions or handler/override overlaps detected.${a.length>0?` Conflicting extensions: ${a.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 zd(e,t,n,a){let r=t.map(u=>Jo(u)).filter(u=>u!==null).sort((u,f)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${f.code}:${f.surface}:${f.winner.name}:${f.displaced.name}`));if(r.length===0)return;let o=e==="global"?"--global":"--project",i=G(a,"deactivate"),s=`${G(a,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(u=>[k(u.name),u])),d=new Map;for(let u of r)for(let f of[u.winner.name,u.displaced.name]){let h=k(f);d.set(h,(d.get(h)??0)+1)}let l=[...d.entries()].map(([u,f])=>{let h=c.get(u),p=h?.name??u,m=h?.command_paths??[],w=h?.action_paths??[];return{action:"deactivate",extension:p,command:`${i} ${p} ${o}`,affected_collisions:f,feature_loss:{command_paths:[...m].sort((y,v)=>y.localeCompare(v)),action_paths:[...w].sort((y,v)=>y.localeCompare(v))}}}).sort((u,f)=>{let h=f.affected_collisions-u.affected_collisions;if(h!==0)return h;let p=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,m=f.feature_loss.command_paths.length+f.feature_loss.action_paths.length;return p!==m?p-m:u.extension.localeCompare(f.extension)});return{status:"conflicts_detected",collision_count:r.length,extension_count:d.size,next_best_command:s,collisions:r,remediation_candidates:l}}function Wo(e){let t=[];for(let n of e){let a=n.error.toLowerCase();(a.includes("cannot find package '@unbrained/pm-cli'")||a.includes('cannot find module "@unbrained/pm-cli"')||a.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(a.includes("cannot use import statement outside a module")||a.includes("to load an es module")||a.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,a)=>n.localeCompare(a))}function qo(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let a of t){if(!a||typeof a.name!="string")continue;let r=a.trace?.missing_capability??a.trace?.capability;typeof r=="string"&&r.trim().length>0&&n.push(`extension_capability_missing:${a.name}:${r.trim().toLowerCase()}`)}return[...new Set(n)].sort((a,r)=>a.localeCompare(r))}function Go(e,t){let n=[];for(let a of Ga(e.loaded,t))for(let r of a.unused)n.push(`extension_capability_unused:${a.layer}:${a.name}:${r}`);return[...new Set(n)].sort((a,r)=>a.localeCompare(r))}var Jd=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${G(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: ${kt.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 ${G(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 ${G(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 ${G(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 ${G(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 ${G(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${G(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 Wd(e){let{normalizedWarnings:t,options:n,scope:a,scopeFlag:r,updateCheckFailedTotal:o,policyWarningCount:i,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=[],f={options:n,scope:a,scopeFlag:r,updateCheckFailedTotal:o,policyWarningCount:i};if(t.length>0){let h=Hn(t,{deactivate:`${G(n,"deactivate")} <name> ${r}`,doctor:`${G(n,"doctor")} ${r} --detail deep --trace`});h&&u.push(h);for(let p of Jd)p.matches(t,f)&&u.push(p.build(f))}return s?u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${G(n,"manage")} ${r} --fix-managed-state (or ${G(n,"adopt-all")} ${r}, ${G(n,"adopt")} <name> ${r}, or reinstall via ${G(n,"install")} ${r} <source>).`):c>0&&u.push(`Loaded unmanaged extensions are currently treated as informational. Use ${G(n,"manage")} ${r} --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 ${G(n,"install")} ${r} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${G(n,"manage")} ${r} after extension changes.`),u}function Xt(e,t,n,a={}){let r=[...new Set(t)].sort((S,P)=>S.localeCompare(P)),o=n.filter(S=>S.managed).length,i=n.filter(S=>S.enabled).length,s=n.filter(S=>S.active).length,c=n.filter(S=>S.update_available===!0).length,d=n.filter(S=>S.managed===!1),l=d.filter(S=>Uo(S)).map(S=>S.name).sort((S,P)=>S.localeCompare(P)),u=d.filter(S=>!Uo(S)).map(S=>S.name).sort((S,P)=>S.localeCompare(P)),f={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let S of n)f[S.update_check_status]+=1;let h=f.failed,p=f.skipped_unmanaged,m=f.skipped_non_github,w=u.length>0,y=w?"partial":"full",v=w?[`extension_update_health_partial_coverage:skipped_unmanaged:${u.length}`]:[],x=[...new Set([...r,...v])].sort((S,P)=>S.localeCompare(P)),I=[...new Set(x.map(S=>Bo(S)))].sort((S,P)=>S.localeCompare(P)),b=Md(x),T=e==="global"?"--global":"--project",J=zd(e,r,n,a),W=Wd({normalizedWarnings:r,options:a,scope:e,scopeFlag:T,updateCheckFailedTotal:h,policyWarningCount:b.warning_count,updateHealthPartial:w,skippedUnmanagedTotal:p,skippedNonGithubTotal:m,updateAvailableTotal:c});return{status:x.length===0?"ok":"warn",warning_count:x.length,warning_codes:I,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:i,active_total:s,update_available_total:c,update_health_coverage:y,update_health_partial:w,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(S=>S.name).sort((S,P)=>S.localeCompare(P)),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:f,update_check_failed_total:h,top_warnings:x.slice(0,8),remediation:W,...J?{collision_plan:J}:{}}}function Ho(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new g(`Invalid --detail value "${e}". Expected summary or deep.`,_.USAGE)}function Bo(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function pt(e){let t=new Set,n=[];for(let a of e){let r=(()=>{let o=ya(a);return o?[o]:wa(a)})();for(let o of r){let i=`${o.layer}:${o.name}:${o.capability}`;t.has(i)||(t.add(i),n.push(o))}}return n}function ft(){return{version:xt.version,capabilities:[...xt.capabilities],legacy_aliases:{...xt.legacy_aliases}}}function Uo(e){let t=k(e.name),n=k(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Vo(e,t,n,a,r){if(e!=="project"||r)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=>k(l.name)))].sort((l,u)=>l.localeCompare(u)),i=[...new Set(n.filter(l=>l.layer==="project").map(l=>k(l.name)))].sort((l,u)=>l.localeCompare(u)),s=new Set(a.map(l=>k(l.name))),c=o.filter(l=>!i.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:i.length,active_project_names:o,loaded_project_names:i,missing_active_project_names:c}}}import{randomUUID as qd}from"node:crypto";import F from"node:fs/promises";import Gd from"node:os";import N 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]="9c598dc3-e766-595d-80f1-6d55e1667d6b")}catch{}})();var Ko=3,Hd=120,Yo=250,Bd=12e4,Vd=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Xo=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Qo=e=>Vd.has(String(Xo(e))),ht=(e,t)=>Xo(e)===t,Zo=e=>new Promise(t=>{setTimeout(t,e)}),ei=async e=>{let t=N.join(e,"package.json");await E(t)||await F.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
20
- `,"utf8")},ti=async e=>{let t=be(import.meta.url,["../../.."]),n=N.join(e,"node_modules","@unbrained"),a=N.join(n,"pm-cli");await F.mkdir(n,{recursive:!0}),await F.rm(a,{recursive:!0,force:!0}),await F.symlink(t,a,process.platform==="win32"?"junction":"dir")},Bn=async e=>{let t=N.resolve(e),n=N.dirname(t),a=N.parse(n).root,r=await F.realpath(a).catch(()=>a),o=N.relative(a,n),i=o===""?[]:o.split(N.sep);for(let[s,c]of i.entries()){let d=N.join(r,c);try{r=await F.realpath(d)}catch{r=N.join(r,...i.slice(s));break}}return N.join(r,N.basename(t))},ni=async(e,t,n,a=Gd.tmpdir())=>{let r=N.resolve(e),o=await F.realpath(r).catch(()=>r),i=await Bn(t);if(o===i)return;if(!oe(o,i)){await n(e,t,{recursive:!0,force:!0});return}let s=f=>{let h=N.resolve(f);if(h!==r&&!oe(r,h))return!1;let p=N.resolve(o,N.relative(r,h));if(p===i||oe(i,p))return!1;let w=N.relative(o,p).split(N.sep);return w.some(y=>y==="node_modules"||y.startsWith(".pm-extension-install-backup-"))?!1:w[0]!==".agents"},c=await F.realpath(N.resolve(a)).catch(()=>Bn(a)),d=oe(o,c)?N.dirname(o):c;if(oe(o,d))throw new g(`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 F.mkdtemp(N.join(d,"pm-extension-copy-")),u=N.join(l,"extension");try{await n(e,u,{recursive:!0,force:!0,filter:s}),await n(u,t,{recursive:!0,force:!0})}finally{await F.rm(l,{recursive:!0,force:!0})}},ai=async(e,t,n=F.cp)=>{for(let a=1;a<=Ko;a+=1)try{await F.rm(t,{recursive:!0,force:!0}),await ni(e,t,n);return}catch(r){if(!Qo(r)||a===Ko)throw r;await Zo(Yo)}},Vn=async e=>{let t;try{t=await F.readFile(N.join(e,"owner.json"),"utf8")}catch(r){if(!ht(r,"ENOENT"))throw r;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let a=n.token;return typeof a=="string"&&a.length>0?a:null},ri=async(e,t)=>await Vn(e)!==t?!1:(await F.rm(e,{recursive:!0,force:!0}),!0),Kd=async(e,t)=>{let n;try{n=await F.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let a=await Vn(e);return a===null?(await F.rm(e,{recursive:!0,force:!0}),!0):ri(e,a)},Yd=(e,t,n)=>{let a=Promise.resolve(),r=setInterval(()=>{a=a.then(async()=>{if(await Vn(e)!==t)return;let o=new Date;await F.utimes(e,o,o)}).catch(()=>{})},n);return r.unref(),async()=>{clearInterval(r),await a}},Xd=async(e,t)=>{await F.mkdir(e);try{await F.writeFile(N.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
21
- `,"utf8")}catch(n){throw await F.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Qd=async(e,t,n,a,r)=>{for(let o=1;o<=n;o+=1)try{return await Xd(e,t),!0}catch(i){if(!ht(i,"EEXIST"))throw i;await Kd(e,r)?o-=1:await Zo(a)}return!1},Kn=async(e,t,n,a)=>{let r=N.join(e,"runtime","extension-install-locks"),o=N.join(r,"scope.lock");await F.mkdir(r,{recursive:!0});let{attempts:i=Hd,delay_ms:s=Yo,stale_ms:c=Bd,heartbeat_ms:d}=a??{};if(![i,s,c,d].filter(y=>y!==void 0).every(Number.isFinite))throw new g("Extension install lock timings must be finite numbers.",_.USAGE);let l=Math.max(1,Math.floor(i)),u=Math.max(0,Math.floor(s)),f=Math.floor(c),h=Math.floor(d??f/3);if(f<=0||h<=0||h>=f)throw new g("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",_.USAGE);let p={pid:process.pid,token:qd(),created_at:A(),destination:t};if(!await Qd(o,p,l,u,f))throw new g(`Timed out waiting for extension install lock for "${t}".`,_.CONFLICT);let w=Yd(o,p.token,h);try{return await n()}finally{await w(),await ri(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 oi=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let a=new Array(e.length),r=0,o=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let i=r;r+=1,a[i]=await n(e[i])}});return await Promise.all(o),a};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b17dfc10-9e07-5912-b294-c5663133f192")}catch{}})();function ii(e,t){let n=k(e),a=t.find(r=>k(r.name)===n);return{command_paths:[...a?.command_paths??[]].sort((r,o)=>r.localeCompare(o)),action_paths:[...a?.action_paths??[]].sort((r,o)=>r.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]="0dc7b063-dc72-595f-8e40-8a06f9db69e1")}catch{}})();function si(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${k(o.name)}`]:[])),a=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>!n.has(`${o.layer}:${k(o.name)}`)).map(o=>`extension_output_service_override_global:${o.service}:${o.layer}:${o.name}`),r=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([...a,...r])].sort((o,i)=>o.localeCompare(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]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var ci=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=Ot(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,a)=>a.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 Zd=1e4,el=(e,t,n)=>{let a=e.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).map(i=>{let[s,c=""]=i.split(/\s+/);return{commit:s,ref:c}}),r=a.find(i=>i.ref.endsWith("^{}"))??a[0];if(!r)return{checked_at:n,available:null,error:"no_remote_reference_found"};let o=t?.trim();return o?{checked_at:n,remote_commit:r.commit,available:r.commit!==o}:{checked_at:n,remote_commit:r.commit,available:null,error:"missing_installed_commit"}},di=async(e,t=Ht)=>{let n=A();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let a=[e.ref?.trim(),"HEAD"].find(Boolean),r=await t(["ls-remote",e.repository,a,`${a}^{}`],void 0,Zd);return el(r,e.commit,n)}catch(a){return{checked_at:n,available:null,error:a instanceof Error?a.message:String(a)}}};import tl from"node:fs/promises";import nl 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 Yn(e){return nl.join(e,"extension-migrations.json")}function li(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 ui(e,t){return`${e.layer}:${e.name}:${t}`}async function al(e){let t=Yn(e);if(!await E(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await tl.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(a=>typeof a?.key=="string"&&(a.status==="applied"||a.status==="failed")):[]}}async function Xn(e,t){let n=await al(e),a=new Map(n.entries.map(r=>[r.key,r]));return t.forEach((r,o)=>{let i=li(r,o),s=a.get(ui(r,i));s&&(r.definition.status=s.status,s.status==="failed"?r.definition.reason=s.error:(delete r.definition.reason,delete r.definition.error,delete r.definition.message))}),n}async function rl(e){let t=await Xn(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),a=[],r=!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 f=li(l,u),h=ui(l,f),p=n.get(h),m=String(l.definition.status??"pending").toLowerCase(),w=p?.status??(m==="applied"||m==="failed"?m:"pending");if(w==="applied"){a.push({key:h,layer:l.layer,extension:l.name,id:f,before:w,outcome:"skipped"});continue}if(e.dryRun===!0){a.push({key:h,layer:l.layer,extension:l.name,id:f,before:w,outcome:"pending"});continue}let y=l.runtime_definition?.run??l.definition.run;if(typeof y!="function"){a.push({key:h,layer:l.layer,extension:l.name,id:f,before:w,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(y({id:f,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:w}));let x={key:h,layer:l.layer,extension:l.name,id:f,status:"applied",attempted_at:v};n.set(h,x),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,a.push({key:h,layer:l.layer,extension:l.name,id:f,before:w,outcome:"applied"}),r=!0}catch(x){let I=x instanceof Error?x.message:String(x),b={key:h,layer:l.layer,extension:l.name,id:f,status:"failed",attempted_at:v,error:I};n.set(h,b),l.definition.status="failed",l.definition.reason=I,a.push({key:h,layer:l.layer,extension:l.name,id:f,before:w,outcome:"failed",error:I}),r=!0}}if(r){let l=await R(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((f,h)=>f.key.localeCompare(h.key))};await jt({pmRoot:e.pmRoot,filePath:Yn(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
22
- `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let i=a.filter(l=>l.outcome==="pending").length,s=a.filter(l=>l.outcome==="applied").length,c=a.filter(l=>l.outcome==="skipped").length,d=a.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:Yn(e.pmRoot),total:a.length,pending_count:i,applied_count:s,skipped_count:c,failed_count:d,migrations:a}}async function mi(e){let t=await R(e.resolvedRoots.settings_root),n=await ie({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),a=await se(n);e.warnings.push(...n.warnings,...a.warnings);let r=await rl({pmRoot:e.resolvedRoots.pm_root,migrations:a.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:r,load_failure_count:n.failed.length,activation_failure_count:a.failed.length},r.ok)}(function(){try{var e=typeof window<"u"?window:typeof 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 pi(e,t,n){let a=typeof t=="string"?null:await dt(e),r=a===null?null:e.trim().toLowerCase(),o=r===null?null:await po(r),i=Vt(a??e,{forceGithub:typeof t=="string",ref:n}),s=r===null?null:await go(e);return{bundledAliasName:r,bundledPackageName:o,installSource:i,sourceResolution:{requested:e,selected:{kind:r===null?i.kind:"builtin",input:r??i.input,...o===null?{}:{package:o}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...r===null?[]:[{kind:"builtin",input:r,...o===null?{}:{package:o},command:`pm install ${r}`}],...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 je from"node:fs/promises";import ol 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 Qn=async e=>je.readFile(e).catch(t=>{if(ht(t,"ENOENT"))return null;throw t}),fi=async(e,t,n,a,r)=>{let o=it(e),i=ee(t),[s,c]=await Promise.all([Qn(o),Qn(i)]);return a&&await je.cp(n,r,{recursive:!0,force:!0}),{backupDirectory:r,destinationDirectory:n,destinationExists:a,managedStatePath:o,managedStateContents:s,settingsPath:i,settingsContents:c}},hi=async e=>{await je.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await je.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 je.rm(t,{force:!0}):(await je.mkdir(ol.dirname(t),{recursive:!0}),await je.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]="f4b47053-cc05-51f2-b5cb-cc6dba3365c2")}catch{}})();var il=4,vi=[["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"]],gi=vi.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),sl={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"},cl="__pm_native_output",dl=["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"],bi=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],ll=["disabled","require_trusted","require_provenance"],ki={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:[]},ul=e=>{let t=e??ki,n={};for(let a of dl)n[a]=Q(t[a]??[]);return n},ml=(e,t)=>{for(let n of bi)t[n].length>0&&(e[n]=t[n]);return e},pl=(e,t)=>{for(let n of ll)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},fl=e=>{let t={};for(let n of bi)t[n]=Q(e[n]??[]);return t},hl=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:ml(pl({name:t},e),fl(e))},gl=e=>(e??[]).map(t=>hl(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),_l=e=>{let t=Object.assign({},ki,e??{}),n=ul(e),a=gl(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:a}},xi=async(e,t)=>{let n=[t],a=await fo(t);a&&n.push(a);let r=[...new Set(n.map(o=>k(o)).filter(o=>o.length>0))];for(let o of r){let i=e.find(c=>k(c.name)===o);if(i)return i;let s=e.find(c=>k(c.directory)===o);if(s)return s}},Si=(e,t)=>{let n=t.trim(),a=new Set(Q(e.extensions.enabled));return new Set(Q(e.extensions.disabled)).has(n)?!1:a.size===0?!0:a.has(n)},Ei=(e,t)=>{let n=t.trim(),a=new Set(Q(e.extensions.enabled)),r=new Set(Q(e.extensions.disabled)),o=[...a],i=[...r];return r.delete(n),a.size>0&&a.add(n),e.extensions.enabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==i.join("\0")},yl=(e,t)=>{let n=t.trim(),a=new Set(Q(e.extensions.enabled)),r=new Set(Q(e.extensions.disabled)),o=[...a],i=[...r];return a.delete(n),r.add(n),e.extensions.enabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==i.join("\0")},wl=(e,t)=>{let n=t.trim(),a=new Set(Q(e.extensions.enabled)),r=new Set(Q(e.extensions.disabled)),o=[...a],i=[...r];return a.delete(n),r.delete(n),e.extensions.enabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==i.join("\0")},vl=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),a=vi.map(([r,o,i])=>({action:o,flag:i,distance:_a(t,r,n)})).filter(r=>r.distance!==null).sort((r,o)=>r.distance-o.distance)[0];return a?{action:a.action,flag:a.flag}:null},bl=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=vl(e);if(!a)return new g(`One action flag is required. Use one of: ${gi}. Bare \`pm package\` and \`pm extension\` default to --explore.`,_.USAGE);let r=`pm ${n} ${a.flag}`;return new g(`Unknown ${n} lifecycle action "${e}". Did you mean "${a.flag}"?`,_.USAGE,{code:"unknown_lifecycle_action",required:`Use one of: ${gi}.`,examples:[r,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:r,fallback_candidates:[{source:"lifecycle_action",command:r,reason:`nearest lifecycle action for "${e}"`}]}})},kl=[["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"]],xl={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Sl=e=>xl[e]??null,El=(e,t)=>{let n=[...new Set(kl.filter(([a])=>t[a]===!0).map(([,a])=>a))];if(n.length===0){if(e===void 0)return"explore";let a=Sl(e.trim().toLowerCase());if(a)return a;throw bl(e,t)}if(n.length>1)throw new g("Extension action flags are mutually exclusive.",_.USAGE);return n[0]},$l=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new g('Options "--project/--local" and "--global" are mutually exclusive.',_.USAGE);return n?"global":"project"},Tl=[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"}}],$i=e=>{for(let t of Tl){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Ti=(e,t,n,a)=>{let r=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:r.contributions,managed:!!n,source:r.source,update_available:r.update_available,last_update_check_at:r.last_update_check_at,last_update_remote_commit:r.last_update_remote_commit,update_error:r.update_error,update_check_status:a.status,update_check_reason:a.reason}},Il=(e,t,n,a)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},a),o=a?Si(n,a.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Ti({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:o},t,a,$i(a))}},Al=async(e,t,n,a,r,o)=>{let i=ne.join(e,t),s=ne.join(i,"manifest.json"),c=o.get(k(t));if(!await E(s))return Il(t,n,a,c);let d=Symbol("invalid-extension-manifest-json"),l=await Ie.readFile(s,"utf8").then(h=>JSON.parse(h)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=Pn(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let f=r.get(k(u.name))??o.get(k(t));return{summary:Ti({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:Si(a,u.name)},n,f,$i(f))}},ue=async(e,t,n,a)=>{if(!await E(e))return{extensions:[],warnings:[]};let o=(await Ie.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),i=new Map(a.entries.map(l=>[k(l.name),l])),s=new Map(a.entries.map(l=>[k(l.directory),l])),c=[],d=[];for(let l of o){let u=await Al(e,l,t,n,i,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))}},Cl=Ba(),Rl=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Ol=(e,t,n,a)=>{let r=n.command_paths.map(s=>`pm ${s} --help`),o=a?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,i=n.command_paths.length>0?[...r]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&i.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Rl(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:r,next_steps:i,...o?{sdk_dependency_status:"missing"}:{}}},Nl=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(([,a])=>a!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},Ii=e=>e.map(t=>Nl(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),Ai=(e,t,n)=>{let a=k(e);return t.find(r=>(n===void 0||r.layer===n)&&k(r.name)===a)},Dl=(e,t,n,a)=>n.find(o=>o.scope===t&&k(o.name)===k(e))?.activation_status??(a?"failed":"unknown"),Ci=(e,t,n,a,r)=>Cl.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,i=await Ie.mkdtemp(ne.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=be(import.meta.url,["../.."]);try{let s=await ie({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:r.noExtensions===!0,reload_token:mn(),cache_bust:!0,module_graph_snapshot_root:i}),c=await se({...s}),d=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...Ii(c.failed)],l=Object.fromEntries(s.loaded.map(u=>[k(u.name),Ia(qe(c,{extensionName:u.name}))]));return{installed:Yt(a,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 Ie.rm(i,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),ea=async(e,t,n,a)=>{let r=n.filter(c=>!c.managed),o=[...r].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),i=a,s=[];for(let c of o){let d=ne.join(e,c.directory),l=await Ke(d),u=A(),f={kind:"local",input:c.name,location:d};i=ct(i,{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:f}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:f})}return s.length>0&&await De(e,i),{state:i,adopted_entries:s,unmanaged_candidates:o,already_managed_count:n.length-r.length}},Pl=(e,t)=>{let n=D(process.cwd(),t.path),a=Le(n,process.cwd()),r=e==="global"?Et(process.cwd()):n,o=e==="global"?a.global:a.project;return{pm_root:n,scope:e,settings_root:r,selected_root:o,roots:a}},Qt=e=>{let t=[e.gh,e.github].filter(a=>typeof a=="string").map(a=>a.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new g('Options "--gh" and "--github" must match when both are provided.',_.USAGE);return n[0]},jl=e=>sl[e],Ll=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=e==="install"?"source":"name",r=`${n} ${a}`,o=jl(e),i=`<${a}>`,s=`pm ${n} ${o} ${i}`;throw new g(`Action "${e}" requires ${r} input.`,_.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${a} target for ${e}.`,examples:[`pm ${n} ${e} ${i}`,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 ${a} target`}]}})},Zt=(e,t,n={})=>{let a=e?.trim();if(a)return a;if(t==="init")throw new g('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',_.USAGE);return Ll(t,n)},Ml=(e,t)=>{let n=new Set([...t.registrations.item_types.map(a=>({entry:a,count:a.types.length})),...t.registrations.item_fields.map(a=>({entry:a,count:a.fields.length}))].filter(({count:a})=>a>0).map(({entry:a})=>`${a.layer}:${k(a.name)}`));return e.loaded.filter(a=>(a.activation?.commands??[]).length>0).filter(a=>n.has(`${a.layer}:${k(a.name)}`)).map(a=>`extension_schema_narrow_activation:${a.layer}:${a.name}`).filter((a,r,o)=>o.indexOf(a)===r).sort((a,r)=>a.localeCompare(r))},Fl=(e,t)=>{let a=[{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(r=>r.triggered&&!r.allowed);if(a)throw new g(a.message,_.USAGE)},Ul=(e,t,n)=>{let a=String(e??"").trim().toLowerCase(),r=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:r?[]:["init","scaffold"]}[t]??[]).includes(a)?void 0:e},zl=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},Jl=(e,t,n)=>{let a={ok:n,action:e.action,scope:e.scope,roots:zl(e),warnings:[...new Set(e.warnings)].sort((r,o)=>r.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(a,cl,{value:!0,enumerable:!1,configurable:!1}),a},ta=async(e,t,n)=>{let a=El(e,t);Fl(a,t);let r=Ul(e,a,t),o=$l(t),i=Pl(o,n),c={action:a,normalizedTarget:r,scope:o,resolvedRoots:i,warnings:[],options:t,global:n},l={...c,withResult:(u,f=!0)=>Jl(c,u,f)};return await bu(l)},Wl=(e,t)=>{let n=t.vocabulary??"extension",a=e.target_path.replace(/\\/g,"/"),r=En(a),o={package:`Install dependencies: cd ${r}, then run "npm install"`,extension:`Install type-check dependencies: cd ${r}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},i={package:`Validate the package: cd ${r}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${r}, 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: ${Nr(n==="package"?["install","--project",a]:["extension","--install","--project",a])}`,`Smoke-test command path: pm ${e.command_name}`,i[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},ql=async e=>{let{action:t,normalizedTarget:n,options:a,withResult:r}=e;if([Qt(a),a.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new g('Action "init" does not accept --gh/--github/--ref options.',_.USAGE);let s=Zt(n,t,a),c=await Po(s,a.vocabulary??"extension",a.capability,a.declarative===!0);return r({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:Wl(c,a)})},Gl=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:a,options:r,global:o,withResult:i}=e;if(t!==void 0)throw new g('Action "reload" does not accept a target argument.',_.USAGE);let s=await R(n.settings_root),c=mn(),d=await ie({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});a.push(...d.warnings);let l=await se(d);a.push(...l.warnings);let u={reload:{token:c,cache_bust:!0,watch:r.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(f=>({name:f.name,layer:f.layer,version:f.version})),failed_extensions:d.failed.map(f=>({name:f.name,layer:f.layer,error:f.error})),activation_failures:l.failed.map(f=>({name:f.name,layer:f.layer,error:f.error}))};return r.watch===!0&&a.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),i(u)},Hl=async e=>{let{normalizedTarget:t,scope:n,options:a,global:r,withResult:o}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new g('Action "catalog" does not accept a package target.',_.USAGE);return o(await ho(n,r,a))},Bl=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Vl=e=>({kind:"local",input:e.input,location:e.absolute_path}),Kl=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),Yl=(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}),Xl=(e,t,n,a)=>e?Bl(e,t):n.kind==="local"?Vl(n):n.kind==="npm"?Kl(n,a):Yl(n,a),Ql=(e,t,n,a)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:a}:so(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:a}:{installed_at:a,updated_at:a},Zl=async(e,t)=>{let{scope:n,resolvedRoots:a,warnings:r}=e,{validated:o,destinationDirectoryName:i}=t,s=await R(a.settings_root),c=await B(a.selected_root);r.push(...c.warnings);let d=ne.join(a.selected_root,i),l=await E(d),u=await xo(o.directory,d);await Ie.mkdir(a.selected_root,{recursive:!0});let f=await Ie.mkdtemp(ne.join(a.selected_root,".pm-extension-install-backup-")),h=ne.join(f,"destination");try{let p=await fi(a.selected_root,a.settings_root,d,l,h),m=Xl(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),w=c.state.entries.find(I=>k(I.name)===k(o.manifest.name)),y=Ql(w,o.manifest.version,m,A()),v=ct(c.state,{name:o.manifest.name,directory:i,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,...y,source:m}),x=Ei(s,o.manifest.name);try{u||await ai(o.directory,d),await ei(d),await ti(d),await De(a.selected_root,v),x&&await Lt(a.settings_root,s,"settings:write")}catch(I){try{await hi(p)}catch(b){throw new AggregateError([I,b],`Extension install failed: ${String(I)}; rollback failed: ${String(b)}`,{cause:b})}throw I}return{settings:s,managedState:v,sourceRecord:m,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:x}}finally{await Ie.rm(f,{recursive:!0,force:!0}).catch(()=>{})}},eu=async(e,t,n)=>{let a=n.filter(r=>k(r.name)===k(t)).flatMap(r=>r.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&a.length>0&&await rt(e.resolvedRoots.pm_root,a,e.warnings,"install:type-folder"),a},tu=(e,t,n,a,r)=>{let o=Ai(t,n.activation_failures,e.scope),i=Dl(t,e.scope,n.installed,o),s=[!n.extensions_disabled,i==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${i}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:i,failure:o,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:i,activated:s,registered_commands:a.command_paths,registered_actions:a.action_paths,registered_item_types:r,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},nu=async(e,t)=>{let{scope:n,resolvedRoots:a,warnings:r,global:o,withResult:i}=e,{validated:s,destinationDirectoryName:c}=t,d=await Zl(e,t),l=await ue(a.selected_root,n,d.settings,d.managedState);r.push(...l.warnings);let u=await Ci(a.pm_root,ne.dirname(a.selected_root),d.settings,l.extensions,o);r.push(...u.warnings);let f=await eu(e,s.manifest.name,u.item_type_registrations),h=ii(s.manifest.name,u.installed),p=tu(e,s.manifest.name,u,h,f),m=u.contribution_inventories[k(s.manifest.name)];return m&&(d.managedState=await co(a.selected_root,d.managedState,s.manifest.name,m)),i({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:h.command_paths,action_paths:h.action_paths,contributions:m,command_discovery:Ol(s.manifest.name,d.sourceRecord,h,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)},au=async e=>{let{options:t,global:n,warnings:a,withResult:r}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new g('Action "install all" does not accept --ref.',_.USAGE);let o=[],i=new Map;for(let c of await Gt()){let d=await dt(c),l=ne.resolve(d),u=i.get(l);u===void 0&&(u=await ta(c,{...t,install:!0},n),i.set(l,u)),o.push({alias:c,result:u})}a.push(...o.flatMap(c=>c.result.warnings));let s=o.every(c=>c.result.ok);return r({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)},ru=async(e,t,n)=>{let{resolvedRoots:a}=e,{bundledAliasName:r,bundledPackageName:o,installSource:i,sourceResolution:s}=await pi(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:${r}:npm:${d.package}`)}let c=await ko(i);try{let d=await Ke(c.directory,{source_kind:i.kind,source_input:i.input,source_root:c.source_root}),l=Wt(d.manifest.name);return await Kn(a.settings_root,l,()=>nu(e,{validated:d,destinationDirectoryName:l,bundledAliasName:r,bundledPackageName:o,sourceResolution:s,installSource:i,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},ou=async e=>{let t=Qt(e.options),n=t??Zt(e.normalizedTarget,e.action,e.options);return[t===void 0,uo(n)].every(Boolean)?au(e):ru(e,n,t)},iu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:r,options:o,withResult:i}=e;if(t!==void 0)throw new g('Action "adopt-all" does not accept a target argument.',_.USAGE);if(Qt(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new g('Action "adopt-all" does not accept --gh/--github/--ref options.',_.USAGE);let c=await R(a.settings_root),d=await B(a.selected_root);r.push(...d.warnings);let l=await ue(a.selected_root,n,c,d.state);r.push(...l.warnings);let u=await ea(a.selected_root,n,l.extensions,d.state),f=await ue(a.selected_root,n,c,u.state);r.push(...f.warnings);let h=Xt(n,r,f.extensions,o);r.push(...h.warnings);let p=new Map(f.extensions.map(y=>[`${k(y.name)}:${k(y.directory)}`,y])),m=new Map(f.extensions.map(y=>[k(y.directory),y])),w=u.adopted_entries.map(y=>{let v=k(y.directory),x=p.get(`${k(y.name)}:${v}`)??m.get(v);return{...y,...Ri(x)}});return i({adopted_all:w.length>0,adopted_count:w.length,already_managed_count:u.already_managed_count,extensions:w,triage:h,warning_codes:h.warning_codes,update_health_partial:h.update_health_partial,update_health_coverage:h.update_health_coverage})},Ri=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),su=(e,t,n,a)=>{if(e===void 0)return{kind:"local",input:t,location:n};let r=Vt(e,{forceGithub:!0,ref:a});if(r.kind!=="github")throw new g(`Invalid GitHub shorthand "${e}".`,_.USAGE);return{kind:"github",input:r.input,location:r.subpath??".",repository:r.repository,owner:r.owner,repo:r.repo,ref:r.ref,subpath:r.subpath}},cu=async e=>{let{action:t,normalizedTarget:n,scope:a,resolvedRoots:r,warnings:o,options:i,withResult:s}=e,c=Zt(n,t,i),d=Qt(i),l=await R(r.settings_root),u=await B(r.selected_root);o.push(...u.warnings);let f=await ue(r.selected_root,a,l,u.state);o.push(...f.warnings);let h=await xi(f.extensions,c);if(!h)throw new g(`Installed extension "${c}" was not found in ${a} scope.`,_.NOT_FOUND);if(h.managed)return s({adopted:!1,already_managed:!0,extension:{name:h.name,directory:h.directory}});let p=ne.join(r.selected_root,h.directory),m=await Ke(p),w=A(),y=su(d,c,p,i.ref),v=ct(u.state,{name:m.manifest.name,directory:h.directory,scope:a,manifest_version:m.manifest.version,manifest_entry:m.manifest.entry,capabilities:[...m.manifest.capabilities],contributions:m.manifest.contributions,installed_at:w,updated_at:w,source:y});await De(r.selected_root,v);let x=await ue(r.selected_root,a,l,v);o.push(...x.warnings);let I=x.extensions.find(b=>k(b.name)===k(m.manifest.name))??x.extensions.find(b=>k(b.directory)===k(h.directory));return s({adopted:!0,extension:{name:m.manifest.name,directory:h.directory,version:m.manifest.version,entry:m.manifest.entry},source:y,...Ri(I)})},Oi=async e=>{let{action:t,normalizedTarget:n,scope:a,resolvedRoots:r,warnings:o,options:i}=e,s=Zt(n,t,i),c=await R(r.settings_root),d=await B(r.selected_root);o.push(...d.warnings);let l=await ue(r.selected_root,a,c,d.state);o.push(...l.warnings);let u=await xi(l.extensions,s);if(!u)throw new g(`Installed extension "${s}" was not found in ${a} scope.`,_.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},du=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:a,managedStateRead:r,candidate:o}=await Oi(e),i=ne.join(t.selected_root,o.directory);await Ie.rm(i,{recursive:!0,force:!0});let s={...r.state,updated_at:A(),entries:r.state.entries.filter(d=>k(d.name)!==k(o.name)&&k(d.directory)!==k(o.directory))};await De(t.selected_root,s);let c=wl(a,o.name);return c&&await Lt(t.settings_root,a,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:i,settings_changed:c})},_i=async e=>{let{action:t,resolvedRoots:n,warnings:a,global:r,withResult:o}=e,{settings:i,candidate:s}=await Oi(e),c=t==="activate"?Ei(i,s.name):yl(i,s.name);c&&await Lt(n.settings_root,i,"settings:write");let d=t==="activate"?await Ci(n.pm_root,ne.dirname(n.selected_root),i,[s],r).then(l=>(a.push(...l.warnings),Ai(s.name,l.activation_failures,e.scope))):void 0;return d&&a.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:[...i.extensions.enabled],disabled:[...i.extensions.disabled]}},d===void 0)},lu=(e,t,n,a,r,o)=>{let i=a==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[i],c=r?.adopted_entries.length??0,d=[[o!==null,o??""],[t>0,`Run pm ${i} explore --project and pm ${i} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${i} ${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))]},Zn=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),uu=(e,t,n,a)=>{if(e!=="project"||t||!Zn(a))return null;let r=n==="package"?"package":"extension";return`Global ${r} registrations are included in project diagnostics. For hermetic ${r} smoke tests, rerun pm ${r} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},mu=(e,t,n)=>{if(String(e??"").trim().length>0)throw new g('Action "doctor" does not accept a target argument.',_.USAGE);let a=[n.isolated,n.ignoreGlobal].includes(!0);if([a,t==="global"].every(Boolean))throw new g("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",_.USAGE);let r=Ho(n.detail),o=n.trace===!0;if([o,r!=="deep"].every(Boolean))throw new g("--trace requires --detail deep with --doctor.",_.USAGE);return{isolated:a,detailMode:r,includeTrace:o}},pu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let a=await ea(e.resolvedRoots.selected_root,e.scope,t,n);return{state:a.state,fix:a}},fu=(e,t,n,a)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:Zn(a),rerun_command:null,pm_global_path_recipe:null};let o=`pm ${r} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:Zn(a),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},hu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:r,options:o,global:i,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=mu(t,n,o),u=await R(a.settings_root),f=await B(a.selected_root);r.push(...f.warnings);let h=await ue(a.selected_root,n,u,f.state);r.push(...h.warnings);let{state:p,fix:m}=await pu(e,h.extensions,f.state),w=await ue(a.selected_root,n,u,p);r.push(...w.warnings);let y=await ie({pmRoot:a.pm_root,settings:u,cwd:process.cwd(),noExtensions:i.noExtensions===!0,ignoreGlobalExtensions:c}),v=await se({...y,loaded:y.loaded});r.push(...y.warnings),r.push(...Wo(y.failed)),r.push(...v.warnings),r.push(...qo(v.failed)),r.push(...Go(y,v)),r.push(...si(v,y)),r.push(...Ml(y,v)),r.push(...ci(v));let x=Yt(w.extensions,y,v),I=Vo(n,x,y.loaded.map(C=>({layer:C.layer,name:C.name})),y.failed.map(C=>({name:C.name})),y.disabled_by_flag);r.push(...I.warnings);let b=x.filter(C=>C.update_check_status==="failed").map(C=>`extension_update_check_failed:${C.name}`);r.push(...b);let T=Xt(n,r,x,o);r.push(...T.warnings);let J=[...T.warnings],W={mode:y.policy.mode,trust_mode:y.policy.trust_mode,require_provenance:y.policy.require_provenance,default_sandbox_profile:y.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:y.policy.trusted_extensions.length,allowed_extensions_count:y.policy.allowed_extensions.length,blocked_extensions_count:y.policy.blocked_extensions.length,allowed_capabilities_count:y.policy.allowed_capabilities.length,blocked_capabilities_count:y.policy.blocked_capabilities.length,allowed_surfaces_count:y.policy.allowed_surfaces.length,blocked_surfaces_count:y.policy.blocked_surfaces.length,allowed_commands_count:y.policy.allowed_commands.length,blocked_commands_count:y.policy.blocked_commands.length,allowed_actions_count:y.policy.allowed_actions.length,blocked_actions_count:y.policy.blocked_actions.length,allowed_services_count:y.policy.allowed_services.length,blocked_services_count:y.policy.blocked_services.length,extension_override_count:y.policy.extension_overrides.length},S=pt(J),P=ft(),ae=T.warning_codes,et=uu(n,c,o.vocabulary,y),bt=lu(T.remediation,y.failed.length,v.failed.length,o.vocabulary,m,et),tt=fu(n,c,o.vocabulary,y),ga={status:T.status,scope:n,warning_count:T.warning_count,warning_codes:ae,total_extensions:x.length,managed_total:x.filter(C=>C.managed).length,enabled_total:x.filter(C=>C.enabled).length,active_total:x.filter(C=>C.active).length,unmanaged_loaded_extension_count:T.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:T.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:T.unmanaged_expected_extension_count,runtime_active_total:x.filter(C=>C.runtime_active===!0).length,activation_status_totals:{ok:x.filter(C=>C.activation_status==="ok").length,failed:x.filter(C=>C.activation_status==="failed").length,not_loaded:x.filter(C=>C.activation_status==="not_loaded").length,unknown:x.filter(C=>C.activation_status==="unknown").length},unknown_capability_count:S.length,capability_contract_version:P.version,update_available_total:x.filter(C=>C.update_available===!0).length,update_health_coverage:T.update_health_coverage,update_health_partial:T.update_health_partial,update_check_failed_total:x.filter(C=>C.update_check_status==="failed").length,load_failure_count:y.failed.length,activation_failure_count:v.failed.length,load_failures:Gn(y.failed),activation_failures:Gn(v.failed),blocking_failure_count:y.failed.length+v.failed.length,has_blocking_failures:y.failed.length+v.failed.length>0,consistency_warning_count:I.warnings.length,trace_enabled:l,isolation:tt,policy:W,remediation:bt},ln=m?{requested:!0,applied:m.adopted_entries.length>0,adopted_count:m.adopted_entries.length,already_managed_count:m.already_managed_count,adopted_extensions:m.adopted_entries.map(C=>C.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:w.extensions.filter(C=>C.managed).length,adopted_extensions:[]},Ae={mode:d,summary:ga,triage:T,trace_enabled:l,capability_contract:P,capability_guidance:S,managed_state_fix:ln,isolation:tt,policy:y.policy};if(d==="deep"){let C=l?v.failed:v.failed.map(j=>{let{trace:Pp,...ss}=j;return ss});Ae.deep={warnings:J,warning_codes:ae,capability_contract:P,capability_guidance:S,trace_enabled:l,managed_state:{path:f.path,count:p.entries.length,entries:p.entries},installed_extensions:x,load:{roots:y.roots,policy:y.policy,warnings:y.warnings,failed:y.failed,loaded:y.loaded.map(j=>({layer:j.layer,directory:j.directory,name:j.name,version:j.version,entry:j.entry,priority:j.priority}))},activation:{failed:C,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:I.summary},l&&(Ae.deep.trace={activation_failures:v.failed.filter(j=>j.trace!==void 0).map(j=>({layer:j.layer,name:j.name,entry_path:j.entry_path,error:j.error,method:j.trace.method,command:j.trace.command,capability:j.trace.capability,missing_capability:j.trace.missing_capability,registration_index:j.trace.registration_index,expected_schema:j.trace.expected_schema,hint:j.trace.hint,received:j.trace.received}))})}return s(Ae)},gu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:r,options:o,global:i,withResult:s}=e,c=await R(a.settings_root),d=await ie({pmRoot:a.pm_root,settings:c,cwd:process.cwd(),noExtensions:i.noExtensions===!0}),l=await se(d);r.push(...d.warnings),r.push(...l.warnings);let u=Lo(t,d,l);if(t!==void 0&&u.extensions.length===0){let f=o.vocabulary==="package"?"package":"extension",h=[...new Set(d.loaded.map(m=>o.vocabulary==="package"&&typeof m.source_package=="string"&&m.source_package.trim().length>0?m.source_package.trim():m.name))].sort((m,w)=>m.localeCompare(w)),p=h.length>0?` Loaded ${f} names: ${h.join(", ")}.`:"";throw new g(`No loaded ${f} named "${t}" was found in ${n} scope.${p} Run pm ${f} explore to list discovered ${f}s.`,_.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},_u=async(e,t,n)=>{let a=n,r=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await ea(e.resolvedRoots.selected_root,e.scope,t,n),a=r.state),e.action==="manage"){let o=await oi(a.entries,il,async i=>{if(i.source.kind!=="github")return i;let s=await di(i.source);return{...i,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});a={...a,updated_at:A(),entries:st(o)},await De(e.resolvedRoots.selected_root,a)}return{state:a,fix:r}},yu=async(e,t,n)=>{let a=await ie({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await se({...a,loaded:a.loaded});return e.warnings.push(...a.warnings,...r.warnings),{installed:Yt(n,a,r),failures:Ii(r.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:a.failed.length,activation_failure_count:r.failed.length,warning_count:[...new Set([...a.warnings,...r.warnings])].length,policy:a.policy}}},wu=(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},yi=async e=>{let{action:t,scope:n,resolvedRoots:a,warnings:r,options:o,withResult:i}=e,s=await R(a.settings_root),c=_l(s.extensions.policy),d=await B(a.selected_root);r.push(...d.warnings);let l=await ue(a.selected_root,n,s,d.state);r.push(...l.warnings);let{state:u,fix:f}=await _u(e,l.extensions,d.state),h=await ue(a.selected_root,n,s,u);if(r.push(...h.warnings),t==="manage"){let v=h.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);r.push(...v)}let p=await yu(e,s,h.extensions),m=p.installed,w=Xt(n,r,m,o);r.push(...w.warnings);let y={total:m.length,managed_total:m.filter(v=>v.managed).length,enabled_total:m.filter(v=>v.enabled).length,active_total:m.filter(v=>v.active).length,extensions:m,triage:w,policy:c};return p.failures!==void 0&&(y.activation_diagnostics={failed_count:p.failures.length,failed:p.failures}),t==="explore"&&(y.runtime_probe=p.summary),t==="manage"&&(y.runtime_probe=p.summary,y.managed_state_fix=wu(f,m)),i(y)},wi={init:ql,install:ou,uninstall:du,explore:yi,manage:yi,describe:gu,reload:Gl,doctor:hu,catalog:Hl,adopt:cu,"adopt-all":iu,activate:_i,deactivate:_i,migrate:mi},vu=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),bu=e=>vu(e)?Kn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>wi[e.action](e)):wi[e.action](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]="cdfc451a-1148-50c5-934a-cd8bc2bb39e7")}catch{}})();var Eu=Su(ku),$u="@unbrained/pm-cli",Tu="latest";function Iu(e){let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new g('Options "--project/--local" and "--global" are mutually exclusive.',_.USAGE);return n?"global":"project"}function tn(e){return e.trim().toLowerCase()}function Ni(e,t){let n=tn(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(r=>typeof r=="string"&&tn(r)===n)}function Au(e,t){let n=D(process.cwd(),t.path),a=Le(n,process.cwd());return{selected_root:e==="global"?a.global:a.project}}async function Cu(e,t,n){try{let a=await Eu(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:a.stdout,stderr:a.stderr}}catch(a){let r=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr??""):"",o=r.trim().length>0?r.trim():a instanceof Error?a.message:String(a);throw new g(`Command failed: ${e} ${t.join(" ")}
23
- ${o}`,_.GENERIC_FAILURE)}}async function Ru(){return ka(import.meta.url,["../../.."])}function nn(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():Tu}function en(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():$u}async function Ou(e,t){let n=e.commandRunner??Cu,a=en(e),r=nn(e),o=`${a}@${r}`,i=["npm","install","-g",o];e.repair===!0&&i.push("--force");let s=await Ru(),c={requested:!0,status:"planned",package:a,target:o,command:i,before_version:s,repair:e.repair===!0};if(t)return c;try{await n(i[0],i.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 Nu(e){return xu.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function Du(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!Nu(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 Pu(e,t){let n=Du(e,t);return e.kind!=="local"||await E(n)?n:await E(e.location)?e.location:n}function ju(e,t,n,a){let r=["pm","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&a&&a.trim().length>0&&r.push("--ref",a.trim()),r}async function Di(e,t){let n=Au(e,t);return(await B(n.selected_root)).state.entries.filter(r=>r.scope===e)}async function Lu(e,t,n){let a=await Di(e,t);return a.find(r=>Ni(r,n.name))??a.find(r=>tn(r.directory)===tn(n.directory))}async function Mu(e,t,n,a,r){let o=nn(t),i=await Pu(e.source,o),s=ju(e.source,i,a,e.source.ref),c={name:e.name,directory:e.directory,scope:a,source:e.source,status:"planned",command:s,previous_version:e.manifest_version};if(r)return c;try{await ta(i,{install:!0,project:a==="project",global:a==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await Lu(a,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 Fu(e,t,n,a){let r=[n?e.status:void 0,...t.map(o=>o.status)].filter(o=>typeof o=="string");return{requested_cli:n,requested_packages:a,planned:r.filter(o=>o==="planned").length,updated:r.filter(o=>o==="updated").length,skipped:r.filter(o=>o==="skipped").length,failed:r.filter(o=>o==="failed").length}}async function O_(e,t,n){if(t.cliOnly===!0&&t.packagesOnly===!0)throw new g('Options "--cli-only" and "--packages-only" are mutually exclusive.',_.USAGE);let a=Iu(t),r=t.dryRun===!0,o=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&o)throw new g('A package target cannot be used with "--cli-only".',_.USAGE);let i=!(t.packagesOnly===!0||o),s=t.cliOnly!==!0,c=i?await Ou(t,r):{requested:!1,status:"skipped",package:en(t),target:`${en(t)}@${nn(t)}`,command:["npm","install","-g",`${en(t)}@${nn(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await Di(a,n):[];if(o&&(d=d.filter(f=>Ni(f,o)),d.length===0))throw new g(`Managed package "${o}" was not found in ${a} scope.`,_.NOT_FOUND);let l=[];for(let f of d)l.push(await Mu(f,t,n,a,r));let u=Fu(c,l,i,s);return{ok:u.failed===0,action:"upgrade",dry_run:r,scope:a,target:o,cli:c,packages:l,summary:u}}import Ye from"node:fs/promises";import sn from"node:path";import an from"node:fs/promises";import na 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]="8cc32963-26eb-5e08-bffb-2d8da152a43f")}catch{}})();var Uu=864e5;function rn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function zu(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 Ju(e,t){let n;try{n=await an.readdir(e,{withFileTypes:!0})}catch(r){if(rn(r,"ENOENT"))return[];throw r}let a=[];for(let r of n)if(r.isDirectory()){let o=na.join(e,r.name),i;try{i=await an.readdir(o)}catch(s){rn(s,"ENOENT")||t.push(`checkpoint_subdir_unreadable:${r.name}`);continue}for(let s of i)s.endsWith(".json")&&a.push(`${r.name}/${s}`)}else r.name.endsWith(".json")&&a.push(r.name);return a.sort()}async function Pi(e,t){let{dryRun:n,hooks:a}=t,r=t.now??Date.now(),o=Math.max(0,t.retentionDays)*Uu,i=na.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await Ju(i,s.warnings);for(let d of c){let l=na.join(i,d),u=`checkpoints/${d}`;s.scanned+=1,a?.onRead&&s.warnings.push(...await a.onRead(l));let f;try{f=await an.readFile(l,"utf8")}catch(y){if(rn(y,"ENOENT")){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 h=zu(f),p=h===null?Number.NaN:Date.parse(h);if(!Number.isFinite(p)){s.warnings.push(`checkpoint_unparseable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:h,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=r-p,w={file:u,created_at:h,age_seconds:Math.floor(m/1e3),stale:m>o,reason:m>o?"expired":"active"};if(!w.stale){s.retained.push(u),s.entries.push(w);continue}if(!n){try{await an.unlink(l)}catch(y){if(!rn(y,"ENOENT")){s.warnings.push(`checkpoint_remove_failed:${d}`),s.retained.push(u),s.entries.push(w);continue}}a?.onWrite&&s.warnings.push(...await a.onWrite(l))}s.removed.push(u),s.entries.push(w)}return s}import aa from"node:fs/promises";import ji 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]="a6c0aa24-501a-5e76-a669-91d125634cf1")}catch{}})();var Wu=1440*60*1e3,qu=new Set(["committed","compensated"]);function Gu(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Hu(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 Bu(e,t,n,a,r){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 i=a-o;return qu.has(t)?i>r?{entry:{file:e,status:t,age_seconds:Math.floor(i/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(i/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(i/1e3),stale:!1,reason:"active"},remove:!1}}async function Vu(e,t,n,a){let r=a.hooks?.onRead?await a.hooks.onRead(e):[],o=Hu(await aa.readFile(e,"utf8")),i=Bu(t,o.status,o.updatedAt,a.nowMs,a.retentionMs);return i.entry.reason==="unparseable"&&r.push(`transaction_journal_unparseable:${n}`),i.remove&&!a.dryRun&&(await aa.rm(e,{force:!0}),a.hooks?.onWrite&&r.push(...await a.hooks.onWrite(e))),{decision:i,warnings:r}}async function Li(e,t){let{dryRun:n,hooks:a}=t,r=t.now??Date.now(),o=Math.max(0,t.retentionDays)*Wu,i=ji.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await aa.readdir(i)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(Gu(d,"ENOENT"))return s;throw d}for(let d of c){let l=ji.join(i,d),u=`transactions/sdk/${d}`,f=await Vu(l,u,d,{dryRun:n,hooks:a,nowMs:r,retentionMs:o});s.warnings.push(...f.warnings),s.scanned+=1;let{decision:h}=f;if(!h.remove){s.retained.push(u),s.entries.push(h.entry);continue}s.removed.push(u),s.entries.push(h.entry)}return s}import gt from"node:fs/promises";import on 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]="a026943f-1a46-526b-bfaa-435025c65c2a")}catch{}})();function Ku(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:a,owner:r,created_at:o,ttl_seconds:i}=n;return typeof a!="string"||typeof r!="string"||typeof o!="string"||typeof i!="number"||!Number.isFinite(i)?null:{id:a,owner:r,created_at:o,ttl_seconds:i}}function _t(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Mi(e,t,n){let a=Ku(t);if(a===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let r=Date.parse(a.created_at);if(!Number.isFinite(r))return{detail:"invalid_timestamp",entry:{file:e,id:a.id,owner:a.owner,created_at:a.created_at,ttl_seconds:a.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let o=n-r,i=Math.floor(o/1e3),s=o>a.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:a.id,owner:a.owner,created_at:a.created_at,ttl_seconds:a.ttl_seconds,age_seconds:i,stale:s,reason:s?"expired":"active"}}}async function Fi(e,t){let n=t??Date.now(),a=on.join(e,"locks"),r={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await gt.readdir(a)).filter(s=>s.endsWith(".lock")).sort()}catch(i){if(_t(i,"ENOENT"))return r;throw i}for(let i of o){let s;try{s=await gt.readFile(on.join(a,i),"utf8")}catch(d){if(_t(d,"ENOENT"))continue;r.scanned+=1,r.unreadable_lock_count+=1;continue}r.scanned+=1;let{detail:c}=Mi(i,s,n);c==="active"?r.active_lock_count+=1:c==="expired"?r.stale_lock_count+=1:r.unparseable_lock_count+=1}return r}async function Ui(e,t){let{dryRun:n,hooks:a}=t,r=t.now??Date.now(),o=on.join(e,"locks"),i={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await gt.readdir(o)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if(_t(c,"ENOENT"))return i;throw c}for(let c of s){i.scanned+=1;let d=on.join(o,c),l=`locks/${c}`;if(a?.onRead){let h=await a.onRead(d);i.warnings.push(...h)}let u;try{u=await gt.readFile(d,"utf8")}catch(h){if(_t(h,"ENOENT")){i.scanned-=1;continue}i.warnings.push(`lock_unreadable:${c}`),i.retained.push(l),i.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=Mi(c,u,r);if(f.detail==="unparseable_json"){i.warnings.push(`lock_unparseable:${c}`),i.retained.push(l),i.entries.push(f.entry);continue}if(f.detail==="invalid_timestamp"){i.warnings.push(`lock_invalid_timestamp:${c}`),i.retained.push(l),i.entries.push(f.entry);continue}if(f.detail==="active"){i.retained.push(l),i.entries.push(f.entry);continue}if(!n){try{await gt.unlink(d)}catch(h){if(!_t(h,"ENOENT")){i.warnings.push(`lock_remove_failed:${c}`),i.retained.push(l),i.entries.push(f.entry);continue}}if(a?.onWrite){let h=await a.onWrite(d);i.warnings.push(...h)}}i.removed.push(l),i.entries.push(f.entry)}return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0973a87f-2b63-5fa1-9624-82897d181f71")}catch{}})();var yt=["index","embeddings","runtime","locks","checkpoints","transactions"],Yu=1440*60*1e3,Xu=[{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"}];function zi(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function Qu(e,t,n){let a=t.relativePath,r=sn.join(e,a),o=await fe({path:r,scope:"project"});try{let i=await Ye.stat(r);if(t.kind==="file"&&!i.isFile())return{removed:!1,warnings:[...o,`not_a_file:${a}`]};if(t.kind==="directory"&&!i.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${a}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await Ye.unlink(r):await Ye.rm(r,{recursive:!0,force:!0});let s=await U({path:r,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...s]}}catch(i){if(zi(i,"ENOENT"))return{removed:!1,warnings:o};throw i}}async function Zu(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],a=[],r=[],o=[],i=Date.now()-Yu;for(let s of n){let c=sn.join(e,s.relativePath);if(!await E(c))continue;let d=(await Ye.readdir(c)).filter(l=>l.startsWith(s.prefix)).sort();for(let l of d){let u=sn.posix.join(s.relativePath,l),f=sn.join(c,l);o.push(...await fe({path:f,scope:"project"}));let h=await Ye.stat(f).catch(p=>{if(!zi(p,"ENOENT"))throw p});if(h){if(h.mtimeMs>i){r.push(u);continue}a.push(u),!t&&(await Ye.rm(f,{recursive:!0,force:!0}),o.push(...await U({path:f,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:a,retained:r,warnings:o}}function em(e){if(!e||e.length===0)return[...yt];let t=e.flatMap(a=>a.split(",")).map(a=>a.trim().toLowerCase()).filter(a=>a.length>0);if(t.length===0)throw new g(`--scope requires at least one value (${yt.join(",")})`,_.USAGE);let n=new Set;for(let a of t){if(!yt.includes(a))throw new g(`Invalid --scope value "${a}". Expected one or more of: ${yt.join(", ")}`,_.USAGE);n.add(a)}return yt.filter(a=>n.has(a))}function tm(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"),a=e.removed.some(r=>r==="index/manifest.json"||r==="search/embeddings.jsonl"||r==="search/vectorization-status.json"||r==="search/lancedb"||r==="search/pending-refresh.json"||r==="search/pending-refresh.gate.lock");return n&&a&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(r=>r.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(r=>r.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function ty(e,t={}){let n=D(process.cwd(),e.path);if(!await E(ee(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,_.NOT_FOUND);let a=await R(n),r=t.dryRun===!0,o=em(t.scope),i=Xu.filter(p=>o.includes(p.scope)),s=[],c=[],d=[];for(let p of i){let m=await Qu(n,p,r);m.removed?s.push(p.relativePath):c.push(p.relativePath),d.push(...m.warnings)}if(o.includes("runtime")){let p=await Zu(n,r);s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(o.includes("locks")){let p=await Ui(n,{dryRun:r,hooks:{onRead:m=>fe({path:m,scope:"project"}),onWrite:m=>U({path:m,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=a.checkpoints.retention_days,m=await Li(n,{dryRun:r,retentionDays:p,hooks:{onRead:w=>fe({path:w,scope:"project"}),onWrite:w=>U({path:w,scope:"project",op:"gc:transaction_journal_remove"})}});s.push(...m.removed),c.push(...m.retained),d.push(...m.warnings),u={scanned:m.scanned,removed:m.removed.length,retained:m.retained.length,retention_days:p}}let f;if(o.includes("checkpoints")){let p=a.checkpoints.retention_days,m=await Pi(n,{dryRun:r,retentionDays:p,hooks:{onRead:w=>fe({path:w,scope:"project"}),onWrite:w=>U({path:w,scope:"project",op:"gc:checkpoint_remove"})}});s.push(...m.removed),c.push(...m.retained),d.push(...m.warnings),f={scanned:m.scanned,removed:m.removed.length,retained:m.retained.length,retention_days:p}}d.push(...await Dt({mode:r?"gc:dry-run":"gc",total_items:i.length}));let h=tm({dryRun:r,scopes:o,removed:s});return{ok:d.length===0,dry_run:r,scope:o,removed:s,retained:c,warnings:d,...l?{locks:l}:{},...f?{checkpoints:f}:{},...u?{transactions:u}:{},guidance:h,generated_at:A()}}import ve from"node:fs/promises";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]="4efa3db2-6be7-5650-b1c7-d80e125694aa")}catch{}})();var nm=new Set(xr),Wi=25,wt=8,am=V.join("runtime","telemetry","events.jsonl"),rm=V.join("runtime","telemetry","state.json"),om=2500,im=500,qi=kr-3,sm=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Gi(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("stale_in_progress_items:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Hi(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Qe(e){return e.trim().toLowerCase()}function ia(e,t){let n=Qe(e),a=Qe(t);return n.startsWith("builtin-")?!0:a==="beads"||a==="todos"}async function da(e){try{return(await ve.stat(e)).isDirectory()}catch{return!1}}async function cm(e){let t=(await ve.readdir(e,{withFileTypes:!0})).filter(a=>a.isDirectory()),n=await Promise.all(t.map(a=>ve.readdir(V.join(e,a.name),{withFileTypes:!0})));return new Set(n.flatMap(a=>a.filter(r=>r.isFile()).filter(r=>un.some(o=>r.name.endsWith(o))).map(r=>V.parse(r.name).name)))}async function dm(e,t,n,a){let r=await fe({path:e,scope:"project"}),o=t!=="_workspace"&&!a.has(t);if(!n.enabled&&!o)return{warnings:r,overThreshold:!1,classification:"live"};let i;try{i=await ve.readFile(e,"utf8")}catch{return{warnings:r,overThreshold:!1,classification:"unreadable"}}let s="live";if(o){let d=i.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?i.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:r,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function lm(e,t,n){let a=V.join(e,"history");if(!await da(a))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let r=(await ve.readdir(a)).filter(u=>u.endsWith(".jsonl")).sort((u,f)=>u.localeCompare(f)),i=t.enabled?t.max_entries:null,s=[],c=[],d=[],l=[];for(let u of r){let f=V.join(a,u),h=u.slice(0,-6),p=await dm(f,h,t,n);s.push(...p.warnings),p.classification==="tombstone"&&d.push(h),p.classification==="orphaned"&&l.push(h),p.overThreshold&&c.push(h)}return{count:r.length,warnings:[...s,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:i,tombstones:d,orphaned:l}}function sa(e,t){return V.relative(e,t).replaceAll("\\","/")}async function Bi(e,t){let n=[...new Set(Object.values(t))].sort((r,o)=>r.localeCompare(o)),a=[];for(let r of n){let o=V.join(e,r),i=[];try{i=await ve.readdir(o)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")continue;continue}for(let s of i)un.some(c=>s.toLowerCase().endsWith(c))&&a.push(V.join(o,s))}return a.sort((r,o)=>sa(e,r).localeCompare(sa(e,o))),a}function um(e){return!(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")}async function mm(e,t,n){let a=await Bi(e,t),r=[],o=[],i=[],s=[],c=St(M());for(let d of a){let l=sa(e,d),u;try{u=await ve.readFile(d,"utf8")}catch{r.push(l);continue}let f=yn(u);if(f){o.push({path:l,...f});continue}try{let h=Pt(u,{format:Ea(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:Va(h.metadata)})}catch{i.push(l)}}return{paths:a,unreadable:r,conflictMarkers:o,parseFailures:i,formatVersions:s}}async function pm(e){let t=V.join(e,"history"),n=[],a=[],r=[],o=[];try{o=(await ve.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,s)=>i.localeCompare(s))}catch(i){um(i)&&n.push("history")}for(let i of o){let s=i.slice(0,-6),c;try{c=await ve.readFile(V.join(t,i),"utf8")}catch{n.push(s);continue}let d=yn(c);if(d){a.push({id:s,...d});continue}c.split(/\r?\n/).forEach((l,u)=>{if(l.trim())try{JSON.parse(l)}catch{r.push({id:s,line:u+1})}})}return{files:o,unreadable:n,conflictMarkers:a,invalidJson:r}}async function fm(e,t,n,a){let r=await mm(e,t,n),o=await pm(e),i=Ka(r.formatVersions),s=await Cr(e),c=await Sr(e),d=c===null?null:await Er(c),l=c===null?[]:await Rr(c),u=d?.status==="missing"&&d.missing_keys.length===5&&d.drifted_keys.length===0,f=[...r.unreadable.map(p=>`integrity_item_unreadable:${p}`),...r.conflictMarkers.map(p=>`integrity_item_conflict_marker:${p.path}:L${p.line}`),...r.parseFailures.map(p=>`integrity_item_parse_failed:${p}`),...o.unreadable.map(p=>`integrity_history_unreadable:${p}`),...o.conflictMarkers.map(p=>`integrity_history_conflict_marker:${p.id}:L${p.line}`),...o.invalidJson.map(p=>`integrity_history_invalid_json:${p.id}:L${p.line}`),...i.outdated.map(p=>`integrity_item_outdated_format_version:${p}`),...i.ahead.map(p=>`integrity_item_ahead_format_version:${p}`),...s.tracked_path_count>0?[`tracked_runtime_cache_files:${s.tracked_path_count}`]:[],...d!==null&&d.status!=="ok"?[`merge_driver_configuration_${u?"missing":"drift"}:${d.missing_keys.length+d.drifted_keys.length}`]:[],...l.length>0?[`merge_decisions_unreviewed:${l.length}`]:[]],h=[...new Set(f)].sort((p,m)=>p.localeCompare(m));return{check:{name:"integrity",status:h.length===0?"ok":"warn",details:{checked_item_files:r.paths.length,checked_history_streams:o.files.length,counts:{item_unreadable:r.unreadable.length,item_conflict_markers:r.conflictMarkers.length,item_parse_failures:r.parseFailures.length,history_unreadable:o.unreadable.length,history_conflict_markers:o.conflictMarkers.length,history_invalid_json:o.invalidJson.length,item_outdated_format_version:i.outdated.length,item_ahead_format_version:i.ahead.length,tracked_runtime_cache_files:s.tracked_path_count,merge_driver_configuration:d===null||d.status==="ok"?0:d.missing_keys.length+d.drifted_keys.length,pending_merge_decisions:l.length},item_unreadable:r.unreadable,item_conflict_markers:r.conflictMarkers,item_parse_failures:r.parseFailures,item_outdated_format_version:i.outdated,item_ahead_format_version:i.ahead,history_unreadable:o.unreadable,history_conflict_markers:o.conflictMarkers,history_invalid_json:o.invalidJson,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},merge_driver_configuration:d===null?null:{...d,required:a},pending_merge_decision_items:[...new Set(l.map(p=>p.item_id))].sort((p,m)=>p.localeCompare(m))}},warnings:h}}function hm(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function gm(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:hm(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function _m(e,t){let n=ke(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function ym(e){let n=ke(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function wm(e){return ke(e.reason)??ke(e.error)??ke(e.message)}function ra(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let a=(e.name??"").localeCompare(t.name??"");return a!==0?a:(e.id??"").localeCompare(t.id??"")}function vm(e){let t=[],n=[],a=[];e.forEach((o,i)=>{let s=_m(o.definition,i),c=ym(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:s,status:c});return}if(c==="failed"){a.push({layer:o.layer,name:o.name,id:s,status:c,reason:wm(o.definition)});return}n.push({layer:o.layer,name:o.name,id:s,status:c})}),t.sort(ra),n.sort(ra),a.sort(ra);let r=[...a.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:a,applied_count:t.length,pending_count:n.length,failed_count:a.length},warnings:r}}function Vi(e,t,n,a,r,o,i,s,c){let d=[...new Set(e)].sort((w,y)=>w.localeCompare(y)),l=[...new Set(d.map(w=>Hi(w)))].sort((w,y)=>w.localeCompare(y)),u=d.filter(w=>w.startsWith("extension_capability_unknown:")).length,f=c.length>0,h=f?"partial":"full",p=[],m=Hn(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return m&&p.push(m),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."),(a.failed_count>0||a.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),r>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: ${kt.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(w=>w.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(w=>w.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."),f?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>."):i.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:a.failed_count,migration_pending_count:a.pending_count,managed_state_warning_count:r,managed_extension_entries_count:o,unmanaged_loaded_extension_count:i.length,unmanaged_loaded_extensions:i,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:h,update_health_partial:f,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function bm(e,t,n){let a=await ie({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),r=a.loaded.map(b=>gm(b)),o=await se({...a,loaded:a.loaded}),[i,s]=await Promise.all([B(a.roots.project),B(a.roots.global)]);await Xn(e,o.registrations.migrations);let c=vm(o.registrations.migrations),d={failed:o.failed,warnings:o.warnings,hook_counts:o.hook_counts,command_override_count:o.command_override_count,command_handler_count:o.command_handler_count,parser_override_count:o.parser_override_count,preflight_override_count:o.preflight_override_count,service_override_count:o.service_override_count,renderer_override_count:o.renderer_override_count,registration_counts:o.registration_counts,registrations:o.registrations,migration_status:c.summary,managed_extensions:{project:{path:i.path,count:i.state.entries.length,entries:i.state.entries},global:{path:s.path,count:s.state.entries.length,entries:s.state.entries}}},l=new Set(i.state.entries.map(b=>Qe(b.name))),u=new Set(s.state.entries.map(b=>Qe(b.name))),f=[...new Map(a.loaded.filter(b=>!(b.layer==="project"?l:u).has(Qe(b.name))).map(b=>[`${b.layer}:${b.name}`,{layer:b.layer,name:b.name,directory:b.directory}])).values()].sort((b,T)=>{let J=`${b.layer}:${b.name}`,W=`${T.layer}:${T.name}`;return J.localeCompare(W)}),h=f.map(b=>`${b.layer}:${b.name}`).sort((b,T)=>b.localeCompare(T)),p=f.filter(b=>ia(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,T)=>b.localeCompare(T)),m=f.filter(b=>!ia(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,T)=>b.localeCompare(T)),w=m.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${m.length}`]:[],y=[...a.warnings,...d.warnings,...c.warnings,...i.warnings,...s.warnings,...w],v=pt(y),x=ft(),I=Vi(y,a.failed.length,o.failed.length,c.summary,i.warnings.length+s.warnings.length,i.state.entries.length+s.state.entries.length,h,p,m);return{check:{name:"extensions",status:y.length===0?"ok":"warn",details:{...a,loaded:r,warnings:y,activation:d,triage:I,...c.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:v}},warnings:y}}function km(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function we(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function xm(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 cn(e,t){let n=we(e,t);return{...n,sample:n.sample.map(a=>xm(a))}}function L(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(a=>typeof a=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function Sm(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 Em={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:L(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:L(e.missing_required,t),missing_optional:L(e.missing_optional,t),missing:L(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:L(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:cn(e.discovered,t),effective:cn(e.effective,t),loaded:cn(e.loaded,t),failed:we(e.failed,t),warnings:L(e.warnings,t),activation:{failed:we(n.failed,t),warnings:L(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:Sm(n.migration_status)},triage:e.triage,capability_contract:e.capability_contract,capability_guidance:we(e.capability_guidance,t)}},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:L(n.affected_item_ids,t),samples:we(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:L(e.item_unreadable,t),item_conflict_markers:we(e.item_conflict_markers,t),item_parse_failures:L(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:L(n.tracked_paths,t)},history_unreadable:L(e.history_unreadable,t),history_conflict_markers:we(e.history_conflict_markers,t),history_invalid_json:we(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>({checked_items:e.checked_items,counts:e.counts,drifted_items:L(e.drifted_items,t),missing_streams:L(e.missing_streams,t),unreadable_streams:L(e.unreadable_streams,t),hash_mismatches:L(e.hash_mismatches,t),chain_mismatches:L(e.chain_mismatches,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:L(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:L(e.stale_items_after,t),skipped:e.skipped})};function Ki(e,t){let n=Em[e.name];return n?n(e.details,t):e.details}function $m(e){let t=L(e.warnings,wt);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,details:Ki(n,wt)})),warnings:t.sample,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:wt},generated_at:e.generated_at}}function Ji(e){return e.details.skipped===!0}function Tm(e){let t=L(e.warnings,wt),n=e.checks.filter(Ji).map(a=>a.name);return{ok:e.ok,checks:e.checks.filter(a=>!Ji(a)).map(a=>({name:a.name,status:a.status,details:{}})),warning_count:t.count,warnings:t.sample,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:wt,omitted_checks:n},generated_at:e.generated_at}}function ca(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=km(e,Wi);return{values:n.values,truncated:n.truncated,total:e.length}}function Xe(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Im(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return nm.has(e)?e:null}function dn(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 Yi(e){let t=0,n=0,a=0,r=0,o=0;for(let i of e.split(`
24
- `)){let s=i.trim();if(s.length!==0){a+=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>=qi&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:a,highRetryEntries:r,maxAttempts:o}}function Am(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Cm(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 Rm(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await Xi(n)}}function Om(e,t,n){let a=[];if(t.invalidRows>0&&a.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return a;let r=n.last_successful_flush_at,o=n.last_failed_flush_at,i=o&&(!r||o>r),s=!r,c=t.validEntries>=im;return(i||s||c)&&a.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&a.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),a}function Nm(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function Dm(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>br?[`telemetry_schema_version_behind:${t}`]:[]}function Pm(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,a=t.last_otel_success_at,r=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!r&&(!a||r>=a)?[`telemetry_otel_export_failing:${n}`]:[]}function jm(){return{telemetry_disabled:Xe("PM_TELEMETRY_DISABLED")||Xe("PM_NO_TELEMETRY"),pm_no_telemetry:Xe("PM_NO_TELEMETRY"),telemetry_otel_disabled:Xe("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:Xe("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:Im()}}function Lm(e,t){return e.telemetry.enabled&&t.validEntries>0}function Mm(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Xi(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(om)});return{probe_url:dn(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let a of sm){let r=n.headers.get(a)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:dn(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function Fm(e,t){let n=Et(process.cwd()),a=V.join(n,am),r=V.join(n,rm),o=await q(a),i=o!==null,s=o?Buffer.byteLength(o,"utf8"):0,c=o?Yi(o):Am(),d=await q(r),{runtimeState:l,stateParseFailed:u}=Cm(d),f=e.telemetry.endpoint.trim(),h=dn(f),p=await Rm(e,t.checkTelemetry),m=[];u&&m.push("telemetry_state_invalid_json"),m.push(...Om(e,c,l),...Nm(p),...Dm(p),...Pm(e,l));let w=Lm(e,c),y=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:m.length===0?"ok":"warn",details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:h,global_pm_root:n,queue_path:a,queue_exists:i,queue_entries:c.validEntries,queue_draining:Mm(w,m),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:qi,queue_max_attempts:c.maxAttempts,runtime_state_path:r,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:y,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:jm()}},warnings:m}}async function Um(e){let t;try{t=await Fi(e)}catch(a){let r=a instanceof Error?a.message:String(a);return{check:{name:"locks",status:"warn",details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:r,pm_root:e}},warnings:[`locks_scan_failed:${r}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",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 zm(e,t){let n="metadata",{missingStreams:a,unreadableStreams:r,hashMismatches:o,chainMismatches:i,driftedItems:s}=await Tr(e,t,{cacheHitVerification:n}),c=[...a.map(d=>`history_drift_missing_stream:${d}`),...r.map(d=>`history_drift_unreadable_stream:${d}`),...o.map(d=>`history_drift_hash_mismatch:${d}`),...i.map(d=>`history_drift_chain_mismatch:${d}`)];return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,cache_hit_verification:n,drifted_items:s,counts:{drifted:s.length,missing_streams:a.length,unreadable_streams:r.length,hash_mismatches:o.length,chain_mismatches:i.length},missing_streams:a,unreadable_streams:r,hash_mismatches:o,chain_mismatches:i}},warnings:c}}function Jm(e,t){let n=Mt(e),a=at(n.settings),r=Ft(n.settings,t),o=a.active?Re(a.active.name,a.active.model):null;return{runtimeDefaults:n,providerResolution:a,vectorStoreResolution:r,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(a.active&&r.active)}}function Wm(){return{refreshed:[],skipped:[],warnings:[]}}async function qm(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?Wm():yr(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function Gm(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Je(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function Hm(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,a)=>n.localeCompare(a))}function Bm(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Qi(e,t){let n=t.providerResolution.active?.name??null,a=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:bn(n,e.search?.provider??null),vector_store_active:a,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:bn(a,e.vector_store?.adapter??null)}}function Vm(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function Km(e,t,n){return e.enabled&&n.length>0&&t}async function Ym(e,t,n,a,r){let o=Jm(t,e),i=await We(e),s=o.semanticRuntimeAvailable?Sn(n,i.entries):[],c=await qm({pmRoot:e,snapshot:o,refreshPolicy:a,staleBefore:s}),d=await We(e),l=o.semanticRuntimeAvailable?Sn(n,d.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,f=Gm({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:i,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),h=Hm({ledgerBefore:i,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:f,staleAfter:l}),p=ca(s,r),m=ca(l,r),w=Km(a,o.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:h.length===0?"ok":"warn",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:Vm(a),...Qi(t,o),embedding_identity_changed:f,embedding_identity_before:i.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(i.entries).length,stale_items_detail_mode:r?"full":"summary",stale_items_summary_limit:Wi,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:w,refresh_skipped_reason:Bm(a,o.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:m.total,stale_items_after:m.values,stale_items_after_truncated:m.truncated}},warnings:h}}function Xm(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 Zi(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new g("--check-only cannot be combined with --refresh-vectors",_.USAGE);if(n&&e.noRefresh===!0)throw new g("--no-refresh cannot be combined with --refresh-vectors",_.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var Qm=new Set(["extensions","locks","search"]);function Zm(e){let t=new Set(va.filter(r=>r.length>0)),n=new Set,a=new Set(Object.values(ba));for(let r of e.folders)t.has(r)&&!a.has(r)||(t.delete(r),n.add(r));for(let r of Qm)t.delete(r),n.add(r);return{requiredDirs:[...t].sort((r,o)=>r.localeCompare(o)),optionalDirs:[...n].sort((r,o)=>r.localeCompare(o)),optionalDirSet:n}}async function ep(e,t,n){let{requiredDirs:a,optionalDirs:r,optionalDirSet:o}=Zm(t),i=[],s=[],c=[];for(let d of[...a,...r]){let l=V.join(e,d);c.push(...await fe({path:l,scope:"project"})),!await da(l)&&(o.has(d)?s.push(d):i.push(d))}return{requiredDirs:a,optionalDirs:r,missingRequiredDirs:i,missingOptionalDirs:s,missingDirs:n?[...i,...s]:[...i],hookWarnings:c}}function es(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,a=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||a)&&e.full!==!0,skipDrift:(e.skipDrift===!0||a)&&e.full!==!0,skipVectors:(e.skipVectors===!0||a)&&e.full!==!0}}async function tp(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?ar(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):rr(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function oa(e){return{check:{name:e,status:"ok",details:{skipped:!0}},warnings:[]}}function np(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function ap(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function rp(e){return{name:"settings_values",status:e.length===0?"ok":"warn",details:{warnings:e}}}var la=e=>e.unknown_event_count??0,ua=e=>e.actionable_unknown_event_count??la(e);function op(e,t,n,a,r){let o=la(a),i=ua(a),s=o>0,c=i>0,d=r.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!c&&!d?"ok":"warn",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},...s?{author_attribution:a}:{},...d?{stale_in_progress:r}:{},...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 ts(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function ip(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.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function sp(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function cp(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historySummary.over_threshold.map(t=>`history_stream_over_compact_threshold:${t}`),...e.authorAttributionWarnings,...e.staleInProgressWarnings],locks:e.locksCheck.warnings,integrity:e.integrityCheck.warnings,history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function dp(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-repair --all";if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function lp(e){for(let t of e.checks){let n=Ir(e.remediationSources[t.name]);dp({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}function ns(e,t,n){return n?Tm(e):t.brief===!0?$m(e):e}async function Fy(e,t={}){let n=D(process.cwd(),e.path),a=ee(n);if(!await E(a))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,_.NOT_FOUND);let{settings:r,warnings:o}=await Ya(n),i=[...new Set(o)],s=H(r,M()),c=t.strictDirectories===!0,d=Zi(t),l=await ep(n,s,c),u=Xm(r),f=await Fm(r,{checkTelemetry:t.checkTelemetry===!0}),h=await bm(n,r,!!e.noExtensions),p=es(t),m=[],w=await tp({pmRoot:n,settings:r,typeRegistry:s,skipPolicy:p,itemReadWarnings:m}),y=w,v=[...new Set(m)],x=p.skipDrift?{warnings:[]}:await Xa({pmRoot:n,settings:r,itemIds:w.map(Ae=>Ae.id),commandLabel:"health"}),I=await lm(n,r.history.compact_policy,await cm(n)),b=await Ar(n,20,t.verboseAuthorEvents===!0),T=ua(b),J=T>0?[`history_unknown_author_events:${T}`]:[],W=ts(await wr(n,w,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),S=await Um(n),P=p.skipIntegrity?oa("integrity"):await fm(n,s.type_to_folder,r.schema,t.requireMergeDrivers===!0),ae=p.skipDrift?oa("history_drift"):await zm(n,y),et=p.skipVectors?oa("vectorization"):await Ym(n,r,y,d,t.verboseStaleItems===!0),bt=[np(a,r,i),ap(l,c),rp(u),f.check,h.check,op(w,r,I,b,W.scan),S.check,P.check,ae.check,et.check],tt=ip({directoryState:l,normalizedSettingsReadWarnings:i,settingWarnings:u,normalizedItemReadWarnings:v,telemetryCheck:f,extensionCheck:h,historyPolicyWarnings:x.warnings,historySummary:I,authorAttributionWarnings:J,staleInProgressWarnings:W.warnings,locksCheck:S,integrityCheck:P,historyDriftCheck:ae,vectorizationCheck:et});lp({checks:bt,remediationSources:cp({directoryState:l,normalizedSettingsReadWarnings:i,settingWarnings:u,telemetryCheck:f,extensionCheck:h,historySummary:I,authorAttributionWarnings:J,staleInProgressWarnings:W.warnings,locksCheck:S,integrityCheck:P,historyDriftCheck:ae,vectorizationCheck:et}),historyDriftedCount:sp(ae),overThresholdCount:I.over_threshold.length});let ln={ok:tt.filter(Ae=>!Gi(Ae,t.requireMergeDrivers===!0)).length===0,checks:bt,warnings:tt,generated_at:A()};return ns(ln,t,p.summaryMode)}var Uy={buildExtensionHealthTriageSummary:Vi,buildCapabilityContractMetadata:ft,buildStaleInProgressHealthSummary:ts,buildVectorizationProviderDetails:Qi,collectUnknownCapabilityGuidance:pt,isAdvisoryHealthWarning:Gi,isDirectory:da,isExpectedUnmanagedExtension:ia,listItemDocumentPaths:Bi,normalizeEndpointForDisplay:dn,normalizeExtensionNameForMatch:Qe,parseTelemetryQueue:Yi,probeTelemetryEndpointHealth:Xi,projectHealthResult:ns,resolveActionableUnknownAuthorEventCount:ua,resolveHealthSkipPolicy:es,resolveUnknownAuthorEventCount:la,resolveVectorRefreshPolicy:Zi,selectStaleItemDetail:ca,summarizeHealthCheckDetails:Ki,summarizeExtensionList:cn,summarizeRecordList:we,summarizeStringList:L,telemetryEnvFlagEnabled:Xe,warningCode:Hi};import up from"node:fs/promises";import vt 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]="fc124f85-8d28-508b-a3f7-2fe767382197")}catch{}})();var ma="index/manifest.json",pa="search/embeddings.jsonl",mp="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function pp(e){return e.progress===!0||process.stderr.isTTY===!0}function z(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
25
- `)}catch{}}function fp(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new g("Reindex mode must be one of keyword|semantic|hybrid",_.USAGE)}async function hp(e,t,n,a){let r=[];return{candidates:await er(e,t,n,r,a),warnings:r}}async function ha(e,t,n,a,r){let o=St(M()),i=[];for(let s of t)if(!(r&&!r.has(s.metadata.id))){if(typeof s.body=="string"){i.push({metadata:s.metadata,body:s.body});continue}try{let c=await up.readFile(s.item_path,"utf8"),d=Pt(c,{format:s.item_format,schema:n,extensionFieldNames:o,onWarning:l=>a.push(l)});i.push({metadata:s.metadata,body:d.body})}catch{a.push(`item_list_item_read_failed:${vt.relative(e,s.item_path)}`),i.push({metadata:s.metadata,body:""})}}return i}function gp(e,t,n){let a=e.metadata;return{id:a.id,mode:t,updated_at:a.updated_at,corpus:cr(e,{fields:n})}}var Ze=ke;function _p(e){let t=M(),n=Ze(e.search?.provider);if(!n)return null;let a=or(t,n);if(!a)return null;let r=a.runtime_definition??a.definition,o=Ze(r.name)??Ze(a.definition.name);if(!o)return null;let i=r.embedBatch,s=r.embed_batch,c=r.embed,d=typeof i=="function"?i:typeof s=="function"?s:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:o,embedBatch:d,embed:l}}function yp(e){let t=M(),n=Ze(e.vector_store?.adapter);if(!n)return null;let a=ir(t,n);if(!a)return null;let r=a.runtime_definition??a.definition,o=Ze(r.name)??Ze(a.definition.name);if(!o)return null;let i=r.upsert,s=r.delete;return{adapterName:o,...typeof i=="function"?{upsert:i}:{},...typeof s=="function"?{delete:s}:{}}}function fa(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new g(`Invalid vector returned by ${t}`,_.GENERIC_FAILURE);return e}async function wp(e,t,n){let a=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let o=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:a}));if(!Array.isArray(o))throw new g(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,_.GENERIC_FAILURE);return o.map((i,s)=>fa(i,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new g(`Extension search provider "${e.name}" does not implement embed/embedBatch`,_.GENERIC_FAILURE);let r=[];for(let[o,i]of n.entries()){let s=await Promise.resolve(e.embed({input:i,settings:t,model:a}));r.push(fa(s,`extension search provider "${e.name}" embed output at index ${o}`))}return r}function as(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function rs(e,t,n){let a=n?Re(n.name,as(e)):t?Re(t.name,t.model):null;if(!a)throw new g("No embedding identity available for semantic reindex mode",_.USAGE);return a}function vp(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,a)=>n.localeCompare(a))}async function os(e,t,n,a,r,o,i,s){let c=a?.name??n?.name,d=dr(c,e.search.embedding_corpus_max_characters).maxCharacters,l=kn(e),u=r.map(p=>lr(p,{providerName:c,maxCharacters:d,fields:l})),f=[],h=null;if(a)try{f=await wp(a,e,u),h=Re(a.name,as(e))}catch(p){if(!n)throw new g(`Extension search provider "${a.name}" failed to generate embeddings: ${p instanceof Error?p.message:String(p)}`,_.GENERIC_FAILURE);o.push(`Extension search provider "${a.name}" failed; falling back to built-in provider (${p instanceof Error?p.message:String(p)})`)}if(f.length===0){if(!n)throw new g(`No embedding executor available for reindex mode '${t}'`,_.USAGE);let p=await ur(n,e,u,{onProgress:m=>{m.phase==="complete"&&(i.batches_completed=m.batch_index),z(s,`embedding_batch_${m.phase} batch=${m.batch_index}/${m.batch_total} size=${m.batch_size} completed_inputs=${m.completed_inputs}/${m.total_inputs}`)}});o.push(...p.warnings),f=p.vectors,h=Re(n.name,n.model)}if(z(s,`embedding_complete vectors=${f.length}`),f.length!==r.length)throw new g(`Embedding output size mismatch (expected ${r.length}, received ${f.length})`,_.GENERIC_FAILURE);if(!h)throw new g(`No embedding identity available for reindex mode '${t}'`,_.USAGE);return{vectors:f,embeddingIdentity:h}}async function bp(e,t,n,a,r,o){let i=Object.keys(n);if(t){if(i.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:i.sort((s,c)=>s.localeCompare(c)),settings:a}))}catch(s){throw new g(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,_.GENERIC_FAILURE)}else i.length>0&&r.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${i.length}`);if(!e)return}e&&await fr(e,i,{},o)}async function is(e,t,n,a,r){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:a}))}catch(o){throw new g(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${o instanceof Error?o.message:String(o)}`,_.GENERIC_FAILURE)}else r.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await pr(e,n)}}function kp(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function xp(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(a=>({id:a.metadata.id,type:a.metadata.type,status:a.metadata.status,priority:a.metadata.priority,updated_at:a.metadata.updated_at}))}}function Sp(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=at(e.settings);if(!t.active&&!e.extensionEmbedding)throw new g(`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=Ft(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new g(`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 Ep(e){let t=H(e.settings,M()),n=await hp(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(a=>({metadata:a.metadata,body:typeof a.body=="string"?a.body:""}))}}async function $p(e){let t=await We(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 rs(e.settings,at(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&Je(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(mp))}async function Tp(e){let t=await We(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=rs(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),a=new Set(e.metadataDocuments.map(d=>d.metadata.id)),r=vp(t.entries,a),o=Je(t.embedding,n);e.forceFullSemantic&&!o&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let i=e.forceFullSemantic||o?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),s=new Set(i.map(d=>d.metadata.id)),c=s.size>0?await ha(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:r,resetRequired:o,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function Ip(e){let t=new Set(e.metadataDocuments.map(r=>r.metadata.id)),n=await ha(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,z(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let a=await os(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...a,staleDocuments:n,vectorDimension:xn(a.vectors,"Reindex embeddings")}}async function Ap(e){let t=await os(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,a=t.embeddingIdentity,r=xn(n,"Reindex embeddings");if(!(!e.resetRequired&&(Je(e.ledgerEmbedding,a)||gr(e.ledgerEmbedding,r))))return{vectors:n,embeddingIdentity:a,staleDocuments:e.staleDocuments,vectorDimension:r,resetRequired:e.resetRequired};let i=await Ip(e);return n=i.vectors,a=i.embeddingIdentity,r=i.vectorDimension,{vectors:n,embeddingIdentity:a,staleDocuments:i.staleDocuments,vectorDimension:r,resetRequired:!0}}async function Cp(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(z(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new g(`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,z(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof g)throw t;if(!e.activeVectorStore)throw new g(`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)})`),z(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){z(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await mr(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,z(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new g(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,_.USAGE)}function Rp(e,t){return e.map((n,a)=>({id:n.metadata.id,vector:fa(t[a],`reindex embeddings output at index ${a}`),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 Op(e){z(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await Ap({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?(z(e.progressEnabled,"vector_reset_start"),await bp(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),z(e.progressEnabled,"vector_reset_complete")):await is(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=Rp(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await Cp({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:hr(t.embeddingIdentity,t.vectorDimension)}}async function Np(e){let t=await Tp(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(z(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 z(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await is(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let a=await Op({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let r=new Map(a.staleDocuments.map(o=>[o.metadata.id,o]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(o=>r.get(o.metadata.id)??o),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:a.embeddingMetadata}}async function Dp(e){let t=vt.join(e.pmRoot,ma),n=vt.join(e.pmRoot,pa),a=kn(e.settings),r=e.documentsForKeywordArtifacts.map(i=>JSON.stringify(gp(i,e.mode,a))).join(`
26
- `);z(e.progressEnabled,"writing keyword artifacts"),await re(t,`${JSON.stringify(e.manifest,null,2)}
27
- `),await re(n,`${r}
28
- `);let o=[];if(e.mode!=="keyword")try{z(e.progressEnabled,"writing vectorization status ledger"),await _r(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(i){o.push(`search_vectorization_status_ledger_write_failed:${i instanceof Error?i.message:String(i)}`)}return o}async function Gy(e,t){let n=fp(e.mode),a=pp(e),r=e.full===!0;z(a,`start mode=${n}`);let o=D(process.cwd(),t.path);if(!await E(ee(o)))throw new g(`Tracker is not initialized at ${o}. Run pm init first.`,_.NOT_FOUND);let i=Mt(await R(o)).settings,s=null;try{s=await X(o,sr,i.locks.ttl_seconds,Y(void 0,"pm-reindex"),!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms)}catch(c){throw c instanceof g&&c.exitCode===_.CONFLICT?new g("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=_p(i),d=yp(i),l=Sp({requestedMode:n,pmRoot:o,settings:i,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;z(a,"loading item corpus");let f=await Ep({pmRoot:o,settings:i}),h=f.warnings,{documentCandidates:p,metadataDocuments:m}=f;z(a,`loaded_items=${m.length}`);let w=A(),y=xp(u,w,m),v=vt.join(o,ma),x=vt.join(o,pa),I=u==="keyword"?await ha(o,p,i.schema,h):m,b=[],T={},J=null,W=kp(u);if(u==="keyword"&&await $p({pmRoot:o,settings:i,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:h}),u!=="keyword"){let ae=await Np({pmRoot:o,settings:i,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:p,metadataDocuments:m,documentsForKeywordArtifacts:I,forceFullSemantic:r,reindexWarnings:h,semanticWarnings:b,semanticSummary:W,progressEnabled:a});I=ae.documentsForKeywordArtifacts,T=ae.vectorizationLedgerEntries,J=ae.vectorizationEmbeddingMetadata}let S=await Dp({pmRoot:o,mode:u,manifest:y,documentsForKeywordArtifacts:I,settings:i,vectorizationLedgerEntries:T,vectorizationEmbeddingMetadata:J,progressEnabled:a}),P=[...await U({path:v,scope:"project",op:"reindex:manifest"}),...await U({path:x,scope:"project",op:"reindex:embeddings"}),...await Dt({mode:u,total_items:m.length})];return z(a,"done"),{ok:!0,mode:u,total_items:m.length,semantic:W,artifacts:{manifest:ma,embeddings:pa},warnings:[...h,...b,...S,...P],generated_at:w}}finally{await s?.()}}export{Wr as a,Nr as b,Ys as c,Ff as d,Uf as e,rt as f,zf as g,Jf as h,Wf as i,qf as j,Gf as k,Hf as l,Bf as m,Vf as n,Kf as o,Yf as p,Xf as q,ta as r,O_ as s,ty as t,Fy as u,Uy as v,Gy as w};
29
- //# sourceMappingURL=chunk-PL2EYDJK.js.map
1
+ import{a as hn,c as Ct,d as Rt,e as La,g as Ma,h as _n,i as Fa,j as ze,k as Je,l as Ua,m as za,n as yn,o as Ja,p as We,q as qe,r as Wa,s as qa,t as wn}from"./chunk-75774JWP.js";import{P as Cr,U as Rr,X as Or,Y as Nr,i as Er,m as $r,n as Tr,q as Ir,r as Ar}from"./chunk-3CQECMKR.js";import{a as Va}from"./chunk-IW43E4XL.js";import{B as Pt}from"./chunk-I4YM2I7S.js";import{f as $n}from"./chunk-RKWSCYYN.js";import{$ as Ge,Ba as kr,Ca as xr,Da as Sr,H as zt,I as cr,J as xn,K as st,M as Sn,Q as dr,R as lr,S as ur,T as mr,U as Jt,W as pr,X as fr,Y as hr,Z as Re,_ as gr,aa as _r,ba as En,ca as He,da as yr,e as ir,ea as wr,f as sr,wa as vr,xa as br}from"./chunk-MXYSIQ56.js";import{a as Na,b as Ot,c as gn,d as Da,e as Pa,f as me,g as Nt,h as ja,i as Ee}from"./chunk-DZGAHZZV.js";import{Fa as bn,Ia as Ft,Ka as fe,L as X,La as Qa,M as A,Ma as R,Na as Ut,Pa as Za,Q,Ua as er,X as Ya,_ as Xa,_a as tr,ab as nr,b as Ka,bb as ar,ca as vn,cb as rr,ea as Mt,eb as he,fb as or,ib as kn,k as M,n as U,p as pe,r as Lt}from"./chunk-FF4MNAYB.js";import{Aa as Ra,Ba as Oa,C as Ea,Ca as Ue,D as $a,E as B,Ea as se,Ga as ce,Ia as G,J as pn,Ja as ne,K as P,La as Y,M as At,Ma as de,N as te,P as Ta,Qa as it,Sa as Dt,U as Se,Wa as jt,X as Ia,Xa as Ha,Ya as Ba,a as wa,d as va,e as ba,h as It,p as E,qa as Aa,r as q,ra as Ca,s as oe,v as ie,w as xe,x as Sa,za as fn}from"./chunk-2EXI2DKR.js";import{P as ka,R as xa,Y as y,Z as _,a as $t,d as Tt,ka as Ga}from"./chunk-GHTN2ILR.js";import{execFile as $u}from"node:child_process";import Tu from"node:path";import{promisify as Iu}from"node:util";import Ce from"node:fs/promises";import ae from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1d184acd-e639-5b28-a294-98d22de2ebc7")}catch{}})();var ms=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Be(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(jt(t.extensionName));for(let p of t.extensionNames??[])n.add(jt(p));let a=p=>n.size===0||n.has(jt(p)),r=(p,g)=>Dr(p.filter(w=>a(w.name)).map(g)),o=(p,g)=>Dr(p.filter(w=>a(w.name)).flatMap(g)),{registrations:i,commands:s,parsers:c,preflight:d,services:l,renderers:u,hooks:m}=e,h=o(i.relationship_kinds??[],p=>p.definitions.map(g=>g.kind)),f=u.overrides.filter(p=>a(p.name)&&((p.commands?.length??0)>0||p.resultDiscriminator!==void 0)).map(p=>({format:p.format,commands:[...p.commands??[]],result_discriminator:p.resultDiscriminator!==void 0})).sort((p,g)=>p.format.localeCompare(g.format));return{capabilities:Ha(e,t),commands:r(i.commands,p=>p.command),command_overrides:r(s.overrides,p=>p.command),command_handlers:r(s.handlers,p=>p.command),hooks:ms.filter(([p])=>m[p].some(g=>a(g.name))).map(([,p])=>p),flag_commands:r(i.flags,p=>p.target_command),item_types:o(i.item_types,p=>p.types.map(g=>g.name)),item_fields:o(i.item_fields,p=>p.fields.map(g=>g.name)),...h.length>0?{relationship_kinds:h}:{},migrations:o(i.migrations,p=>typeof p.definition.id=="string"?[p.definition.id]:[]),profiles:r(i.profiles,p=>p.profile.name),importers:r(i.importers,p=>p.importer),exporters:r(i.exporters,p=>p.exporter),search_providers:r(i.search_providers,p=>p.definition.name),vector_store_adapters:r(i.vector_store_adapters,p=>p.definition.name),parser_overrides:r(c.overrides,p=>p.command),service_overrides:r(l.overrides,p=>p.service),renderer_overrides:r(u.overrides,p=>p.format),...f.length>0?{renderer_ownership:f}:{},preflight_overrides:d.overrides.filter(p=>a(p.name)).length,preflight_ownership:d.overrides.filter(p=>a(p.name)).map(p=>({commands:[...p.commands??[]]}))}}function Dr(e){return[...new Set(e)].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]="288a7da9-888b-527d-88fb-4711917cec5b")}catch{}})();var ps=e=>{let t='"',n=0;for(let a of e){if(a==="\\"){n+=1;continue}t+="\\".repeat(a==='"'?n*2+1:n),t+=a,n=0}return`${t}${"\\".repeat(n*2)}"`},Tn=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?ps(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,Pr=(e,t=process.platform)=>{let n=e.map(a=>Tn(a,t)).join(" ");return n.length>0?`pm ${n}`:"pm"};import tc from"node:path";import{mkdir as nc}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]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();var fs=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function hs(e){let t=fs.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function gs(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function jr(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,a=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,r=new Map;for(let i of e){let s=typeof i=="string"?i.trim():"";if(s.length===0)continue;let c=hs(s);if(c===void 0)continue;let d=r.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<a&&d.examples.push(s),r.set(c,d)}let o=[];for(let[i,s]of r.entries()){if(s.count<n)continue;let c=gs(i);o.push({name:c,prefix:i,count:s.count,examples:s.examples,shadows_builtin:Na(c)!==void 0})}return o.sort((i,s)=>s.count-i.count||i.name.localeCompare(s.name)),o}import{createHash as Vr}from"node:crypto";import Ne from"node:fs/promises";import Ke from"node:path";import{mkdir as _s,readFile as ys}from"node:fs/promises";import Jr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d49ec604-c10c-5706-9d87-510845e55e1a")}catch{}})();var In=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},ws="sdk-workspace-transaction",vs=/^[a-zA-Z0-9._-]+$/,bs=30,ks=3e3;function Lr(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!vs.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Mr(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 Fr(e,t,n){let a=e??t;if(!Number.isInteger(a)||a<=0)throw new TypeError(`${n} must be a positive integer`);return a}function Wr(e,t){return Jr.join(e,"transactions","sdk",`${t}.json`)}async function $e(e,t){t.updatedAt=A();let n=Wr(e,t.transactionId);await _s(Jr.dirname(n),{recursive:!0}),await oe(n,`${JSON.stringify(t,null,2)}
2
+ `)}function xs(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Oe(e){return Object.assign(Object.create(null),e)}function Ss(e,t){try{let n=JSON.stringify(e,(a,r)=>{if(typeof r=="number"&&!Number.isFinite(r))throw new TypeError(`${t} contains a non-finite number`);if(r===void 0||typeof r=="function"||typeof r=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return r});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function An(e,t){return e===void 0?void 0:Ss(e,t)}function Cn(e,t,n,a){let r=An(n,a);r===void 0?delete e[t]:e[t]=r}function Ur(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function zr(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Es(e,t){if(!zr(e.startedStepIds,t)||!zr(e.completedStepIds,t)||!Ur(e.results)||!Ur(e.compensationData))return!1;let n=e.startedStepIds,a=new Set(n),r=e.completedStepIds,o=new Set(r);return Object.keys(e.compensationData).some(i=>!a.has(i))||Object.keys(e.results).some(i=>!o.has(i))?!1:e.status==="committed"?t.every(i=>o.has(i)):e.status!=="compensated"||o.size===0&&a.size===0}function $s(e,t,n){let a;try{a=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!a||typeof a!="object"||Array.isArray(a))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let r=a,o=r.schemaVersion===1&&r.transactionId===t,i=Array.isArray(r.stepIds)&&r.stepIds.length===n.length&&r.stepIds.every((l,u)=>l===n[u]),s=Es(r,n),c=xs(r),d=["applying","compensating","compensated","committed"].includes(String(r.status));if(!o||!i||!s||!c||!d)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...r,results:Oe(r.results),compensationData:Oe(r.compensationData)}}async function Ts(e,t,n,a,r){let o=r,i=o!==void 0;if(o?.status==="compensating"&&await qr(e,o),o===void 0||o.status==="compensated"){let s=A();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??s,updatedAt:s,stepIds:a,startedStepIds:[],completedStepIds:[],results:Oe(),compensationData:Oe()},await $e(e.pmRoot,o),await ge(e,o,"prepared")}return{journal:o,recovered:i}}async function Is(e,t,n){try{await Cs(t,e.steps),await $e(e.pmRoot,t);let a=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let o of e.steps){if(a.has(o.id))continue;let i=await o.inspect(),s=An(i.result,`Step ${o.id} result`);if(i.state!=="applied"){let c=await o.prepareCompensation?.();Cn(t.compensationData,o.id,c,`Step ${o.id} compensation data`),r.add(o.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>r.has(l)),await $e(e.pmRoot,t);let d=await o.apply();s=An(d,`Step ${o.id} result`)}await ge(e,t,"step_applied",o.id),a.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>a.has(c)),Cn(t.results,o.id,s,`Step ${o.id} result`),await $e(e.pmRoot,t),await ge(e,t,"step_recorded",o.id)}return await ge(e,t,"committing"),t.status="committed",await $e(e.pmRoot,t),await ge(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Oe(t.results)}}catch(a){if(a instanceof In||t.status==="committed")throw a;try{await qr(e,t)}catch(r){throw new AggregateError([a,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw a}}async function As(e,t,n){try{return $s(await ys(Wr(e,t),"utf8"),t,n)}catch(a){if(a!==null&&typeof a=="object"&&"code"in a&&a.code==="ENOENT")return;throw a}}async function ge(e,t,n,a){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...a===void 0?{}:{stepId:a}})}async function Cs(e,t){let n=new Set,a=Oe();for(let r of t){let o=await r.inspect();o.state==="applied"&&(n.add(r.id),Cn(a,r.id,o.result,`Step ${r.id} result`))}e.results=a,e.completedStepIds=t.map(r=>r.id).filter(r=>n.has(r))}async function qr(e,t){t.status="compensating",await $e(e.pmRoot,t),await ge(e,t,"compensating");let n=new Set(t.completedStepIds),a=new Set(t.startedStepIds);for(let r of[...e.steps].reverse()){if(!a.has(r.id)&&!n.has(r.id))continue;let o;try{o=a.has(r.id)&&(await r.inspect()).state==="applied"}catch{o=a.has(r.id)}o&&(await ge(e,t,"step_compensating",r.id),await r.compensate(t.compensationData[r.id])),n.delete(r.id),a.delete(r.id),t.completedStepIds=e.steps.map(i=>i.id).filter(i=>n.has(i)),t.startedStepIds=e.steps.map(i=>i.id).filter(i=>a.has(i)),delete t.results[r.id],delete t.compensationData[r.id],await $e(e.pmRoot,t),await ge(e,t,"step_compensated",r.id)}t.status="compensated",await $e(e.pmRoot,t),await ge(e,t,"compensated")}async function Gr(e){let t=Mr(e.pmRoot,"Transaction pmRoot"),n=Lr(e.transactionId,"Transaction id"),a=Mr(e.author,"Transaction author"),r=Fr(e.lockTtlSeconds,bs,"Transaction lock TTL"),o=Fr(e.lockWaitMs,ks,"Transaction lock wait"),i=[...e.steps];if(i.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=i.map(l=>{let u=Lr(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:a,steps:i,lockTtlSeconds:r,lockWaitMs:o},d=await Q(t,ws,r,a,!1,!1,o);try{let l=await As(t,n,s),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Oe(l.results)};let m=await Ts(c,n,a,s,l);return await Is(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]="7d175791-016d-59b6-a44d-a70371f36751")}catch{}})();function _e(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Kr(e){let t=_e(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Yr(e,t){let n=On(e),a=_e(t,"migrationScope");return`auto-${Vr("sha256").update(JSON.stringify({scope:a,request:n})).digest("hex").slice(0,20)}`}function On(e){let t=e.kind==="rename-type"?{kind:e.kind,from:_e(e.from,"source"),to:_e(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:G(_e(e.from,"source")),to:G(_e(e.to,"target")),...e.type===void 0?{}:{type:_e(e.type,"type")}}:{kind:e.kind,from:G(_e(e.from,"source")),to:G(_e(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Rs(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Os(e,t,n){let a=Y(t.schema),r=Rs(n);return de(e,a.files[r],ne[r])}function Xr(e,t){return Ke.join(e,"transactions","schema",`${t}-plan.json`)}function Wt(e){return e.length===0?null:JSON.parse(e)}async function Ve(e){let t=await q(e);return{exists:t!==null,raw:t??""}}async function Qr(e,t){t.exists?await oe(e,t.raw):await Ne.rm(e,{force:!0})}function Ns(e,t,n){let a=me(e),r=a.definitions.findIndex(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),o=a.definitions.findIndex(i=>i.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return Ee(a);if(r<0)throw new TypeError(`Unknown custom type "${t.from}".`);a.definitions.push({...a.definitions[r],name:t.to})}else r>=0&&a.definitions.splice(r,1);return Ee(a)}function Ds(e,t,n){let a=ze(e),r=a.fields.findIndex(i=>i.key===t.from),o=a.fields.findIndex(i=>i.key===t.to);if(n==="stage"){if(o>=0)return Je(a);if(r<0)throw new TypeError(`Unknown custom field "${t.from}".`);let i=a.fields[r];a.fields.push({...i,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else r>=0&&a.fields.splice(r,1);return Je(a)}function Ps(e,t,n){let a=We(e),r=a.statuses.findIndex(i=>i.id===t.from),o=a.statuses.findIndex(i=>i.id===t.to);if(n==="stage"){if(o>=0)return qe(a);if(r<0)throw new TypeError(`Unknown custom status "${t.from}".`);a.statuses.push({...a.statuses[r],id:t.to})}else r>=0&&a.statuses.splice(r,1);return qe(a)}function js(e,t,n){return t.kind==="rename-type"?Ns(e,t,n):t.kind==="rename-field"?Ds(e,t,n):Ps(e,t,n)}function Te(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Nn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Ye(e){return Array.isArray(e)?e.map(t=>Nn(t)).filter(t=>t!==void 0):[]}function Ls(e,t){for(let n of Ye(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(a=>Te(a,t)));for(let n of Ye(e.type_workflows))n.type=Te(n.type,t)}function Ms(e,t){for(let a of Ye(e.definitions))a.default_status=Te(a.default_status,t);let n=Nn(e.workflow);if(n)for(let[a,r]of Object.entries(n))n[a]=Te(r,t);for(let a of Ye(e.type_workflows))Array.isArray(a.allowed_transitions)&&(a.allowed_transitions=a.allowed_transitions.map(r=>Array.isArray(r)?r.map(o=>Te(o,t)):r))}function Fs(e,t){for(let n of Ye(e.definitions)){for(let a of["required_create_fields","required_create_repeatables"])Array.isArray(n[a])&&(n[a]=n[a].map(r=>Te(r,t)));for(let a of["options","command_option_policies"])for(let r of Ye(n[a])){let o=a==="options"?"key":"option";r[o]=Te(r[o],t)}}}function Us(e,t){let n=Nn(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 a=t.kind==="rename-type"?"type":"status";n[a]=Te(n[a],t)}function Rn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let a=n;return t.kind==="rename-type"?Ls(a,t):t.kind==="rename-field"?Fs(a,t):Ms(a,t),Us(a,t),`${JSON.stringify(a,null,2)}
3
+ `}function Zr(e,t){if(t.kind==="rename-type"){let a=me(e).definitions;return{source:a.some(r=>r.name.trim().toLowerCase()===t.from.toLowerCase()),target:a.some(r=>r.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let a=ze(e).fields;return{source:a.some(r=>r.key===t.from),target:a.some(r=>r.key===t.to)}}let n=We(e).statuses;return{source:n.some(a=>a.id===t.from),target:n.some(a=>a.id===t.to)}}function zs(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 Js(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 eo(e,t){let n=On(t.request),a=t.migrationId===void 0?Yr(n,t.migrationScope??"plan"):Kr(t.migrationId),r=e.map(c=>Js(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),o=Vr("sha256").update(JSON.stringify({migrationId:a,request:n,items:r})).digest("hex"),i=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=r.filter(c=>!i.has(c.id));return Object.freeze({migration_id:a,request:n,fingerprint:o,affected_item_count:r.length,pending_item_count:s.length,skipped_completed_count:r.length-s.length,items:Object.freeze(s)})}async function Ws(e){let t=B(e.settings,M()),n=[...new Set(Object.values(t.type_to_folder))],a=await tr(e.pmRoot,n),r=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=a?await er({pmRoot:e.pmRoot,expectedSourceCursor:a.source_cursor,query:r}):null;return o?{items:o.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await he(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function qs(e,t){let n=await q(Xr(e,t));if(n===null)return null;try{let a=JSON.parse(n);if(a.schema_version!==1||a.plan.migration_id!==t||!Array.isArray(a.plan.items))throw new TypeError("invalid plan envelope");return a.plan}catch(a){throw new _(`Stored schema migration plan "${t}" is invalid: ${Ia(a)}`,y.GENERIC_FAILURE)}}async function Gs(e,t){let n=Xr(e,t.migration_id);await Ne.mkdir(Ke.dirname(n),{recursive:!0});let a={schema_version:1,plan:t,created_at:new Date().toISOString()};await oe(n,`${JSON.stringify(a,null,2)}
4
+ `)}function Hs(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Bs(e){let t=await ar(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new _(`Schema migration item "${e.id}" no longer exists.`,y.NOT_FOUND);return(await rr(t,{schema:e.settings.schema})).document.metadata}function Hr(e,t,n){let a=n==="forward"?t.from:t.to,r=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===r.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==a.toLowerCase())throw new TypeError(`Schema migration expected type "${a}" on item "${e.metadata.id}".`);return e.metadata.type=r,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===r.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==a.toLowerCase())throw new TypeError(`Schema migration expected status "${a}" on item "${e.metadata.id}".`);return e.metadata.status=r,["status"]}let o=e.metadata;if(Object.prototype.hasOwnProperty.call(o,r)&&!Object.prototype.hasOwnProperty.call(o,a))return[];if(!Object.prototype.hasOwnProperty.call(o,a)||Object.prototype.hasOwnProperty.call(o,r))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return o[r]=o[a],delete o[a],[a,r]}function Br(e){return{id:e.id,inspect:async()=>{let t=await Ve(e.filePath),n=Zr(t.raw,e.request),a=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:a?"applied":"pending",...a?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Ve(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ve(e.filePath);return await oe(e.filePath,js(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 Qr(e.filePath,{exists:t.exists,raw:t.raw})}}}function Vs(e){return{id:e.stepId,inspect:async()=>{let t=await Ve(e.filePath);return{state:Rn(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Ve(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ve(e.filePath);return await oe(e.filePath,Rn(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 Qr(e.filePath,{exists:t.exists,raw:t.raw})}}}function Ks(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await R(e.pmRoot),n=B(t,M()).type_to_folder,a=await Bs({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),r=zs(a,e.request).length===0;return{state:r?"applied":"pending",...r?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await R(e.pmRoot),n=B(t,M()).type_to_folder,a=await kn({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(r){return{changedFields:Hr(r,e.request,"forward")}}});return{item_id:e.id,changed_fields:a.changedFields}},compensate:async()=>{let t=await R(e.pmRoot),n=B(t,M()).type_to_folder;await kn({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(a){return{changedFields:Hr(a,e.request,"reverse")}}})}}}async function Ys(e){let t=await qs(e.pmRoot,e.migrationId);if(t){if(!Hs(t.request,e.request))throw new _(`Schema migration id "${e.migrationId}" already belongs to a different request.`,y.CONFLICT);return{plan:t,stored:!0}}let n=await Ws({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...eo(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Xs(e){let t=Zr(await q(e.schemaPath)??"",e.request);if(!t.source)throw new _(`Schema migration source "${e.request.from}" is not a custom definition.`,y.NOT_FOUND);if(t.target)throw new _(`Schema migration target "${e.request.to}" already exists.`,y.CONFLICT);await Gs(e.pmRoot,e.plan)}async function Qs(e){let t=Y(e.settings.schema),n=[...new Set([["types",ne.types],["fields",ne.fields],["workflows",ne.workflows]].map(([r,o])=>de(e.pmRoot,t.files[r],o)).filter(r=>r!==e.schemaPath))];try{let r=Ke.join(e.pmRoot,"templates"),o=await Ne.readdir(r,{withFileTypes:!0});n.push(...o.filter(i=>i.isFile()&&i.name.toLowerCase().endsWith(".json")).map(i=>Ke.join(r,i.name)))}catch(r){if(typeof r!="object"||r===null||!("code"in r)||r.code!=="ENOENT")throw r}n.sort((r,o)=>r.localeCompare(o));let a=[];for(let r of n){let o=await q(r);o!==null&&Rn(o,e.request)!==o&&a.push({filePath:r,beforeRaw:o})}return{paths:n,snapshots:a}}async function Zs(e){for(let t of e.snapshots){let n=await Ne.readFile(t.filePath,"utf8"),a=Ke.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await bn({pmRoot:e.pmRoot,author:e.author,documentPath:a,before:Wt(t.beforeRaw),after:Wt(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${a}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function ec(e,t,n){let a=On(e),r=P(process.cwd(),n.path);if(!await E(te(r)))throw new _(`Tracker is not initialized at ${r}. Run pm init first.`,y.NOT_FOUND);let o=t.migrationId===void 0?Yr(a,await Ne.realpath(r)):Kr(t.migrationId),i=await R(r),s=X(t.author,i.author_default),c=await Ys({pmRoot:r,settings:i,migrationId:o,request:a}),d=c.plan;if(t.dryRun===!0)return{...d,action:a.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Os(r,i,a),u=await Ne.readFile(l,"utf8");c.stored||await Xs({pmRoot:r,schemaPath:l,request:a,plan:d});let m=await Qs({pmRoot:r,schemaPath:l,settings:i,request:a}),h=[Br({id:"stage-schema",filePath:l,request:a,phase:"stage"}),...m.paths.map((w,v)=>Vs({filePath:w,request:a,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>Ks({pmRoot:r,id:w.id,request:a,author:s,force:t.force===!0})),Br({id:"retire-source",filePath:l,request:a,phase:"retire"})],f=await Gr({pmRoot:r,transactionId:`schema-${o}`,author:s,steps:h,lockTtlSeconds:Math.max(i.locks.ttl_seconds,300),lockWaitMs:i.locks.wait_ms}),p=await Ne.readFile(l,"utf8"),{historyPath:g}=await bn({pmRoot:r,author:s,documentPath:Ke.relative(r,l).replaceAll("\\","/"),before:Wt(u),after:Wt(p),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${a.kind}: ${a.from} -> ${a.to}; affected=${d.affected_item_count}`,lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms});return await Zs({pmRoot:r,author:s,settings:i,request:a,plan:d,snapshots:m.snapshots}),{...d,action:a.kind,applied:!0,recovered:f.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:g}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a035e10-b8fe-52cd-a9c7-0762dd0ab160")}catch{}})();var qt="schema-types",to="schema-statuses",no="schema-fields";function Ie(e){return Ft({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 Xf(e,t,n){let a=P(process.cwd(),n.path);await ye(a);let r;try{r=gn({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(h){throw new _(h instanceof Error?h.message:String(h),y.USAGE)}let o=await R(a),i=Y(o.schema),s=de(a,i.files.types,ne.types),c=[],d=X(t.author,o.author_default),l=fe(o),u=await Q(a,qt,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms),m;try{let h=await q(s),f;try{f=me(h)}catch(p){throw new _(p instanceof Error?p.message:String(p),y.GENERIC_FAILURE)}try{Da(r,f);let p=new Map,g=B(o,M());for(let[w,v]of Object.entries(g.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!p.has(x)&&p.set(x,w)}Pa(r,f,p)}catch(p){throw new _(p instanceof Error?p.message:String(p),y.USAGE)}m=Nt(f,r),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await Ie({pmRoot:a,filePath:s,raw:Ee(m.file),op:"schema:add-type",author:d,settings:o}),await ct(a,[m.definition],c,"schema:add-type-folder"),c.push(...await U({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await ao(a,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Ae(c),generated_at:A()}}async function ye(e){if(!await E(te(e)))throw new _(`Tracker is not initialized at ${e}. Run pm init first.`,y.NOT_FOUND)}async function ao(e,t){try{let n=await Tr(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 Ae(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function ac(e,t,n,a){let r=B(t,M()),o=a.trim().toLowerCase();return(await he(e,t.item_format,r.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===o).length}async function rc(e,t,n,a){let r=B(t,M()),o=it(n),i=G(a);return(await he(e,t.item_format,r.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(o.alias_to_id.get(G(d))??G(d))===i}).length}async function oc(e,t,n,a,r){if(r.length===0||yn.has(r))return;let o=await rc(t,n,a,r);o>0&&e.push(`items_using_status:${o}`);let i=ic(a.workflow,r);i.length>0&&e.push(`status_referenced_by_workflow:${i.join(",")}`)}function ic(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(([,a])=>a!==void 0&&G(a)===t).map(([a])=>a)}async function Qf(e,t,n){let a=P(process.cwd(),n.path);await ye(a);let r=await R(a),o=Y(r.schema),i=de(a,o.files.types,ne.types),s=[],c=X(t.author,r.author_default),d=fe(r),l=await Q(a,qt,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let m=await q(i),h;try{h=me(m)}catch(f){throw new _(f instanceof Error?f.message:String(f),y.GENERIC_FAILURE)}try{u=ja(h,e)}catch(f){throw new _(f instanceof Error?f.message:String(f),y.USAGE)}if(u.removed){let f=(u.definition?.name??e??"").trim();if(f.length>0){let p=await ac(a,r,o,f);p>0&&s.push(`items_using_type:${p}`)}await Ie({pmRoot:a,filePath:i,raw:Ee(u.file),op:"schema:remove-type",author:c,settings:r}),s.push(...await U({path:i,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await ao(a,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:i,definitions:u.file.definitions.length},warnings:Ae(s),generated_at:A()}}function Dn(e,t){return de(e,t.files.statuses,ne.statuses)}function Gt(e,t){return de(e,t.files.fields,ne.fields)}function ro(e,t){return de(e,t.files.types,ne.types)}async function ct(e,t,n,a){for(let r of t){let o=$a(r.folder??Ea(r.name)),i=tc.join(e,o);await E(i)||(await nc(i,{recursive:!0}),n.push(...await U({path:i,scope:"project",op:a})))}}function Pn(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 sc(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 cc(e){let t=new Map;for(let n of e){let a=G(n.id);if(a.length!==0){t.set(a,a);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let o=G(r);o.length>0&&!t.has(o)&&t.set(o,a)}}}return t}async function Zf(e,t,n){let a=P(process.cwd(),n.path);await ye(a);let r;try{r=Ja({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(p){throw new _(p instanceof Error?p.message:String(p),y.USAGE)}let o=await R(a),i=Y(o.schema),s=Dn(a,i),c=it(i);try{wn(r,c.alias_to_id)}catch(p){throw new _(p instanceof Error?p.message:String(p),y.USAGE)}let d=sc(c.by_id.get(r.id)),l=[],u=X(t.author,o.author_default),m=fe(o),h=await Q(a,to,o.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,o.locks.wait_ms),f;try{let p=await q(s),g;try{g=We(p)}catch(v){throw new _(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let w=cc(g.statuses);try{wn(r,w)}catch(v){throw new _(v instanceof Error?v.message:String(v),y.USAGE)}f=Wa(g,r,d),await Ie({pmRoot:a,filePath:s,raw:qe(f.file),op:"schema:add-status",author:u,settings:o}),l.push(...await U({path:s,scope:"project",op:"schema:add-status"}))}finally{await h()}return{action:"add-status",registered:!0,replaced:f.replaced,status:f.definition,file:{path:s,statuses:f.file.statuses.length},warnings:Ae(l),generated_at:A()}}async function eh(e,t,n){let a=P(process.cwd(),n.path);await ye(a);let r=await R(a),o=Y(r.schema),i=Dn(a,o),s=[],c=X(t.author,r.author_default),d=fe(r),l=await Q(a,to,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let m=await q(i),h;try{h=We(m)}catch(f){throw new _(f instanceof Error?f.message:String(f),y.GENERIC_FAILURE)}try{u=qa(h,e)}catch(f){throw new _(f instanceof Error?f.message:String(f),y.USAGE)}if(u.removed){let f=G(u.definition?.id??e);await oc(s,a,r,o,f),await Ie({pmRoot:a,filePath:i,raw:qe(u.file),op:"schema:remove-status",author:c,settings:r}),s.push(...await U({path:i,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:i,statuses:u.file.statuses.length},warnings:Ae(s),generated_at:A()}}function oo(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 dc(e,t,n){return{...oo(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 io(e){return{id:e.id,source:yn.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 so(e,t,n){let a=e.toLowerCase();return n.has(a)?"extension":t.has(a)?"custom":"builtin"}function lc(){let e=new Map,t=M();for(let n of t?.item_types??[]){let a=n.types;if(Array.isArray(a))for(let r of a){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r.name;typeof o=="string"&&o.trim().length>0&&e.set(o.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function uc(e){let t=it(e),n=[],a=[];for(let r of t.definitions){let o=io(r);o.source==="builtin"?n.push(o):a.push(o)}return{builtin:n,custom:a}}async function dt(e){let t=P(process.cwd(),e.path);await ye(t);let n=await R(t),a=Y(n.schema),r=de(t,a.files.types,ne.types),o=Dn(t,a),i=B(n,M()),s=lc(),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:r,statusesPath:o,byType:i.by_type,customNames:c,extensionProvenance:s,schema:a}}async function th(e){let t=await dt(e),n=[],a=[],r=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=so(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=oo(s);c==="extension"?r.push(d):c==="custom"?a.push(d):n.push(d)}let o=uc(t.schema),i=Dt(t.schema).definitions.map(Pn);return{action:"list",builtin:n,custom:a,extension:r,counts:{builtin:n.length,custom:a.length,extension:r.length,total:n.length+a.length+r.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:i,counts:{total:i.length}},file:{path:t.typesPath},generated_at:A()}}async function nh(e,t){let n=(e??"").trim();if(n.length===0)throw new _("Type name must not be empty.",y.USAGE);let a=await dt(t),r=Object.values(a.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(i=>i.toLowerCase()===n.toLowerCase()));if(!r)throw new _(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Ot(n)}" to register it.`,y.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:dc(r,so(r.name,a.customNames,new Set(a.extensionProvenance.keys())),a.extensionProvenance.get(r.name.toLowerCase())),file:{path:a.typesPath},generated_at:A()}}async function ah(e,t){let n=G(e);if(n.length===0)throw new _("Status id must not be empty.",y.USAGE);let a=await dt(t),r=it(a.schema),o=r.alias_to_id.get(n)??n,i=r.by_id.get(o);if(!i)throw new _(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Ot(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:io(i),file:{path:a.statusesPath},generated_at:A()}}async function rh(e,t,n){let a=P(process.cwd(),n.path);await ye(a);let r;try{r=Fa({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(f){throw new _(f instanceof Error?f.message:String(f),y.USAGE)}let o=await R(a),i=Y(o.schema),s=Gt(a,i),c=[],d=Pt(r.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=X(t.author,o.author_default),u=fe(o),m=await Q(a,no,o.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,o.locks.wait_ms),h;try{let f=await q(s),p;try{p=ze(f)}catch(g){throw new _(g instanceof Error?g.message:String(g),y.GENERIC_FAILURE)}h=Ua(p,r),await Ie({pmRoot:a,filePath:s,raw:Je(h.file),op:"schema:add-field",author:l,settings:o}),c.push(...await U({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:h.replaced,field:h.definition,file:{path:s,fields:h.file.fields.length},warnings:Ae(c),generated_at:A()}}async function mc(e,t,n,a){let r=B(t,M());return(await he(e,t.item_format,r.type_to_folder,[],n)).filter(i=>{let s=i[a];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function oh(e,t,n){let a=P(process.cwd(),n.path);await ye(a);let r=await R(a),o=Y(r.schema),i=Gt(a,o),s=[],c=X(t.author,r.author_default),d=fe(r),l=await Q(a,no,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let m=await q(i),h;try{h=ze(m)}catch(f){throw new _(f instanceof Error?f.message:String(f),y.GENERIC_FAILURE)}try{u=za(h,e)}catch(f){throw new _(f instanceof Error?f.message:String(f),y.USAGE)}if(u.removed){let f=G(u.definition?.key??e),p=G(u.definition?.metadata_key??u.definition?.front_matter_key??f);if(p.length>0){let g=await mc(a,r,o,p);g>0&&s.push(`items_using_field:${g}`)}await Ie({pmRoot:a,filePath:i,raw:Je(u.file),op:"schema:remove-field",author:c,settings:r}),s.push(...await U({path:i,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:i,fields:u.file.fields.length},warnings:Ae(s),generated_at:A()}}async function ih(e){let t=await dt(e),n=Dt(t.schema).definitions.map(Pn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Gt(t.pmRoot,t.schema)},generated_at:A()}}async function sh(e,t){let n=G(e);if(n.length===0)throw new _("Field key must not be empty.",y.USAGE);let a=await dt(t),r=Dt(a.schema).by_key.get(n);if(!r)throw new _(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Ot(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Pn(r),file:{path:Gt(a.pmRoot,a.schema)},generated_at:A()}}async function ch(e,t,n){let a=P(process.cwd(),n.path);await ye(a);let r;try{let p=Ma(e);if(p===void 0)throw new Error(`Type preset name is required. Allowed: ${La.join(", ")}.`);r=p}catch(p){throw new _(p instanceof Error?p.message:String(p),y.USAGE)}let o=await R(a),i=Y(o.schema),s=ro(a,i),c=[],d=X(t.author,o.author_default),l=fe(o),u=[],m=[],h,f=await Q(a,qt,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms);try{let p=await q(s),g;try{g=me(p)}catch(v){throw new _(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let w=g;for(let v of _n(r)){let x=Nt(w,v);w=x.file,(x.replaced?m:u).push(x.definition.name)}h=w.definitions.length,await Ie({pmRoot:a,filePath:s,raw:Ee(w),op:"schema:apply-preset",author:d,settings:o}),await ct(a,_n(r),c,"schema:apply-preset-folder"),c.push(...await U({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await f()}return{action:"apply-preset",preset:r,registered:u,replaced:m,file:{path:s,definitions:h},warnings:Ae(c),generated_at:A()}}function pc(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new _("--min-count must be a positive integer (>= 1).",y.USAGE);return e}async function dh(e,t){let n=P(process.cwd(),t.path);await ye(n);let a=await R(n),r=Y(a.schema),o=ro(n,r),i=pc(e.minCount),s=B(a,M()),d=(await he(n,a.item_format,s.type_to_folder,[],r)).map(x=>typeof x.title=="string"?x.title:""),l=jr(d,{minCount:i}),u=[],m=[],h=[],f=[],p;if(!e.apply){let x;try{x=me(await q(o))}catch(I){throw new _(I instanceof Error?I.message:String(I),y.GENERIC_FAILURE)}return p=x.definitions.length,{action:"infer-types",applied:!1,min_count:i,candidates:l,registered:m,replaced:h,skipped:f,file:{path:o,definitions:p},warnings:u,generated_at:A()}}let g=X(e.author,a.author_default),w=fe(a),v=await Q(n,qt,a.locks.ttl_seconds,g,!!e.force,w.force_required_for_stale_lock,a.locks.wait_ms);try{let x=await q(o),I;try{I=me(x)}catch(T){throw new _(T instanceof Error?T.message:String(T),y.GENERIC_FAILURE)}let b=I;for(let T of l){if(T.shadows_builtin){f.push({name:T.name,reason:"shadows_builtin"});continue}let J;try{J=gn({name:T.name})}catch{f.push({name:T.name,reason:"invalid_type_token"});continue}let W=Nt(b,J);b=W.file,(W.replaced?h:m).push(W.definition.name)}p=b.definitions.length,await Ie({pmRoot:n,filePath:o,raw:Ee(b),op:"schema:infer-types",author:g,settings:a}),await ct(n,b.definitions.filter(T=>m.includes(T.name)||h.includes(T.name)),u,"schema:infer-types-folder"),u.push(...await U({path:o,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:i,candidates:l,registered:m,replaced:h,skipped:f,file:{path:o,definitions:p},warnings:Ae(u),generated_at:A()}}import co from"node:fs/promises";import jn 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 Z(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function k(e){return e.trim().toLowerCase()}function Ht(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let a=t.length;for(;a>n&&t[a-1]==="-";)a-=1;let r=t.slice(n,a);if(r.length===0)throw new _("Extension manifest name must resolve to a non-empty directory name.",y.USAGE);if(r==="."||r==="..")throw new _('Extension manifest name must not resolve to "." or "..".',y.USAGE);return r}function Ln(e){return Ra(e)}async function fc(e){try{let t=JSON.parse(await co.readFile(jn.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(a=>typeof t.scripts?.[a]=="string")}}catch{return{has_build_script:!1}}}async function hc(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new _(`Extension entry file is missing at "${t}".`,y.USAGE);let a=await fc(n.source_root),r=a.package_name?`pm install npm:${a.package_name}`:void 0,o=n.source_input??n.source_root;return new _(`Extension entry "${e.entry}" is absent from GitHub source "${o}". pm install copies GitHub repositories without running package scripts${a.has_build_script?", and this package declares a build or publish script":""}. ${r?`Try "${r}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,y.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:r?[r,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:r?[`Retry with ${r}.`,"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],...r?{next_best_command:r}:{}}})}async function Xe(e,t={}){let n=jn.join(e,"manifest.json");if(!await E(n))throw new _(`Extension manifest is missing at "${n}".`,y.USAGE);let a;try{a=JSON.parse(await co.readFile(n,"utf8"))}catch(i){throw new _(`Failed to parse extension manifest at "${n}": ${gc(i)}`,y.USAGE)}let r=Ln(a);if(!r)throw new _(`Extension manifest at "${n}" is invalid.`,y.USAGE);let o=jn.resolve(e,r.entry);if(!ie(e,o))throw new _(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,y.USAGE);if(!await E(o))throw await hc(r,o,t);if(!await Oa(e,o))throw new _(`Extension entry "${r.entry}" resolves outside extension directory after symlink resolution.`,y.USAGE);return{directory:e,manifest_path:n,entry_path:o,manifest:r}}function gc(e){return e instanceof Error?e.message:String(e)}import Mn from"node:fs/promises";import _c 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]="5d60cd29-09fb-515c-acaa-b5a2b136d8ab")}catch{}})();var yc=".managed-extensions.json",Bt=1;function lt(e){return _c.join(e,yc)}function wc(){return{version:Bt,updated_at:A(),entries:[]}}function ut(e){return[...e].sort((t,n)=>{let a=t.scope.localeCompare(n.scope);if(a!==0)return a;let r=t.name.localeCompare(n.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function lo(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function ee(e){return typeof e=="string"?e:void 0}function vc(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 bc(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:ee(t.name),package:ee(t.package),version:ee(t.version),repository:ee(t.repository),owner:ee(t.owner),repo:ee(t.repo),ref:ee(t.ref),subpath:ee(t.subpath),commit:ee(t.commit)}}function kc(e){if(typeof e!="object"||e===null)return null;let t=e;if(!vc(t))return null;let n=bc(t.source);if(!n)return null;let a=Aa(t.contributions);return a===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Z(t.capabilities),contributions:a,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:ee(t.last_update_check_at),last_update_remote_commit:ee(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:ee(t.update_error)}}function xc(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Bt||!Array.isArray(t.entries))return null;let n=[];for(let a of t.entries){let r=kc(a);r&&n.push(r)}return{version:Bt,updated_at:ee(t.updated_at)??A(),entries:ut(n)}}async function V(e){let t=lt(e),n=wc();try{let a=await Mn.readFile(t,"utf8"),r=JSON.parse(a),o=xc(r);if(!o)throw new _(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE);return{path:t,state:o,warnings:[]}}catch(a){if(a instanceof _)throw a;if(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT")return{path:t,state:n,warnings:[]};throw new _(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE)}}async function De(e,t){let n=lt(e),a={version:Bt,updated_at:A(),entries:ut(t.entries)};await Mn.mkdir(e,{recursive:!0}),await Mn.writeFile(n,`${JSON.stringify(a,null,2)}
5
+ `,"utf8")}function mt(e,t){let n=e.entries.filter(a=>k(a.name)!==k(t.name)&&k(a.directory)!==k(t.directory));return n.push(t),{...e,updated_at:A(),entries:ut(n)}}async function uo(e,t,n,a){let r=t.entries.find(i=>k(i.name)===k(n));if(!r)return t;let o=mt(t,{...r,contributions:a});return await De(e,o),o}import{execFile as Dc}from"node:child_process";import O from"node:fs/promises";import Wn from"node:os";import $ from"node:path";import{fileURLToPath as Pc}from"node:url";import{promisify as jc}from"node:util";import Lc from"npm-package-arg";import{extract as Mc,list as Fc}from"tar";import Sc from"node:fs/promises";import re from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="259656b0-09b7-52c5-8f54-52ac29eec607")}catch{}})();var Ec="PM_CLI_PACKAGE_ROOT",mo={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},$c=new Set(["*","all"]);function Fn(){let e=[],t=process.env[Ec];return typeof t=="string"&&t.trim().length>0&&e.push(re.resolve(t.trim())),e.push(xe(import.meta.url,["../../.."])),[...new Set(e)]}async function pt(e){let t=e.trim().toLowerCase(),n=await fo(t);if(n)return n;let a=mo[t];if(!a)return null;for(let r of Fn()){let o=re.join(r,".agents","pm","extensions",a.legacy_extension_directory);if(await E(re.join(o,"manifest.json")))return o}return null}function po(e){return $c.has(e.trim().toLowerCase())}function Tc(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Ic(e,t){let n=await Sc.readdir(e,{withFileTypes:!0});for(let a of n){if(!a.isDirectory()||!a.name.startsWith("pm-"))continue;let r=re.join(e,a.name);if(!await E(re.join(r,"package.json")))continue;let o=await Ct(r),i=o.aliases&&o.aliases.length>0?o.aliases:[Tc(a.name)];for(let s of i){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:a.name,package_root:r,package_name:o.package_name??null})}}}async function Un(){let e=new Map;for(let t of Fn()){let n=re.join(t,"packages");await E(n)&&await Ic(n,e)}for(let[t,n]of Object.entries(mo))if(!e.has(t))for(let a of Fn()){let r=re.join(a,"packages",n.package_directory);if(await E(re.join(r,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:r,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Vt(){return(await Un()).map(e=>e.alias)}async function fo(e){let t=e.trim().toLowerCase();return(await Un()).find(a=>a.alias===t||a.package_directory.toLowerCase()===t||a.package_name?.toLowerCase()===t)?.package_root??null}async function ho(e){let t=await fo(e);return t?(await Ct(t)).package_name??null:null}async function go(e){let t=await pt(e);if(!t)return null;try{let n=await Rt(t);return n.length!==1?null:(await Xe(n[0])).manifest.name}catch{return null}}function Ac(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 Cc(e,t,n,a,r,o){let i=a==="global"?"--global":"--project",s=Object.fromEntries(hn.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=>r.has(c))||o.has(re.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${i}`,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:Ac(e),media:e.catalog?.media}}}async function _o(e,t,n={}){let a=Ue(P(process.cwd(),t.path),process.cwd()),r=e==="global"?a.global:a.project,o=await V(r),i=new Set(o.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>re.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 Un()){let h=re.resolve(m.package_root),f=d.get(h)??[];f.push(m),d.set(h,f)}for(let m of d.values()){let h=m[0],f=m.map(g=>g.alias).sort((g,w)=>g.localeCompare(w)),p=await Ct(h.package_root);c.push(Cc(p,h,f,e,s,i))}let l=Oc(n.fields),u=l?c.map(m=>Nc(m,l)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:hn.filter(m=>m!=="extensions"),packages:u}}var Rc=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 Oc(e){if(e===void 0)return;let t=br(e);if(t.length===0)throw new _("Package catalog --fields requires a comma-separated list of field names",y.USAGE);let n=t.filter(a=>!Rc.has(a));if(n.length>0)throw new _(`Unknown package catalog --fields value(s): ${n.join(", ")}`,y.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function Nc(e,t){let n={};for(let a of t)a==="category"?n[a]=e.catalog?.category??null:a==="display_name"?n[a]=e.catalog?.display_name??null:n[a]=e[a]??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]="8994c8e2-8e3a-5e00-a3ca-7bd553c045d7")}catch{}})();var qn=jc(Dc),Yt="@unbrained/pm-cli",Uc={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},zn;async function yo(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let a=$.resolve(t);for(;;){let r=$.join(a,"node_modules",...n.split("/")),o=$.join(r,"package.json");if(await E(o))try{let s=JSON.parse(await O.readFile(o,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:r}}catch{return null}let i=$.dirname(a);if(i===a)return null;a=i}}function Jn(e,t,n){let a=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(a.length<2)return null;let r=a[0],o=a[1].replace(/\.git$/i,"");if(r.length===0||o.length===0)return null;let i=a.slice(2),s,c;return i[0]==="tree"&&i.length>=2?(s=i[1],c=i.slice(2).join("/")):i.length>0&&(c=i.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:r,repo:o,repository:`https://github.com/${r}/${o}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function zc(e,t,n){let a=e.slice(4).trim();if(a.length===0)throw new _('npm package source must include a package spec after "npm:".',y.USAGE);if(t)throw new _('Options "--gh/--github" cannot be combined with npm: package sources.',y.USAGE);if(n)throw new _('Option "--ref" cannot be combined with npm: package sources.',y.USAGE);return{kind:"npm",input:e,spec:a}}function Xt(e,t={}){let n=e.trim();if(n.length===0)throw new _("Extension source is required for --install.",y.USAGE);let a=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return zc(n,t.forceGithub===!0,a);let r=(()=>{try{let i=new URL(n);if(i.hostname!=="github.com")return null;let s=i.pathname.replace(/^\/+/,"");return Jn(s,n,a)}catch{return null}})();if(r)return r;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let i=Jn(o,n,a);if(!i)throw new _(`Invalid GitHub source "${n}".`,y.USAGE);return i}if(t.forceGithub){let i=Jn(n,n,a);if(!i)throw new _(`Invalid GitHub shorthand "${n}".`,y.USAGE);return i}if(/^https?:\/\//i.test(n))throw new _(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,y.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function Kt(e,t=qn,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(a){let r=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr):"",o=r.trim().length>0?r.trim():a instanceof Error?a.message:String(a);throw new _(`Git command failed: git ${e.join(" ")}
6
+ ${o}`,y.GENERIC_FAILURE)}}function Jc(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Wc(e=process.platform){return e==="win32"}async function wo(e,t,n=qn,a=process.platform){let r=Jc(a);try{return((await n(r,e,{cwd:t,encoding:"utf8",shell:Wc(a)})).stdout??"").trim()}catch(o){let i=typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr):"",s=i.trim().length>0?i.trim():o instanceof Error?o.message:String(o);throw new _(`npm command failed: ${r} ${e.join(" ")}
7
+ ${s}`,y.GENERIC_FAILURE)}}function qc(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 Gc(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 Hc(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return Gc(e)||n.includes("not found")}function Bc(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Vc(e){let t=qc(e),n=Bc(t),a=t.replace(/^.*\//,""),r=n?`github.com/unbraind/${a}`:void 0,o=r?`pm install --project ${r}`: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}`],...r&&o?{fallback_candidates:[{source:r,command:o,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:o}:{}}}}}function Kc(e,t){if(!Hc(t))return null;let n=Vc(e);return new _(n.message,y.NOT_FOUND,n.context)}async function vo(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await E(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=Pc(t);return await E(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await E(t))return t}return null}async function Yc(e){let t=await vo(e);if(t)return t;let n=Xc(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Xc(e,t=process.cwd()){let n="@file:",a=e.lastIndexOf(n);if(a<=0)return e;let r=e.slice(0,a),o=e.slice(a+n.length);if(r.trim().length===0||o.trim().length===0||o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${r}@${$.resolve(t,o)}`;let i;try{i=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(i)?i.slice(1):i;return`${r}@${s}`}function Qc(e,t){try{let a=JSON.parse(e),r=Array.isArray(a)?a[0]:void 0;if(r&&typeof r.filename=="string"&&r.filename.trim().length>0)return{tarball:$.resolve(t,r.filename),package:typeof r.name=="string"?r.name:void 0,version:typeof r.version=="string"?r.version:void 0}}catch{}let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0).at(-1);if(!n)throw new _("npm pack did not report a tarball filename.",y.GENERIC_FAILURE);return{tarball:$.resolve(t,n)}}async function Zc(e){return ed(e,wo)}async function ed(e,t){let n=await vo(e.spec);if(n){if((await O.stat(n)).isFile()&&bo(n))return ko(n);let s=$.join(n,"package.json"),c=await E(s)?JSON.parse(await O.readFile(s,"utf8")):{};return{directory:await ft(n,e.input),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{}}}let a=await O.mkdtemp($.join(Wn.tmpdir(),"pm-npm-package-source-")),r=$.join(a,"pack"),o=$.join(a,"extract");await O.mkdir(r,{recursive:!0}),await O.mkdir(o,{recursive:!0});try{let i=await Yc(e.spec),s=await t(["pack",i,"--json","--pack-destination",r]),c=Qc(s,r);await qn("tar",["-xzf",c.tarball,"-C",o],{encoding:"utf8"});let d=$.join(o,"package");return await xo(d),{directory:await ft(d,e.input),package:c.package,version:c.version,cleanup:async()=>{await O.rm(a,{recursive:!0,force:!0})}}}catch(i){await O.rm(a,{recursive:!0,force:!0});let s=Kc(e.spec,i);throw s||i}}function bo(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function we(e){throw new _(e,y.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function td(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&we(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let a=e.path,r=a.split("/");(a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||r.some(o=>o===".."))&&we(`Local package archive contains an escaping path: "${a}".`),r[0]!=="package"&&we(`Local package archive entry "${a}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&we(`Local package archive link "${a}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&we(`Local package archive entry "${a}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&we(`Local package archive entry "${a}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&we(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),a==="package/package.json"&&(n.packageJsonEntries+=1)}async function ko(e,t=Uc){(await O.stat(e)).size>t.maxArchiveBytes&&we(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let a=await O.mkdtemp($.join(Wn.tmpdir(),"pm-local-package-archive-")),r=$.join(a,"extract");await O.mkdir(r,{recursive:!0});let o={entries:0,expandedBytes:0,packageJsonEntries:0},i;try{if(await Fc({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(i===void 0)try{td(l,t,o)}catch(u){i=u}}}),i!==void 0)throw i;o.packageJsonEntries!==1&&we(`Local package archive must contain exactly one package/package.json entry; found ${o.packageJsonEntries}.`),await Mc({file:e,cwd:r,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=$.join(r,"package"),c=$.join(s,"package.json"),d=JSON.parse(await O.readFile(c,"utf8"));return await xo(s),{directory:await ft(s,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await O.rm(a,{recursive:!0,force:!0})}}}catch(s){throw await O.rm(a,{recursive:!0,force:!0}),s}}async function xo(e,t=wo){let n=$.join(e,"package.json");if(!await E(n))return;let a;try{a=JSON.parse(await O.readFile(n,"utf8"))}catch{return}if(typeof a!="object"||a===null)return;let r=a,o=sd(r),i=nd(r);if(o.length===0&&!i)return;let s={...a};delete s.devDependencies;let c={...s};ad(c),await O.writeFile(n,`${JSON.stringify(c,null,2)}
8
+ `,"utf8");try{await Promise.all([O.rm($.join(e,"package-lock.json"),{force:!0}),O.rm($.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),i&&await rd(e)}finally{await O.writeFile(n,`${JSON.stringify(s,null,2)}
9
+ `,"utf8")}}function nd(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Yt in t)return!0;return!1}function ad(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let a={...n};delete a[Yt],Object.keys(a).length===0?delete e[t]:e[t]=a}}async function rd(e){let t=xe(import.meta.url,["../../.."]),[n,a]=Yt.split("/"),r=$.join(e,"node_modules",n),o=$.join(r,a);await O.mkdir(r,{recursive:!0}),await O.rm(o,{recursive:!0,force:!0}),await O.symlink(t,o,od(process.platform))}function od(e){return e==="win32"?"junction":"dir"}function id(e,t){if(e.startsWith("-"))throw new _(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,y.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(a=>{let r=a.charCodeAt(0);return r<=31||r===127||"&|;()`\"'".includes(a)}))throw new _(`Extension runtime dependency "${e}" has an unsafe version specifier.`,y.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Lc.resolve(e,t)}catch{throw new _(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,y.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function sd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[a,r]of Object.entries(n)){if(a===Yt||typeof r!="string"||r.trim().length===0||t.has(a))continue;let o=r.trim();t.set(a,id(a,o))}return[...t.values()]}async function ft(e,t){let n=await Rt(e);if(n.length===1)return n[0];if(n.length>1){let a=n.map(r=>$.relative(e,r).replaceAll($.sep,"/")).sort((r,o)=>r.localeCompare(o));throw new _(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${a.join(", ")}`,y.USAGE)}throw new _(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,y.USAGE)}async function cd(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push($.posix.join(".agents/pm/extensions",t.subpath)),n.push($.posix.join(".custom/pm-extensions",t.subpath)),n.push($.posix.join(".custom/pm-extension",t.subpath)));for(let r of n){let o=$.resolve(e,r);if(ie(e,o)&&await E($.join(o,"manifest.json")))return{directory:o,resolved_subpath:r}}if(await E($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let a=await ft(e,t.input);return{directory:a,resolved_subpath:$.relative(e,a).replaceAll($.sep,"/")}}function dd(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 ld(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!dd(n))return new _(t,y.NOT_FOUND);let a=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,i=typeof o=="string"&&o.trim().length>0?$.resolve(o.trim()):"";zn?.key!==i&&(zn={key:i,aliases:await Vt()}),a=zn.aliases}catch{}let r=[`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): ${a.join(", ")}`];return new _(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,y.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:r,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function So(e){if(e.kind==="local"){let a;try{a=await O.stat(e.absolute_path)}catch{throw await ld(e)}if(a.isFile()&&bo(e.absolute_path)){let o=await ko(e.absolute_path);return{source:e,directory:o.directory,source_root:$.dirname(o.directory),resolved_subpath:$.relative($.dirname(o.directory),o.directory).replaceAll($.sep,"/"),npm_package:o.package,npm_version:o.version,cleanup:o.cleanup}}if(!a.isDirectory())throw new _(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,y.USAGE);let r=await ft(e.absolute_path,e.input);return{source:e,directory:r,source_root:e.absolute_path}}if(e.kind==="npm"){let a=await Zc(e);return{source:e,directory:a.directory,source_root:$.dirname(a.directory),cleanup:a.cleanup,resolved_subpath:$.relative($.dirname(a.directory),a.directory).replaceAll($.sep,"/"),npm_package:a.package,npm_version:a.version}}let t=await O.mkdtemp($.join(Wn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Kt(n);let a=await Kt(["-C",t,"rev-parse","HEAD"]),r=await cd(t,e);return{source:e,directory:r.directory,source_root:t,resolved_subpath:r.resolved_subpath,commit:a,cleanup:async()=>{await O.rm(t,{recursive:!0,force:!0})}}}catch(a){throw await O.rm(t,{recursive:!0,force:!0}),a}}async function Eo(e,t){if(!await E(e)||!await E(t))return!1;let[n,a]=await Promise.all([O.realpath(e),O.realpath(t)]);return n===a}import ht from"node:fs/promises";import gt 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]="30dfc6e4-27c5-56c0-981b-94e85b780f1f")}catch{}})();var Gn=1,Pe="2026.6.24",ud=">=22.18.0",md={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},$o=new Set([...Ga.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Va).map(e=>e.toLowerCase()),"scaffold"]),pd="^6.0.0",fd="^22.0.0",Ao=["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."," }"," }","}",""],le=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function To(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Co(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 Ro(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 hd={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Io=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Oo={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"]},gd={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"]'},_d={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."},yd={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."},No="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",wd={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."]},vd={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."]},bd={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`."]},kd={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 Do(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 Po(e,t){return e==="schema"?bd[t]:e==="profile"?kd[t]:vd[t]}function xd(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(),a=0;for(;t[a]?.toLowerCase()==="starter";)a+=1;let r=t[a]?.toLowerCase(),o=a>0&&(a===t.length||r!==void 0&&$o.has(r));return`${($o.has(n)||o?["starter",...t]:t).join(" ")} ping`}function jo(e){let t=e,n=`${e}s`,a=e.replace(/-/g,""),r=a===t?[]:[a],o=`${e.replace(/-/g,"_")}_owner`,i="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(r)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(i)},`,' 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(i)}],`,` [${JSON.stringify(i)}, "in_progress"],`,` [${JSON.stringify(i)}, "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 Sd(e,t,n){let a=`${e}-search`,r=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,i=[" 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 i;if(n==="search")return[...i,""," // 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(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."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(r)},`,' 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[...i,""," // 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"?[...i,""," // 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({",...jo(e).map(s=>` ${s}`)," });"]:n==="importers"?[...i,""," // 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"?[...i,""," // 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"?[...i,""," // 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"?[...i,""," // 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 };`," });"]:[...i,""," // 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 Ed(e,t,n){let a=n==="hooks",r=n==="search",o=n==="importers",i=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",m=gd[n],h=e,f=`${e}s`,p=`${e.replace(/-/g,"_")}_note`,g=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=a?[`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;",...le,"});",""]:[],x=r?Hn(e,t,"search",m):[],I=o?Hn(e,t,"importers",m):[],b=i?[`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 {",...To(Co({extensionName:e,itemTypeName:h,itemTypeFolder:f,fieldName:p,migrationId:g,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...le,"});",""]:[],T=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 {",...To(Ro(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...le,"});",""]:[],J=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;",...le,"});",""]:[],W=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;",...le,"});",""]:[],S=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;",...le,"});",""]:[],L=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;",...le,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...r?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Ao,`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;",...le,"});","",...v,...x,...I,...b,...T,...J,...W,...S,...L,`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(`
10
+ `)}function $d(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let a=`${e.replace(/-/g," ")} items`;return[t,`${a} import`,`${a} export`]}return[t]}var Td={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"},Id={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 Ad(e,t,n){let a=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.",',...a?[" 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,",...a?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function Cd(e,t,n){let a=[],r=[...Ad(e,t,n)],o=[" commands: [pingCommand],"],i=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),m=u===d?[]:[u],h=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":a.push("defineAfterCommandHook"),r.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":a.push("defineSearchProvider","defineVectorStoreAdapter"),r.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(i)},`," 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":a.push("defineExporter","defineImporter"),r.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":a.push("defineItemField","defineItemType","defineMigration"),r.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(h)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(f)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),o.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":a.push("defineProjectProfile"),r.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({",...jo(e),"});"),o.push(" profiles: [starterProfile],");break;case"renderers":a.push("defineRendererOverride"),r.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":a.push("defineParserOverride"),r.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":a.push("definePreflightOverride"),r.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":a.push("defineServiceOverride"),r.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:a,definitions:r,blueprintFields:o}}function Rd(e,t,n){let a=Cd(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...a.builderImports].sort((o,i)=>o.localeCompare(i)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...a.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({",...a.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(`
11
+ `)}function Hn(e,t,n,a){if(n==="commands")return[];let r=`${e}-search`,o=`${e}-vector`,i=`${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: ${a},`," });"],m=h=>[...u," let deactivated = false;"," try {",...h.map(f=>f===""?f:` ${f}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...le];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(r)}, 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 query = await ext.runSearchProvider({",` provider: ${JSON.stringify(r)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings: {} as PmSettings,"," 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(r)},`,' operation: "embed",',' context: { input: "abc", settings: {} as PmSettings, 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: {} as PmSettings },"," });",' 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(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(i)},`,' 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(i)},`,' 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(Co({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Ro(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 Od(e,t,n){let a=n==="parser",r=JSON.stringify([...Oo[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" };',"",...Ao,`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(Pe)},`," },",` target: { pmVersion: ${JSON.stringify(Pe)} },`," });"," // 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, ${r});`,` assert.deepEqual(report.manifest?.capabilities, ${r});`,"});","",`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: ${r},`," });"," 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)},`,...a?[" 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;",...le,"});","",...Hn(e,t,n,r)].join(`
12
+ `)}function Nd(e,t,n){let a=Do(n,"package"),r=Po(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",a,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${Td[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`.",No,"- `.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 ${Id[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.",...r,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Gn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Pe}\`. 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(`
13
+ `)}function Dd(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 Pd(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 jd(e,t,n,a){let r=["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"&&r.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&r.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(a.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(a.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"&&r.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"&&r.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(a.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(a.itemTypeName)},`,` folder: ${JSON.stringify(a.itemTypeFolder)},`,` aliases: ${JSON.stringify(a.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(a.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&r.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(a.itemTypeName)}, folder: ${JSON.stringify(a.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&r.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&r.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&r.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"&&r.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),r}function Ld(e,t,n){let a=[];return t==="renderers"&&a.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&a.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&a.push(" api.registerPreflight(preflightOverride);"),t==="services"&&a.push(' api.registerService("output_format", outputService);'),t==="hooks"&&a.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&a.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&a.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&a.push(" api.registerProfile(starterProfile);"),t==="importers"&&a.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.",'," },"," ],"," });"),a}function Md(e,t,n,a="commands",r=!1){let o=`pm-${e}`,i=Oo[a],s=$d(e,t,a),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Gn,pm_min_version:Pe,trusted:!0,sandbox_profile:"strict",permissions:{...md},capabilities:i,...s.length>0?{activation:{commands:s}}:{}},null,2)}
14
+ `,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Sd(e,t,a),"}","","// `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(`
15
+ `),l=`${JSON.stringify(hd,null,2)}
16
+ `,u=_d[a],m=Do(a,"package"),h=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:ud},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Pe}`},devDependencies:{"@types/node":fd,typescript:pd},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)}
17
+ `,f=Ed(e,t,a),p=yd[a],g=["node_modules/","*.log","*.tsbuildinfo",""].join(`
18
+ `),w=Dd(e),x=["```ts",`import { ${Pd(a)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...jd(e,t,a,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Ld(t,a,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],I=[`# ${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,p,No,"- `.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`.",...wd[a],...Po(a,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Pe}\`. 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 \`${Gn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Pe}\`. 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(`
19
+ `);return{"package.json":h,"manifest.json":c,"index.ts":r?Rd(e,t,a):d,"index.test.ts":r?Od(e,t,a):f,"tsconfig.json":l,".gitignore":g,"README.md":r?Nd(o,t,a):I}}async function Lo(e,t="extension",n="commands",a=!1){let r=n.trim().toLowerCase();if(!Io.includes(r))throw new _(`Unknown scaffold capability "${n}". Supported capabilities: ${Io.join(", ")}.`,y.USAGE);let o=r;if(a&&t!=="package")throw new _("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",y.USAGE);let i=a?"declarative":"imperative",s=e.trim(),c=gt.resolve(process.cwd(),s),d=Ht(gt.basename(c)).replace(/^(?:pm-)+/u,""),l=xd(d),u=Md(d,l,t,o,a),m=!1;if(await E(c)){if(!(await ht.stat(c)).isDirectory())throw new _(`Scaffold target "${c}" exists and is not a directory.`,y.CONFLICT)}else await ht.mkdir(c,{recursive:!0}),m=!0;for(let[f,p]of Object.entries(u)){let g=gt.join(c,f);if(!await E(g))continue;if(await ht.readFile(g,"utf8")!==p)throw new _(`Scaffold file "${f}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,y.CONFLICT)}let h=[];for(let[f,p]of Object.entries(u)){let g=gt.join(c,f);if(await E(g)){h.push({path:f,status:"unchanged"});continue}await ht.mkdir(gt.dirname(g),{recursive:!0}),await ht.writeFile(g,p,"utf8"),h.push({path:f,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:o,style:i,target_path:c,created_directory:m,files:h}}(function(){try{var e=typeof window<"u"?window:typeof 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 Mo(e,t){return`${e}:${k(t)}`}function Fd(e,t){let n=[];for(let[a,r]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let i of r){let s=o.get(i.command)??[];o.set(i.command,[...s,i])}for(let[i,s]of o){if(t!==null&&!s.some(d=>t.has(k(d.name))))continue;let c=s.at(-1);n.push({command:i,surface:a,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((a,r)=>a.command.localeCompare(r.command)||a.surface.localeCompare(r.surface))}function Fo(e,t,n){let a=new Set(n.failed.map(d=>Mo(d.layer,d.name))),r=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:a.has(Mo(d.layer,d.name))?"failed":"ok",surfaces:Be(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:Be(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),o=typeof e=="string"?k(e):null,i=o===null?null:new Set(t.loaded.filter(d=>k(d.name)===o||typeof d.source_package=="string"&&k(d.source_package)===o||(d.source_aliases??[]).some(l=>k(l)===o)).map(d=>k(d.name)).concat(o)),s=i===null?r:r.filter(d=>i.has(k(d.name))),c=i===null?{}:{extensionNames:[...i]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Be(n,c),command_ownership:Fd(n,i)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function Bn(e){return e.map(({layer:t,name:n,error:a})=>({layer:t,name:n,error:a}))}function Qt(e,t,n){let a=k(t),r=n.trim();if(a.length===0||r.length===0)return;let o=e.get(a)??new Set;o.add(r),e.set(a,o)}function Ud(e){let t=new Map,n=new Map;for(let a of e.registrations.commands)Qt(t,a.name,a.command),Qt(n,a.name,a.action);for(let a of e.commands.handlers)Qt(t,a.name,a.command);for(let a of e.commands.overrides)Qt(t,a.name,a.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Uo(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function zd(e){let{enabled:t,normalizedName:n,loadedNames:a,loadFailedNames:r,activationFailedNames:o}=e;return t?r.has(n)||o.has(n)?{runtime_active:!1,activation_status:"failed"}:a.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function Zt(e,t,n){let a=new Set(t.loaded.map(c=>k(c.name))),r=new Set(t.failed.map(c=>k(c.name))),o=new Set(n.failed.map(c=>k(c.name))),{commandPathsByExtension:i,actionPathsByExtension:s}=Ud(n);return e.map(c=>{let d=k(c.name),l=Uo(i.get(d)),u=Uo(s.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},h=zd({enabled:c.enabled,normalizedName:d,loadedNames:a,loadFailedNames:r,activationFailedNames:o});return{...c,...h,...m}})}function Jd(e){let t=0,n=0,a=0;for(let r of e)if(r.startsWith("extension_policy_")){if(t+=1,r.startsWith("extension_policy_violation_")){n+=1;continue}r.startsWith("extension_policy_blocked_")&&(a+=1)}return{warning_count:t,violation_count:n,blocked_count:a}}function H(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Wo=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 Wd(e){return Wo.has(Ko(e))}function zo(e){return e==="project"||e==="global"}function qo(e){let t=e.split(":"),n=t[0];if(!n||!Wo.has(n))return null;let a=t.at(-4),r=t.at(-3)?.trim(),o=t.at(-2),i=t.at(-1)?.trim();return!zo(a)||!zo(o)||!r||!i?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:a,name:r},displaced:{layer:o,name:i}}}function qd(e){let t=new Set;for(let n of e){let a=qo(n);a&&(t.add(a.winner.name),t.add(a.displaced.name))}return[...t].sort((n,a)=>n.localeCompare(a))}function Vn(e,t){let n=e.filter(Wd);if(n.length===0)return null;let a=qd(n);return`Extension registration collisions or handler/override overlaps detected.${a.length>0?` Conflicting extensions: ${a.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 Gd(e,t,n,a){let r=t.map(u=>qo(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(r.length===0)return;let o=e==="global"?"--global":"--project",i=H(a,"deactivate"),s=`${H(a,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(u=>[k(u.name),u])),d=new Map;for(let u of r)for(let m of[u.winner.name,u.displaced.name]){let h=k(m);d.set(h,(d.get(h)??0)+1)}let l=[...d.entries()].map(([u,m])=>{let h=c.get(u),f=h?.name??u,p=h?.command_paths??[],g=h?.action_paths??[];return{action:"deactivate",extension:f,command:`${i} ${f} ${o}`,affected_collisions:m,feature_loss:{command_paths:[...p].sort((w,v)=>w.localeCompare(v)),action_paths:[...g].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let h=m.affected_collisions-u.affected_collisions;if(h!==0)return h;let f=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,p=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return f!==p?f-p:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:r.length,extension_count:d.size,next_best_command:s,collisions:r,remediation_candidates:l}}function Go(e){let t=[];for(let n of e){let a=n.error.toLowerCase();(a.includes("cannot find package '@unbrained/pm-cli'")||a.includes('cannot find module "@unbrained/pm-cli"')||a.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(a.includes("cannot use import statement outside a module")||a.includes("to load an es module")||a.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,a)=>n.localeCompare(a))}function Ho(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let a of t){if(!a||typeof a.name!="string")continue;let r=a.trace?.missing_capability??a.trace?.capability;typeof r=="string"&&r.trim().length>0&&n.push(`extension_capability_missing:${a.name}:${r.trim().toLowerCase()}`)}return[...new Set(n)].sort((a,r)=>a.localeCompare(r))}function Bo(e,t){let n=[];for(let a of Ba(e.loaded,t))for(let r of a.unused)n.push(`extension_capability_unused:${a.layer}:${a.name}:${r}`);return[...new Set(n)].sort((a,r)=>a.localeCompare(r))}var Hd=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${H(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: ${$t.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 ${H(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 ${H(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 ${H(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 ${H(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 ${H(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${H(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 Bd(e){let{normalizedWarnings:t,options:n,scope:a,scopeFlag:r,updateCheckFailedTotal:o,policyWarningCount:i,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=[],m={options:n,scope:a,scopeFlag:r,updateCheckFailedTotal:o,policyWarningCount:i};if(t.length>0){let h=Vn(t,{deactivate:`${H(n,"deactivate")} <name> ${r}`,doctor:`${H(n,"doctor")} ${r} --detail deep --trace`});h&&u.push(h);for(let f of Hd)f.matches(t,m)&&u.push(f.build(m))}return s?u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${H(n,"manage")} ${r} --fix-managed-state (or ${H(n,"adopt-all")} ${r}, ${H(n,"adopt")} <name> ${r}, or reinstall via ${H(n,"install")} ${r} <source>).`):c>0&&u.push(`Loaded unmanaged extensions are currently treated as informational. Use ${H(n,"manage")} ${r} --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 ${H(n,"install")} ${r} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${H(n,"manage")} ${r} after extension changes.`),u}function en(e,t,n,a={}){let r=[...new Set(t)].sort((S,L)=>S.localeCompare(L)),o=n.filter(S=>S.managed).length,i=n.filter(S=>S.enabled).length,s=n.filter(S=>S.active).length,c=n.filter(S=>S.update_available===!0).length,d=n.filter(S=>S.managed===!1),l=d.filter(S=>Jo(S)).map(S=>S.name).sort((S,L)=>S.localeCompare(L)),u=d.filter(S=>!Jo(S)).map(S=>S.name).sort((S,L)=>S.localeCompare(L)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let S of n)m[S.update_check_status]+=1;let h=m.failed,f=m.skipped_unmanaged,p=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([...r,...v])].sort((S,L)=>S.localeCompare(L)),I=[...new Set(x.map(S=>Ko(S)))].sort((S,L)=>S.localeCompare(L)),b=Jd(x),T=e==="global"?"--global":"--project",J=Gd(e,r,n,a),W=Bd({normalizedWarnings:r,options:a,scope:e,scopeFlag:T,updateCheckFailedTotal:h,policyWarningCount:b.warning_count,updateHealthPartial:g,skippedUnmanagedTotal:f,skippedNonGithubTotal:p,updateAvailableTotal:c});return{status:x.length===0?"ok":"warn",warning_count:x.length,warning_codes:I,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:i,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(S=>S.name).sort((S,L)=>S.localeCompare(L)),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:h,top_warnings:x.slice(0,8),remediation:W,...J?{collision_plan:J}:{}}}function Vo(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new _(`Invalid --detail value "${e}". Expected summary or deep.`,y.USAGE)}function Ko(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function _t(e){let t=new Set,n=[];for(let a of e){let r=(()=>{let o=va(a);return o?[o]:ba(a)})();for(let o of r){let i=`${o.layer}:${o.name}:${o.capability}`;t.has(i)||(t.add(i),n.push(o))}}return n}function yt(){return{version:Tt.version,capabilities:[...Tt.capabilities],legacy_aliases:{...Tt.legacy_aliases}}}function Jo(e){let t=k(e.name),n=k(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Yo(e,t,n,a,r){if(e!=="project"||r)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=>k(l.name)))].sort((l,u)=>l.localeCompare(u)),i=[...new Set(n.filter(l=>l.layer==="project").map(l=>k(l.name)))].sort((l,u)=>l.localeCompare(u)),s=new Set(a.map(l=>k(l.name))),c=o.filter(l=>!i.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:i.length,active_project_names:o,loaded_project_names:i,missing_active_project_names:c}}}import{randomUUID as Vd}from"node:crypto";import F from"node:fs/promises";import Kd from"node:os";import N 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]="9c598dc3-e766-595d-80f1-6d55e1667d6b")}catch{}})();var Xo=3,Yd=120,Qo=250,Xd=12e4,Qd=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Zo=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,ei=e=>Qd.has(String(Zo(e))),wt=(e,t)=>Zo(e)===t,ti=e=>new Promise(t=>{setTimeout(t,e)}),ni=async e=>{let t=N.join(e,"package.json");await E(t)||await F.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
20
+ `,"utf8")},ai=async e=>{let t=xe(import.meta.url,["../../.."]),n=N.join(e,"node_modules","@unbrained"),a=N.join(n,"pm-cli");await F.mkdir(n,{recursive:!0}),await F.rm(a,{recursive:!0,force:!0}),await F.symlink(t,a,process.platform==="win32"?"junction":"dir")},Kn=async e=>{let t=N.resolve(e),n=N.dirname(t),a=N.parse(n).root,r=await F.realpath(a).catch(()=>a),o=N.relative(a,n),i=o===""?[]:o.split(N.sep);for(let[s,c]of i.entries()){let d=N.join(r,c);try{r=await F.realpath(d)}catch{r=N.join(r,...i.slice(s));break}}return N.join(r,N.basename(t))},ri=async(e,t,n,a=Kd.tmpdir())=>{let r=N.resolve(e),o=await F.realpath(r).catch(()=>r),i=await Kn(t);if(o===i)return;if(!ie(o,i)){await n(e,t,{recursive:!0,force:!0});return}let s=m=>{let h=N.resolve(m);if(h!==r&&!ie(r,h))return!1;let f=N.resolve(o,N.relative(r,h));if(f===i||ie(i,f))return!1;let g=N.relative(o,f).split(N.sep);return g.some(w=>w==="node_modules"||w.startsWith(".pm-extension-install-backup-"))?!1:g[0]!==".agents"},c=await F.realpath(N.resolve(a)).catch(()=>Kn(a)),d=ie(o,c)?N.dirname(o):c;if(ie(o,d))throw new _(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,y.USAGE,{code:"extension_install_source_contains_destination"});let l=await F.mkdtemp(N.join(d,"pm-extension-copy-")),u=N.join(l,"extension");try{await n(e,u,{recursive:!0,force:!0,filter:s}),await n(u,t,{recursive:!0,force:!0})}finally{await F.rm(l,{recursive:!0,force:!0})}},oi=async(e,t,n=F.cp)=>{for(let a=1;a<=Xo;a+=1)try{await F.rm(t,{recursive:!0,force:!0}),await ri(e,t,n);return}catch(r){if(!ei(r)||a===Xo)throw r;await ti(Qo)}},Yn=async e=>{let t;try{t=await F.readFile(N.join(e,"owner.json"),"utf8")}catch(r){if(!wt(r,"ENOENT"))throw r;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let a=n.token;return typeof a=="string"&&a.length>0?a:null},ii=async(e,t)=>await Yn(e)!==t?!1:(await F.rm(e,{recursive:!0,force:!0}),!0),Zd=async(e,t)=>{let n;try{n=await F.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let a=await Yn(e);return a===null?(await F.rm(e,{recursive:!0,force:!0}),!0):ii(e,a)},el=(e,t,n)=>{let a=Promise.resolve(),r=setInterval(()=>{a=a.then(async()=>{if(await Yn(e)!==t)return;let o=new Date;await F.utimes(e,o,o)}).catch(()=>{})},n);return r.unref(),async()=>{clearInterval(r),await a}},tl=async(e,t)=>{await F.mkdir(e);try{await F.writeFile(N.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
21
+ `,"utf8")}catch(n){throw await F.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},nl=async(e,t,n,a,r)=>{for(let o=1;o<=n;o+=1)try{return await tl(e,t),!0}catch(i){if(!wt(i,"EEXIST"))throw i;await Zd(e,r)?o-=1:await ti(a)}return!1},Xn=async(e,t,n,a)=>{let r=N.join(e,"runtime","extension-install-locks"),o=N.join(r,"scope.lock");await F.mkdir(r,{recursive:!0});let{attempts:i=Yd,delay_ms:s=Qo,stale_ms:c=Xd,heartbeat_ms:d}=a??{};if(![i,s,c,d].filter(w=>w!==void 0).every(Number.isFinite))throw new _("Extension install lock timings must be finite numbers.",y.USAGE);let l=Math.max(1,Math.floor(i)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),h=Math.floor(d??m/3);if(m<=0||h<=0||h>=m)throw new _("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",y.USAGE);let f={pid:process.pid,token:Vd(),created_at:A(),destination:t};if(!await nl(o,f,l,u,m))throw new _(`Timed out waiting for extension install lock for "${t}".`,y.CONFLICT);let g=el(o,f.token,h);try{return await n()}finally{await g(),await ii(o,f.token).catch(()=>!1)}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d3c62e9-9116-5cdc-bbda-48bbd2e39476")}catch{}})();var si=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let a=new Array(e.length),r=0,o=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let i=r;r+=1,a[i]=await n(e[i])}});return await Promise.all(o),a};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b17dfc10-9e07-5912-b294-c5663133f192")}catch{}})();function ci(e,t){let n=k(e),a=t.find(r=>k(r.name)===n);return{command_paths:[...a?.command_paths??[]].sort((r,o)=>r.localeCompare(o)),action_paths:[...a?.action_paths??[]].sort((r,o)=>r.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]="0dc7b063-dc72-595f-8e40-8a06f9db69e1")}catch{}})();function di(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${k(o.name)}`]:[])),a=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>!n.has(`${o.layer}:${k(o.name)}`)).map(o=>`extension_output_service_override_global:${o.service}:${o.layer}:${o.name}`),r=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([...a,...r])].sort((o,i)=>o.localeCompare(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]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var li=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=Pt(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,a)=>a.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 al=1e4,rl=(e,t,n)=>{let a=e.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).map(i=>{let[s,c=""]=i.split(/\s+/);return{commit:s,ref:c}}),r=a.find(i=>i.ref.endsWith("^{}"))??a[0];if(!r)return{checked_at:n,available:null,error:"no_remote_reference_found"};let o=t?.trim();return o?{checked_at:n,remote_commit:r.commit,available:r.commit!==o}:{checked_at:n,remote_commit:r.commit,available:null,error:"missing_installed_commit"}},ui=async(e,t=Kt)=>{let n=A();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let a=[e.ref?.trim(),"HEAD"].find(Boolean),r=await t(["ls-remote",e.repository,a,`${a}^{}`],void 0,al);return rl(r,e.commit,n)}catch(a){return{checked_at:n,available:null,error:a instanceof Error?a.message:String(a)}}};import ol from"node:fs/promises";import il from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="56290db9-933c-590d-8b9f-df62ff45e515")}catch{}})();function Qn(e){return il.join(e,"extension-migrations.json")}function mi(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 pi(e,t){return`${e.layer}:${e.name}:${t}`}async function sl(e){let t=Qn(e);if(!await E(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await ol.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(a=>typeof a?.key=="string"&&(a.status==="applied"||a.status==="failed")):[]}}async function Zn(e,t){let n=await sl(e),a=new Map(n.entries.map(r=>[r.key,r]));return t.forEach((r,o)=>{let i=mi(r,o),s=a.get(pi(r,i));s&&(r.definition.status=s.status,s.status==="failed"?r.definition.reason=s.error:(delete r.definition.reason,delete r.definition.error,delete r.definition.message))}),n}async function cl(e){let t=await Zn(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),a=[],r=!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=mi(l,u),h=pi(l,m),f=n.get(h),p=String(l.definition.status??"pending").toLowerCase(),g=f?.status??(p==="applied"||p==="failed"?p:"pending");if(g==="applied"){a.push({key:h,layer:l.layer,extension:l.name,id:m,before:g,outcome:"skipped"});continue}if(e.dryRun===!0){a.push({key:h,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"){a.push({key:h,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:h,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(h,x),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,a.push({key:h,layer:l.layer,extension:l.name,id:m,before:g,outcome:"applied"}),r=!0}catch(x){let I=x instanceof Error?x.message:String(x),b={key:h,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:I};n.set(h,b),l.definition.status="failed",l.definition.reason=I,a.push({key:h,layer:l.layer,extension:l.name,id:m,before:g,outcome:"failed",error:I}),r=!0}}if(r){let l=await R(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,h)=>m.key.localeCompare(h.key))};await Ft({pmRoot:e.pmRoot,filePath:Qn(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
22
+ `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let i=a.filter(l=>l.outcome==="pending").length,s=a.filter(l=>l.outcome==="applied").length,c=a.filter(l=>l.outcome==="skipped").length,d=a.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:Qn(e.pmRoot),total:a.length,pending_count:i,applied_count:s,skipped_count:c,failed_count:d,migrations:a}}async function fi(e){let t=await R(e.resolvedRoots.settings_root),n=await se({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),a=await ce(n);e.warnings.push(...n.warnings,...a.warnings);let r=await cl({pmRoot:e.resolvedRoots.pm_root,migrations:a.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:r,load_failure_count:n.failed.length,activation_failure_count:a.failed.length},r.ok)}(function(){try{var e=typeof window<"u"?window:typeof 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 hi(e,t,n){let a=typeof t=="string"?null:await pt(e),r=a===null?null:e.trim().toLowerCase(),o=r===null?null:await ho(r),i=Xt(a??e,{forceGithub:typeof t=="string",ref:n}),s=r===null?null:await yo(e);return{bundledAliasName:r,bundledPackageName:o,installSource:i,sourceResolution:{requested:e,selected:{kind:r===null?i.kind:"builtin",input:r??i.input,...o===null?{}:{package:o}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...r===null?[]:[{kind:"builtin",input:r,...o===null?{}:{package:o},command:`pm install ${r}`}],...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 je from"node:fs/promises";import dl 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 ea=async e=>je.readFile(e).catch(t=>{if(wt(t,"ENOENT"))return null;throw t}),gi=async(e,t,n,a,r)=>{let o=lt(e),i=te(t),[s,c]=await Promise.all([ea(o),ea(i)]);return a&&await je.cp(n,r,{recursive:!0,force:!0}),{backupDirectory:r,destinationDirectory:n,destinationExists:a,managedStatePath:o,managedStateContents:s,settingsPath:i,settingsContents:c}},_i=async e=>{await je.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await je.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 je.rm(t,{force:!0}):(await je.mkdir(dl.dirname(t),{recursive:!0}),await je.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]="f4b47053-cc05-51f2-b5cb-cc6dba3365c2")}catch{}})();var ll=4,ki=[["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"]],yi=ki.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),ul={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"},ml="__pm_native_output",pl=["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"],xi=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],fl=["disabled","require_trusted","require_provenance"],Si={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:[]},hl=e=>{let t=e??Si,n={};for(let a of pl)n[a]=Z(t[a]??[]);return n},gl=(e,t)=>{for(let n of xi)t[n].length>0&&(e[n]=t[n]);return e},_l=(e,t)=>{for(let n of fl)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},yl=e=>{let t={};for(let n of xi)t[n]=Z(e[n]??[]);return t},wl=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:gl(_l({name:t},e),yl(e))},vl=e=>(e??[]).map(t=>wl(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),bl=e=>{let t=Object.assign({},Si,e??{}),n=hl(e),a=vl(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:a}},Ei=async(e,t)=>{let n=[t],a=await go(t);a&&n.push(a);let r=[...new Set(n.map(o=>k(o)).filter(o=>o.length>0))];for(let o of r){let i=e.find(c=>k(c.name)===o);if(i)return i;let s=e.find(c=>k(c.directory)===o);if(s)return s}},$i=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled));return new Set(Z(e.extensions.disabled)).has(n)?!1:a.size===0?!0:a.has(n)},Ti=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled)),r=new Set(Z(e.extensions.disabled)),o=[...a],i=[...r];return r.delete(n),a.size>0&&a.add(n),e.extensions.enabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==i.join("\0")},kl=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled)),r=new Set(Z(e.extensions.disabled)),o=[...a],i=[...r];return a.delete(n),r.add(n),e.extensions.enabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==i.join("\0")},xl=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled)),r=new Set(Z(e.extensions.disabled)),o=[...a],i=[...r];return a.delete(n),r.delete(n),e.extensions.enabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==i.join("\0")},Sl=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),a=ki.map(([r,o,i])=>({action:o,flag:i,distance:wa(t,r,n)})).filter(r=>r.distance!==null).sort((r,o)=>r.distance-o.distance)[0];return a?{action:a.action,flag:a.flag}:null},El=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=Sl(e);if(!a)return new _(`One action flag is required. Use one of: ${yi}. Bare \`pm package\` and \`pm extension\` default to --explore.`,y.USAGE);let r=`pm ${n} ${a.flag}`;return new _(`Unknown ${n} lifecycle action "${e}". Did you mean "${a.flag}"?`,y.USAGE,{code:"unknown_lifecycle_action",required:`Use one of: ${yi}.`,examples:[r,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:r,fallback_candidates:[{source:"lifecycle_action",command:r,reason:`nearest lifecycle action for "${e}"`}]}})},$l=[["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"]],Tl={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Il=e=>Tl[e]??null,Al=(e,t)=>{let n=[...new Set($l.filter(([a])=>t[a]===!0).map(([,a])=>a))];if(n.length===0){if(e===void 0)return"explore";let a=Il(e.trim().toLowerCase());if(a)return a;throw El(e,t)}if(n.length>1)throw new _("Extension action flags are mutually exclusive.",y.USAGE);return n[0]},Cl=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new _('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"},Rl=[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"}}],Ii=e=>{for(let t of Rl){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Ai=(e,t,n,a)=>{let r=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:r.contributions,managed:!!n,source:r.source,update_available:r.update_available,last_update_check_at:r.last_update_check_at,last_update_remote_commit:r.last_update_remote_commit,update_error:r.update_error,update_check_status:a.status,update_check_reason:a.reason}},Ol=(e,t,n,a)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},a),o=a?$i(n,a.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Ai({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:o},t,a,Ii(a))}},Nl=async(e,t,n,a,r,o)=>{let i=ae.join(e,t),s=ae.join(i,"manifest.json"),c=o.get(k(t));if(!await E(s))return Ol(t,n,a,c);let d=Symbol("invalid-extension-manifest-json"),l=await Ce.readFile(s,"utf8").then(h=>JSON.parse(h)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=Ln(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=r.get(k(u.name))??o.get(k(t));return{summary:Ai({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:$i(a,u.name)},n,m,Ii(m))}},ue=async(e,t,n,a)=>{if(!await E(e))return{extensions:[],warnings:[]};let o=(await Ce.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),i=new Map(a.entries.map(l=>[k(l.name),l])),s=new Map(a.entries.map(l=>[k(l.directory),l])),c=[],d=[];for(let l of o){let u=await Nl(e,l,t,n,i,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))}},Dl=Ka(),Pl=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,jl=(e,t,n,a)=>{let r=n.command_paths.map(s=>`pm ${s} --help`),o=a?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,i=n.command_paths.length>0?[...r]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&i.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Pl(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:r,next_steps:i,...o?{sdk_dependency_status:"missing"}:{}}},Ll=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(([,a])=>a!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},Ci=e=>e.map(t=>Ll(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),Ri=(e,t,n)=>{let a=k(e);return t.find(r=>(n===void 0||r.layer===n)&&k(r.name)===a)},Ml=(e,t,n,a)=>n.find(o=>o.scope===t&&k(o.name)===k(e))?.activation_status??(a?"failed":"unknown"),Oi=(e,t,n,a,r)=>Dl.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,i=await Ce.mkdtemp(ae.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=xe(import.meta.url,["../.."]);try{let s=await se({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:r.noExtensions===!0,reload_token:fn(),cache_bust:!0,module_graph_snapshot_root:i}),c=await ce({...s}),d=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...Ci(c.failed)],l=Object.fromEntries(s.loaded.map(u=>[k(u.name),Ca(Be(c,{extensionName:u.name}))]));return{installed:Zt(a,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 Ce.rm(i,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),na=async(e,t,n,a)=>{let r=n.filter(c=>!c.managed),o=[...r].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),i=a,s=[];for(let c of o){let d=ae.join(e,c.directory),l=await Xe(d),u=A(),m={kind:"local",input:c.name,location:d};i=mt(i,{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 De(e,i),{state:i,adopted_entries:s,unmanaged_candidates:o,already_managed_count:n.length-r.length}},Fl=(e,t)=>{let n=P(process.cwd(),t.path),a=Ue(n,process.cwd()),r=e==="global"?At(process.cwd()):n,o=e==="global"?a.global:a.project;return{pm_root:n,scope:e,settings_root:r,selected_root:o,roots:a}},tn=e=>{let t=[e.gh,e.github].filter(a=>typeof a=="string").map(a=>a.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new _('Options "--gh" and "--github" must match when both are provided.',y.USAGE);return n[0]},Ul=e=>ul[e],zl=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=e==="install"?"source":"name",r=`${n} ${a}`,o=Ul(e),i=`<${a}>`,s=`pm ${n} ${o} ${i}`;throw new _(`Action "${e}" requires ${r} input.`,y.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${a} target for ${e}.`,examples:[`pm ${n} ${e} ${i}`,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 ${a} target`}]}})},nn=(e,t,n={})=>{let a=e?.trim();if(a)return a;if(t==="init")throw new _('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',y.USAGE);return zl(t,n)},Jl=(e,t)=>{let n=new Set([...t.registrations.item_types.map(a=>({entry:a,count:a.types.length})),...t.registrations.item_fields.map(a=>({entry:a,count:a.fields.length}))].filter(({count:a})=>a>0).map(({entry:a})=>`${a.layer}:${k(a.name)}`));return e.loaded.filter(a=>(a.activation?.commands??[]).length>0).filter(a=>n.has(`${a.layer}:${k(a.name)}`)).map(a=>`extension_schema_narrow_activation:${a.layer}:${a.name}`).filter((a,r,o)=>o.indexOf(a)===r).sort((a,r)=>a.localeCompare(r))},Wl=(e,t)=>{let a=[{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(r=>r.triggered&&!r.allowed);if(a)throw new _(a.message,y.USAGE)},ql=(e,t,n)=>{let a=String(e??"").trim().toLowerCase(),r=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:r?[]:["init","scaffold"]}[t]??[]).includes(a)?void 0:e},Gl=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},Hl=(e,t,n)=>{let a={ok:n,action:e.action,scope:e.scope,roots:Gl(e),warnings:[...new Set(e.warnings)].sort((r,o)=>r.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(a,ml,{value:!0,enumerable:!1,configurable:!1}),a},aa=async(e,t,n)=>{let a=Al(e,t);Wl(a,t);let r=ql(e,a,t),o=Cl(t),i=Fl(o,n),c={action:a,normalizedTarget:r,scope:o,resolvedRoots:i,warnings:[],options:t,global:n},l={...c,withResult:(u,m=!0)=>Hl(c,u,m)};return await Eu(l)},Bl=(e,t)=>{let n=t.vocabulary??"extension",a=e.target_path.replace(/\\/g,"/"),r=Tn(a),o={package:`Install dependencies: cd ${r}, then run "npm install"`,extension:`Install type-check dependencies: cd ${r}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},i={package:`Validate the package: cd ${r}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${r}, 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",a]:["extension","--install","--project",a])}`,`Smoke-test command path: pm ${e.command_name}`,i[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},Vl=async e=>{let{action:t,normalizedTarget:n,options:a,withResult:r}=e;if([tn(a),a.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new _('Action "init" does not accept --gh/--github/--ref options.',y.USAGE);let s=nn(n,t,a),c=await Lo(s,a.vocabulary??"extension",a.capability,a.declarative===!0);return r({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:Bl(c,a)})},Kl=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:a,options:r,global:o,withResult:i}=e;if(t!==void 0)throw new _('Action "reload" does not accept a target argument.',y.USAGE);let s=await R(n.settings_root),c=fn(),d=await se({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});a.push(...d.warnings);let l=await ce(d);a.push(...l.warnings);let u={reload:{token:c,cache_bust:!0,watch:r.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 r.watch===!0&&a.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),i(u)},Yl=async e=>{let{normalizedTarget:t,scope:n,options:a,global:r,withResult:o}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new _('Action "catalog" does not accept a package target.',y.USAGE);return o(await _o(n,r,a))},Xl=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Ql=e=>({kind:"local",input:e.input,location:e.absolute_path}),Zl=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),eu=(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}),tu=(e,t,n,a)=>e?Xl(e,t):n.kind==="local"?Ql(n):n.kind==="npm"?Zl(n,a):eu(n,a),nu=(e,t,n,a)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:a}:lo(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:a}:{installed_at:a,updated_at:a},au=async(e,t)=>{let{scope:n,resolvedRoots:a,warnings:r}=e,{validated:o,destinationDirectoryName:i}=t,s=await R(a.settings_root),c=await V(a.selected_root);r.push(...c.warnings);let d=ae.join(a.selected_root,i),l=await E(d),u=await Eo(o.directory,d);await Ce.mkdir(a.selected_root,{recursive:!0});let m=await Ce.mkdtemp(ae.join(a.selected_root,".pm-extension-install-backup-")),h=ae.join(m,"destination");try{let f=await gi(a.selected_root,a.settings_root,d,l,h),p=tu(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),g=c.state.entries.find(I=>k(I.name)===k(o.manifest.name)),w=nu(g,o.manifest.version,p,A()),v=mt(c.state,{name:o.manifest.name,directory:i,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,...w,source:p}),x=Ti(s,o.manifest.name);try{u||await oi(o.directory,d),await ni(d),await ai(d),await De(a.selected_root,v),x&&await Ut(a.settings_root,s,"settings:write")}catch(I){try{await _i(f)}catch(b){throw new AggregateError([I,b],`Extension install failed: ${String(I)}; rollback failed: ${String(b)}`,{cause:b})}throw I}return{settings:s,managedState:v,sourceRecord:p,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:x}}finally{await Ce.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},ru=async(e,t,n)=>{let a=n.filter(r=>k(r.name)===k(t)).flatMap(r=>r.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&a.length>0&&await ct(e.resolvedRoots.pm_root,a,e.warnings,"install:type-folder"),a},ou=(e,t,n,a,r)=>{let o=Ri(t,n.activation_failures,e.scope),i=Ml(t,e.scope,n.installed,o),s=[!n.extensions_disabled,i==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${i}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:i,failure:o,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:i,activated:s,registered_commands:a.command_paths,registered_actions:a.action_paths,registered_item_types:r,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},iu=async(e,t)=>{let{scope:n,resolvedRoots:a,warnings:r,global:o,withResult:i}=e,{validated:s,destinationDirectoryName:c}=t,d=await au(e,t),l=await ue(a.selected_root,n,d.settings,d.managedState);r.push(...l.warnings);let u=await Oi(a.pm_root,ae.dirname(a.selected_root),d.settings,l.extensions,o);r.push(...u.warnings);let m=await ru(e,s.manifest.name,u.item_type_registrations),h=ci(s.manifest.name,u.installed),f=ou(e,s.manifest.name,u,h,m),p=u.contribution_inventories[k(s.manifest.name)];return p&&(d.managedState=await uo(a.selected_root,d.managedState,s.manifest.name,p)),i({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:f.activated,settings_changed:d.activationChanged,runtime_activation_status:f.status,command_paths:h.command_paths,action_paths:h.action_paths,contributions:p,command_discovery:jl(s.manifest.name,d.sourceRecord,h,f.failure),verification:f.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:f.failure??null}},f.activated)},su=async e=>{let{options:t,global:n,warnings:a,withResult:r}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new _('Action "install all" does not accept --ref.',y.USAGE);let o=[],i=new Map;for(let c of await Vt()){let d=await pt(c),l=ae.resolve(d),u=i.get(l);u===void 0&&(u=await aa(c,{...t,install:!0},n),i.set(l,u)),o.push({alias:c,result:u})}a.push(...o.flatMap(c=>c.result.warnings));let s=o.every(c=>c.result.ok);return r({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)},cu=async(e,t,n)=>{let{resolvedRoots:a}=e,{bundledAliasName:r,bundledPackageName:o,installSource:i,sourceResolution:s}=await hi(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:${r}:npm:${d.package}`)}let c=await So(i);try{let d=await Xe(c.directory,{source_kind:i.kind,source_input:i.input,source_root:c.source_root}),l=Ht(d.manifest.name);return await Xn(a.settings_root,l,()=>iu(e,{validated:d,destinationDirectoryName:l,bundledAliasName:r,bundledPackageName:o,sourceResolution:s,installSource:i,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},du=async e=>{let t=tn(e.options),n=t??nn(e.normalizedTarget,e.action,e.options);return[t===void 0,po(n)].every(Boolean)?su(e):cu(e,n,t)},lu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:r,options:o,withResult:i}=e;if(t!==void 0)throw new _('Action "adopt-all" does not accept a target argument.',y.USAGE);if(tn(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new _('Action "adopt-all" does not accept --gh/--github/--ref options.',y.USAGE);let c=await R(a.settings_root),d=await V(a.selected_root);r.push(...d.warnings);let l=await ue(a.selected_root,n,c,d.state);r.push(...l.warnings);let u=await na(a.selected_root,n,l.extensions,d.state),m=await ue(a.selected_root,n,c,u.state);r.push(...m.warnings);let h=en(n,r,m.extensions,o);r.push(...h.warnings);let f=new Map(m.extensions.map(w=>[`${k(w.name)}:${k(w.directory)}`,w])),p=new Map(m.extensions.map(w=>[k(w.directory),w])),g=u.adopted_entries.map(w=>{let v=k(w.directory),x=f.get(`${k(w.name)}:${v}`)??p.get(v);return{...w,...Ni(x)}});return i({adopted_all:g.length>0,adopted_count:g.length,already_managed_count:u.already_managed_count,extensions:g,triage:h,warning_codes:h.warning_codes,update_health_partial:h.update_health_partial,update_health_coverage:h.update_health_coverage})},Ni=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),uu=(e,t,n,a)=>{if(e===void 0)return{kind:"local",input:t,location:n};let r=Xt(e,{forceGithub:!0,ref:a});if(r.kind!=="github")throw new _(`Invalid GitHub shorthand "${e}".`,y.USAGE);return{kind:"github",input:r.input,location:r.subpath??".",repository:r.repository,owner:r.owner,repo:r.repo,ref:r.ref,subpath:r.subpath}},mu=async e=>{let{action:t,normalizedTarget:n,scope:a,resolvedRoots:r,warnings:o,options:i,withResult:s}=e,c=nn(n,t,i),d=tn(i),l=await R(r.settings_root),u=await V(r.selected_root);o.push(...u.warnings);let m=await ue(r.selected_root,a,l,u.state);o.push(...m.warnings);let h=await Ei(m.extensions,c);if(!h)throw new _(`Installed extension "${c}" was not found in ${a} scope.`,y.NOT_FOUND);if(h.managed)return s({adopted:!1,already_managed:!0,extension:{name:h.name,directory:h.directory}});let f=ae.join(r.selected_root,h.directory),p=await Xe(f),g=A(),w=uu(d,c,f,i.ref),v=mt(u.state,{name:p.manifest.name,directory:h.directory,scope:a,manifest_version:p.manifest.version,manifest_entry:p.manifest.entry,capabilities:[...p.manifest.capabilities],contributions:p.manifest.contributions,installed_at:g,updated_at:g,source:w});await De(r.selected_root,v);let x=await ue(r.selected_root,a,l,v);o.push(...x.warnings);let I=x.extensions.find(b=>k(b.name)===k(p.manifest.name))??x.extensions.find(b=>k(b.directory)===k(h.directory));return s({adopted:!0,extension:{name:p.manifest.name,directory:h.directory,version:p.manifest.version,entry:p.manifest.entry},source:w,...Ni(I)})},Di=async e=>{let{action:t,normalizedTarget:n,scope:a,resolvedRoots:r,warnings:o,options:i}=e,s=nn(n,t,i),c=await R(r.settings_root),d=await V(r.selected_root);o.push(...d.warnings);let l=await ue(r.selected_root,a,c,d.state);o.push(...l.warnings);let u=await Ei(l.extensions,s);if(!u)throw new _(`Installed extension "${s}" was not found in ${a} scope.`,y.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},pu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:a,managedStateRead:r,candidate:o}=await Di(e),i=ae.join(t.selected_root,o.directory);await Ce.rm(i,{recursive:!0,force:!0});let s={...r.state,updated_at:A(),entries:r.state.entries.filter(d=>k(d.name)!==k(o.name)&&k(d.directory)!==k(o.directory))};await De(t.selected_root,s);let c=xl(a,o.name);return c&&await Ut(t.settings_root,a,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:i,settings_changed:c})},wi=async e=>{let{action:t,resolvedRoots:n,warnings:a,global:r,withResult:o}=e,{settings:i,candidate:s}=await Di(e),c=t==="activate"?Ti(i,s.name):kl(i,s.name);c&&await Ut(n.settings_root,i,"settings:write");let d=t==="activate"?await Oi(n.pm_root,ae.dirname(n.selected_root),i,[s],r).then(l=>(a.push(...l.warnings),Ri(s.name,l.activation_failures,e.scope))):void 0;return d&&a.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:[...i.extensions.enabled],disabled:[...i.extensions.disabled]}},d===void 0)},fu=(e,t,n,a,r,o)=>{let i=a==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[i],c=r?.adopted_entries.length??0,d=[[o!==null,o??""],[t>0,`Run pm ${i} explore --project and pm ${i} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${i} ${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))]},ta=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),hu=(e,t,n,a)=>{if(e!=="project"||t||!ta(a))return null;let r=n==="package"?"package":"extension";return`Global ${r} registrations are included in project diagnostics. For hermetic ${r} smoke tests, rerun pm ${r} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},gu=(e,t,n)=>{if(String(e??"").trim().length>0)throw new _('Action "doctor" does not accept a target argument.',y.USAGE);let a=[n.isolated,n.ignoreGlobal].includes(!0);if([a,t==="global"].every(Boolean))throw new _("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",y.USAGE);let r=Vo(n.detail),o=n.trace===!0;if([o,r!=="deep"].every(Boolean))throw new _("--trace requires --detail deep with --doctor.",y.USAGE);return{isolated:a,detailMode:r,includeTrace:o}},_u=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let a=await na(e.resolvedRoots.selected_root,e.scope,t,n);return{state:a.state,fix:a}},yu=(e,t,n,a)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:ta(a),rerun_command:null,pm_global_path_recipe:null};let o=`pm ${r} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:ta(a),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},wu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:r,options:o,global:i,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=gu(t,n,o),u=await R(a.settings_root),m=await V(a.selected_root);r.push(...m.warnings);let h=await ue(a.selected_root,n,u,m.state);r.push(...h.warnings);let{state:f,fix:p}=await _u(e,h.extensions,m.state),g=await ue(a.selected_root,n,u,f);r.push(...g.warnings);let w=await se({pmRoot:a.pm_root,settings:u,cwd:process.cwd(),noExtensions:i.noExtensions===!0,ignoreGlobalExtensions:c}),v=await ce({...w,loaded:w.loaded});r.push(...w.warnings),r.push(...Go(w.failed)),r.push(...v.warnings),r.push(...Ho(v.failed)),r.push(...Bo(w,v)),r.push(...di(v,w)),r.push(...Jl(w,v)),r.push(...li(v));let x=Zt(g.extensions,w,v),I=Yo(n,x,w.loaded.map(C=>({layer:C.layer,name:C.name})),w.failed.map(C=>({name:C.name})),w.disabled_by_flag);r.push(...I.warnings);let b=x.filter(C=>C.update_check_status==="failed").map(C=>`extension_update_check_failed:${C.name}`);r.push(...b);let T=en(n,r,x,o);r.push(...T.warnings);let J=[...T.warnings],W={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},S=_t(J),L=yt(),ke=T.warning_codes,Et=hu(n,c,o.vocabulary,w),at=fu(T.remediation,w.failed.length,v.failed.length,o.vocabulary,p,Et),Le=yu(n,c,o.vocabulary,w),Me={status:T.status,scope:n,warning_count:T.warning_count,warning_codes:ke,total_extensions:x.length,managed_total:x.filter(C=>C.managed).length,enabled_total:x.filter(C=>C.enabled).length,active_total:x.filter(C=>C.active).length,unmanaged_loaded_extension_count:T.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:T.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:T.unmanaged_expected_extension_count,runtime_active_total:x.filter(C=>C.runtime_active===!0).length,activation_status_totals:{ok:x.filter(C=>C.activation_status==="ok").length,failed:x.filter(C=>C.activation_status==="failed").length,not_loaded:x.filter(C=>C.activation_status==="not_loaded").length,unknown:x.filter(C=>C.activation_status==="unknown").length},unknown_capability_count:S.length,capability_contract_version:L.version,update_available_total:x.filter(C=>C.update_available===!0).length,update_health_coverage:T.update_health_coverage,update_health_partial:T.update_health_partial,update_check_failed_total:x.filter(C=>C.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Bn(w.failed),activation_failures:Bn(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:I.warnings.length,trace_enabled:l,isolation:Le,policy:W,remediation:at},rt=p?{requested:!0,applied:p.adopted_entries.length>0,adopted_count:p.adopted_entries.length,already_managed_count:p.already_managed_count,adopted_extensions:p.adopted_entries.map(C=>C.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:g.extensions.filter(C=>C.managed).length,adopted_extensions:[]},Fe={mode:d,summary:Me,triage:T,trace_enabled:l,capability_contract:L,capability_guidance:S,managed_state_fix:rt,isolation:Le,policy:w.policy};if(d==="deep"){let C=l?v.failed:v.failed.map(D=>{let{trace:ya,...ot}=D;return ot});Fe.deep={warnings:J,warning_codes:ke,capability_contract:L,capability_guidance:S,trace_enabled:l,managed_state:{path:m.path,count:f.entries.length,entries:f.entries},installed_extensions:x,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(D=>({layer:D.layer,directory:D.directory,name:D.name,version:D.version,entry:D.entry,priority:D.priority}))},activation:{failed:C,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:I.summary},l&&(Fe.deep.trace={activation_failures:v.failed.filter(D=>D.trace!==void 0).map(D=>({layer:D.layer,name:D.name,entry_path:D.entry_path,error:D.error,method:D.trace.method,command:D.trace.command,capability:D.trace.capability,missing_capability:D.trace.missing_capability,registration_index:D.trace.registration_index,expected_schema:D.trace.expected_schema,hint:D.trace.hint,received:D.trace.received}))})}return s(Fe)},vu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:r,options:o,global:i,withResult:s}=e,c=await R(a.settings_root),d=await se({pmRoot:a.pm_root,settings:c,cwd:process.cwd(),noExtensions:i.noExtensions===!0}),l=await ce(d);r.push(...d.warnings),r.push(...l.warnings);let u=Fo(t,d,l);if(t!==void 0&&u.extensions.length===0){let m=o.vocabulary==="package"?"package":"extension",h=[...new Set(d.loaded.map(p=>o.vocabulary==="package"&&typeof p.source_package=="string"&&p.source_package.trim().length>0?p.source_package.trim():p.name))].sort((p,g)=>p.localeCompare(g)),f=h.length>0?` Loaded ${m} names: ${h.join(", ")}.`:"";throw new _(`No loaded ${m} named "${t}" was found in ${n} scope.${f} Run pm ${m} explore to list discovered ${m}s.`,y.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},bu=async(e,t,n)=>{let a=n,r=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await na(e.resolvedRoots.selected_root,e.scope,t,n),a=r.state),e.action==="manage"){let o=await si(a.entries,ll,async i=>{if(i.source.kind!=="github")return i;let s=await ui(i.source);return{...i,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});a={...a,updated_at:A(),entries:ut(o)},await De(e.resolvedRoots.selected_root,a)}return{state:a,fix:r}},ku=async(e,t,n)=>{let a=await se({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await ce({...a,loaded:a.loaded});return e.warnings.push(...a.warnings,...r.warnings),{installed:Zt(n,a,r),failures:Ci(r.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:a.failed.length,activation_failure_count:r.failed.length,warning_count:[...new Set([...a.warnings,...r.warnings])].length,policy:a.policy}}},xu=(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},vi=async e=>{let{action:t,scope:n,resolvedRoots:a,warnings:r,options:o,withResult:i}=e,s=await R(a.settings_root),c=bl(s.extensions.policy),d=await V(a.selected_root);r.push(...d.warnings);let l=await ue(a.selected_root,n,s,d.state);r.push(...l.warnings);let{state:u,fix:m}=await bu(e,l.extensions,d.state),h=await ue(a.selected_root,n,s,u);if(r.push(...h.warnings),t==="manage"){let v=h.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);r.push(...v)}let f=await ku(e,s,h.extensions),p=f.installed,g=en(n,r,p,o);r.push(...g.warnings);let w={total:p.length,managed_total:p.filter(v=>v.managed).length,enabled_total:p.filter(v=>v.enabled).length,active_total:p.filter(v=>v.active).length,extensions:p,triage:g,policy:c};return f.failures!==void 0&&(w.activation_diagnostics={failed_count:f.failures.length,failed:f.failures}),t==="explore"&&(w.runtime_probe=f.summary),t==="manage"&&(w.runtime_probe=f.summary,w.managed_state_fix=xu(m,p)),i(w)},bi={init:Vl,install:du,uninstall:pu,explore:vi,manage:vi,describe:vu,reload:Kl,doctor:wu,catalog:Yl,adopt:mu,"adopt-all":lu,activate:wi,deactivate:wi,migrate:fi},Su=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),Eu=e=>Su(e)?Xn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>bi[e.action](e)):bi[e.action](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]="cdfc451a-1148-50c5-934a-cd8bc2bb39e7")}catch{}})();var Au=Iu($u),Cu="@unbrained/pm-cli",Ru="latest";function Ou(e){let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new _('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"}function rn(e){return e.trim().toLowerCase()}function Pi(e,t){let n=rn(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(r=>typeof r=="string"&&rn(r)===n)}function Nu(e,t){let n=P(process.cwd(),t.path),a=Ue(n,process.cwd());return{selected_root:e==="global"?a.global:a.project}}async function Du(e,t,n){try{let a=await Au(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:a.stdout,stderr:a.stderr}}catch(a){let r=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr??""):"",o=r.trim().length>0?r.trim():a instanceof Error?a.message:String(a);throw new _(`Command failed: ${e} ${t.join(" ")}
23
+ ${o}`,y.GENERIC_FAILURE)}}async function Pu(){return Sa(import.meta.url,["../../.."])}function on(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():Ru}function an(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():Cu}async function ju(e,t){let n=e.commandRunner??Du,a=an(e),r=on(e),o=`${a}@${r}`,i=["npm","install","-g",o];e.repair===!0&&i.push("--force");let s=await Pu(),c={requested:!0,status:"planned",package:a,target:o,command:i,before_version:s,repair:e.repair===!0};if(t)return c;try{await n(i[0],i.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 Lu(e){return Tu.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function Mu(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!Lu(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 Fu(e,t){let n=Mu(e,t);return e.kind!=="local"||await E(n)?n:await E(e.location)?e.location:n}function Uu(e,t,n,a){let r=["pm","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&a&&a.trim().length>0&&r.push("--ref",a.trim()),r}async function ji(e,t){let n=Nu(e,t);return(await V(n.selected_root)).state.entries.filter(r=>r.scope===e)}async function zu(e,t,n){let a=await ji(e,t);return a.find(r=>Pi(r,n.name))??a.find(r=>rn(r.directory)===rn(n.directory))}async function Ju(e,t,n,a,r){let o=on(t),i=await Fu(e.source,o),s=Uu(e.source,i,a,e.source.ref),c={name:e.name,directory:e.directory,scope:a,source:e.source,status:"planned",command:s,previous_version:e.manifest_version};if(r)return c;try{await aa(i,{install:!0,project:a==="project",global:a==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await zu(a,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 Wu(e,t,n,a){let r=[n?e.status:void 0,...t.map(o=>o.status)].filter(o=>typeof o=="string");return{requested_cli:n,requested_packages:a,planned:r.filter(o=>o==="planned").length,updated:r.filter(o=>o==="updated").length,skipped:r.filter(o=>o==="skipped").length,failed:r.filter(o=>o==="failed").length}}async function q_(e,t,n){if(t.cliOnly===!0&&t.packagesOnly===!0)throw new _('Options "--cli-only" and "--packages-only" are mutually exclusive.',y.USAGE);let a=Ou(t),r=t.dryRun===!0,o=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&o)throw new _('A package target cannot be used with "--cli-only".',y.USAGE);let i=!(t.packagesOnly===!0||o),s=t.cliOnly!==!0,c=i?await ju(t,r):{requested:!1,status:"skipped",package:an(t),target:`${an(t)}@${on(t)}`,command:["npm","install","-g",`${an(t)}@${on(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await ji(a,n):[];if(o&&(d=d.filter(m=>Pi(m,o)),d.length===0))throw new _(`Managed package "${o}" was not found in ${a} scope.`,y.NOT_FOUND);let l=[];for(let m of d)l.push(await Ju(m,t,n,a,r));let u=Wu(c,l,i,s);return{ok:u.failed===0,action:"upgrade",dry_run:r,scope:a,target:o,cli:c,packages:l,summary:u}}import Qe from"node:fs/promises";import ln from"node:path";import sn from"node:fs/promises";import ra 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]="8cc32963-26eb-5e08-bffb-2d8da152a43f")}catch{}})();var qu=864e5;function cn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Gu(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 Hu(e,t){let n;try{n=await sn.readdir(e,{withFileTypes:!0})}catch(r){if(cn(r,"ENOENT"))return[];throw r}let a=[];for(let r of n)if(r.isDirectory()){let o=ra.join(e,r.name),i;try{i=await sn.readdir(o)}catch(s){cn(s,"ENOENT")||t.push(`checkpoint_subdir_unreadable:${r.name}`);continue}for(let s of i)s.endsWith(".json")&&a.push(`${r.name}/${s}`)}else r.name.endsWith(".json")&&a.push(r.name);return a.sort()}async function Li(e,t){let{dryRun:n,hooks:a}=t,r=t.now??Date.now(),o=Math.max(0,t.retentionDays)*qu,i=ra.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await Hu(i,s.warnings);for(let d of c){let l=ra.join(i,d),u=`checkpoints/${d}`;s.scanned+=1,a?.onRead&&s.warnings.push(...await a.onRead(l));let m;try{m=await sn.readFile(l,"utf8")}catch(w){if(cn(w,"ENOENT")){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 h=Gu(m),f=h===null?Number.NaN:Date.parse(h);if(!Number.isFinite(f)){s.warnings.push(`checkpoint_unparseable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:h,age_seconds:null,stale:!1,reason:"unparseable"});continue}let p=r-f,g={file:u,created_at:h,age_seconds:Math.floor(p/1e3),stale:p>o,reason:p>o?"expired":"active"};if(!g.stale){s.retained.push(u),s.entries.push(g);continue}if(!n){try{await sn.unlink(l)}catch(w){if(!cn(w,"ENOENT")){s.warnings.push(`checkpoint_remove_failed:${d}`),s.retained.push(u),s.entries.push(g);continue}}a?.onWrite&&s.warnings.push(...await a.onWrite(l))}s.removed.push(u),s.entries.push(g)}return s}import oa from"node:fs/promises";import Mi 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]="a6c0aa24-501a-5e76-a669-91d125634cf1")}catch{}})();var Bu=1440*60*1e3,Vu=new Set(["committed","compensated"]);function Ku(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Yu(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 Xu(e,t,n,a,r){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 i=a-o;return Vu.has(t)?i>r?{entry:{file:e,status:t,age_seconds:Math.floor(i/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(i/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(i/1e3),stale:!1,reason:"active"},remove:!1}}async function Qu(e,t,n,a){let r=a.hooks?.onRead?await a.hooks.onRead(e):[],o=Yu(await oa.readFile(e,"utf8")),i=Xu(t,o.status,o.updatedAt,a.nowMs,a.retentionMs);return i.entry.reason==="unparseable"&&r.push(`transaction_journal_unparseable:${n}`),i.remove&&!a.dryRun&&(await oa.rm(e,{force:!0}),a.hooks?.onWrite&&r.push(...await a.hooks.onWrite(e))),{decision:i,warnings:r}}async function Fi(e,t){let{dryRun:n,hooks:a}=t,r=t.now??Date.now(),o=Math.max(0,t.retentionDays)*Bu,i=Mi.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await oa.readdir(i)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(Ku(d,"ENOENT"))return s;throw d}for(let d of c){let l=Mi.join(i,d),u=`transactions/sdk/${d}`,m=await Qu(l,u,d,{dryRun:n,hooks:a,nowMs:r,retentionMs:o});s.warnings.push(...m.warnings),s.scanned+=1;let{decision:h}=m;if(!h.remove){s.retained.push(u),s.entries.push(h.entry);continue}s.removed.push(u),s.entries.push(h.entry)}return s}import vt from"node:fs/promises";import dn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a026943f-1a46-526b-bfaa-435025c65c2a")}catch{}})();function Zu(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:a,owner:r,created_at:o,ttl_seconds:i}=n;return typeof a!="string"||typeof r!="string"||typeof o!="string"||typeof i!="number"||!Number.isFinite(i)?null:{id:a,owner:r,created_at:o,ttl_seconds:i}}function bt(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Ui(e,t,n){let a=Zu(t);if(a===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let r=Date.parse(a.created_at);if(!Number.isFinite(r))return{detail:"invalid_timestamp",entry:{file:e,id:a.id,owner:a.owner,created_at:a.created_at,ttl_seconds:a.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let o=n-r,i=Math.floor(o/1e3),s=o>a.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:a.id,owner:a.owner,created_at:a.created_at,ttl_seconds:a.ttl_seconds,age_seconds:i,stale:s,reason:s?"expired":"active"}}}async function zi(e,t){let n=t??Date.now(),a=dn.join(e,"locks"),r={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await vt.readdir(a)).filter(s=>s.endsWith(".lock")).sort()}catch(i){if(bt(i,"ENOENT"))return r;throw i}for(let i of o){let s;try{s=await vt.readFile(dn.join(a,i),"utf8")}catch(d){if(bt(d,"ENOENT"))continue;r.scanned+=1,r.unreadable_lock_count+=1;continue}r.scanned+=1;let{detail:c}=Ui(i,s,n);c==="active"?r.active_lock_count+=1:c==="expired"?r.stale_lock_count+=1:r.unparseable_lock_count+=1}return r}async function Ji(e,t){let{dryRun:n,hooks:a}=t,r=t.now??Date.now(),o=dn.join(e,"locks"),i={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await vt.readdir(o)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if(bt(c,"ENOENT"))return i;throw c}for(let c of s){i.scanned+=1;let d=dn.join(o,c),l=`locks/${c}`;if(a?.onRead){let h=await a.onRead(d);i.warnings.push(...h)}let u;try{u=await vt.readFile(d,"utf8")}catch(h){if(bt(h,"ENOENT")){i.scanned-=1;continue}i.warnings.push(`lock_unreadable:${c}`),i.retained.push(l),i.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=Ui(c,u,r);if(m.detail==="unparseable_json"){i.warnings.push(`lock_unparseable:${c}`),i.retained.push(l),i.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){i.warnings.push(`lock_invalid_timestamp:${c}`),i.retained.push(l),i.entries.push(m.entry);continue}if(m.detail==="active"){i.retained.push(l),i.entries.push(m.entry);continue}if(!n){try{await vt.unlink(d)}catch(h){if(!bt(h,"ENOENT")){i.warnings.push(`lock_remove_failed:${c}`),i.retained.push(l),i.entries.push(m.entry);continue}}if(a?.onWrite){let h=await a.onWrite(d);i.warnings.push(...h)}}i.removed.push(l),i.entries.push(m.entry)}return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0973a87f-2b63-5fa1-9624-82897d181f71")}catch{}})();var kt=["index","embeddings","runtime","locks","checkpoints","transactions"],em=1440*60*1e3,tm=[{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"}];function Wi(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function nm(e,t,n){let a=t.relativePath,r=ln.join(e,a),o=await pe({path:r,scope:"project"});try{let i=await Qe.stat(r);if(t.kind==="file"&&!i.isFile())return{removed:!1,warnings:[...o,`not_a_file:${a}`]};if(t.kind==="directory"&&!i.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${a}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await Qe.unlink(r):await Qe.rm(r,{recursive:!0,force:!0});let s=await U({path:r,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...s]}}catch(i){if(Wi(i,"ENOENT"))return{removed:!1,warnings:o};throw i}}async function am(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],a=[],r=[],o=[],i=Date.now()-em;for(let s of n){let c=ln.join(e,s.relativePath);if(!await E(c))continue;let d=(await Qe.readdir(c)).filter(l=>l.startsWith(s.prefix)).sort();for(let l of d){let u=ln.posix.join(s.relativePath,l),m=ln.join(c,l);o.push(...await pe({path:m,scope:"project"}));let h=await Qe.stat(m).catch(f=>{if(!Wi(f,"ENOENT"))throw f});if(h){if(h.mtimeMs>i){r.push(u);continue}a.push(u),!t&&(await Qe.rm(m,{recursive:!0,force:!0}),o.push(...await U({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:a,retained:r,warnings:o}}function rm(e){if(!e||e.length===0)return[...kt];let t=e.flatMap(a=>a.split(",")).map(a=>a.trim().toLowerCase()).filter(a=>a.length>0);if(t.length===0)throw new _(`--scope requires at least one value (${kt.join(",")})`,y.USAGE);let n=new Set;for(let a of t){if(!kt.includes(a))throw new _(`Invalid --scope value "${a}". Expected one or more of: ${kt.join(", ")}`,y.USAGE);n.add(a)}return kt.filter(a=>n.has(a))}function om(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"),a=e.removed.some(r=>r==="index/manifest.json"||r==="search/embeddings.jsonl"||r==="search/vectorization-status.json"||r==="search/lancedb"||r==="search/pending-refresh.json"||r==="search/pending-refresh.gate.lock");return n&&a&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(r=>r.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(r=>r.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function py(e,t={}){let n=P(process.cwd(),e.path);if(!await E(te(n)))throw new _(`Tracker is not initialized at ${n}. Run pm init first.`,y.NOT_FOUND);let a=await R(n),r=t.dryRun===!0,o=rm(t.scope),i=tm.filter(f=>o.includes(f.scope)),s=[],c=[],d=[];for(let f of i){let p=await nm(n,f,r);p.removed?s.push(f.relativePath):c.push(f.relativePath),d.push(...p.warnings)}if(o.includes("runtime")){let f=await am(n,r);s.push(...f.removed),c.push(...f.retained),d.push(...f.warnings)}let l;if(o.includes("locks")){let f=await Ji(n,{dryRun:r,hooks:{onRead:p=>pe({path:p,scope:"project"}),onWrite:p=>U({path:p,scope:"project",op:"gc:lock_remove"})}});s.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),l={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length}}let u;if(o.includes("transactions")){let f=a.checkpoints.retention_days,p=await Fi(n,{dryRun:r,retentionDays:f,hooks:{onRead:g=>pe({path:g,scope:"project"}),onWrite:g=>U({path:g,scope:"project",op:"gc:transaction_journal_remove"})}});s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),u={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length,retention_days:f}}let m;if(o.includes("checkpoints")){let f=a.checkpoints.retention_days,p=await Li(n,{dryRun:r,retentionDays:f,hooks:{onRead:g=>pe({path:g,scope:"project"}),onWrite:g=>U({path:g,scope:"project",op:"gc:checkpoint_remove"})}});s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),m={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length,retention_days:f}}d.push(...await Lt({mode:r?"gc:dry-run":"gc",total_items:i.length}));let h=om({dryRun:r,scopes:o,removed:s});return{ok:d.length===0,dry_run:r,scope:o,removed:s,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:h,generated_at:A()}}import qi from"node:fs/promises";import Gi 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]="60154e1b-8348-5b6b-badf-e76bba43bef8")}catch{}})();var im=8388608,sm=new Set(["resolved","failed"]),cm=[{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 Ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function dm(e){try{return(await qi.readdir(Gi.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function lm(e,t,n){let a;try{a=await qi.open(Gi.join(e,"history",t),"r");let r=(await a.stat()).size,o=Math.min(r,Math.max(0,n)),i=Buffer.alloc(o),{bytesRead:s}=await a.read(i,0,o,0),c=i.subarray(0,s).toString("utf8"),d=s>=r,l=c.lastIndexOf(`
24
+ `),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:s,complete:d}}catch{return null}finally{await a?.close()}}function um(e){try{let t=JSON.parse(e);return Ze(t)?t:null}catch{return null}}function mm(e,t,n){let a=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(a===void 0)return;let r=Ze(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(r).forEach(([i,s])=>{if(!Ze(s))return;let c=cm.find(u=>u.matches(s.value))?.kind;if(!c)return;let d=`${a}\0${i}\0${c}`,l=n.get(d)??{harness:a,dimension:i,kind:c,count:0};l.count+=1,n.set(d,l)}),!Ze(e.context))return;let o=e.context.agent_provenance_outcomes;Ze(o)&&Object.entries(o).forEach(([i,s])=>{if(!Ze(s)||typeof s.resolver!="string"||!sm.has(String(s.status)))return;let c=`${a}\0${i}\0${s.resolver}`,d=t.get(c)??{harness:a,dimension:i,resolver:s.resolver,attempts:0,successes:0};d.attempts+=1,s.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function pm(e,t,n,a,r){let o=r;for(let i of e.split(`
25
+ `)){if(i.trim().length===0)continue;if(o>=a)return{eventsRead:o,truncated:!0};o+=1;let s=um(i);s&&mm(s,t,n)}return{eventsRead:o,truncated:!1}}async function Hi(e,t=1e4){let n=new Map,a=new Map,r=0,o=0,i=!1;for(let d of await dm(e)){let l=await lm(e,d,Math.max(0,im-o));if(l===null)continue;o+=l.bytesRead;let u=pm(l.content,n,a,t,r);if(r=u.eventsRead,u.truncated){i=!0;break}if(!l.complete){i=!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=[...a.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:i?[]:[...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:r,truncated:i}}import be from"node:fs/promises";import K from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="539b0cb4-5e20-51e2-a33e-1a43ca961f05")}catch{}})();var fm=new Set(Sr),Vi=25,xt=8,hm=K.join("runtime","telemetry","events.jsonl"),gm=K.join("runtime","telemetry","state.json"),_m=2500,ym=500,Ki=xr-3,wm=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Yi(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Xi(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function tt(e){return e.trim().toLowerCase()}function ca(e,t){let n=tt(e),a=tt(t);return n.startsWith("builtin-")?!0:a==="beads"||a==="todos"}async function ua(e){try{return(await be.stat(e)).isDirectory()}catch{return!1}}async function vm(e){let t=(await be.readdir(e,{withFileTypes:!0})).filter(a=>a.isDirectory()),n=await Promise.all(t.map(a=>be.readdir(K.join(e,a.name),{withFileTypes:!0})));return new Set(n.flatMap(a=>a.filter(r=>r.isFile()).filter(r=>pn.some(o=>r.name.endsWith(o))).map(r=>K.parse(r.name).name)))}async function bm(e,t,n,a){let r=await pe({path:e,scope:"project"}),o=t!=="_workspace"&&!a.has(t);if(!n.enabled&&!o)return{warnings:r,overThreshold:!1,classification:"live"};let i;try{i=await be.readFile(e,"utf8")}catch{return{warnings:r,overThreshold:!1,classification:"unreadable"}}let s="live";if(o){let d=i.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?i.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:r,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function km(e,t,n){let a=K.join(e,"history");if(!await ua(a))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let r=(await be.readdir(a)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),i=t.enabled?t.max_entries:null,s=[],c=[],d=[],l=[];for(let u of r){let m=K.join(a,u),h=u.slice(0,-6),f=await bm(m,h,t,n);s.push(...f.warnings),f.classification==="tombstone"&&d.push(h),f.classification==="orphaned"&&l.push(h),f.overThreshold&&c.push(h)}return{count:r.length,warnings:[...s,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:i,tombstones:d,orphaned:l}}function da(e,t){return K.relative(e,t).replaceAll("\\","/")}async function Qi(e,t){let n=[...new Set(Object.values(t))].sort((r,o)=>r.localeCompare(o)),a=[];for(let r of n){let o=K.join(e,r),i=[];try{i=await be.readdir(o)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")continue;continue}for(let s of i)pn.some(c=>s.toLowerCase().endsWith(c))&&a.push(K.join(o,s))}return a.sort((r,o)=>da(e,r).localeCompare(da(e,o))),a}function xm(e){return!(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")}async function Sm(e,t,n){let a=await Qi(e,t),r=[],o=[],i=[],s=[],c=It(M());for(let d of a){let l=da(e,d),u;try{u=await be.readFile(d,"utf8")}catch{r.push(l);continue}let m=vn(u);if(m){o.push({path:l,...m});continue}try{let h=Mt(u,{format:Ta(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:Ya(h.metadata)})}catch{i.push(l)}}return{paths:a,unreadable:r,conflictMarkers:o,parseFailures:i,formatVersions:s}}async function Em(e){let t=K.join(e,"history"),n=[],a=[],r=[],o=[];try{o=(await be.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,s)=>i.localeCompare(s))}catch(i){xm(i)&&n.push("history")}for(let i of o){let s=i.slice(0,-6),c;try{c=await be.readFile(K.join(t,i),"utf8")}catch{n.push(s);continue}let d=vn(c);if(d){a.push({id:s,...d});continue}c.split(/\r?\n/).forEach((l,u)=>{if(l.trim())try{JSON.parse(l)}catch{r.push({id:s,line:u+1})}})}return{files:o,unreadable:n,conflictMarkers:a,invalidJson:r}}async function $m(e,t,n,a){let r=await Sm(e,t,n),o=await Em(e),i=Xa(r.formatVersions),s=await Rr(e),c=await Er(e),d=c===null?null:await $r(c),l=c===null?[]:await Or(c,{includeLossless:!0,pmRoot:e}),{pendingDecisions:u,lossless:m}=Nr(l),h=d?.status==="missing"&&d.missing_keys.length===5&&d.drifted_keys.length===0,f=[...r.unreadable.map(g=>`integrity_item_unreadable:${g}`),...r.conflictMarkers.map(g=>`integrity_item_conflict_marker:${g.path}:L${g.line}`),...r.parseFailures.map(g=>`integrity_item_parse_failed:${g}`),...o.unreadable.map(g=>`integrity_history_unreadable:${g}`),...o.conflictMarkers.map(g=>`integrity_history_conflict_marker:${g.id}:L${g.line}`),...o.invalidJson.map(g=>`integrity_history_invalid_json:${g.id}:L${g.line}`),...i.outdated.map(g=>`integrity_item_outdated_format_version:${g}`),...i.ahead.map(g=>`integrity_item_ahead_format_version:${g}`),...s.tracked_path_count>0?[`tracked_runtime_cache_files:${s.tracked_path_count}`]:[],...d!==null&&d.status!=="ok"?[`merge_driver_configuration_${h?"missing":"drift"}:${d.missing_keys.length+d.drifted_keys.length}`]:[],...u.length>0?[`merge_decisions_unreviewed:${u.length}`]:[]],p=[...new Set(f)].sort((g,w)=>g.localeCompare(w));return{check:{name:"integrity",status:p.length===0?"ok":"warn",details:{checked_item_files:r.paths.length,checked_history_streams:o.files.length,counts:{item_unreadable:r.unreadable.length,item_conflict_markers:r.conflictMarkers.length,item_parse_failures:r.parseFailures.length,history_unreadable:o.unreadable.length,history_conflict_markers:o.conflictMarkers.length,history_invalid_json:o.invalidJson.length,item_outdated_format_version:i.outdated.length,item_ahead_format_version:i.ahead.length,tracked_runtime_cache_files:s.tracked_path_count,merge_driver_configuration:d===null||d.status==="ok"?0:d.missing_keys.length+d.drifted_keys.length,pending_merge_decisions:u.length,lossless_merge_receipts:m.length},item_unreadable:r.unreadable,item_conflict_markers:r.conflictMarkers,item_parse_failures:r.parseFailures,item_outdated_format_version:i.outdated,item_ahead_format_version:i.ahead,history_unreadable:o.unreadable,history_conflict_markers:o.conflictMarkers,history_invalid_json:o.invalidJson,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},merge_driver_configuration:d===null?null:{...d,required:a},pending_merge_decision_items:[...new Set(u.map(g=>g.item_id))].sort((g,w)=>g.localeCompare(w)),lossless_merge_receipt_items:[...new Set(m.map(g=>g.item_id))].sort((g,w)=>g.localeCompare(w))}},warnings:p}}function Tm(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function Im(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:Tm(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Am(e,t){let n=Se(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Cm(e){let n=Se(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function Rm(e){return Se(e.reason)??Se(e.error)??Se(e.message)}function ia(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let a=(e.name??"").localeCompare(t.name??"");return a!==0?a:(e.id??"").localeCompare(t.id??"")}function Om(e){let t=[],n=[],a=[];e.forEach((o,i)=>{let s=Am(o.definition,i),c=Cm(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:s,status:c});return}if(c==="failed"){a.push({layer:o.layer,name:o.name,id:s,status:c,reason:Rm(o.definition)});return}n.push({layer:o.layer,name:o.name,id:s,status:c})}),t.sort(ia),n.sort(ia),a.sort(ia);let r=[...a.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:a,applied_count:t.length,pending_count:n.length,failed_count:a.length},warnings:r}}function Zi(e,t,n,a,r,o,i,s,c){let d=[...new Set(e)].sort((g,w)=>g.localeCompare(w)),l=[...new Set(d.map(g=>Xi(g)))].sort((g,w)=>g.localeCompare(w)),u=d.filter(g=>g.startsWith("extension_capability_unknown:")).length,m=c.length>0,h=m?"partial":"full",f=[],p=Vn(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return p&&f.push(p),t>0&&f.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&f.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(a.failed_count>0||a.pending_count>0)&&f.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),r>0&&f.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&f.push(`Unknown extension capabilities detected. Allowed capabilities: ${$t.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(g=>g.startsWith("extension_capability_legacy_alias:"))&&f.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(g=>g.startsWith("extension_command_definition_legacy_handler_alias:"))&&f.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?f.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):i.length>0&&f.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),f.length===0&&f.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:a.failed_count,migration_pending_count:a.pending_count,managed_state_warning_count:r,managed_extension_entries_count:o,unmanaged_loaded_extension_count:i.length,unmanaged_loaded_extensions:i,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:h,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:f}}async function Nm(e,t,n){let a=await se({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),r=a.loaded.map(b=>Im(b)),o=await ce({...a,loaded:a.loaded}),[i,s]=await Promise.all([V(a.roots.project),V(a.roots.global)]);await Zn(e,o.registrations.migrations);let c=Om(o.registrations.migrations),d={failed:o.failed,warnings:o.warnings,hook_counts:o.hook_counts,command_override_count:o.command_override_count,command_handler_count:o.command_handler_count,parser_override_count:o.parser_override_count,preflight_override_count:o.preflight_override_count,service_override_count:o.service_override_count,renderer_override_count:o.renderer_override_count,registration_counts:o.registration_counts,registrations:o.registrations,migration_status:c.summary,managed_extensions:{project:{path:i.path,count:i.state.entries.length,entries:i.state.entries},global:{path:s.path,count:s.state.entries.length,entries:s.state.entries}}},l=new Set(i.state.entries.map(b=>tt(b.name))),u=new Set(s.state.entries.map(b=>tt(b.name))),m=[...new Map(a.loaded.filter(b=>!(b.layer==="project"?l:u).has(tt(b.name))).map(b=>[`${b.layer}:${b.name}`,{layer:b.layer,name:b.name,directory:b.directory}])).values()].sort((b,T)=>{let J=`${b.layer}:${b.name}`,W=`${T.layer}:${T.name}`;return J.localeCompare(W)}),h=m.map(b=>`${b.layer}:${b.name}`).sort((b,T)=>b.localeCompare(T)),f=m.filter(b=>ca(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,T)=>b.localeCompare(T)),p=m.filter(b=>!ca(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,T)=>b.localeCompare(T)),g=p.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${p.length}`]:[],w=[...a.warnings,...d.warnings,...c.warnings,...i.warnings,...s.warnings,...g],v=_t(w),x=yt(),I=Zi(w,a.failed.length,o.failed.length,c.summary,i.warnings.length+s.warnings.length,i.state.entries.length+s.state.entries.length,h,f,p);return{check:{name:"extensions",status:w.length===0?"ok":"warn",details:{...a,loaded:r,warnings:w,activation:d,triage:I,...c.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:v}},warnings:w}}function Dm(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function ve(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function Pm(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 un(e,t){let n=ve(e,t);return{...n,sample:n.sample.map(a=>Pm(a))}}function j(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(a=>typeof a=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function jm(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 Lm={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:j(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:j(e.missing_required,t),missing_optional:j(e.missing_optional,t),missing:j(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:j(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:un(e.discovered,t),effective:un(e.effective,t),loaded:un(e.loaded,t),failed:ve(e.failed,t),warnings:j(e.warnings,t),activation:{failed:ve(n.failed,t),warnings:j(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:jm(n.migration_status)},triage:e.triage,capability_contract:e.capability_contract,capability_guidance:ve(e.capability_guidance,t)}},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:j(n.affected_item_ids,t),samples:ve(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:j(e.item_unreadable,t),item_conflict_markers:ve(e.item_conflict_markers,t),item_parse_failures:j(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:j(n.tracked_paths,t)},history_unreadable:j(e.history_unreadable,t),history_conflict_markers:ve(e.history_conflict_markers,t),history_invalid_json:ve(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>({checked_items:e.checked_items,counts:e.counts,drifted_items:j(e.drifted_items,t),missing_streams:j(e.missing_streams,t),unreadable_streams:j(e.unreadable_streams,t),hash_mismatches:j(e.hash_mismatches,t),chain_mismatches:j(e.chain_mismatches,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:j(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:j(e.stale_items_after,t),skipped:e.skipped})};function es(e,t){let n=Lm[e.name];return n?n(e.details,t):e.details}function Mm(e){let t=j(e.warnings,xt);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,details:es(n,xt)})),warnings:t.sample,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:xt},generated_at:e.generated_at}}function Bi(e){return e.details.skipped===!0}function Fm(e){let t=j(e.warnings,xt),n=e.checks.filter(Bi).map(a=>a.name);return{ok:e.ok,checks:e.checks.filter(a=>!Bi(a)).map(a=>({name:a.name,status:a.status,details:{}})),warning_count:t.count,warnings:t.sample,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:xt,omitted_checks:n},generated_at:e.generated_at}}function la(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Dm(e,Vi);return{values:n.values,truncated:n.truncated,total:e.length}}function et(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Um(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return fm.has(e)?e:null}function mn(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 ts(e){let t=0,n=0,a=0,r=0,o=0;for(let i of e.split(`
26
+ `)){let s=i.trim();if(s.length!==0){a+=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>=Ki&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:a,highRetryEntries:r,maxAttempts:o}}function zm(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Jm(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 Wm(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await ns(n)}}function qm(e,t,n){let a=[];if(t.invalidRows>0&&a.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return a;let r=n.last_successful_flush_at,o=n.last_failed_flush_at,i=o&&(!r||o>r),s=!r,c=t.validEntries>=ym;return(i||s||c)&&a.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&a.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),a}function Gm(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function Hm(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>kr?[`telemetry_schema_version_behind:${t}`]:[]}function Bm(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,a=t.last_otel_success_at,r=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!r&&(!a||r>=a)?[`telemetry_otel_export_failing:${n}`]:[]}function Vm(){return{telemetry_disabled:et("PM_TELEMETRY_DISABLED")||et("PM_NO_TELEMETRY"),pm_no_telemetry:et("PM_NO_TELEMETRY"),telemetry_otel_disabled:et("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:et("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:Um()}}function Km(e,t){return e.telemetry.enabled&&t.validEntries>0}function Ym(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function ns(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(_m)});return{probe_url:mn(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let a of wm){let r=n.headers.get(a)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:mn(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function Xm(e,t){let n=At(process.cwd()),a=K.join(n,hm),r=K.join(n,gm),o=await q(a),i=o!==null,s=o?Buffer.byteLength(o,"utf8"):0,c=o?ts(o):zm(),d=await q(r),{runtimeState:l,stateParseFailed:u}=Jm(d),m=e.telemetry.endpoint.trim(),h=mn(m),f=await Wm(e,t.checkTelemetry),p=[];u&&p.push("telemetry_state_invalid_json"),p.push(...qm(e,c,l),...Gm(f),...Hm(f),...Bm(e,l));let g=Km(e,c),w=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:p.length===0?"ok":"warn",details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:h,global_pm_root:n,queue_path:a,queue_exists:i,queue_entries:c.validEntries,queue_draining:Ym(g,p),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Ki,queue_max_attempts:c.maxAttempts,runtime_state_path:r,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans: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:f??{attempted:!1},env_overrides:Vm()}},warnings:p}}async function Qm(e){let t;try{t=await zi(e)}catch(a){let r=a instanceof Error?a.message:String(a);return{check:{name:"locks",status:"warn",details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:r,pm_root:e}},warnings:[`locks_scan_failed:${r}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",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 Zm(e,t){let n="metadata",{missingStreams:a,unreadableStreams:r,hashMismatches:o,chainMismatches:i,driftedItems:s}=await Ir(e,t,{cacheHitVerification:n}),c=[...a.map(d=>`history_drift_missing_stream:${d}`),...r.map(d=>`history_drift_unreadable_stream:${d}`),...o.map(d=>`history_drift_hash_mismatch:${d}`),...i.map(d=>`history_drift_chain_mismatch:${d}`)];return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,cache_hit_verification:n,drifted_items:s,counts:{drifted:s.length,missing_streams:a.length,unreadable_streams:r.length,hash_mismatches:o.length,chain_mismatches:i.length},missing_streams:a,unreadable_streams:r,hash_mismatches:o,chain_mismatches:i}},warnings:c}}function ep(e,t){let n=zt(e),a=st(n.settings),r=Jt(n.settings,t),o=a.active?Re(a.active.name,a.active.model):null;return{runtimeDefaults:n,providerResolution:a,vectorStoreResolution:r,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(a.active&&r.active)}}function tp(){return{refreshed:[],skipped:[],warnings:[]}}async function np(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?tp():wr(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function ap(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Ge(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function rp(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,a)=>n.localeCompare(a))}function op(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function as(e,t){let n=t.providerResolution.active?.name??null,a=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:xn(n,e.search?.provider??null),vector_store_active:a,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:xn(a,e.vector_store?.adapter??null)}}function ip(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function sp(e,t,n){return e.enabled&&n.length>0&&t}async function cp(e,t,n,a,r){let o=ep(t,e),i=await He(e),s=o.semanticRuntimeAvailable?$n(n,i.entries):[],c=await np({pmRoot:e,snapshot:o,refreshPolicy:a,staleBefore:s}),d=await He(e),l=o.semanticRuntimeAvailable?$n(n,d.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,m=ap({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:i,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),h=rp({ledgerBefore:i,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),f=la(s,r),p=la(l,r),g=sp(a,o.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:h.length===0?"ok":"warn",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:ip(a),...as(t,o),embedding_identity_changed:m,embedding_identity_before:i.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(i.entries).length,stale_items_detail_mode:r?"full":"summary",stale_items_summary_limit:Vi,stale_items_before_total:f.total,stale_items_before:f.values,stale_items_before_truncated:f.truncated,refresh_attempted:g,refresh_skipped_reason:op(a,o.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:p.total,stale_items_after:p.values,stale_items_after_truncated:p.truncated}},warnings:h}}function dp(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 rs(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new _("--check-only cannot be combined with --refresh-vectors",y.USAGE);if(n&&e.noRefresh===!0)throw new _("--no-refresh cannot be combined with --refresh-vectors",y.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var lp=new Set(["extensions","locks","search"]);function up(e){let t=new Set(ka.filter(r=>r.length>0)),n=new Set,a=new Set(Object.values(xa));for(let r of e.folders)t.has(r)&&!a.has(r)||(t.delete(r),n.add(r));for(let r of lp)t.delete(r),n.add(r);return{requiredDirs:[...t].sort((r,o)=>r.localeCompare(o)),optionalDirs:[...n].sort((r,o)=>r.localeCompare(o)),optionalDirSet:n}}async function mp(e,t,n){let{requiredDirs:a,optionalDirs:r,optionalDirSet:o}=up(t),i=[],s=[],c=[];for(let d of[...a,...r]){let l=K.join(e,d);c.push(...await pe({path:l,scope:"project"})),!await ua(l)&&(o.has(d)?s.push(d):i.push(d))}return{requiredDirs:a,optionalDirs:r,missingRequiredDirs:i,missingOptionalDirs:s,missingDirs:n?[...i,...s]:[...i],hookWarnings:c}}function os(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,a=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||a)&&e.full!==!0,skipDrift:(e.skipDrift===!0||a)&&e.full!==!0,skipVectors:(e.skipVectors===!0||a)&&e.full!==!0}}async function pp(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?he(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):or(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function sa(e){return{check:{name:e,status:"ok",details:{skipped:!0}},warnings:[]}}function fp(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function hp(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function gp(e){return{name:"settings_values",status:e.length===0?"ok":"warn",details:{warnings:e}}}var ma=e=>e.unknown_event_count??0,pa=e=>e.actionable_unknown_event_count??ma(e);function _p(e,t,n,a,r,o,i){let s=ma(a),c=pa(a),d=s>0,l=c>0,u=r.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",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:a}:{},...u?{stale_in_progress:r}:{},...o.length>0?{provenance_resolver_outcomes:o}:{},...i.length>0?{provenance_invalid_values:i}:{},...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 is(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function yp(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 wp(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function vp(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historySummary.over_threshold.map(t=>`history_stream_over_compact_threshold:${t}`),...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:e.integrityCheck.warnings,history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function bp(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-repair --all";if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function kp(e){for(let t of e.checks){let n=Ar(e.remediationSources[t.name]);bp({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}function ss(e,t,n){return n?Fm(e):t.brief===!0?Mm(e):e}async function tw(e,t={}){let n=P(process.cwd(),e.path),a=te(n);if(!await E(a))throw new _(`Tracker is not initialized at ${n}. Run pm init first.`,y.NOT_FOUND);let{settings:r,warnings:o}=await Qa(n),i=[...new Set(o)],s=B(r,M()),c=t.strictDirectories===!0,d=rs(t),l=await mp(n,s,c),u=dp(r),m=await Xm(r,{checkTelemetry:t.checkTelemetry===!0}),h=await Nm(n,r,!!e.noExtensions),f=os(t),p=[],g=await pp({pmRoot:n,settings:r,typeRegistry:s,skipPolicy:f,itemReadWarnings:p}),w=g,v=[...new Set(p)],x=f.skipDrift?{warnings:[]}:await Za({pmRoot:n,settings:r,itemIds:g.map(ot=>ot.id),commandLabel:"health"}),I=await km(n,r.history.compact_policy,await vm(n)),b=await Cr(n,20,t.verboseAuthorEvents===!0),T=pa(b),J=T>0?[`history_unknown_author_events:${T}`]:[],W=is(await vr(n,g,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),S=await Hi(n),L=S.outcomes,ke=S.invalid_values,Et=S.warnings,at=await Qm(n),Le=f.skipIntegrity?sa("integrity"):await $m(n,s.type_to_folder,r.schema,t.requireMergeDrivers===!0),Me=f.skipDrift?sa("history_drift"):await Zm(n,w),rt=f.skipVectors?sa("vectorization"):await cp(n,r,w,d,t.verboseStaleItems===!0),Fe=[fp(a,r,i),hp(l,c),gp(u),m.check,h.check,_p(g,r,I,b,W.scan,L,ke),at.check,Le.check,Me.check,rt.check],C=yp({directoryState:l,normalizedSettingsReadWarnings:i,settingWarnings:u,normalizedItemReadWarnings:v,telemetryCheck:m,extensionCheck:h,historyPolicyWarnings:x.warnings,historySummary:I,authorAttributionWarnings:J,staleInProgressWarnings:W.warnings,provenanceWarnings:Et,locksCheck:at,integrityCheck:Le,historyDriftCheck:Me,vectorizationCheck:rt});kp({checks:Fe,remediationSources:vp({directoryState:l,normalizedSettingsReadWarnings:i,settingWarnings:u,telemetryCheck:m,extensionCheck:h,historySummary:I,authorAttributionWarnings:J,staleInProgressWarnings:W.warnings,provenanceWarnings:Et,locksCheck:at,integrityCheck:Le,historyDriftCheck:Me,vectorizationCheck:rt}),historyDriftedCount:wp(Me),overThresholdCount:I.over_threshold.length});let ya={ok:C.filter(ot=>!Yi(ot,t.requireMergeDrivers===!0)).length===0,checks:Fe,warnings:C,generated_at:A()};return ss(ya,t,f.summaryMode)}var nw={buildExtensionHealthTriageSummary:Zi,buildCapabilityContractMetadata:yt,buildStaleInProgressHealthSummary:is,buildVectorizationProviderDetails:as,collectUnknownCapabilityGuidance:_t,isAdvisoryHealthWarning:Yi,isDirectory:ua,isExpectedUnmanagedExtension:ca,listItemDocumentPaths:Qi,normalizeEndpointForDisplay:mn,normalizeExtensionNameForMatch:tt,parseTelemetryQueue:ts,probeTelemetryEndpointHealth:ns,projectHealthResult:ss,resolveActionableUnknownAuthorEventCount:pa,resolveHealthSkipPolicy:os,resolveUnknownAuthorEventCount:ma,resolveVectorRefreshPolicy:rs,selectStaleItemDetail:la,summarizeHealthCheckDetails:es,summarizeExtensionList:un,summarizeRecordList:ve,summarizeStringList:j,telemetryEnvFlagEnabled:et,warningCode:Xi};import xp from"node:fs/promises";import St 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]="fc124f85-8d28-508b-a3f7-2fe767382197")}catch{}})();var fa="index/manifest.json",ha="search/embeddings.jsonl",Sp="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function Ep(e){return e.progress===!0||process.stderr.isTTY===!0}function z(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
27
+ `)}catch{}}function $p(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new _("Reindex mode must be one of keyword|semantic|hybrid",y.USAGE)}async function Tp(e,t,n,a){let r=[];return{candidates:await nr(e,t,n,r,a),warnings:r}}async function _a(e,t,n,a,r){let o=It(M()),i=[];for(let s of t)if(!(r&&!r.has(s.metadata.id))){if(typeof s.body=="string"){i.push({metadata:s.metadata,body:s.body});continue}try{let c=await xp.readFile(s.item_path,"utf8"),d=Mt(c,{format:s.item_format,schema:n,extensionFieldNames:o,onWarning:l=>a.push(l)});i.push({metadata:s.metadata,body:d.body})}catch{a.push(`item_list_item_read_failed:${St.relative(e,s.item_path)}`),i.push({metadata:s.metadata,body:""})}}return i}function Ip(e,t,n){let a=e.metadata;return{id:a.id,mode:t,updated_at:a.updated_at,corpus:dr(e,{fields:n})}}var nt=Se;function Ap(e){let t=M(),n=nt(e.search?.provider);if(!n)return null;let a=ir(t,n);if(!a)return null;let r=a.runtime_definition??a.definition,o=nt(r.name)??nt(a.definition.name);if(!o)return null;let i=r.embedBatch,s=r.embed_batch,c=r.embed,d=typeof i=="function"?i:typeof s=="function"?s:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:o,embedBatch:d,embed:l}}function Cp(e){let t=M(),n=nt(e.vector_store?.adapter);if(!n)return null;let a=sr(t,n);if(!a)return null;let r=a.runtime_definition??a.definition,o=nt(r.name)??nt(a.definition.name);if(!o)return null;let i=r.upsert,s=r.delete;return{adapterName:o,...typeof i=="function"?{upsert:i}:{},...typeof s=="function"?{delete:s}:{}}}function ga(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new _(`Invalid vector returned by ${t}`,y.GENERIC_FAILURE);return e}async function Rp(e,t,n){let a=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let o=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:a}));if(!Array.isArray(o))throw new _(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,y.GENERIC_FAILURE);return o.map((i,s)=>ga(i,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new _(`Extension search provider "${e.name}" does not implement embed/embedBatch`,y.GENERIC_FAILURE);let r=[];for(let[o,i]of n.entries()){let s=await Promise.resolve(e.embed({input:i,settings:t,model:a}));r.push(ga(s,`extension search provider "${e.name}" embed output at index ${o}`))}return r}function cs(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function ds(e,t,n){let a=n?Re(n.name,cs(e)):t?Re(t.name,t.model):null;if(!a)throw new _("No embedding identity available for semantic reindex mode",y.USAGE);return a}function Op(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,a)=>n.localeCompare(a))}async function ls(e,t,n,a,r,o,i,s){let c=a?.name??n?.name,d=lr(c,e.search.embedding_corpus_max_characters).maxCharacters,l=Sn(e),u=r.map(f=>ur(f,{providerName:c,maxCharacters:d,fields:l})),m=[],h=null;if(a)try{m=await Rp(a,e,u),h=Re(a.name,cs(e))}catch(f){if(!n)throw new _(`Extension search provider "${a.name}" failed to generate embeddings: ${f instanceof Error?f.message:String(f)}`,y.GENERIC_FAILURE);o.push(`Extension search provider "${a.name}" failed; falling back to built-in provider (${f instanceof Error?f.message:String(f)})`)}if(m.length===0){if(!n)throw new _(`No embedding executor available for reindex mode '${t}'`,y.USAGE);let f=await mr(n,e,u,{onProgress:p=>{p.phase==="complete"&&(i.batches_completed=p.batch_index),z(s,`embedding_batch_${p.phase} batch=${p.batch_index}/${p.batch_total} size=${p.batch_size} completed_inputs=${p.completed_inputs}/${p.total_inputs}`)}});o.push(...f.warnings),m=f.vectors,h=Re(n.name,n.model)}if(z(s,`embedding_complete vectors=${m.length}`),m.length!==r.length)throw new _(`Embedding output size mismatch (expected ${r.length}, received ${m.length})`,y.GENERIC_FAILURE);if(!h)throw new _(`No embedding identity available for reindex mode '${t}'`,y.USAGE);return{vectors:m,embeddingIdentity:h}}async function Np(e,t,n,a,r,o){let i=Object.keys(n);if(t){if(i.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:i.sort((s,c)=>s.localeCompare(c)),settings:a}))}catch(s){throw new _(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,y.GENERIC_FAILURE)}else i.length>0&&r.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${i.length}`);if(!e)return}e&&await hr(e,i,{},o)}async function us(e,t,n,a,r){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:a}))}catch(o){throw new _(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${o instanceof Error?o.message:String(o)}`,y.GENERIC_FAILURE)}else r.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await fr(e,n)}}function Dp(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function Pp(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(a=>({id:a.metadata.id,type:a.metadata.type,status:a.metadata.status,priority:a.metadata.priority,updated_at:a.metadata.updated_at}))}}function jp(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=st(e.settings);if(!t.active&&!e.extensionEmbedding)throw new _(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,y.USAGE);let n=Jt(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new _(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,y.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function Lp(e){let t=B(e.settings,M()),n=await Tp(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(a=>({metadata:a.metadata,body:typeof a.body=="string"?a.body:""}))}}async function Mp(e){let t=await He(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 ds(e.settings,st(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&Ge(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(Sp))}async function Fp(e){let t=await He(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=ds(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),a=new Set(e.metadataDocuments.map(d=>d.metadata.id)),r=Op(t.entries,a),o=Ge(t.embedding,n);e.forceFullSemantic&&!o&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let i=e.forceFullSemantic||o?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),s=new Set(i.map(d=>d.metadata.id)),c=s.size>0?await _a(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:r,resetRequired:o,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function Up(e){let t=new Set(e.metadataDocuments.map(r=>r.metadata.id)),n=await _a(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,z(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let a=await ls(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...a,staleDocuments:n,vectorDimension:En(a.vectors,"Reindex embeddings")}}async function zp(e){let t=await ls(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,a=t.embeddingIdentity,r=En(n,"Reindex embeddings");if(!(!e.resetRequired&&(Ge(e.ledgerEmbedding,a)||_r(e.ledgerEmbedding,r))))return{vectors:n,embeddingIdentity:a,staleDocuments:e.staleDocuments,vectorDimension:r,resetRequired:e.resetRequired};let i=await Up(e);return n=i.vectors,a=i.embeddingIdentity,r=i.vectorDimension,{vectors:n,embeddingIdentity:a,staleDocuments:i.staleDocuments,vectorDimension:r,resetRequired:!0}}async function Jp(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(z(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new _(`Extension vector adapter "${t}" does not support upserting vectors.`,y.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,z(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof _)throw t;if(!e.activeVectorStore)throw new _(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,y.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),z(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){z(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await pr(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,z(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new _(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,y.USAGE)}function Wp(e,t){return e.map((n,a)=>({id:n.metadata.id,vector:ga(t[a],`reindex embeddings output at index ${a}`),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 qp(e){z(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await zp({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?(z(e.progressEnabled,"vector_reset_start"),await Np(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),z(e.progressEnabled,"vector_reset_complete")):await us(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=Wp(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await Jp({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:gr(t.embeddingIdentity,t.vectorDimension)}}async function Gp(e){let t=await Fp(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(z(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 z(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await us(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let a=await qp({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let r=new Map(a.staleDocuments.map(o=>[o.metadata.id,o]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(o=>r.get(o.metadata.id)??o),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:a.embeddingMetadata}}async function Hp(e){let t=St.join(e.pmRoot,fa),n=St.join(e.pmRoot,ha),a=Sn(e.settings),r=e.documentsForKeywordArtifacts.map(i=>JSON.stringify(Ip(i,e.mode,a))).join(`
28
+ `);z(e.progressEnabled,"writing keyword artifacts"),await oe(t,`${JSON.stringify(e.manifest,null,2)}
29
+ `),await oe(n,`${r}
30
+ `);let o=[];if(e.mode!=="keyword")try{z(e.progressEnabled,"writing vectorization status ledger"),await yr(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(i){o.push(`search_vectorization_status_ledger_write_failed:${i instanceof Error?i.message:String(i)}`)}return o}async function sw(e,t){let n=$p(e.mode),a=Ep(e),r=e.full===!0;z(a,`start mode=${n}`);let o=P(process.cwd(),t.path);if(!await E(te(o)))throw new _(`Tracker is not initialized at ${o}. Run pm init first.`,y.NOT_FOUND);let i=zt(await R(o)).settings,s=null;try{s=await Q(o,cr,i.locks.ttl_seconds,X(void 0,"pm-reindex"),!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms)}catch(c){throw c instanceof _&&c.exitCode===y.CONFLICT?new _("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",y.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=Ap(i),d=Cp(i),l=jp({requestedMode:n,pmRoot:o,settings:i,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;z(a,"loading item corpus");let m=await Lp({pmRoot:o,settings:i}),h=m.warnings,{documentCandidates:f,metadataDocuments:p}=m;z(a,`loaded_items=${p.length}`);let g=A(),w=Pp(u,g,p),v=St.join(o,fa),x=St.join(o,ha),I=u==="keyword"?await _a(o,f,i.schema,h):p,b=[],T={},J=null,W=Dp(u);if(u==="keyword"&&await Mp({pmRoot:o,settings:i,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:h}),u!=="keyword"){let ke=await Gp({pmRoot:o,settings:i,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:f,metadataDocuments:p,documentsForKeywordArtifacts:I,forceFullSemantic:r,reindexWarnings:h,semanticWarnings:b,semanticSummary:W,progressEnabled:a});I=ke.documentsForKeywordArtifacts,T=ke.vectorizationLedgerEntries,J=ke.vectorizationEmbeddingMetadata}let S=await Hp({pmRoot:o,mode:u,manifest:w,documentsForKeywordArtifacts:I,settings:i,vectorizationLedgerEntries:T,vectorizationEmbeddingMetadata:J,progressEnabled:a}),L=[...await U({path:v,scope:"project",op:"reindex:manifest"}),...await U({path:x,scope:"project",op:"reindex:embeddings"}),...await Lt({mode:u,total_items:p.length})];return z(a,"done"),{ok:!0,mode:u,total_items:p.length,semantic:W,artifacts:{manifest:fa,embeddings:ha},warnings:[...h,...b,...S,...L],generated_at:g}}finally{await s?.()}}export{Gr as a,Pr as b,ec as c,Xf as d,Qf as e,ct as f,Zf as g,eh as h,th as i,nh as j,ah as k,rh as l,oh as m,ih as n,sh as o,ch as p,dh as q,aa as r,q_ as s,py as t,Hi as u,tw as v,nw as w,sw as x};
31
+ //# sourceMappingURL=chunk-KR5RVXLQ.js.map