@unbrained/pm-cli 2026.8.9 → 2026.8.11

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 (249) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +142 -80
  3. package/dist/cli/commander-usage.js +94 -17
  4. package/dist/cli/error-guidance.d.ts +10 -0
  5. package/dist/cli/error-guidance.js +76 -25
  6. package/dist/cli/help-json-payload.js +51 -16
  7. package/dist/cli/main.js +11 -6
  8. package/dist/cli/register-assurance.d.ts +8 -0
  9. package/dist/cli/register-assurance.js +52 -0
  10. package/dist/cli/register-files-lookup.js +14 -3
  11. package/dist/cli/register-mutation.js +30 -9
  12. package/dist/cli/register-operations.js +16 -11
  13. package/dist/cli-bundle/bundle-manifest.json +163 -163
  14. package/dist/cli-bundle/chunks/{chunk-RJC7TPF4.js → chunk-2OOU2AFH.js} +2 -2
  15. package/dist/cli-bundle/chunks/chunk-2RA2YTHJ.js +33 -0
  16. package/dist/cli-bundle/chunks/chunk-A2SJGHSI.js +3 -0
  17. package/dist/cli-bundle/chunks/chunk-DSKYD4LG.js +13 -0
  18. package/dist/cli-bundle/chunks/chunk-HC3GM6YY.js +194 -0
  19. package/dist/cli-bundle/chunks/chunk-IUNRVDAI.js +2 -0
  20. package/dist/cli-bundle/chunks/chunk-W7CPZGSB.js +2 -0
  21. package/dist/cli-bundle/chunks/{chunk-YC3UF2IO.js → chunk-WMEZHCFI.js} +66 -60
  22. package/dist/cli-bundle/chunks/{chunk-GMX5YOI3.js → chunk-ZU34C3LH.js} +48 -48
  23. package/dist/cli-bundle/chunks/chunk-ZXOC6HG5.js +5 -0
  24. package/dist/cli-bundle/chunks/{register-list-query-BUE7PTCU.js → register-list-query-HAUXVUPY.js} +8 -8
  25. package/dist/cli-bundle/chunks/register-mutation-7Y5U7ABT.js +20 -0
  26. package/dist/cli-bundle/chunks/register-operations-EQX3DLAZ.js +2 -0
  27. package/dist/cli-bundle/chunks/{register-setup-UQDTNTLJ.js → register-setup-NOCOOWQY.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-KNEHLPBF.js → chunk-23FTGO3W.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-6DO4YQWZ.js → chunk-2DL3MRTD.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/chunk-3AYKXMYX.js +2 -0
  31. package/dist/cli-bundle/focused-chunks/chunk-4AHEC74N.js +2 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-MRWVJ3ZG.js → chunk-4H5IA6AV.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-4SV3ZKG3.js +16 -0
  34. package/dist/cli-bundle/focused-chunks/chunk-55BIB6DV.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/chunk-6JW6Z2P5.js +8 -0
  36. package/dist/cli-bundle/focused-chunks/chunk-BKPIY34S.js +2 -0
  37. package/dist/cli-bundle/focused-chunks/chunk-D4PIWE6D.js +2 -0
  38. package/dist/cli-bundle/focused-chunks/chunk-DPO7TEFX.js +31 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-3WVHTUAW.js → chunk-E3KCL7AY.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/chunk-ERAAFLPS.js +153 -0
  41. package/dist/cli-bundle/focused-chunks/chunk-F6E4JZKG.js +2 -0
  42. package/dist/cli-bundle/focused-chunks/chunk-FPSYO5ZG.js +18 -0
  43. package/dist/cli-bundle/focused-chunks/{chunk-73FIJONU.js → chunk-J5EKAIVD.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-KDH5OX3D.js +4 -0
  45. package/dist/cli-bundle/focused-chunks/chunk-OJ3LVVIS.js +2 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-TL5M2PAY.js +3 -0
  47. package/dist/cli-bundle/focused-chunks/chunk-UDAZWT25.js +6 -0
  48. package/dist/cli-bundle/focused-chunks/chunk-VABB4L5Y.js +17 -0
  49. package/dist/cli-bundle/main.js +13 -13
  50. package/dist/cli-bundle/sdk-authoring.js +1 -1
  51. package/dist/cli-bundle/sdk-contracts.js +1 -1
  52. package/dist/cli-bundle/sdk-core.js +41 -39
  53. package/dist/cli-bundle/sdk-governance.js +1 -1
  54. package/dist/cli-bundle/sdk-graph.js +1 -1
  55. package/dist/cli-bundle/sdk-merge.js +1 -1
  56. package/dist/cli-bundle/sdk-query.js +1 -1
  57. package/dist/cli-bundle/sdk-runtime.js +1 -1
  58. package/dist/cli-bundle/sdk-testing.js +1 -1
  59. package/dist/cli-bundle/sdk.js +2 -2
  60. package/dist/core/diagnostics/remediation.js +9 -9
  61. package/dist/core/fs/fs-utils.d.ts +10 -0
  62. package/dist/core/fs/fs-utils.js +16 -4
  63. package/dist/core/item/item-format.js +3 -32
  64. package/dist/core/schema/fields-file.d.ts +1 -2
  65. package/dist/core/schema/fields-file.js +4 -11
  66. package/dist/core/schema/runtime-schema.js +3 -10
  67. package/dist/core/schema/status-defs-file.d.ts +1 -2
  68. package/dist/core/schema/status-defs-file.js +4 -32
  69. package/dist/core/schema/status-token.d.ts +2 -0
  70. package/dist/core/schema/status-token.js +32 -0
  71. package/dist/core/schema/type-workflows.d.ts +1 -2
  72. package/dist/core/schema/type-workflows.js +4 -11
  73. package/dist/core/session/session-state.d.ts +47 -0
  74. package/dist/core/session/session-state.js +207 -6
  75. package/dist/core/shared/author.d.ts +8 -2
  76. package/dist/core/shared/author.js +85 -52
  77. package/dist/core/shared/errors.d.ts +12 -0
  78. package/dist/core/shared/errors.js +2 -2
  79. package/dist/core/shared/text-normalization.d.ts +1 -1
  80. package/dist/core/shared/text-normalization.js +2 -2
  81. package/dist/sdk/agent/command-recovery.d.ts +4 -0
  82. package/dist/sdk/agent/command-recovery.js +52 -0
  83. package/dist/sdk/agent/command-suggestions.d.ts +4 -0
  84. package/dist/sdk/agent/command-suggestions.js +67 -0
  85. package/dist/sdk/agent/create-option-policy.d.ts +12 -0
  86. package/dist/sdk/agent/create-option-policy.js +32 -0
  87. package/dist/sdk/agent/item-addressing.d.ts +19 -0
  88. package/dist/sdk/agent/item-addressing.js +208 -0
  89. package/dist/sdk/agent/refusal-reachability.d.ts +40 -0
  90. package/dist/sdk/agent/refusal-reachability.js +72 -0
  91. package/dist/sdk/agent/subcommand-recovery.d.ts +40 -0
  92. package/dist/sdk/agent/subcommand-recovery.js +84 -0
  93. package/dist/sdk/cli-bootstrap.d.ts +9 -1
  94. package/dist/sdk/cli-bootstrap.js +25 -10
  95. package/dist/sdk/cli-contracts/commander-mutation-options.js +16 -4
  96. package/dist/sdk/cli-contracts/completeness.js +13 -3
  97. package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
  98. package/dist/sdk/cli-contracts/enum-contracts.js +3 -2
  99. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  100. package/dist/sdk/cli-contracts/flag-contracts.js +77 -21
  101. package/dist/sdk/cli-contracts/registration-helpers.js +10 -2
  102. package/dist/sdk/cli-contracts/runtime-contracts.js +6 -3
  103. package/dist/sdk/cli-contracts/schemas/assurance-definition.d.ts +513 -0
  104. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +251 -0
  105. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +6 -0
  106. package/dist/sdk/cli-contracts/tool-option-contracts.js +4 -2
  107. package/dist/sdk/cli-contracts/tool-parameter-tables.js +96 -4
  108. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  109. package/dist/sdk/cli-contracts/tool-schema.js +49 -6
  110. package/dist/sdk/cli-contracts.d.ts +1 -1
  111. package/dist/sdk/cli-contracts.js +3 -3
  112. package/dist/sdk/completion.js +9 -3
  113. package/dist/sdk/config.js +9 -3
  114. package/dist/sdk/context/semantic-session-attribution.d.ts +32 -0
  115. package/dist/sdk/context/semantic-session-attribution.js +83 -0
  116. package/dist/sdk/context-intent-runtime.js +8 -5
  117. package/dist/sdk/context-signal-store.d.ts +34 -0
  118. package/dist/sdk/context-signal-store.js +24 -2
  119. package/dist/sdk/core-governance.d.ts +3 -1
  120. package/dist/sdk/core-governance.js +5 -3
  121. package/dist/sdk/core.d.ts +1 -1
  122. package/dist/sdk/core.js +2 -2
  123. package/dist/sdk/dependency-flag-validation.d.ts +15 -1
  124. package/dist/sdk/dependency-flag-validation.js +54 -2
  125. package/dist/sdk/error-code-catalog.d.ts +13 -0
  126. package/dist/sdk/error-code-catalog.js +35 -2
  127. package/dist/sdk/extension.js +18 -17
  128. package/dist/sdk/files.d.ts +11 -0
  129. package/dist/sdk/files.js +82 -24
  130. package/dist/sdk/generated-error-code-catalog.js +104 -13
  131. package/dist/sdk/governance/assurance-action-contracts.d.ts +7 -0
  132. package/dist/sdk/governance/assurance-action-contracts.js +5 -0
  133. package/dist/sdk/governance/assurance-action.d.ts +70 -0
  134. package/dist/sdk/governance/assurance-action.js +198 -0
  135. package/dist/sdk/governance/assurance-limits.d.ts +7 -0
  136. package/dist/sdk/governance/assurance-limits.js +11 -0
  137. package/dist/sdk/governance/assurance-runtime.d.ts +20 -0
  138. package/dist/sdk/governance/assurance-runtime.js +131 -0
  139. package/dist/sdk/governance/assurance.d.ts +432 -0
  140. package/dist/sdk/governance/assurance.js +689 -0
  141. package/dist/sdk/governance/health.js +14 -7
  142. package/dist/sdk/governance/provenance-health.d.ts +13 -0
  143. package/dist/sdk/governance/provenance-health.js +63 -17
  144. package/dist/sdk/governance/validate-item-reader.d.ts +13 -0
  145. package/dist/sdk/governance/validate-item-reader.js +18 -0
  146. package/dist/sdk/governance/validate.d.ts +2 -2
  147. package/dist/sdk/governance/validate.js +15 -6
  148. package/dist/sdk/graph/run.js +8 -3
  149. package/dist/sdk/index.d.ts +10 -1
  150. package/dist/sdk/index.js +12 -3
  151. package/dist/sdk/lifecycle/claim.js +18 -3
  152. package/dist/sdk/lifecycle/close.js +17 -14
  153. package/dist/sdk/lifecycle/create.d.ts +2 -0
  154. package/dist/sdk/lifecycle/create.js +62 -9
  155. package/dist/sdk/lifecycle/focus.js +13 -3
  156. package/dist/sdk/lifecycle/plan.js +8 -3
  157. package/dist/sdk/lifecycle/update-many.js +39 -27
  158. package/dist/sdk/lifecycle/update.d.ts +6 -1
  159. package/dist/sdk/lifecycle/update.js +47 -10
  160. package/dist/sdk/merge/index.d.ts +1 -1
  161. package/dist/sdk/merge/index.js +3 -3
  162. package/dist/sdk/merge/install.d.ts +4 -0
  163. package/dist/sdk/merge/install.js +28 -16
  164. package/dist/sdk/merge/receipts.d.ts +3 -0
  165. package/dist/sdk/merge/receipts.js +81 -17
  166. package/dist/sdk/output-projection.js +24 -4
  167. package/dist/sdk/provenance.d.ts +38 -0
  168. package/dist/sdk/provenance.js +64 -2
  169. package/dist/sdk/query/context.d.ts +2 -0
  170. package/dist/sdk/query/context.js +24 -10
  171. package/dist/sdk/query/light-metadata.d.ts +3 -0
  172. package/dist/sdk/query/light-metadata.js +19 -0
  173. package/dist/sdk/runtime-extended-actions.js +22 -5
  174. package/dist/sdk/runtime-primitives.d.ts +2 -0
  175. package/dist/sdk/runtime-primitives.js +4 -2
  176. package/dist/sdk/runtime.d.ts +8 -1
  177. package/dist/sdk/runtime.js +37 -28
  178. package/dist/sdk/schema-migration.js +7 -9
  179. package/dist/sdk/similarity-scoring.d.ts +1 -2
  180. package/dist/sdk/similarity-scoring.js +4 -16
  181. package/dist/sdk/telemetry.js +7 -4
  182. package/dist/sdk/traceability/runtime-files-lookup.d.ts +8 -0
  183. package/dist/sdk/traceability/runtime-files-lookup.js +33 -0
  184. package/dist/sdk/traceability/source-traceability.d.ts +102 -0
  185. package/dist/sdk/traceability/source-traceability.js +293 -0
  186. package/dist/sdk/workspace-snapshot.d.ts +4 -0
  187. package/dist/sdk/workspace-snapshot.js +24 -11
  188. package/dist/types.d.ts +8 -2
  189. package/dist/types.js +2 -2
  190. package/docs/AGENT_GUIDE.md +3 -1
  191. package/docs/ASSURANCE.md +132 -0
  192. package/docs/COMMANDS.md +8 -5
  193. package/docs/MERGE_SAFETY.md +7 -5
  194. package/docs/README.md +3 -5
  195. package/docs/READ_OUTPUT_CONTRACTS.md +2 -2
  196. package/docs/RELEASING.md +9 -5
  197. package/docs/SDK.md +44 -8
  198. package/docs/SDK_AGENT_SESSION_CONTEXT.md +43 -6
  199. package/docs/SDK_CONTEXT.md +97 -0
  200. package/docs/SDK_CONTEXT_INTEGRITY.md +18 -3
  201. package/docs/SDK_EVIDENCE_TRACEABILITY.md +39 -1
  202. package/docs/SDK_RUNTIME_BOUNDARIES.md +36 -1
  203. package/docs/TESTING.md +12 -9
  204. package/docs/agent-task-token-baseline.json +2 -2
  205. package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -0
  206. package/marketplace.json +2 -2
  207. package/package.json +7 -6
  208. package/packages/pm-beads/package.json +1 -1
  209. package/packages/pm-calendar/package.json +1 -1
  210. package/packages/pm-command-kit/package.json +1 -1
  211. package/packages/pm-digital-twin/package.json +1 -1
  212. package/packages/pm-governance-audit/package.json +1 -1
  213. package/packages/pm-guide-shell/package.json +1 -1
  214. package/packages/pm-kanban/package.json +1 -1
  215. package/packages/pm-lifecycle-hooks/package.json +1 -1
  216. package/packages/pm-linked-test-adapters/package.json +1 -1
  217. package/packages/pm-search-advanced/package.json +1 -1
  218. package/packages/pm-templates/extensions/templates/index.ts +9 -3
  219. package/packages/pm-templates/package.json +1 -1
  220. package/packages/pm-todos/package.json +1 -1
  221. package/packages/pm-vcs/package.json +1 -1
  222. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  223. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  224. package/sdk/public-surface.json +1028 -48
  225. package/dist/cli-bundle/chunks/chunk-2DTCZXSD.js +0 -13
  226. package/dist/cli-bundle/chunks/chunk-5JO6R4BS.js +0 -3
  227. package/dist/cli-bundle/chunks/chunk-5KN4DZYV.js +0 -194
  228. package/dist/cli-bundle/chunks/chunk-EF43KODO.js +0 -2
  229. package/dist/cli-bundle/chunks/chunk-HUV2Z7IS.js +0 -28
  230. package/dist/cli-bundle/chunks/chunk-MHBVCUF2.js +0 -2
  231. package/dist/cli-bundle/chunks/chunk-PYO5GZU6.js +0 -5
  232. package/dist/cli-bundle/chunks/register-mutation-FC3XLVIK.js +0 -20
  233. package/dist/cli-bundle/chunks/register-operations-YH2WAOXU.js +0 -2
  234. package/dist/cli-bundle/focused-chunks/chunk-2VVP5RAA.js +0 -153
  235. package/dist/cli-bundle/focused-chunks/chunk-3GSFUDAI.js +0 -2
  236. package/dist/cli-bundle/focused-chunks/chunk-4H6MVCK3.js +0 -16
  237. package/dist/cli-bundle/focused-chunks/chunk-54TZJ4BM.js +0 -2
  238. package/dist/cli-bundle/focused-chunks/chunk-5NK5TJ5D.js +0 -2
  239. package/dist/cli-bundle/focused-chunks/chunk-C3GCHDSQ.js +0 -31
  240. package/dist/cli-bundle/focused-chunks/chunk-JGRSQZJT.js +0 -18
  241. package/dist/cli-bundle/focused-chunks/chunk-NL57J7BZ.js +0 -4
  242. package/dist/cli-bundle/focused-chunks/chunk-P6BBIQRG.js +0 -6
  243. package/dist/cli-bundle/focused-chunks/chunk-PZAGVQNN.js +0 -3
  244. package/dist/cli-bundle/focused-chunks/chunk-QDAO3XEK.js +0 -14
  245. package/dist/cli-bundle/focused-chunks/chunk-T4IGQCSY.js +0 -2
  246. package/dist/cli-bundle/focused-chunks/chunk-U46GQJNY.js +0 -2
  247. package/dist/cli-bundle/focused-chunks/chunk-VRXJSGIT.js +0 -8
  248. package/dist/cli-bundle/focused-chunks/chunk-XC2ZW3CJ.js +0 -2
  249. package/dist/cli-bundle/focused-chunks/chunk-ZG54B4XG.js +0 -2
@@ -1,31 +0,0 @@
1
- import{a as gn,c as At,d as Ct,e as La,g as Ma,h as yn,i as Nt,j as Fa,k as Fe,l as Ue,m as Ua,n as za,o as wn,p as pe,q as Ja,r as ze,s as Je,t as Wa,u as qa,v as vn}from"./chunk-P6BBIQRG.js";import{N as Rr,S as Or,V as Nr,W as Dr,g as $r,k as Tr,l as Ir,o as Ar,p as Cr}from"./chunk-QDAO3XEK.js";import{a as Va}from"./chunk-3GSFUDAI.js";import{B as Pt}from"./chunk-54TZJ4BM.js";import{f as Tn}from"./chunk-U46GQJNY.js";import{$ as We,Aa as xr,Ba as Sr,Ca as Er,H as zt,I as lr,J as Sn,K as ot,M as En,Q as dr,R as ur,S as mr,T as pr,U as Jt,W as fr,X as hr,Y as gr,Z as Re,_ as _r,aa as yr,ba as $n,ca as qe,da as wr,e as sr,ea as vr,f as cr,va as br,wa as kr}from"./chunk-JGRSQZJT.js";import{a as Na,b as Rt,c as _n,d as Da,e as Pa,f as me,g as Ot,h as ja,i as xe}from"./chunk-PZAGVQNN.js";import{Fa as kn,Ia as Ft,Ka as he,L as Y,La as Qa,M as A,Ma as R,Na as Ut,Pa as Za,Q as X,Ua as er,X as Ya,_ as Xa,_a as tr,ab as nr,b as Ka,bb as ar,ca as bn,cb as rr,db as or,ea as Mt,eb as Ce,fb as ir,ib as xn,k as M,n as U,p as fe,r as Lt}from"./chunk-2VVP5RAA.js";import{Aa as Oa,B as Ea,Ba as Me,C as $a,D as H,Da as ie,Fa as se,Ga as te,I as fn,Ia as K,J as P,Ja as ce,L as It,M as ee,Na as rt,O as Ta,Pa as Dt,T as ke,Ua as jt,Va as Ha,W as Ia,Wa as Ba,a as wa,d as va,e as ba,h as Tt,p as E,pa as Aa,q,qa as Ca,r as re,u as oe,v as be,w as Sa,ya as hn,za as Ra}from"./chunk-NL57J7BZ.js";import{P as ka,R as xa,Y as y,Z as _,a as Et,d as $t,ka as Ga}from"./chunk-ZG54B4XG.js";import{execFile as Iu}from"node:child_process";import Au from"node:path";import{promisify as Cu}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 fs=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Ge(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)=>Pr(p.filter(w=>a(w.name)).map(g)),o=(p,g)=>Pr(p.filter(w=>a(w.name)).flatMap(g)),{registrations:i,commands:s,parsers:c,preflight:l,services:d,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:fs.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(d.overrides,p=>p.service),renderer_overrides:r(u.overrides,p=>p.format),...f.length>0?{renderer_ownership:f}:{},preflight_overrides:l.overrides.filter(p=>a(p.name)).length,preflight_ownership:l.overrides.filter(p=>a(p.name)).map(p=>({commands:[...p.commands??[]]}))}}function Pr(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 hs=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)}"`},In=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?hs(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,jr=(e,t=process.platform)=>{let n=e.map(a=>In(a,t)).join(" ");return n.length>0?`pm ${n}`:"pm"};import ac from"node:path";import{mkdir as rc}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 gs=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function _s(e){let t=gs.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function ys(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Lr(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=_s(s);if(c===void 0)continue;let l=r.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<a&&l.examples.push(s),r.set(c,l)}let o=[];for(let[i,s]of r.entries()){if(s.count<n)continue;let c=ys(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 Kr}from"node:crypto";import Ne from"node:fs/promises";import Ve from"node:path";import{mkdir as ws,readFile as vs}from"node:fs/promises";import Wr 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 An=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},bs="sdk-workspace-transaction",ks=/^[a-zA-Z0-9._-]+$/,xs=30,Ss=3e3;function Mr(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!ks.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Fr(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 Ur(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 qr(e,t){return Wr.join(e,"transactions","sdk",`${t}.json`)}async function Se(e,t){t.updatedAt=A();let n=qr(e,t.transactionId);await ws(Wr.dirname(n),{recursive:!0}),await re(n,`${JSON.stringify(t,null,2)}
2
- `)}function Es(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 $s(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 Cn(e,t){return e===void 0?void 0:$s(e,t)}function Rn(e,t,n,a){let r=Cn(n,a);r===void 0?delete e[t]:e[t]=r}function zr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Jr(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Ts(e,t){if(!Jr(e.startedStepIds,t)||!Jr(e.completedStepIds,t)||!zr(e.results)||!zr(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 Is(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((d,u)=>d===n[u]),s=Ts(r,n),c=Es(r),l=["applying","compensating","compensated","committed"].includes(String(r.status));if(!o||!i||!s||!c||!l)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 As(e,t,n,a,r){let o=r,i=o!==void 0;if(o?.status==="compensating"&&await Gr(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 Cs(e,t,n){try{await Os(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=Cn(i.result,`Step ${o.id} result`);if(i.state!=="applied"){let c=await o.prepareCompensation?.();Rn(t.compensationData,o.id,c,`Step ${o.id} compensation data`),r.add(o.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>r.has(d)),await Se(e.pmRoot,t);let l=await o.apply();s=Cn(l,`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)),Rn(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 An||t.status==="committed")throw a;try{await Gr(e,t)}catch(r){throw new AggregateError([a,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw a}}async function Rs(e,t,n){try{return Is(await vs(qr(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 Os(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),Rn(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 Gr(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 Hr(e){let t=Fr(e.pmRoot,"Transaction pmRoot"),n=Mr(e.transactionId,"Transaction id"),a=Fr(e.author,"Transaction author"),r=Ur(e.lockTtlSeconds,xs,"Transaction lock TTL"),o=Ur(e.lockWaitMs,Ss,"Transaction lock wait"),i=[...e.steps];if(i.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=i.map(d=>{let u=Mr(d.id,"Transaction step id");if(u!==d.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},l=await X(t,bs,r,a,!1,!1,o);try{let d=await Rs(t,n,s),u=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Oe(d.results)};let m=await As(c,n,a,s,d);return await Cs(c,m.journal,u||m.recovered)}finally{await l()}}(function(){try{var e=typeof window<"u"?window:typeof 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 He(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Yr(e){let t=He(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Xr(e,t){let n=Nn(e),a=He(t,"migrationScope");return`auto-${Kr("sha256").update(JSON.stringify({scope:a,request:n})).digest("hex").slice(0,20)}`}function Nn(e){let t=a=>He(a,"source or target").toLowerCase().replaceAll(/[\s-]+/g,"_"),n=e.kind==="rename-type"?{kind:e.kind,from:He(e.from,"source"),to:He(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:t(e.from),to:t(e.to),...e.type===void 0?{}:{type:He(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 Ns(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Ds(e,t,n){let a=K(t.schema),r=Ns(n);return ce(e,a.files[r],te[r])}function Qr(e,t){return Ve.join(e,"transactions","schema",`${t}-plan.json`)}function Wt(e){return e.length===0?null:JSON.parse(e)}async function Be(e){let t=await q(e);return{exists:t!==null,raw:t??""}}async function Zr(e,t){t.exists?await re(e,t.raw):await Ne.rm(e,{force:!0})}function Ps(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 js(e,t,n){let a=Fe(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 Ue(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 Ue(a)}function Ls(e,t,n){let a=ze(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 Je(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 Je(a)}function Ms(e,t,n){return t.kind==="rename-type"?Ps(e,t,n):t.kind==="rename-field"?js(e,t,n):Ls(e,t,n)}function Ee(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Dn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Ke(e){return Array.isArray(e)?e.map(t=>Dn(t)).filter(t=>t!==void 0):[]}function Fs(e,t){for(let n of Ke(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(a=>Ee(a,t)));for(let n of Ke(e.type_workflows))n.type=Ee(n.type,t)}function Us(e,t){for(let a of Ke(e.definitions))a.default_status=Ee(a.default_status,t);let n=Dn(e.workflow);if(n)for(let[a,r]of Object.entries(n))n[a]=Ee(r,t);for(let a of Ke(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 zs(e,t){for(let n of Ke(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 Ke(n[a])){let o=a==="options"?"key":"option";r[o]=Ee(r[o],t)}}}function Js(e,t){let n=Dn(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 On(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"?Fs(a,t):t.kind==="rename-field"?zs(a,t):Us(a,t),Js(a,t),`${JSON.stringify(a,null,2)}
3
- `}function eo(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=Fe(e).fields;return{source:a.some(r=>r.key===t.from),target:a.some(r=>r.key===t.to)}}let n=ze(e).statuses;return{source:n.some(a=>a.id===t.from),target:n.some(a=>a.id===t.to)}}function Ws(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 qs(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 to(e,t){let n=Nn(t.request),a=t.migrationId===void 0?Xr(n,t.migrationScope??"plan"):Yr(t.migrationId),r=e.map(c=>qs(c,n)).filter(c=>c!==null).sort((c,l)=>c.id.localeCompare(l.id)),o=Kr("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 Gs(e){let t=H(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 Ce(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Hs(e,t){let n=await q(Qr(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 Bs(e,t){let n=Qr(e,t.migration_id);await Ne.mkdir(Ve.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 Vs(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Ks(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 Br(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 Vr(e){return{id:e.id,inspect:async()=>{let t=await Be(e.filePath),n=eo(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 Be(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Be(e.filePath);return await re(e.filePath,Ms(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 Zr(e.filePath,{exists:t.exists,raw:t.raw})}}}function Ys(e){return{id:e.stepId,inspect:async()=>{let t=await Be(e.filePath);return{state:On(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Be(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Be(e.filePath);return await re(e.filePath,On(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 Zr(e.filePath,{exists:t.exists,raw:t.raw})}}}function Xs(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await R(e.pmRoot),n=H(t,M()).type_to_folder,a=await Ks({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),r=Ws(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 xn({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:Br(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 xn({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:Br(a,e.request,"reverse")}}})}}}async function Qs(e){let t=await Hs(e.pmRoot,e.migrationId);if(t){if(!Vs(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 Gs({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...to(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Zs(e){let t=eo(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 Bs(e.pmRoot,e.plan)}async function ec(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=Ve.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=>Ve.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&&On(o,e.request)!==o&&a.push({filePath:r,beforeRaw:o})}return{paths:n,snapshots:a}}async function tc(e){for(let t of e.snapshots){let n=await Ne.readFile(t.filePath,"utf8"),a=Ve.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await kn({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 nc(e,t,n){let a=Nn(e),r=P(process.cwd(),n.path);if(!await E(ee(r)))throw new _(`Tracker is not initialized at ${r}. Run pm init first.`,y.NOT_FOUND);let o=t.migrationId===void 0?Xr(a,await Ne.realpath(r)):Yr(t.migrationId),i=await R(r),s=Y(t.author,i.author_default),c=await Qs({pmRoot:r,settings:i,migrationId:o,request:a}),l=c.plan;if(t.dryRun===!0)return{...l,action:a.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=Ds(r,i,a),u=await Ne.readFile(d,"utf8");c.stored||await Zs({pmRoot:r,schemaPath:d,request:a,plan:l});let m=await ec({pmRoot:r,schemaPath:d,settings:i,request:a}),h=[Vr({id:"stage-schema",filePath:d,request:a,phase:"stage"}),...m.paths.map((w,v)=>Ys({filePath:w,request:a,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...l.items.map(w=>Xs({pmRoot:r,id:w.id,request:a,author:s,force:t.force===!0})),Vr({id:"retire-source",filePath:d,request:a,phase:"retire"})],f=await Hr({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(d,"utf8"),{historyPath:g}=await kn({pmRoot:r,author:s,documentPath:Ve.relative(r,d).replaceAll("\\","/"),before:Wt(u),after:Wt(p),op:"schema_migration",idempotencyKey:`${l.migration_id}:${l.fingerprint}`,message:`${a.kind}: ${a.from} -> ${a.to}; affected=${l.affected_item_count}`,lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms});return await tc({pmRoot:r,author:s,settings:i,request:a,plan:l,snapshots:m.snapshots}),{...l,action:a.kind,applied:!0,recovered:f.recovered,migrated_item_count:l.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",no="schema-statuses",ao="schema-fields";function $e(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 Yf(e,t,n){let a=P(process.cwd(),n.path);await _e(a);let r;try{r=_n({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=K(o.schema),s=ce(a,i.files.types,te.types),c=[],l=Y(t.author,o.author_default),d=he(o),u=await X(a,qt,o.locks.ttl_seconds,l,!!t.force,d.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=H(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=Ot(f,r),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await $e({pmRoot:a,filePath:s,raw:xe(m.file),op:"schema:add-type",author:l,settings:o}),await it(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 ro(a,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Te(c),generated_at:A()}}async function _e(e){if(!await E(ee(e)))throw new _(`Tracker is not initialized at ${e}. Run pm init first.`,y.NOT_FOUND)}async function ro(e,t){try{let n=await Ir(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 oc(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 ic(e,t,n,a){let r=H(t,M()),o=rt(n),i=pe(a);return(await Ce(e,t.item_format,r.type_to_folder,[],n)).filter(c=>{let l=typeof c.status=="string"?c.status:"";return(o.alias_to_id.get(pe(l))??pe(l))===i}).length}async function sc(e,t,n,a,r){if(r.length===0||wn.has(r))return;let o=await ic(t,n,a,r);o>0&&e.push(`items_using_status:${o}`);let i=cc(a.workflow,r);i.length>0&&e.push(`status_referenced_by_workflow:${i.join(",")}`)}function cc(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 Xf(e,t,n){let a=P(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),l=he(r),d=await X(a,qt,r.locks.ttl_seconds,c,!!t.force,l.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 oc(a,r,o,f);p>0&&s.push(`items_using_type:${p}`)}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 d()}return u.removed&&await ro(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 Pn(e,t){return ce(e,t.files.statuses,te.statuses)}function Gt(e,t){return ce(e,t.files.fields,te.fields)}function oo(e,t){return ce(e,t.files.types,te.types)}async function it(e,t,n,a){for(let r of t){let o=$a(r.folder??Ea(r.name)),i=ac.join(e,o);await E(i)||(await rc(i,{recursive:!0}),n.push(...await U({path:i,scope:"project",op:a})))}}function jn(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 lc(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 dc(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 Qf(e,t,n){let a=P(process.cwd(),n.path);await _e(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=K(o.schema),s=Pn(a,i),c=rt(i);try{vn(r,c.alias_to_id)}catch(p){throw new _(p instanceof Error?p.message:String(p),y.USAGE)}let l=lc(c.by_id.get(r.id)),d=[],u=Y(t.author,o.author_default),m=he(o),h=await X(a,no,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=ze(p)}catch(v){throw new _(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let w=dc(g.statuses);try{vn(r,w)}catch(v){throw new _(v instanceof Error?v.message:String(v),y.USAGE)}f=Wa(g,r,l),await $e({pmRoot:a,filePath:s,raw:Je(f.file),op:"schema:add-status",author:u,settings:o}),d.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:Te(d),generated_at:A()}}async function Zf(e,t,n){let a=P(process.cwd(),n.path);await _e(a);let r=await R(a),o=K(r.schema),i=Pn(a,o),s=[],c=Y(t.author,r.author_default),l=he(r),d=await X(a,no,r.locks.ttl_seconds,c,!!t.force,l.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=qa(h,e)}catch(f){throw new _(f instanceof Error?f.message:String(f),y.USAGE)}if(u.removed){let f=pe(u.definition?.id??e);await sc(s,a,r,o,f),await $e({pmRoot:a,filePath:i,raw:Je(u.file),op:"schema:remove-status",author:c,settings:r}),s.push(...await U({path:i,scope:"project",op:"schema:remove-status"}))}}finally{await d()}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 io(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 uc(e,t,n){return{...io(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 so(e){return{id:e.id,source:wn.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 co(e,t,n){let a=e.toLowerCase();return n.has(a)?"extension":t.has(a)?"custom":"builtin"}function mc(){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 pc(e){let t=rt(e),n=[],a=[];for(let r of t.definitions){let o=so(r);o.source==="builtin"?n.push(o):a.push(o)}return{builtin:n,custom:a}}async function st(e){let t=P(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=Pn(t,a),i=H(n,M()),s=mc(),c=new Set((n.item_types?.definitions??[]).map(l=>l.name.trim().toLowerCase()).filter(l=>l.length>0&&!s.has(l)));return{pmRoot:t,typesPath:r,statusesPath:o,byType:i.by_type,customNames:c,extensionProvenance:s,schema:a}}async function eh(e){let t=await st(e),n=[],a=[],r=[];for(let s of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=co(s.name,t.customNames,new Set(t.extensionProvenance.keys())),l=io(s);c==="extension"?r.push(l):c==="custom"?a.push(l):n.push(l)}let o=pc(t.schema),i=Dt(t.schema).definitions.map(jn);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 th(e,t){let n=(e??"").trim();if(n.length===0)throw new _("Type name must not be empty.",y.USAGE);let a=await st(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 "${Rt(n)}" to register it.`,y.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:uc(r,co(r.name,a.customNames,new Set(a.extensionProvenance.keys())),a.extensionProvenance.get(r.name.toLowerCase())),file:{path:a.typesPath},generated_at:A()}}async function nh(e,t){let n=pe(e);if(n.length===0)throw new _("Status id must not be empty.",y.USAGE);let a=await st(t),r=rt(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 "${Rt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:so(i),file:{path:a.statusesPath},generated_at:A()}}async function ah(e,t,n){let a=P(process.cwd(),n.path);await _e(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=K(o.schema),s=Gt(a,i),c=[],l=Pt(r.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let d=Y(t.author,o.author_default),u=he(o),m=await X(a,ao,o.locks.ttl_seconds,d,!!t.force,u.force_required_for_stale_lock,o.locks.wait_ms),h;try{let f=await q(s),p;try{p=Fe(f)}catch(g){throw new _(g instanceof Error?g.message:String(g),y.GENERIC_FAILURE)}h=Ua(p,r),await $e({pmRoot:a,filePath:s,raw:Ue(h.file),op:"schema:add-field",author:d,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:Te(c),generated_at:A()}}async function fc(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 rh(e,t,n){let a=P(process.cwd(),n.path);await _e(a);let r=await R(a),o=K(r.schema),i=Gt(a,o),s=[],c=Y(t.author,r.author_default),l=he(r),d=await X(a,ao,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),u;try{let m=await q(i),h;try{h=Fe(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=Nt(u.definition?.key??e),p=Nt(u.definition?.metadata_key??u.definition?.front_matter_key??f);if(p.length>0){let g=await fc(a,r,o,p);g>0&&s.push(`items_using_field:${g}`)}await $e({pmRoot:a,filePath:i,raw:Ue(u.file),op:"schema:remove-field",author:c,settings:r}),s.push(...await U({path:i,scope:"project",op:"schema:remove-field"}))}}finally{await d()}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 oh(e){let t=await st(e),n=Dt(t.schema).definitions.map(jn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Gt(t.pmRoot,t.schema)},generated_at:A()}}async function ih(e,t){let n=Nt(e);if(n.length===0)throw new _("Field key must not be empty.",y.USAGE);let a=await st(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 "${Rt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:jn(r),file:{path:Gt(a.pmRoot,a.schema)},generated_at:A()}}async function sh(e,t,n){let a=P(process.cwd(),n.path);await _e(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=K(o.schema),s=oo(a,i),c=[],l=Y(t.author,o.author_default),d=he(o),u=[],m=[],h,f=await X(a,qt,o.locks.ttl_seconds,l,!!t.force,d.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 yn(r)){let x=Ot(w,v);w=x.file,(x.replaced?m:u).push(x.definition.name)}h=w.definitions.length,await $e({pmRoot:a,filePath:s,raw:xe(w),op:"schema:apply-preset",author:l,settings:o}),await it(a,yn(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:Te(c),generated_at:A()}}function hc(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 ch(e,t){let n=P(process.cwd(),t.path);await _e(n);let a=await R(n),r=K(a.schema),o=oo(n,r),i=hc(e.minCount),s=H(a,M()),l=(await Ce(n,a.item_format,s.type_to_folder,[],r)).map(x=>typeof x.title=="string"?x.title:""),d=Lr(l,{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:d,registered:m,replaced:h,skipped:f,file:{path:o,definitions:p},warnings:u,generated_at:A()}}let g=Y(e.author,a.author_default),w=he(a),v=await X(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 d){if(T.shadows_builtin){f.push({name:T.name,reason:"shadows_builtin"});continue}let J;try{J=_n({name:T.name})}catch{f.push({name:T.name,reason:"invalid_type_token"});continue}let W=Ot(b,J);b=W.file,(W.replaced?h:m).push(W.definition.name)}p=b.definitions.length,await $e({pmRoot:n,filePath:o,raw:xe(b),op:"schema:infer-types",author:g,settings:a}),await it(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:d,registered:m,replaced:h,skipped:f,file:{path:o,definitions:p},warnings:Te(u),generated_at:A()}}import lo from"node:fs/promises";import Ln from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="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 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 Mn(e){return Ra(e)}async function gc(e){try{let t=JSON.parse(await lo.readFile(Ln.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 _c(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 gc(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 Ye(e,t={}){let n=Ln.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 lo.readFile(n,"utf8"))}catch(i){throw new _(`Failed to parse extension manifest at "${n}": ${yc(i)}`,y.USAGE)}let r=Mn(a);if(!r)throw new _(`Extension manifest at "${n}" is invalid.`,y.USAGE);let o=Ln.resolve(e,r.entry);if(!oe(e,o))throw new _(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,y.USAGE);if(!await E(o))throw await _c(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 yc(e){return e instanceof Error?e.message:String(e)}import Fn from"node:fs/promises";import wc 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 vc=".managed-extensions.json",Bt=1;function ct(e){return wc.join(e,vc)}function bc(){return{version:Bt,updated_at:A(),entries:[]}}function lt(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 uo(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 kc(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 xc(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 Sc(e){if(typeof e!="object"||e===null)return null;let t=e;if(!kc(t))return null;let n=xc(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: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 Ec(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=Sc(a);r&&n.push(r)}return{version:Bt,updated_at:Z(t.updated_at)??A(),entries:lt(n)}}async function B(e){let t=ct(e),n=bc();try{let a=await Fn.readFile(t,"utf8"),r=JSON.parse(a),o=Ec(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=ct(e),a={version:Bt,updated_at:A(),entries:lt(t.entries)};await Fn.mkdir(e,{recursive:!0}),await Fn.writeFile(n,`${JSON.stringify(a,null,2)}
5
- `,"utf8")}function dt(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:lt(n)}}async function mo(e,t,n,a){let r=t.entries.find(i=>k(i.name)===k(n));if(!r)return t;let o=dt(t,{...r,contributions:a});return await De(e,o),o}import{execFile as jc}from"node:child_process";import O from"node:fs/promises";import qn from"node:os";import $ from"node:path";import{fileURLToPath as Lc}from"node:url";import{promisify as Mc}from"node:util";import Fc from"npm-package-arg";import{extract as Uc,list as zc}from"tar";import $c 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]="259656b0-09b7-52c5-8f54-52ac29eec607")}catch{}})();var Tc="PM_CLI_PACKAGE_ROOT",po={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Ic=new Set(["*","all"]);function Un(){let e=[],t=process.env[Tc];return typeof t=="string"&&t.trim().length>0&&e.push(ae.resolve(t.trim())),e.push(be(import.meta.url,["../../.."])),[...new Set(e)]}async function ut(e){let t=e.trim().toLowerCase(),n=await ho(t);if(n)return n;let a=po[t];if(!a)return null;for(let r of Un()){let o=ae.join(r,".agents","pm","extensions",a.legacy_extension_directory);if(await E(ae.join(o,"manifest.json")))return o}return null}function fo(e){return Ic.has(e.trim().toLowerCase())}function Ac(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Cc(e,t){let n=await $c.readdir(e,{withFileTypes:!0});for(let a of n){if(!a.isDirectory()||!a.name.startsWith("pm-"))continue;let r=ae.join(e,a.name);if(!await E(ae.join(r,"package.json")))continue;let o=await At(r),i=o.aliases&&o.aliases.length>0?o.aliases:[Ac(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 zn(){let e=new Map;for(let t of Un()){let n=ae.join(t,"packages");await E(n)&&await Cc(n,e)}for(let[t,n]of Object.entries(po))if(!e.has(t))for(let a of Un()){let r=ae.join(a,"packages",n.package_directory);if(await E(ae.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 zn()).map(e=>e.alias)}async function ho(e){let t=e.trim().toLowerCase();return(await zn()).find(a=>a.alias===t||a.package_directory.toLowerCase()===t||a.package_name?.toLowerCase()===t)?.package_root??null}async function go(e){let t=await ho(e);return t?(await At(t)).package_name??null:null}async function _o(e){let t=await ut(e);if(!t)return null;try{let n=await Ct(t);return n.length!==1?null:(await Ye(n[0])).manifest.name}catch{return null}}function Rc(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 Oc(e,t,n,a,r,o){let i=a==="global"?"--global":"--project",s=Object.fromEntries(gn.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(ae.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:Rc(e),media:e.catalog?.media}}}async function yo(e,t,n={}){let a=Me(P(process.cwd(),t.path),process.cwd()),r=e==="global"?a.global:a.project,o=await B(r),i=new Set(o.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>ae.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=[],l=new Map;for(let m of await zn()){let h=ae.resolve(m.package_root),f=l.get(h)??[];f.push(m),l.set(h,f)}for(let m of l.values()){let h=m[0],f=m.map(g=>g.alias).sort((g,w)=>g.localeCompare(w)),p=await At(h.package_root);c.push(Oc(p,h,f,e,s,i))}let d=Dc(n.fields),u=d?c.map(m=>Pc(m,d)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:gn.filter(m=>m!=="extensions"),packages:u}}var Nc=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 Dc(e){if(e===void 0)return;let t=kr(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=>!Nc.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 Pc(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 Gn=Mc(jc),Yt="@unbrained/pm-cli",Jc={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},Jn;async function wo(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 Wn(e,t,n){let a=e.split("/").map(l=>l.trim()).filter(l=>l.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 Wc(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 Wc(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 Wn(s,n,a)}catch{return null}})();if(r)return r;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let i=Wn(o,n,a);if(!i)throw new _(`Invalid GitHub source "${n}".`,y.USAGE);return i}if(t.forceGithub){let i=Wn(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=Gn,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 qc(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Gc(e=process.platform){return e==="win32"}async function vo(e,t,n=Gn,a=process.platform){let r=qc(a);try{return((await n(r,e,{cwd:t,encoding:"utf8",shell:Gc(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 Hc(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 Bc(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 Vc(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return Bc(e)||n.includes("not found")}function Kc(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Yc(e){let t=Hc(e),n=Kc(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 Xc(e,t){if(!Vc(t))return null;let n=Yc(e);return new _(n.message,y.NOT_FOUND,n.context)}async function bo(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=Lc(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 Qc(e){let t=await bo(e);if(t)return t;let n=Zc(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Zc(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 el(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 tl(e){return nl(e,vo)}async function nl(e,t){let n=await bo(e.spec);if(n){if((await O.stat(n)).isFile()&&ko(n))return xo(n);let s=$.join(n,"package.json"),c=await E(s)?JSON.parse(await O.readFile(s,"utf8")):{};return{directory:await mt(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(qn.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 Qc(e.spec),s=await t(["pack",i,"--json","--pack-destination",r]),c=el(s,r);await Gn("tar",["-xzf",c.tarball,"-C",o],{encoding:"utf8"});let l=$.join(o,"package");return await So(l),{directory:await mt(l,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=Xc(e.spec,i);throw s||i}}function ko(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ye(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 al(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 xo(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(qn.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 zc({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(i===void 0)try{al(d,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 Uc({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"),l=JSON.parse(await O.readFile(c,"utf8"));return await So(s),{directory:await mt(s,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.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 So(e,t=vo){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=ll(r),i=rl(r);if(o.length===0&&!i)return;let s={...a};delete s.devDependencies;let c={...s};ol(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 il(e)}finally{await O.writeFile(n,`${JSON.stringify(s,null,2)}
9
- `,"utf8")}}function rl(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 ol(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 il(e){let t=be(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,sl(process.platform))}function sl(e){return e==="win32"?"junction":"dir"}function cl(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{Fc.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 ll(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,cl(a,o))}return[...t.values()]}async function mt(e,t){let n=await Ct(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 dl(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 mt(e,t.input);return{directory:a,resolved_subpath:$.relative(e,a).replaceAll($.sep,"/")}}function ul(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 ml(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!ul(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()):"";Jn?.key!==i&&(Jn={key:i,aliases:await Vt()}),a=Jn.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 Eo(e){if(e.kind==="local"){let a;try{a=await O.stat(e.absolute_path)}catch{throw await ml(e)}if(a.isFile()&&ko(e.absolute_path)){let o=await xo(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 mt(e.absolute_path,e.input);return{source:e,directory:r,source_root:e.absolute_path}}if(e.kind==="npm"){let a=await tl(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(qn.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 dl(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 $o(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 pt from"node:fs/promises";import ft 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 Hn=1,Pe="2026.6.24",pl=">=22.18.0",fl={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},To=new Set([...Ga.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Va).map(e=>e.toLowerCase()),"scaffold"]),hl="^6.0.0",gl="^22.0.0",Co=["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 Io(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Ro(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 Oo(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 _l={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Ao=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],No={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"]},yl={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"]'},wl={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."},vl={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."},Do="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",bl={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."]},kl={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."]},xl={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`."]},Sl={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 Po(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 jo(e,t){return e==="schema"?xl[t]:e==="profile"?Sl[t]:kl[t]}function El(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&&To.has(r));return`${(To.has(n)||o?["starter",...t]:t).join(" ")} ping`}function Lo(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 $l(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`,l=e.replace(/-/g,""),d=l===s?[]:[l],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(d)},`," // 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({",...Lo(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 Tl(e,t,n){let a=n==="hooks",r=n==="search",o=n==="importers",i=n==="schema",s=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",u=n==="services",m=yl[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?Bn(e,t,"search",m):[],I=o?Bn(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 {",...Io(Ro({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 {",...Io(Oo(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=l?[`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=d?[`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";',"",...Co,`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)},`,...l?[" 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 Il(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 Al={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"},Cl={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 Rl(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 Ol(e,t,n){let a=[],r=[...Rl(e,t,n)],o=[" commands: [pingCommand],"],i=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,l=e,d=`${e}s`,u=e.replace(/-/g,""),m=u===l?[]:[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(l)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` 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({",...Lo(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 Nl(e,t,n){let a=Ol(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 Bn(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`,l=`${e.replace(/-/g,"_")}_note`,d=`${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(Ro({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:l,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Oo(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 Dl(e,t,n){let a=n==="parser",r=JSON.stringify([...No[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" };',"",...Co,`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,"});","",...Bn(e,t,n,r)].join(`
12
- `)}function Pl(e,t,n){let a=Po(n,"package"),r=jo(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 (${Al[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`.",Do,"- `.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 ${Cl[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 \`${Hn}\` 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 jl(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 Ll(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 Ml(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 Fl(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 Ul(e,t,n,a="commands",r=!1){let o=`pm-${e}`,i=No[a],s=Il(e,t,a),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Hn,pm_min_version:Pe,trusted:!0,sandbox_profile:"strict",permissions:{...fl},capabilities:i,...s.length>0?{activation:{commands:s}}:{}},null,2)}
14
- `,l=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...$l(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
- `),d=`${JSON.stringify(_l,null,2)}
16
- `,u=wl[a],m=Po(a,"package"),h=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:pl},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Pe}`},devDependencies:{"@types/node":gl,typescript:hl},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=Tl(e,t,a),p=vl[a],g=["node_modules/","*.log","*.tsbuildinfo",""].join(`
18
- `),w=jl(e),x=["```ts",`import { ${Ll(a)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Ml(e,t,a,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Fl(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,Do,"- `.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`.",...bl[a],...jo(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 \`${Hn}\` 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?Nl(e,t,a):l,"index.test.ts":r?Dl(e,t,a):f,"tsconfig.json":d,".gitignore":g,"README.md":r?Pl(o,t,a):I}}async function Mo(e,t="extension",n="commands",a=!1){let r=n.trim().toLowerCase();if(!Ao.includes(r))throw new _(`Unknown scaffold capability "${n}". Supported capabilities: ${Ao.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=ft.resolve(process.cwd(),s),l=Ht(ft.basename(c)).replace(/^(?:pm-)+/u,""),d=El(l),u=Ul(l,d,t,o,a),m=!1;if(await E(c)){if(!(await pt.stat(c)).isDirectory())throw new _(`Scaffold target "${c}" exists and is not a directory.`,y.CONFLICT)}else await pt.mkdir(c,{recursive:!0}),m=!0;for(let[f,p]of Object.entries(u)){let g=ft.join(c,f);if(!await E(g))continue;if(await pt.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=ft.join(c,f);if(await E(g)){h.push({path:f,status:"unchanged"});continue}await pt.mkdir(ft.dirname(g),{recursive:!0}),await pt.writeFile(g,p,"utf8"),h.push({path:f,status:"created"})}return{extension_name:l,package_name:`pm-${l}`,command_name:d,invocation_command:`pm ${d}`,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 Fo(e,t){return`${e}:${k(t)}`}function zl(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(l=>t.has(k(l.name))))continue;let c=s.at(-1);n.push({command:i,surface:a,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(l=>({name:l.name,layer:l.layer,winner:l===c}))})}}return n.sort((a,r)=>a.command.localeCompare(r.command)||a.surface.localeCompare(r.surface))}function Uo(e,t,n){let a=new Set(n.failed.map(l=>Fo(l.layer,l.name))),r=[...t.loaded.map(l=>({name:l.name,layer:l.layer,version:l.version,activation_status:a.has(Fo(l.layer,l.name))?"failed":"ok",surfaces:Ge(n,{extensionName:l.name})})),...t.failed.map(l=>({name:l.name,layer:l.layer,version:"unknown",activation_status:"not_loaded",surfaces:Ge(n,{extensionName:l.name})}))].sort((l,d)=>l.name.localeCompare(d.name)||l.layer.localeCompare(d.layer)),o=typeof e=="string"?k(e):null,i=o===null?null:new Set(t.loaded.filter(l=>k(l.name)===o||typeof l.source_package=="string"&&k(l.source_package)===o||(l.source_aliases??[]).some(d=>k(d)===o)).map(l=>k(l.name)).concat(o)),s=i===null?r:r.filter(l=>i.has(k(l.name))),c=i===null?{}:{extensionNames:[...i]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Ge(n,c),command_ownership:zl(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 Vn(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 Jl(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 zo(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Wl(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}=Jl(n);return e.map(c=>{let l=k(c.name),d=zo(i.get(l)),u=zo(s.get(l)),m={...d?{command_paths:d}:{},...u?{action_paths:u}:{}},h=Wl({enabled:c.enabled,normalizedName:l,loadedNames:a,loadFailedNames:r,activationFailedNames:o});return{...c,...h,...m}})}function ql(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 qo=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 Gl(e){return qo.has(Yo(e))}function Jo(e){return e==="project"||e==="global"}function Go(e){let t=e.split(":"),n=t[0];if(!n||!qo.has(n))return null;let a=t.at(-4),r=t.at(-3)?.trim(),o=t.at(-2),i=t.at(-1)?.trim();return!Jo(a)||!Jo(o)||!r||!i?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:a,name:r},displaced:{layer:o,name:i}}}function Hl(e){let t=new Set;for(let n of e){let a=Go(n);a&&(t.add(a.winner.name),t.add(a.displaced.name))}return[...t].sort((n,a)=>n.localeCompare(a))}function Kn(e,t){let n=e.filter(Gl);if(n.length===0)return null;let a=Hl(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 Bl(e,t,n,a){let r=t.map(u=>Go(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=G(a,"deactivate"),s=`${G(a,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(u=>[k(u.name),u])),l=new Map;for(let u of r)for(let m of[u.winner.name,u.displaced.name]){let h=k(m);l.set(h,(l.get(h)??0)+1)}let d=[...l.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:l.size,next_best_command:s,collisions:r,remediation_candidates:d}}function Ho(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 Bo(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 Vo(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 Vl=[{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: ${Et.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 Kl(e){let{normalizedWarnings:t,options:n,scope:a,scopeFlag:r,updateCheckFailedTotal:o,policyWarningCount:i,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,u=[],m={options:n,scope:a,scopeFlag:r,updateCheckFailedTotal:o,policyWarningCount:i};if(t.length>0){let h=Kn(t,{deactivate:`${G(n,"deactivate")} <name> ${r}`,doctor:`${G(n,"doctor")} ${r} --detail deep --trace`});h&&u.push(h);for(let f of Vl)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 ${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.`),l>0&&u.push("Non-GitHub managed extensions are skipped by update checks. Use doctor output for non-update diagnostics."),d>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 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,l=n.filter(S=>S.managed===!1),d=l.filter(S=>Wo(S)).map(S=>S.name).sort((S,L)=>S.localeCompare(L)),u=l.filter(S=>!Wo(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=>Yo(S)))].sort((S,L)=>S.localeCompare(L)),b=ql(x),T=e==="global"?"--global":"--project",J=Bl(e,r,n,a),W=Kl({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:l.length,unmanaged_loaded_extensions:l.map(S=>S.name).sort((S,L)=>S.localeCompare(L)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,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 Ko(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 Yo(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function ht(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 gt(){return{version:$t.version,capabilities:[...$t.capabilities],legacy_aliases:{...$t.legacy_aliases}}}function Wo(e){let t=k(e.name),n=k(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Xo(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(d=>d.active).map(d=>k(d.name)))].sort((d,u)=>d.localeCompare(u)),i=[...new Set(n.filter(d=>d.layer==="project").map(d=>k(d.name)))].sort((d,u)=>d.localeCompare(u)),s=new Set(a.map(d=>k(d.name))),c=o.filter(d=>!i.includes(d)&&!s.has(d)).sort((d,u)=>d.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 Yl}from"node:crypto";import F from"node:fs/promises";import Xl 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 Qo=3,Ql=120,Zo=250,Zl=12e4,ed=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),ei=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,ti=e=>ed.has(String(ei(e))),_t=(e,t)=>ei(e)===t,ni=e=>new Promise(t=>{setTimeout(t,e)}),ai=async e=>{let t=N.join(e,"package.json");await E(t)||await F.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
20
- `,"utf8")},ri=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")},Yn=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 l=N.join(r,c);try{r=await F.realpath(l)}catch{r=N.join(r,...i.slice(s));break}}return N.join(r,N.basename(t))},oi=async(e,t,n,a=Xl.tmpdir())=>{let r=N.resolve(e),o=await F.realpath(r).catch(()=>r),i=await Yn(t);if(o===i)return;if(!oe(o,i)){await n(e,t,{recursive:!0,force:!0});return}let s=m=>{let h=N.resolve(m);if(h!==r&&!oe(r,h))return!1;let f=N.resolve(o,N.relative(r,h));if(f===i||oe(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(()=>Yn(a)),l=oe(o,c)?N.dirname(o):c;if(oe(o,l))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 d=await F.mkdtemp(N.join(l,"pm-extension-copy-")),u=N.join(d,"extension");try{await n(e,u,{recursive:!0,force:!0,filter:s}),await n(u,t,{recursive:!0,force:!0})}finally{await F.rm(d,{recursive:!0,force:!0})}},ii=async(e,t,n=F.cp)=>{for(let a=1;a<=Qo;a+=1)try{await F.rm(t,{recursive:!0,force:!0}),await oi(e,t,n);return}catch(r){if(!ti(r)||a===Qo)throw r;await ni(Zo)}},Xn=async e=>{let t;try{t=await F.readFile(N.join(e,"owner.json"),"utf8")}catch(r){if(!_t(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},si=async(e,t)=>await Xn(e)!==t?!1:(await F.rm(e,{recursive:!0,force:!0}),!0),td=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 Xn(e);return a===null?(await F.rm(e,{recursive:!0,force:!0}),!0):si(e,a)},nd=(e,t,n)=>{let a=Promise.resolve(),r=setInterval(()=>{a=a.then(async()=>{if(await Xn(e)!==t)return;let o=new Date;await F.utimes(e,o,o)}).catch(()=>{})},n);return r.unref(),async()=>{clearInterval(r),await a}},ad=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}},rd=async(e,t,n,a,r)=>{for(let o=1;o<=n;o+=1)try{return await ad(e,t),!0}catch(i){if(!_t(i,"EEXIST"))throw i;await td(e,r)?o-=1:await ni(a)}return!1},Qn=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=Ql,delay_ms:s=Zo,stale_ms:c=Zl,heartbeat_ms:l}=a??{};if(![i,s,c,l].filter(w=>w!==void 0).every(Number.isFinite))throw new _("Extension install lock timings must be finite numbers.",y.USAGE);let d=Math.max(1,Math.floor(i)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),h=Math.floor(l??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:Yl(),created_at:A(),destination:t};if(!await rd(o,f,d,u,m))throw new _(`Timed out waiting for extension install lock for "${t}".`,y.CONFLICT);let g=nd(o,f.token,h);try{return await n()}finally{await g(),await si(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 ci=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 li(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 ui=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 od=1e4,id=(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"}},mi=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,od);return id(r,e.commit,n)}catch(a){return{checked_at:n,available:null,error:a instanceof Error?a.message:String(a)}}};import sd from"node:fs/promises";import cd 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 Zn(e){return cd.join(e,"extension-migrations.json")}function pi(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 fi(e,t){return`${e.layer}:${e.name}:${t}`}async function ld(e){let t=Zn(e);if(!await E(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await sd.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 ea(e,t){let n=await ld(e),a=new Map(n.entries.map(r=>[r.key,r]));return t.forEach((r,o)=>{let i=pi(r,o),s=a.get(fi(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 dd(e){let t=await ea(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),a=[],r=!1,o=e.migrations.map((d,u)=>({migration:d,index:u})).filter(({migration:d})=>e.scope===void 0||d.layer===e.scope);for(let{migration:d,index:u}of o){let m=pi(d,u),h=fi(d,m),f=n.get(h),p=String(d.definition.status??"pending").toLowerCase(),g=f?.status??(p==="applied"||p==="failed"?p:"pending");if(g==="applied"){a.push({key:h,layer:d.layer,extension:d.name,id:m,before:g,outcome:"skipped"});continue}if(e.dryRun===!0){a.push({key:h,layer:d.layer,extension:d.name,id:m,before:g,outcome:"pending"});continue}let w=d.runtime_definition?.run??d.definition.run;if(typeof w!="function"){a.push({key:h,layer:d.layer,extension:d.name,id:m,before:g,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:g}));let x={key:h,layer:d.layer,extension:d.name,id:m,status:"applied",attempted_at:v};n.set(h,x),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,a.push({key:h,layer:d.layer,extension:d.name,id:m,before:g,outcome:"applied"}),r=!0}catch(x){let I=x instanceof Error?x.message:String(x),b={key:h,layer:d.layer,extension:d.name,id:m,status:"failed",attempted_at:v,error:I};n.set(h,b),d.definition.status="failed",d.definition.reason=I,a.push({key:h,layer:d.layer,extension:d.name,id:m,before:g,outcome:"failed",error:I}),r=!0}}if(r){let d=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:Zn(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
22
- `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let i=a.filter(d=>d.outcome==="pending").length,s=a.filter(d=>d.outcome==="applied").length,c=a.filter(d=>d.outcome==="skipped").length,l=a.filter(d=>d.outcome==="failed").length;return{ok:l===0,dry_run:e.dryRun===!0,state_path:Zn(e.pmRoot),total:a.length,pending_count:i,applied_count:s,skipped_count:c,failed_count:l,migrations:a}}async function hi(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 dd({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 gi(e,t,n){let a=typeof t=="string"?null:await ut(e),r=a===null?null:e.trim().toLowerCase(),o=r===null?null:await go(r),i=Xt(a??e,{forceGithub:typeof t=="string",ref:n}),s=r===null?null:await wo(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 ud 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 ta=async e=>je.readFile(e).catch(t=>{if(_t(t,"ENOENT"))return null;throw t}),_i=async(e,t,n,a,r)=>{let o=ct(e),i=ee(t),[s,c]=await Promise.all([ta(o),ta(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}},yi=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(ud.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 md=4,xi=[["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"]],wi=xi.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),pd={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"},fd="__pm_native_output",hd=["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"],Si=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],gd=["disabled","require_trusted","require_provenance"],Ei={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:[]},_d=e=>{let t=e??Ei,n={};for(let a of hd)n[a]=Q(t[a]??[]);return n},yd=(e,t)=>{for(let n of Si)t[n].length>0&&(e[n]=t[n]);return e},wd=(e,t)=>{for(let n of gd)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},vd=e=>{let t={};for(let n of Si)t[n]=Q(e[n]??[]);return t},bd=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:yd(wd({name:t},e),vd(e))},kd=e=>(e??[]).map(t=>bd(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),xd=e=>{let t=Object.assign({},Ei,e??{}),n=_d(e),a=kd(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}},$i=async(e,t)=>{let n=[t],a=await _o(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}},Ti=(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)},Ii=(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")},Sd=(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")},Ed=(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")},$d=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),a=xi.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},Td=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=$d(e);if(!a)return new _(`One action flag is required. Use one of: ${wi}. 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: ${wi}.`,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}"`}]}})},Id=[["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"]],Ad={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Cd=e=>Ad[e]??null,Rd=(e,t)=>{let n=[...new Set(Id.filter(([a])=>t[a]===!0).map(([,a])=>a))];if(n.length===0){if(e===void 0)return"explore";let a=Cd(e.trim().toLowerCase());if(a)return a;throw Td(e,t)}if(n.length>1)throw new _("Extension action flags are mutually exclusive.",y.USAGE);return n[0]},Od=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"},Nd=[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"}}],Ai=e=>{for(let t of Nd){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Ci=(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}},Dd=(e,t,n,a)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},a),o=a?Ti(n,a.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Ci({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:o},t,a,Ai(a))}},Pd=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 Dd(t,n,a,c);let l=Symbol("invalid-extension-manifest-json"),d=await Ie.readFile(s,"utf8").then(h=>JSON.parse(h)).catch(()=>l);if(d===l)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=Mn(d);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=r.get(k(u.name))??o.get(k(t));return{summary:Ci({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:Ti(a,u.name)},n,m,Ai(m))}},de=async(e,t,n,a)=>{if(!await E(e))return{extensions:[],warnings:[]};let o=(await Ie.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,u)=>d.localeCompare(u)),i=new Map(a.entries.map(d=>[k(d.name),d])),s=new Map(a.entries.map(d=>[k(d.directory),d])),c=[],l=[];for(let d of o){let u=await Pd(e,d,t,n,i,s);u.warning&&c.push(u.warning),u.summary&&l.push(u.summary)}return{extensions:l.sort((d,u)=>d.name.localeCompare(u.name)),warnings:c.sort((d,u)=>d.localeCompare(u))}},jd=Ka(),Ld=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Md=(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:Ld(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"}:{}}},Fd=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},Ri=e=>e.map(t=>Fd(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),Oi=(e,t,n)=>{let a=k(e);return t.find(r=>(n===void 0||r.layer===n)&&k(r.name)===a)},Ud=(e,t,n,a)=>n.find(o=>o.scope===t&&k(o.name)===k(e))?.activation_status??(a?"failed":"unknown"),Ni=(e,t,n,a,r)=>jd.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:hn(),cache_bust:!0,module_graph_snapshot_root:i}),c=await se({...s}),l=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...Ri(c.failed)],d=Object.fromEntries(s.loaded.map(u=>[k(u.name),Ca(Ge(c,{extensionName:u.name}))]));return{installed:Zt(a,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:l,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:d}}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}}),aa=async(e,t,n,a)=>{let r=n.filter(c=>!c.managed),o=[...r].sort((c,l)=>{let d=c.name.localeCompare(l.name);return d!==0?d:c.directory.localeCompare(l.directory)}),i=a,s=[];for(let c of o){let l=ne.join(e,c.directory),d=await Ye(l),u=A(),m={kind:"local",input:c.name,location:l};i=dt(i,{name:d.manifest.name,directory:c.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:u,updated_at:u,source:m}),s.push({name:d.manifest.name,directory:c.directory,version:d.manifest.version,entry:d.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}},zd=(e,t)=>{let n=P(process.cwd(),t.path),a=Me(n,process.cwd()),r=e==="global"?It(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]},Jd=e=>pd[e],Wd=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=e==="install"?"source":"name",r=`${n} ${a}`,o=Jd(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 Wd(t,n)},qd=(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))},Gd=(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)},Hd=(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},Bd=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},Vd=(e,t,n)=>{let a={ok:n,action:e.action,scope:e.scope,roots:Bd(e),warnings:[...new Set(e.warnings)].sort((r,o)=>r.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(a,fd,{value:!0,enumerable:!1,configurable:!1}),a},ra=async(e,t,n)=>{let a=Rd(e,t);Gd(a,t);let r=Hd(e,a,t),o=Od(t),i=zd(o,n),c={action:a,normalizedTarget:r,scope:o,resolvedRoots:i,warnings:[],options:t,global:n},d={...c,withResult:(u,m=!0)=>Vd(c,u,m)};return await Tu(d)},Kd=(e,t)=>{let n=t.vocabulary??"extension",a=e.target_path.replace(/\\/g,"/"),r=In(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: ${jr(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`]},Yd=async e=>{let{action:t,normalizedTarget:n,options:a,withResult:r}=e;if([tn(a),a.ref].filter(l=>typeof l=="string").map(l=>l.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 Mo(s,a.vocabulary??"extension",a.capability,a.declarative===!0);return r({scaffolded:c.created_directory||c.files.some(l=>l.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:Kd(c,a)})},Xd=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=hn(),l=await ie({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});a.push(...l.warnings);let d=await se(l);a.push(...d.warnings);let u={reload:{token:c,cache_bust:!0,watch:r.watch===!0},loaded_count:l.loaded.length,failed_count:l.failed.length,activated_count:Math.max(0,l.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:l.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:d.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)},Qd=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 yo(n,r,a))},Zd=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),eu=e=>({kind:"local",input:e.input,location:e.absolute_path}),tu=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),nu=(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}),au=(e,t,n,a)=>e?Zd(e,t):n.kind==="local"?eu(n):n.kind==="npm"?tu(n,a):nu(n,a),ru=(e,t,n,a)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:a}:uo(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},ou=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 l=ne.join(a.selected_root,i),d=await E(l),u=await $o(o.directory,l);await Ie.mkdir(a.selected_root,{recursive:!0});let m=await Ie.mkdtemp(ne.join(a.selected_root,".pm-extension-install-backup-")),h=ne.join(m,"destination");try{let f=await _i(a.selected_root,a.settings_root,l,d,h),p=au(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),g=c.state.entries.find(I=>k(I.name)===k(o.manifest.name)),w=ru(g,o.manifest.version,p,A()),v=dt(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=Ii(s,o.manifest.name);try{u||await ii(o.directory,l),await ai(l),await ri(l),await De(a.selected_root,v),x&&await Ut(a.settings_root,s,"settings:write")}catch(I){try{await yi(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:l,destinationExists:d,installInPlace:u,activationChanged:x}}finally{await Ie.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},iu=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 it(e.resolvedRoots.pm_root,a,e.warnings,"install:type-folder"),a},su=(e,t,n,a,r)=>{let o=Oi(t,n.activation_failures,e.scope),i=Ud(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)]}}},cu=async(e,t)=>{let{scope:n,resolvedRoots:a,warnings:r,global:o,withResult:i}=e,{validated:s,destinationDirectoryName:c}=t,l=await ou(e,t),d=await de(a.selected_root,n,l.settings,l.managedState);r.push(...d.warnings);let u=await Ni(a.pm_root,ne.dirname(a.selected_root),l.settings,d.extensions,o);r.push(...u.warnings);let m=await iu(e,s.manifest.name,u.item_type_registrations),h=li(s.manifest.name,u.installed),f=su(e,s.manifest.name,u,h,m),p=u.contribution_inventories[k(s.manifest.name)];return p&&(l.managedState=await mo(a.selected_root,l.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:l.sourceRecord,source_resolution:t.sourceResolution,destination_path:l.destinationDirectory,overwritten:[l.destinationExists,!l.installInPlace].every(Boolean),installed_in_place:l.installInPlace,activated:f.activated,settings_changed:l.activationChanged,runtime_activation_status:f.status,command_paths:h.command_paths,action_paths:h.action_paths,contributions:p,command_discovery:Md(s.manifest.name,l.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)},lu=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 l=await ut(c),d=ne.resolve(l),u=i.get(d);u===void 0&&(u=await ra(c,{...t,install:!0},n),i.set(d,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 l=c.result.details;return{alias:c.alias,ok:c.result.ok,extension:l.extension,source:l.source,source_resolution:l.source_resolution,destination_path:l.destination_path,activated:l.activated,settings_changed:l.settings_changed,command_paths:l.command_paths,action_paths:l.action_paths,command_discovery:l.command_discovery,verification:l.verification,runtime_activation_status:l.runtime_activation_status,activation_diagnostics:l.activation_diagnostics,warnings:c.result.warnings}})},s)},du=async(e,t,n)=>{let{resolvedRoots:a}=e,{bundledAliasName:r,bundledPackageName:o,installSource:i,sourceResolution:s}=await gi(t,n,e.options.ref);if(s.ambiguous){let l=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${r}:npm:${l.package}`)}let c=await Eo(i);try{let l=await Ye(c.directory,{source_kind:i.kind,source_input:i.input,source_root:c.source_root}),d=Ht(l.manifest.name);return await Qn(a.settings_root,d,()=>cu(e,{validated:l,destinationDirectoryName:d,bundledAliasName:r,bundledPackageName:o,sourceResolution:s,installSource:i,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},uu=async e=>{let t=tn(e.options),n=t??nn(e.normalizedTarget,e.action,e.options);return[t===void 0,fo(n)].every(Boolean)?lu(e):du(e,n,t)},mu=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),l=await B(a.selected_root);r.push(...l.warnings);let d=await de(a.selected_root,n,c,l.state);r.push(...d.warnings);let u=await aa(a.selected_root,n,d.extensions,l.state),m=await de(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,...Di(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})},Di=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),pu=(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}},fu=async e=>{let{action:t,normalizedTarget:n,scope:a,resolvedRoots:r,warnings:o,options:i,withResult:s}=e,c=nn(n,t,i),l=tn(i),d=await R(r.settings_root),u=await B(r.selected_root);o.push(...u.warnings);let m=await de(r.selected_root,a,d,u.state);o.push(...m.warnings);let h=await $i(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=ne.join(r.selected_root,h.directory),p=await Ye(f),g=A(),w=pu(l,c,f,i.ref),v=dt(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 de(r.selected_root,a,d,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,...Di(I)})},Pi=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),l=await B(r.selected_root);o.push(...l.warnings);let d=await de(r.selected_root,a,c,l.state);o.push(...d.warnings);let u=await $i(d.extensions,s);if(!u)throw new _(`Installed extension "${s}" was not found in ${a} scope.`,y.NOT_FOUND);return{settings:c,managedStateRead:l,candidate:u}},hu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:a,managedStateRead:r,candidate:o}=await Pi(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(l=>k(l.name)!==k(o.name)&&k(l.directory)!==k(o.directory))};await De(t.selected_root,s);let c=Ed(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})},vi=async e=>{let{action:t,resolvedRoots:n,warnings:a,global:r,withResult:o}=e,{settings:i,candidate:s}=await Pi(e),c=t==="activate"?Ii(i,s.name):Sd(i,s.name);c&&await Ut(n.settings_root,i,"settings:write");let l=t==="activate"?await Ni(n.pm_root,ne.dirname(n.selected_root),i,[s],r).then(d=>(a.push(...d.warnings),Oi(s.name,d.activation_failures,e.scope))):void 0;return l&&a.push(`extension_activate_failed:${e.scope}:${s.name}`),o({extension:{name:s.name,directory:s.directory},active:t==="activate"&&l===void 0,runtime_active:t==="activate"&&l===void 0,activation_failure:l??null,settings_changed:c,settings:{enabled:[...i.extensions.enabled],disabled:[...i.extensions.disabled]}},l===void 0)},gu=(e,t,n,a,r,o)=>{let i=a==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[i],c=r?.adopted_entries.length??0,l=[[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,...l.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},na=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),_u=(e,t,n,a)=>{if(e!=="project"||t||!na(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.`},yu=(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=Ko(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}},wu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let a=await aa(e.resolvedRoots.selected_root,e.scope,t,n);return{state:a.state,fix:a}},vu=(e,t,n,a)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:na(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:na(a),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},bu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:r,options:o,global:i,withResult:s}=e,{isolated:c,detailMode:l,includeTrace:d}=yu(t,n,o),u=await R(a.settings_root),m=await B(a.selected_root);r.push(...m.warnings);let h=await de(a.selected_root,n,u,m.state);r.push(...h.warnings);let{state:f,fix:p}=await wu(e,h.extensions,m.state),g=await de(a.selected_root,n,u,f);r.push(...g.warnings);let w=await ie({pmRoot:a.pm_root,settings:u,cwd:process.cwd(),noExtensions:i.noExtensions===!0,ignoreGlobalExtensions:c}),v=await se({...w,loaded:w.loaded});r.push(...w.warnings),r.push(...Ho(w.failed)),r.push(...v.warnings),r.push(...Bo(v.failed)),r.push(...Vo(w,v)),r.push(...di(v,w)),r.push(...qd(w,v)),r.push(...ui(v));let x=Zt(g.extensions,w,v),I=Xo(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=ht(J),L=gt(),ue=T.warning_codes,tt=_u(n,c,o.vocabulary,w),nt=gu(T.remediation,w.failed.length,v.failed.length,o.vocabulary,p,tt),Ae=vu(n,c,o.vocabulary,w),at={status:T.status,scope:n,warning_count:T.warning_count,warning_codes:ue,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:Vn(w.failed),activation_failures:Vn(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:d,isolation:Ae,policy:W,remediation:nt},xt=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:[]},Le={mode:l,summary:at,triage:T,trace_enabled:d,capability_contract:L,capability_guidance:S,managed_state_fix:xt,isolation:Ae,policy:w.policy};if(l==="deep"){let C=d?v.failed:v.failed.map(D=>{let{trace:St,...ps}=D;return ps});Le.deep={warnings:J,warning_codes:ue,capability_contract:L,capability_guidance:S,trace_enabled:d,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},d&&(Le.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(Le)},ku=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:r,options:o,global:i,withResult:s}=e,c=await R(a.settings_root),l=await ie({pmRoot:a.pm_root,settings:c,cwd:process.cwd(),noExtensions:i.noExtensions===!0}),d=await se(l);r.push(...l.warnings),r.push(...d.warnings);let u=Uo(t,l,d);if(t!==void 0&&u.extensions.length===0){let m=o.vocabulary==="package"?"package":"extension",h=[...new Set(l.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})},xu=async(e,t,n)=>{let a=n,r=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await aa(e.resolvedRoots.selected_root,e.scope,t,n),a=r.state),e.action==="manage"){let o=await ci(a.entries,md,async i=>{if(i.source.kind!=="github")return i;let s=await mi(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:lt(o)},await De(e.resolvedRoots.selected_root,a)}return{state:a,fix:r}},Su=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:Zt(n,a,r),failures:Ri(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}}},Eu=(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},bi=async e=>{let{action:t,scope:n,resolvedRoots:a,warnings:r,options:o,withResult:i}=e,s=await R(a.settings_root),c=xd(s.extensions.policy),l=await B(a.selected_root);r.push(...l.warnings);let d=await de(a.selected_root,n,s,l.state);r.push(...d.warnings);let{state:u,fix:m}=await xu(e,d.extensions,l.state),h=await de(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 Su(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=Eu(m,p)),i(w)},ki={init:Yd,install:uu,uninstall:hu,explore:bi,manage:bi,describe:ku,reload:Xd,doctor:bu,catalog:Qd,adopt:fu,"adopt-all":mu,activate:vi,deactivate:vi,migrate:hi},$u=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),Tu=e=>$u(e)?Qn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>ki[e.action](e)):ki[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 Ru=Cu(Iu),Ou="@unbrained/pm-cli",Nu="latest";function Du(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 ji(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 Pu(e,t){let n=P(process.cwd(),t.path),a=Me(n,process.cwd());return{selected_root:e==="global"?a.global:a.project}}async function ju(e,t,n){try{let a=await Ru(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 Lu(){return Sa(import.meta.url,["../../.."])}function on(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():Nu}function an(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():Ou}async function Mu(e,t){let n=e.commandRunner??ju,a=an(e),r=on(e),o=`${a}@${r}`,i=["npm","install","-g",o];e.repair===!0&&i.push("--force");let s=await Lu(),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 l=await n("pm",["--version"]);return{...c,status:"updated",after_version:l.stdout.trim()||void 0}}catch(l){return{...c,status:"failed",error:l instanceof Error?l.message:String(l)}}}function Fu(e){return Au.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function Uu(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!Fu(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 zu(e,t){let n=Uu(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 Li(e,t){let n=Pu(e,t);return(await B(n.selected_root)).state.entries.filter(r=>r.scope===e)}async function Wu(e,t,n){let a=await Li(e,t);return a.find(r=>ji(r,n.name))??a.find(r=>rn(r.directory)===rn(n.directory))}async function qu(e,t,n,a,r){let o=on(t),i=await zu(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 ra(i,{install:!0,project:a==="project",global:a==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let l=await Wu(a,n,e);return{...c,status:"updated",installed_version:l?.manifest_version}}catch(l){return{...c,status:"failed",error:l instanceof Error?l.message:String(l)}}}function Gu(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 W_(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=Du(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 Mu(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"},l=s?await Li(a,n):[];if(o&&(l=l.filter(m=>ji(m,o)),l.length===0))throw new _(`Managed package "${o}" was not found in ${a} scope.`,y.NOT_FOUND);let d=[];for(let m of l)d.push(await qu(m,t,n,a,r));let u=Gu(c,d,i,s);return{ok:u.failed===0,action:"upgrade",dry_run:r,scope:a,target:o,cli:c,packages:d,summary:u}}import Xe from"node:fs/promises";import dn from"node:path";import sn from"node:fs/promises";import oa 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 Hu=864e5;function cn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Bu(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 Vu(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=oa.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 Mi(e,t){let{dryRun:n,hooks:a}=t,r=t.now??Date.now(),o=Math.max(0,t.retentionDays)*Hu,i=oa.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await Vu(i,s.warnings);for(let l of c){let d=oa.join(i,l),u=`checkpoints/${l}`;s.scanned+=1,a?.onRead&&s.warnings.push(...await a.onRead(d));let m;try{m=await sn.readFile(d,"utf8")}catch(w){if(cn(w,"ENOENT")){s.scanned-=1;continue}s.warnings.push(`checkpoint_unreadable:${l}`),s.retained.push(u),s.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=Bu(m),f=h===null?Number.NaN:Date.parse(h);if(!Number.isFinite(f)){s.warnings.push(`checkpoint_unparseable:${l}`),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(d)}catch(w){if(!cn(w,"ENOENT")){s.warnings.push(`checkpoint_remove_failed:${l}`),s.retained.push(u),s.entries.push(g);continue}}a?.onWrite&&s.warnings.push(...await a.onWrite(d))}s.removed.push(u),s.entries.push(g)}return s}import ia from"node:fs/promises";import Fi 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 Ku=1440*60*1e3,Yu=new Set(["committed","compensated"]);function Xu(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Qu(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 Zu(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 Yu.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 em(e,t,n,a){let r=a.hooks?.onRead?await a.hooks.onRead(e):[],o=Qu(await ia.readFile(e,"utf8")),i=Zu(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 ia.rm(e,{force:!0}),a.hooks?.onWrite&&r.push(...await a.hooks.onWrite(e))),{decision:i,warnings:r}}async function Ui(e,t){let{dryRun:n,hooks:a}=t,r=t.now??Date.now(),o=Math.max(0,t.retentionDays)*Ku,i=Fi.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await ia.readdir(i)).filter(l=>l.endsWith(".json")).sort((l,d)=>l.localeCompare(d))}catch(l){if(Xu(l,"ENOENT"))return s;throw l}for(let l of c){let d=Fi.join(i,l),u=`transactions/sdk/${l}`,m=await em(d,u,l,{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 yt from"node:fs/promises";import ln from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a026943f-1a46-526b-bfaa-435025c65c2a")}catch{}})();function tm(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 wt(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function zi(e,t,n){let a=tm(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 Ji(e,t){let n=t??Date.now(),a=ln.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 yt.readdir(a)).filter(s=>s.endsWith(".lock")).sort()}catch(i){if(wt(i,"ENOENT"))return r;throw i}for(let i of o){let s;try{s=await yt.readFile(ln.join(a,i),"utf8")}catch(l){if(wt(l,"ENOENT"))continue;r.scanned+=1,r.unreadable_lock_count+=1;continue}r.scanned+=1;let{detail:c}=zi(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 Wi(e,t){let{dryRun:n,hooks:a}=t,r=t.now??Date.now(),o=ln.join(e,"locks"),i={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await yt.readdir(o)).filter(l=>l.endsWith(".lock")).sort()}catch(c){if(wt(c,"ENOENT"))return i;throw c}for(let c of s){i.scanned+=1;let l=ln.join(o,c),d=`locks/${c}`;if(a?.onRead){let h=await a.onRead(l);i.warnings.push(...h)}let u;try{u=await yt.readFile(l,"utf8")}catch(h){if(wt(h,"ENOENT")){i.scanned-=1;continue}i.warnings.push(`lock_unreadable:${c}`),i.retained.push(d),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=zi(c,u,r);if(m.detail==="unparseable_json"){i.warnings.push(`lock_unparseable:${c}`),i.retained.push(d),i.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){i.warnings.push(`lock_invalid_timestamp:${c}`),i.retained.push(d),i.entries.push(m.entry);continue}if(m.detail==="active"){i.retained.push(d),i.entries.push(m.entry);continue}if(!n){try{await yt.unlink(l)}catch(h){if(!wt(h,"ENOENT")){i.warnings.push(`lock_remove_failed:${c}`),i.retained.push(d),i.entries.push(m.entry);continue}}if(a?.onWrite){let h=await a.onWrite(l);i.warnings.push(...h)}}i.removed.push(d),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 vt=["index","embeddings","runtime","locks","checkpoints","transactions"],nm=1440*60*1e3,am=[{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 qi(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function rm(e,t,n){let a=t.relativePath,r=dn.join(e,a),o=await fe({path:r,scope:"project"});try{let i=await Xe.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 Xe.unlink(r):await Xe.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(qi(i,"ENOENT"))return{removed:!1,warnings:o};throw i}}async function om(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],a=[],r=[],o=[],i=Date.now()-nm;for(let s of n){let c=dn.join(e,s.relativePath);if(!await E(c))continue;let l=(await Xe.readdir(c)).filter(d=>d.startsWith(s.prefix)).sort();for(let d of l){let u=dn.posix.join(s.relativePath,d),m=dn.join(c,d);o.push(...await fe({path:m,scope:"project"}));let h=await Xe.stat(m).catch(f=>{if(!qi(f,"ENOENT"))throw f});if(h){if(h.mtimeMs>i){r.push(u);continue}a.push(u),!t&&(await Xe.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 im(e){if(!e||e.length===0)return[...vt];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 (${vt.join(",")})`,y.USAGE);let n=new Set;for(let a of t){if(!vt.includes(a))throw new _(`Invalid --scope value "${a}". Expected one or more of: ${vt.join(", ")}`,y.USAGE);n.add(a)}return vt.filter(a=>n.has(a))}function sm(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 my(e,t={}){let n=P(process.cwd(),e.path);if(!await E(ee(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=im(t.scope),i=am.filter(f=>o.includes(f.scope)),s=[],c=[],l=[];for(let f of i){let p=await rm(n,f,r);p.removed?s.push(f.relativePath):c.push(f.relativePath),l.push(...p.warnings)}if(o.includes("runtime")){let f=await om(n,r);s.push(...f.removed),c.push(...f.retained),l.push(...f.warnings)}let d;if(o.includes("locks")){let f=await Wi(n,{dryRun:r,hooks:{onRead:p=>fe({path:p,scope:"project"}),onWrite:p=>U({path:p,scope:"project",op:"gc:lock_remove"})}});s.push(...f.removed),c.push(...f.retained),l.push(...f.warnings),d={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 Ui(n,{dryRun:r,retentionDays:f,hooks:{onRead:g=>fe({path:g,scope:"project"}),onWrite:g=>U({path:g,scope:"project",op:"gc:transaction_journal_remove"})}});s.push(...p.removed),c.push(...p.retained),l.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 Mi(n,{dryRun:r,retentionDays:f,hooks:{onRead:g=>fe({path:g,scope:"project"}),onWrite:g=>U({path:g,scope:"project",op:"gc:checkpoint_remove"})}});s.push(...p.removed),c.push(...p.retained),l.push(...p.warnings),m={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length,retention_days:f}}l.push(...await Lt({mode:r?"gc:dry-run":"gc",total_items:i.length}));let h=sm({dryRun:r,scopes:o,removed:s});return{ok:l.length===0,dry_run:r,scope:o,removed:s,retained:c,warnings:l,...d?{locks:d}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:h,generated_at:A()}}import Gi from"node:fs/promises";import Hi 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]="68d4d540-a878-57f1-b2ae-00b111f94b43")}catch{}})();var cm=8388608;function un(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function lm(e){try{return(await Gi.readdir(Hi.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function dm(e,t,n){let a;try{a=await Gi.open(Hi.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"),l=s>=r,d=c.lastIndexOf(`
24
- `),u=c;return l||(u=d===-1?"":c.slice(0,d+1)),{content:u,bytesRead:s,complete:l}}catch{return null}finally{await a?.close()}}function um(e){try{let t=JSON.parse(e);return un(t)?t:null}catch{return null}}function mm(e,t){if(!un(e.context))return;let n=e.context.agent_provenance_outcomes;if(!(!un(n)||typeof e.agent_harness!="string"))for(let[a,r]of Object.entries(n)){if(!un(r)||typeof r.resolver!="string"||r.status!=="resolved"&&r.status!=="failed")continue;let o=`${e.agent_harness}\0${a}\0${r.resolver}`,i=t.get(o)??{harness:e.agent_harness,dimension:a,resolver:r.resolver,attempts:0,successes:0};i.attempts+=1,r.status==="resolved"&&(i.successes+=1),t.set(o,i)}}function pm(e,t,n,a){let r=a;for(let o of e.split(`
25
- `)){if(o.trim().length===0)continue;if(r>=n)return{eventsRead:r,truncated:!0};r+=1;let i=um(o);i&&mm(i,t)}return{eventsRead:r,truncated:!1}}async function Bi(e,t=1e4){let n=new Map,a=0,r=0,o=!1;for(let s of await lm(e)){let c=await dm(e,s,Math.max(0,cm-r));if(c===null)continue;r+=c.bytesRead;let l=pm(c.content,n,t,a);if(a=l.eventsRead,l.truncated){o=!0;break}if(!c.complete){o=!0;break}}let i=[...n.values()].sort((s,c)=>s.harness.localeCompare(c.harness)||s.dimension.localeCompare(c.dimension)||s.resolver.localeCompare(c.resolver));return{outcomes:i,warnings:o?[]:i.filter(s=>s.attempts>0&&s.successes===0).map(s=>`provenance_resolver_zero_success:${s.harness}:${s.dimension}:${s.resolver}:${String(s.attempts)}`),events_read:a,truncated:o}}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]="97e1ed14-cd36-5910-b829-4619af6080e1")}catch{}})();var fm=new Set(Er),Ki=25,bt=8,hm=V.join("runtime","telemetry","events.jsonl"),gm=V.join("runtime","telemetry","state.json"),_m=2500,ym=500,Yi=Sr-3,wm=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Xi(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 Qi(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Ze(e){return e.trim().toLowerCase()}function la(e,t){let n=Ze(e),a=Ze(t);return n.startsWith("builtin-")?!0:a==="beads"||a==="todos"}async function ma(e){try{return(await ve.stat(e)).isDirectory()}catch{return!1}}async function vm(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=>fn.some(o=>r.name.endsWith(o))).map(r=>V.parse(r.name).name)))}async function bm(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 l=i.split(/\r?\n/).map(d=>d.trim()).filter(Boolean).at(-1);try{s=JSON.parse(l??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?i.split(/\r?\n/).filter(l=>l.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=V.join(e,"history");if(!await ma(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,m)=>u.localeCompare(m)),i=t.enabled?t.max_entries:null,s=[],c=[],l=[],d=[];for(let u of r){let m=V.join(a,u),h=u.slice(0,-6),f=await bm(m,h,t,n);s.push(...f.warnings),f.classification==="tombstone"&&l.push(h),f.classification==="orphaned"&&d.push(h),f.overThreshold&&c.push(h)}return{count:r.length,warnings:[...s,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...d.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:i,tombstones:l,orphaned:d}}function da(e,t){return V.relative(e,t).replaceAll("\\","/")}async function Zi(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)fn.some(c=>s.toLowerCase().endsWith(c))&&a.push(V.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 Zi(e,t),r=[],o=[],i=[],s=[],c=Tt(M());for(let l of a){let d=da(e,l),u;try{u=await ve.readFile(l,"utf8")}catch{r.push(d);continue}let m=bn(u);if(m){o.push({path:d,...m});continue}try{let h=Mt(u,{format:Ta(l),schema:n,extensionFieldNames:c});s.push({ref:d,version:Ya(h.metadata)})}catch{i.push(d)}}return{paths:a,unreadable:r,conflictMarkers:o,parseFailures:i,formatVersions:s}}async function Em(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){xm(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 l=bn(c);if(l){a.push({id:s,...l});continue}c.split(/\r?\n/).forEach((d,u)=>{if(d.trim())try{JSON.parse(d)}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 Or(e),c=await $r(e),l=c===null?null:await Tr(c),d=c===null?[]:await Nr(c,{includeLossless:!0}),{pendingDecisions:u,lossless:m}=Dr(d),h=l?.status==="missing"&&l.missing_keys.length===5&&l.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}`]:[],...l!==null&&l.status!=="ok"?[`merge_driver_configuration_${h?"missing":"drift"}:${l.missing_keys.length+l.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:l===null||l.status==="ok"?0:l.missing_keys.length+l.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:l===null?null:{...l,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=ke(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Cm(e){let n=ke(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function Rm(e){return ke(e.reason)??ke(e.error)??ke(e.message)}function sa(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(sa),n.sort(sa),a.sort(sa);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 es(e,t,n,a,r,o,i,s,c){let l=[...new Set(e)].sort((g,w)=>g.localeCompare(w)),d=[...new Set(l.map(g=>Qi(g)))].sort((g,w)=>g.localeCompare(w)),u=l.filter(g=>g.startsWith("extension_capability_unknown:")).length,m=c.length>0,h=m?"partial":"full",f=[],p=Kn(l,{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: ${Et.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),l.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)."),l.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:l.length===0?"ok":"warn",warning_count:l.length,warning_codes:d,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:l.slice(0,8),remediation:f}}async function Nm(e,t,n){let a=await ie({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),r=a.loaded.map(b=>Im(b)),o=await se({...a,loaded:a.loaded}),[i,s]=await Promise.all([B(a.roots.project),B(a.roots.global)]);await ea(e,o.registrations.migrations);let c=Om(o.registrations.migrations),l={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}}},d=new Set(i.state.entries.map(b=>Ze(b.name))),u=new Set(s.state.entries.map(b=>Ze(b.name))),m=[...new Map(a.loaded.filter(b=>!(b.layer==="project"?d:u).has(Ze(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=>la(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,T)=>b.localeCompare(T)),p=m.filter(b=>!la(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,...l.warnings,...c.warnings,...i.warnings,...s.warnings,...g],v=ht(w),x=gt(),I=es(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:l,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 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 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 mn(e,t){let n=we(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:mn(e.discovered,t),effective:mn(e.effective,t),loaded:mn(e.loaded,t),failed:we(e.failed,t),warnings:j(e.warnings,t),activation:{failed:we(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: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:j(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:j(e.item_unreadable,t),item_conflict_markers:we(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: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: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 ts(e,t){let n=Lm[e.name];return n?n(e.details,t):e.details}function Mm(e){let t=j(e.warnings,bt);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,details:ts(n,bt)})),warnings:t.sample,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:bt},generated_at:e.generated_at}}function Vi(e){return e.details.skipped===!0}function Fm(e){let t=j(e.warnings,bt),n=e.checks.filter(Vi).map(a=>a.name);return{ok:e.ok,checks:e.checks.filter(a=>!Vi(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:bt,omitted_checks:n},generated_at:e.generated_at}}function ua(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Dm(e,Ki);return{values:n.values,truncated:n.truncated,total:e.length}}function Qe(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 pn(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 ns(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 l=Math.max(0,Math.trunc(c.attempts));t+=1,o=Math.max(o,l),l>=Yi&&(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 as(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>xr?[`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:Qe("PM_TELEMETRY_DISABLED")||Qe("PM_NO_TELEMETRY"),pm_no_telemetry:Qe("PM_NO_TELEMETRY"),telemetry_otel_disabled:Qe("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:Qe("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 as(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:pn(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:pn(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function Xm(e,t){let n=It(process.cwd()),a=V.join(n,hm),r=V.join(n,gm),o=await q(a),i=o!==null,s=o?Buffer.byteLength(o,"utf8"):0,c=o?ns(o):zm(),l=await q(r),{runtimeState:d,stateParseFailed:u}=Jm(l),m=e.telemetry.endpoint.trim(),h=pn(m),f=await Wm(e,t.checkTelemetry),p=[];u&&p.push("telemetry_state_invalid_json"),p.push(...qm(e,c,d),...Gm(f),...Hm(f),...Bm(e,d));let g=Km(e,c),w=typeof d.pending_otel_spans=="number"?d.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:Yi,queue_max_attempts:c.maxAttempts,runtime_state_path:r,last_attempted_flush_at:d.last_attempted_flush_at??null,last_successful_flush_at:d.last_successful_flush_at??null,last_failed_flush_at:d.last_failed_flush_at??null,last_failed_flush_error:d.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:d.last_otel_attempt_at??null,last_otel_success_at:d.last_otel_success_at??null,last_otel_failure_at:d.last_otel_failure_at??null,last_otel_failure_error:d.last_otel_failure_error??null,endpoint_probe:f??{attempted:!1},env_overrides:Vm()}},warnings:p}}async function Qm(e){let t;try{t=await Ji(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 Ar(e,t,{cacheHitVerification:n}),c=[...a.map(l=>`history_drift_missing_stream:${l}`),...r.map(l=>`history_drift_unreadable_stream:${l}`),...o.map(l=>`history_drift_hash_mismatch:${l}`),...i.map(l=>`history_drift_chain_mismatch:${l}`)];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=ot(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():vr(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&&We(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 rs(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:Sn(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:Sn(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 qe(e),s=o.semanticRuntimeAvailable?Tn(n,i.entries):[],c=await np({pmRoot:e,snapshot:o,refreshPolicy:a,staleBefore:s}),l=await qe(e),d=o.semanticRuntimeAvailable?Tn(n,l.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:l,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:d}),f=ua(s,r),p=ua(d,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),...rs(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:Ki,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(l.entries).length,stale_items_after_total:p.total,stale_items_after:p.values,stale_items_after_truncated:p.truncated}},warnings:h}}function lp(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 os(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 dp=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 dp)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 l of[...a,...r]){let d=V.join(e,l);c.push(...await fe({path:d,scope:"project"})),!await ma(d)&&(o.has(l)?s.push(l):i.push(l))}return{requiredDirs:a,optionalDirs:r,missingRequiredDirs:i,missingOptionalDirs:s,missingDirs:n?[...i,...s]:[...i],hookWarnings:c}}function is(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?or(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):ir(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function ca(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 pa=e=>e.unknown_event_count??0,fa=e=>e.actionable_unknown_event_count??pa(e);function _p(e,t,n,a,r,o){let i=pa(a),s=fa(a),c=i>0,l=s>0,d=r.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!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},...c?{author_attribution:a}:{},...d?{stale_in_progress:r}:{},...o.length>0?{provenance_resolver_outcomes:o}:{},...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 ss(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=Cr(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 cs(e,t,n){return n?Fm(e):t.brief===!0?Mm(e):e}async function ew(e,t={}){let n=P(process.cwd(),e.path),a=ee(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=H(r,M()),c=t.strictDirectories===!0,l=os(t),d=await mp(n,s,c),u=lp(r),m=await Xm(r,{checkTelemetry:t.checkTelemetry===!0}),h=await Nm(n,r,!!e.noExtensions),f=is(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(St=>St.id),commandLabel:"health"}),I=await km(n,r.history.compact_policy,await vm(n)),b=await Rr(n,20,t.verboseAuthorEvents===!0),T=fa(b),J=T>0?[`history_unknown_author_events:${T}`]:[],W=ss(await br(n,g,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),S=await Bi(n),L=S.outcomes,ue=S.warnings,tt=await Qm(n),nt=f.skipIntegrity?ca("integrity"):await $m(n,s.type_to_folder,r.schema,t.requireMergeDrivers===!0),Ae=f.skipDrift?ca("history_drift"):await Zm(n,w),at=f.skipVectors?ca("vectorization"):await cp(n,r,w,l,t.verboseStaleItems===!0),xt=[fp(a,r,i),hp(d,c),gp(u),m.check,h.check,_p(g,r,I,b,W.scan,L),tt.check,nt.check,Ae.check,at.check],Le=yp({directoryState:d,normalizedSettingsReadWarnings:i,settingWarnings:u,normalizedItemReadWarnings:v,telemetryCheck:m,extensionCheck:h,historyPolicyWarnings:x.warnings,historySummary:I,authorAttributionWarnings:J,staleInProgressWarnings:W.warnings,provenanceWarnings:ue,locksCheck:tt,integrityCheck:nt,historyDriftCheck:Ae,vectorizationCheck:at});kp({checks:xt,remediationSources:vp({directoryState:d,normalizedSettingsReadWarnings:i,settingWarnings:u,telemetryCheck:m,extensionCheck:h,historySummary:I,authorAttributionWarnings:J,staleInProgressWarnings:W.warnings,provenanceWarnings:ue,locksCheck:tt,integrityCheck:nt,historyDriftCheck:Ae,vectorizationCheck:at}),historyDriftedCount:wp(Ae),overThresholdCount:I.over_threshold.length});let D={ok:Le.filter(St=>!Xi(St,t.requireMergeDrivers===!0)).length===0,checks:xt,warnings:Le,generated_at:A()};return cs(D,t,f.summaryMode)}var tw={buildExtensionHealthTriageSummary:es,buildCapabilityContractMetadata:gt,buildStaleInProgressHealthSummary:ss,buildVectorizationProviderDetails:rs,collectUnknownCapabilityGuidance:ht,isAdvisoryHealthWarning:Xi,isDirectory:ma,isExpectedUnmanagedExtension:la,listItemDocumentPaths:Zi,normalizeEndpointForDisplay:pn,normalizeExtensionNameForMatch:Ze,parseTelemetryQueue:ns,probeTelemetryEndpointHealth:as,projectHealthResult:cs,resolveActionableUnknownAuthorEventCount:fa,resolveHealthSkipPolicy:is,resolveUnknownAuthorEventCount:pa,resolveVectorRefreshPolicy:os,selectStaleItemDetail:ua,summarizeHealthCheckDetails:ts,summarizeExtensionList:mn,summarizeRecordList:we,summarizeStringList:j,telemetryEnvFlagEnabled:Qe,warningCode:Qi};import xp from"node:fs/promises";import kt 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 ha="index/manifest.json",ga="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 ya(e,t,n,a,r){let o=Tt(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"),l=Mt(c,{format:s.item_format,schema:n,extensionFieldNames:o,onWarning:d=>a.push(d)});i.push({metadata:s.metadata,body:l.body})}catch{a.push(`item_list_item_read_failed:${kt.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 et=ke;function Ap(e){let t=M(),n=et(e.search?.provider);if(!n)return null;let a=sr(t,n);if(!a)return null;let r=a.runtime_definition??a.definition,o=et(r.name)??et(a.definition.name);if(!o)return null;let i=r.embedBatch,s=r.embed_batch,c=r.embed,l=typeof i=="function"?i:typeof s=="function"?s:void 0,d=typeof c=="function"?c:void 0;return!l&&!d?null:{name:o,embedBatch:l,embed:d}}function Cp(e){let t=M(),n=et(e.vector_store?.adapter);if(!n)return null;let a=cr(t,n);if(!a)return null;let r=a.runtime_definition??a.definition,o=et(r.name)??et(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 _a(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)=>_a(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(_a(s,`extension search provider "${e.name}" embed output at index ${o}`))}return r}function ls(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function ds(e,t,n){let a=n?Re(n.name,ls(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 us(e,t,n,a,r,o,i,s){let c=a?.name??n?.name,l=ur(c,e.search.embedding_corpus_max_characters).maxCharacters,d=En(e),u=r.map(f=>mr(f,{providerName:c,maxCharacters:l,fields:d})),m=[],h=null;if(a)try{m=await Rp(a,e,u),h=Re(a.name,ls(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 pr(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 gr(e,i,{},o)}async function ms(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 hr(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=ot(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=H(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 qe(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,ot(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&We(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 qe(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=ds(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),a=new Set(e.metadataDocuments.map(l=>l.metadata.id)),r=Op(t.entries,a),o=We(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(l=>t.entries[l.metadata.id]!==l.metadata.updated_at),s=new Set(i.map(l=>l.metadata.id)),c=s.size>0?await ya(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 ya(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 us(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...a,staleDocuments:n,vectorDimension:$n(a.vectors,"Reindex embeddings")}}async function zp(e){let t=await us(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,a=t.embeddingIdentity,r=$n(n,"Reindex embeddings");if(!(!e.resetRequired&&(We(e.ledgerEmbedding,a)||yr(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 fr(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:_a(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 ms(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:_r(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 ms(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=kt.join(e.pmRoot,ha),n=kt.join(e.pmRoot,ga),a=En(e.settings),r=e.documentsForKeywordArtifacts.map(i=>JSON.stringify(Ip(i,e.mode,a))).join(`
28
- `);z(e.progressEnabled,"writing keyword artifacts"),await re(t,`${JSON.stringify(e.manifest,null,2)}
29
- `),await re(n,`${r}
30
- `);let o=[];if(e.mode!=="keyword")try{z(e.progressEnabled,"writing vectorization status ledger"),await wr(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 iw(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(ee(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 X(o,lr,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 _&&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),l=Cp(i),d=jp({requestedMode:n,pmRoot:o,settings:i,extensionEmbedding:c,extensionVectorAdapter:l}),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=kt.join(o,ha),x=kt.join(o,ga),I=u==="keyword"?await ya(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 ue=await Gp({pmRoot:o,settings:i,requestedMode:n,activeEmbeddingProvider:d.activeEmbeddingProvider,activeVectorStore:d.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:f,metadataDocuments:p,documentsForKeywordArtifacts:I,forceFullSemantic:r,reindexWarnings:h,semanticWarnings:b,semanticSummary:W,progressEnabled:a});I=ue.documentsForKeywordArtifacts,T=ue.vectorizationLedgerEntries,J=ue.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:ha,embeddings:ga},warnings:[...h,...b,...S,...L],generated_at:g}}finally{await s?.()}}export{Hr as a,jr as b,nc as c,Yf as d,Xf as e,it as f,Qf as g,Zf as h,eh as i,th as j,nh as k,ah as l,rh as m,oh as n,ih as o,sh as p,ch as q,ra as r,W_ as s,my as t,Bi as u,ew as v,tw as w,iw as x};
31
- //# sourceMappingURL=chunk-C3GCHDSQ.js.map