@unbrained/pm-cli 2026.8.4 → 2026.8.5

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 (214) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +39 -13
  3. package/dist/cli/error-guidance.js +4 -4
  4. package/dist/cli/register-structured-mutation.d.ts +2 -0
  5. package/dist/cli/register-structured-mutation.js +124 -12
  6. package/dist/cli-bundle/bundle-manifest.json +407 -407
  7. package/dist/cli-bundle/chunks/append-VXXGOXSG.js +2 -0
  8. package/dist/cli-bundle/chunks/{chunk-QVO3VTA4.js → chunk-2WFXWAYX.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-NM5G7RLU.js → chunk-3FTILRJ2.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-VH2EAGUG.js → chunk-42E7YPLG.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-RB65T4RX.js → chunk-43HQQI6S.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-J4EPW4GT.js → chunk-45G53IU4.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-PQXEB7W4.js → chunk-4VN6GS4U.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-4YUBDMQM.js +2 -0
  15. package/dist/cli-bundle/chunks/{chunk-D2MBVMVE.js → chunk-54FNT7U2.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-NRDKVOUE.js → chunk-5ZBOIPGP.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-3XZYTRPC.js → chunk-6MSQJOTG.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-GOICHIX4.js → chunk-7A5OT5J2.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-HTYC76A4.js → chunk-7C4PTJG6.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-BKMZTZYL.js → chunk-A62CYISG.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-5H47J5FG.js → chunk-BPELKUQD.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-HE3DZFN4.js → chunk-BXQLRKWF.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-BLINBTMX.js → chunk-CSI3WS5I.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-KH4GVBMC.js → chunk-DXDREUXT.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-KIKLF2W4.js → chunk-E2RKBKWB.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-377OOXUF.js → chunk-EGJ4JTUG.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-SULWTPQO.js → chunk-FPBQHMFT.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-V5K52PYW.js → chunk-GE4KCSZP.js} +35 -35
  29. package/dist/cli-bundle/chunks/{chunk-NPUJ7OLK.js → chunk-HNFD72UK.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-QMWUL66F.js → chunk-HWRRMBJO.js} +5 -5
  31. package/dist/cli-bundle/chunks/chunk-L3AZOELJ.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-CGY5I2GO.js → chunk-LKDGK44W.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-LN2WFEU4.js +2 -0
  34. package/dist/cli-bundle/chunks/{chunk-ZSH4GNBH.js → chunk-M72BKL5Q.js} +2 -2
  35. package/dist/cli-bundle/chunks/{chunk-HQ2WU7OY.js → chunk-MHK6LIWE.js} +2 -2
  36. package/dist/cli-bundle/chunks/{chunk-H6FITE7D.js → chunk-NE5VRDAI.js} +2 -2
  37. package/dist/cli-bundle/chunks/chunk-NY4T3JWN.js +2 -0
  38. package/dist/cli-bundle/chunks/{chunk-DCJ6CM6F.js → chunk-OMXVBQ2N.js} +2 -2
  39. package/dist/cli-bundle/chunks/chunk-OPVH7SKD.js +8 -0
  40. package/dist/cli-bundle/chunks/{chunk-CU5ENFNP.js → chunk-OTHLDSFP.js} +2 -2
  41. package/dist/cli-bundle/chunks/{chunk-NH35JNK5.js → chunk-PMXJEU3F.js} +2 -2
  42. package/dist/cli-bundle/chunks/{chunk-SVDH5CHC.js → chunk-Q35VBGOQ.js} +4 -4
  43. package/dist/cli-bundle/chunks/{chunk-5PZGZMPG.js → chunk-R546TPDE.js} +2 -2
  44. package/dist/cli-bundle/chunks/{chunk-Q5F6OI7C.js → chunk-RKAVWO3O.js} +2 -2
  45. package/dist/cli-bundle/chunks/{chunk-JMKVCQSE.js → chunk-SSF4PIUR.js} +2 -2
  46. package/dist/cli-bundle/chunks/{chunk-PA5XRN2A.js → chunk-UN66FZRO.js} +3 -3
  47. package/dist/cli-bundle/chunks/{chunk-FQ4EFFDU.js → chunk-UP7DTVMD.js} +2 -2
  48. package/dist/cli-bundle/chunks/{chunk-NFF3JAQR.js → chunk-UZBWIUYD.js} +2 -2
  49. package/dist/cli-bundle/chunks/{chunk-2POYGY53.js → chunk-V3774P7D.js} +2 -2
  50. package/dist/cli-bundle/chunks/{chunk-B5ZLCD5Z.js → chunk-V3EUXXOF.js} +2 -2
  51. package/dist/cli-bundle/chunks/{chunk-6S7I3UKV.js → chunk-VCKLFEUN.js} +19 -19
  52. package/dist/cli-bundle/chunks/{chunk-PYYPQLHC.js → chunk-VN5VITU3.js} +2 -2
  53. package/dist/cli-bundle/chunks/chunk-WRL4KNDL.js +20 -0
  54. package/dist/cli-bundle/chunks/{chunk-UJHUR3LZ.js → chunk-XCEZYMNI.js} +2 -2
  55. package/dist/cli-bundle/chunks/{chunk-JDPKBV5P.js → chunk-YEWNL576.js} +2 -2
  56. package/dist/cli-bundle/chunks/{chunk-OB7TRZ2G.js → chunk-YSO3YFZ4.js} +2 -2
  57. package/dist/cli-bundle/chunks/{chunk-UVZREFZU.js → chunk-ZYHOB3SN.js} +2 -2
  58. package/dist/cli-bundle/chunks/close-VZ3OQPN5.js +2 -0
  59. package/dist/cli-bundle/chunks/close-many-SB4TI27P.js +2 -0
  60. package/dist/cli-bundle/chunks/comments-BIF3Q4KY.js +2 -0
  61. package/dist/cli-bundle/chunks/copy-6AI5Z57X.js +2 -0
  62. package/dist/cli-bundle/chunks/{create-RLLCBCXM.js → create-XLKTXTUF.js} +2 -2
  63. package/dist/cli-bundle/chunks/delete-ZY2VHQTP.js +2 -0
  64. package/dist/cli-bundle/chunks/{deps-J4ONTF4X.js → deps-ITTY3GIC.js} +2 -2
  65. package/dist/cli-bundle/chunks/{docs-YL2DJ4WD.js → docs-W4OSRTYR.js} +2 -2
  66. package/dist/cli-bundle/chunks/{files-NGNAIYKK.js → files-EOK4AZI4.js} +2 -2
  67. package/dist/cli-bundle/chunks/focus-DLBNWL7L.js +2 -0
  68. package/dist/cli-bundle/chunks/{history-compact-HW62K5XP.js → history-compact-7UGTMLL3.js} +2 -2
  69. package/dist/cli-bundle/chunks/{history-redact-HVBKUJOW.js → history-redact-4DZRMD6Z.js} +2 -2
  70. package/dist/cli-bundle/chunks/{history-repair-OPNBH5JJ.js → history-repair-UPOSZW5R.js} +2 -2
  71. package/dist/cli-bundle/chunks/{learnings-F36PZXT6.js → learnings-GMRNCBS3.js} +2 -2
  72. package/dist/cli-bundle/chunks/{profile-N3XMWBM7.js → profile-2MUUMHRE.js} +2 -2
  73. package/dist/cli-bundle/chunks/{register-list-query-BKGHBI7Y.js → register-list-query-LR3SQ5ZF.js} +2 -2
  74. package/dist/cli-bundle/chunks/register-mutation-SUOHFVWM.js +20 -0
  75. package/dist/cli-bundle/chunks/register-operations-ARRRKOVN.js +2 -0
  76. package/dist/cli-bundle/chunks/{register-setup-KWV6UD77.js → register-setup-O6AYP6NP.js} +2 -2
  77. package/dist/cli-bundle/chunks/restore-ZVCVHTB5.js +2 -0
  78. package/dist/cli-bundle/chunks/{schema-4PJQMGUY.js → schema-FJ4EA3XF.js} +2 -2
  79. package/dist/cli-bundle/chunks/update-YHV52CSS.js +2 -0
  80. package/dist/cli-bundle/chunks/update-many-M6YHVNXM.js +2 -0
  81. package/dist/cli-bundle/focused-chunks/chunk-7J5TUBUJ.js +153 -0
  82. package/dist/cli-bundle/focused-chunks/{chunk-ONIX2KKW.js → chunk-A7BJ5SS6.js} +2 -2
  83. package/dist/cli-bundle/focused-chunks/chunk-B7LJWAZE.js +2 -0
  84. package/dist/cli-bundle/focused-chunks/{chunk-QM2BIVK7.js → chunk-BIMTMOS7.js} +3 -3
  85. package/dist/cli-bundle/focused-chunks/{chunk-BOGRY7M6.js → chunk-FGKY4MBE.js} +10 -10
  86. package/dist/cli-bundle/focused-chunks/chunk-G6ETT4QK.js +2 -0
  87. package/dist/cli-bundle/focused-chunks/{chunk-C2QSL62X.js → chunk-GJ2TG2CW.js} +2 -2
  88. package/dist/cli-bundle/focused-chunks/{chunk-RO5BQFG3.js → chunk-IPWSFADF.js} +2 -2
  89. package/dist/cli-bundle/focused-chunks/{chunk-UFCPSWIL.js → chunk-MJ7HWSFK.js} +2 -2
  90. package/dist/cli-bundle/focused-chunks/{chunk-2VIIXOAD.js → chunk-N5XU5UVK.js} +2 -2
  91. package/dist/cli-bundle/focused-chunks/chunk-PG2RIZBX.js +2 -0
  92. package/dist/cli-bundle/focused-chunks/{chunk-OYTK4VNH.js → chunk-PIMMYG7Q.js} +2 -2
  93. package/dist/cli-bundle/focused-chunks/{chunk-K37BB4JL.js → chunk-QVHKCI4T.js} +2 -2
  94. package/dist/cli-bundle/focused-chunks/{chunk-SQXVGHMH.js → chunk-RUR5I3TK.js} +2 -2
  95. package/dist/cli-bundle/focused-chunks/chunk-SV3O7TSH.js +8 -0
  96. package/dist/cli-bundle/focused-chunks/{chunk-L6A4NVQC.js → chunk-UIL2M2NA.js} +2 -2
  97. package/dist/cli-bundle/focused-chunks/{chunk-WVGJAD7L.js → chunk-VLYOEYML.js} +2 -2
  98. package/dist/cli-bundle/focused-chunks/chunk-W7BJEWHX.js +2 -0
  99. package/dist/cli-bundle/focused-chunks/{chunk-DQ4PLKEE.js → chunk-WEM2E2PE.js} +2 -2
  100. package/dist/cli-bundle/focused-chunks/chunk-WVIVUWVL.js +5 -0
  101. package/dist/cli-bundle/focused-chunks/chunk-Y4LDYLLT.js +2 -0
  102. package/dist/cli-bundle/main.js +4 -4
  103. package/dist/cli-bundle/sdk-authoring.js +1 -1
  104. package/dist/cli-bundle/sdk-contracts.js +1 -1
  105. package/dist/cli-bundle/sdk-core.js +28 -28
  106. package/dist/cli-bundle/sdk-governance.js +1 -1
  107. package/dist/cli-bundle/sdk-graph.js +1 -1
  108. package/dist/cli-bundle/sdk-merge.js +1 -1
  109. package/dist/cli-bundle/sdk-query.js +1 -1
  110. package/dist/cli-bundle/sdk-runtime.js +1 -1
  111. package/dist/cli-bundle/sdk-testing.js +1 -1
  112. package/dist/cli-bundle/sdk.js +1 -1
  113. package/dist/core/extensions/loader.js +5 -2
  114. package/dist/core/item/item-format.js +14 -20
  115. package/dist/core/shared/constants.js +3 -2
  116. package/dist/core/store/item-store.js +2 -2
  117. package/dist/core/store/settings.js +2 -2
  118. package/dist/mcp/server.js +12 -6
  119. package/dist/mcp/tool-definitions.js +14 -7
  120. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +18 -18
  121. package/dist/sdk/cli-contracts/agent-output-contracts.js +51 -23
  122. package/dist/sdk/cli-contracts/commander-mutation-options.js +26 -2
  123. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  124. package/dist/sdk/cli-contracts/flag-contracts.js +28 -2
  125. package/dist/sdk/cli-contracts/registration-helpers.js +4 -2
  126. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +10 -2
  127. package/dist/sdk/cli-contracts/runtime-contracts.js +20 -5
  128. package/dist/sdk/cli-contracts/tool-schema.js +4 -2
  129. package/dist/sdk/cli-contracts.d.ts +2 -2
  130. package/dist/sdk/cli-contracts.js +4 -4
  131. package/dist/sdk/cli-program.js +3 -3
  132. package/dist/sdk/contracts.d.ts +1 -0
  133. package/dist/sdk/contracts.js +3 -2
  134. package/dist/sdk/dependency-provenance.d.ts +2 -0
  135. package/dist/sdk/dependency-provenance.js +7 -3
  136. package/dist/sdk/error-code-catalog.d.ts +23 -0
  137. package/dist/sdk/error-code-catalog.js +25 -5
  138. package/dist/sdk/generated-error-code-catalog.js +499 -3
  139. package/dist/sdk/graph/governance.js +3 -3
  140. package/dist/sdk/graph/remediation.js +3 -3
  141. package/dist/sdk/graph/run.js +4 -8
  142. package/dist/sdk/index.d.ts +2 -1
  143. package/dist/sdk/index.js +4 -3
  144. package/dist/sdk/item-transaction.d.ts +51 -6
  145. package/dist/sdk/item-transaction.js +132 -22
  146. package/dist/sdk/lifecycle/create.d.ts +4 -0
  147. package/dist/sdk/lifecycle/create.js +26 -10
  148. package/dist/sdk/lifecycle-policy.d.ts +9 -0
  149. package/dist/sdk/lifecycle-policy.js +22 -9
  150. package/dist/sdk/merge/driver.js +6 -3
  151. package/dist/sdk/output-contracts.d.ts +67 -0
  152. package/dist/sdk/output-contracts.js +173 -0
  153. package/dist/sdk/package-import-adapters.js +2 -2
  154. package/dist/sdk/structured-mutations.d.ts +23 -0
  155. package/dist/sdk/structured-mutations.js +219 -10
  156. package/dist/sdk/workspace-snapshot.js +58 -12
  157. package/dist/sdk/workspace.js +30 -4
  158. package/docs/COMMANDS.md +40 -10
  159. package/docs/EXTENSIONS.md +1 -1
  160. package/docs/MERGE_SAFETY.md +2 -0
  161. package/docs/PR_REVIEW_LOOP.md +10 -4
  162. package/docs/README.md +22 -22
  163. package/docs/RELEASING.md +3 -3
  164. package/docs/SCRIPTING.md +32 -9
  165. package/docs/SDK.md +91 -11
  166. package/docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md +13 -0
  167. package/docs/TESTING.md +25 -0
  168. package/docs/examples/sdk-contract-consumer/README.md +11 -1
  169. package/docs/examples/sdk-contract-consumer/package.json +2 -1
  170. package/docs/examples/sdk-contract-consumer/parse-receipt.mjs +22 -0
  171. package/marketplace.json +2 -2
  172. package/package.json +3 -2
  173. package/packages/pm-beads/package.json +1 -1
  174. package/packages/pm-calendar/package.json +1 -1
  175. package/packages/pm-command-kit/package.json +1 -1
  176. package/packages/pm-digital-twin/package.json +1 -1
  177. package/packages/pm-governance-audit/package.json +1 -1
  178. package/packages/pm-guide-shell/package.json +1 -1
  179. package/packages/pm-kanban/package.json +1 -1
  180. package/packages/pm-lifecycle-hooks/package.json +1 -1
  181. package/packages/pm-linked-test-adapters/package.json +1 -1
  182. package/packages/pm-search-advanced/package.json +1 -1
  183. package/packages/pm-templates/package.json +1 -1
  184. package/packages/pm-todos/package.json +1 -1
  185. package/packages/pm-vcs/package.json +1 -1
  186. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  187. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  188. package/sdk/public-surface.json +292 -14
  189. package/dist/cli-bundle/chunks/append-DHBRLHHS.js +0 -2
  190. package/dist/cli-bundle/chunks/chunk-2INN52SU.js +0 -8
  191. package/dist/cli-bundle/chunks/chunk-6RSK4IFN.js +0 -20
  192. package/dist/cli-bundle/chunks/chunk-ASJJKA57.js +0 -2
  193. package/dist/cli-bundle/chunks/chunk-IYAVULRN.js +0 -2
  194. package/dist/cli-bundle/chunks/chunk-RRQBHQOV.js +0 -2
  195. package/dist/cli-bundle/chunks/chunk-XBLOD5TZ.js +0 -2
  196. package/dist/cli-bundle/chunks/close-VLHNN6YB.js +0 -2
  197. package/dist/cli-bundle/chunks/close-many-LSJNZKU6.js +0 -2
  198. package/dist/cli-bundle/chunks/comments-AAIA6A6X.js +0 -2
  199. package/dist/cli-bundle/chunks/copy-Z7YMLEHN.js +0 -2
  200. package/dist/cli-bundle/chunks/delete-KNOHHQJM.js +0 -2
  201. package/dist/cli-bundle/chunks/focus-LFRCGALV.js +0 -2
  202. package/dist/cli-bundle/chunks/register-mutation-GU3DCECN.js +0 -20
  203. package/dist/cli-bundle/chunks/register-operations-PTWH727R.js +0 -2
  204. package/dist/cli-bundle/chunks/restore-4HZSLILR.js +0 -2
  205. package/dist/cli-bundle/chunks/update-E6LPS5IV.js +0 -2
  206. package/dist/cli-bundle/chunks/update-many-OSIC6KRO.js +0 -2
  207. package/dist/cli-bundle/focused-chunks/chunk-5MTKO7TV.js +0 -153
  208. package/dist/cli-bundle/focused-chunks/chunk-6GIZK7VQ.js +0 -2
  209. package/dist/cli-bundle/focused-chunks/chunk-AOP2WIZZ.js +0 -2
  210. package/dist/cli-bundle/focused-chunks/chunk-CL75YW32.js +0 -2
  211. package/dist/cli-bundle/focused-chunks/chunk-E7OFMWGT.js +0 -8
  212. package/dist/cli-bundle/focused-chunks/chunk-I5F5UK3Q.js +0 -2
  213. package/dist/cli-bundle/focused-chunks/chunk-T5TSY36R.js +0 -5
  214. package/dist/cli-bundle/focused-chunks/chunk-VT6BF2IX.js +0 -2
@@ -1,4 +1,4 @@
1
- import{B as pn,C as un,K as mn,g as on,j as cn,q as dn,z as ln}from"./chunk-6S7I3UKV.js";import{a as an}from"./chunk-ASJJKA57.js";import{s as rn}from"./chunk-JMKVCQSE.js";import{b as sn,c as Ie}from"./chunk-JC6FKIFM.js";import{a as nn}from"./chunk-A6KGKEWT.js";import{f as Zt,g as en,i as tn}from"./chunk-ZSH4GNBH.js";import{A as g,Ab as Ft,C as f,Da as Ct,Hc as Bt,Jc as Wt,Kc as Ht,La as oe,Mc as Kt,Na as Pt,Oa as Nt,Qb as He,R as L,Rb as Mt,Sb as Gt,Tb as Ae,Vb as se,Xb as ce,Y as J,Z as X,_b as Jt,ac as Oe,b as k,bb as Rt,bc as zt,c as At,cc as Ut,d as Ot,g as It,j as $e,lc as qt,pb as jt,pf as Qt,qb as Dt,qf as Q,s as Be,uc as de,ud as Vt,w as Tt,xe as Xt,yf as z,z as We,zb as Lt,zd as Yt,zf as Z}from"./chunk-V5K52PYW.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d5e0d6f-5ffa-5302-87da-3e741b80b716")}catch{}})();var Tr=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function le(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Oe(t.extensionName));for(let u of t.extensionNames??[])n.add(Oe(u));let a=u=>n.size===0||n.has(Oe(u)),r=(u,w)=>fn(u.filter(h=>a(h.name)).map(w)),i=(u,w)=>fn(u.filter(h=>a(h.name)).flatMap(w)),{registrations:o,commands:s,parsers:c,preflight:d,services:l,renderers:p,hooks:m}=e,_=i(o.relationship_kinds??[],u=>u.definitions.map(w=>w.kind)),y=p.overrides.filter(u=>a(u.name)&&((u.commands?.length??0)>0||u.resultDiscriminator!==void 0)).map(u=>({format:u.format,commands:[...u.commands??[]],result_discriminator:u.resultDiscriminator!==void 0})).sort((u,w)=>u.format.localeCompare(w.format));return{capabilities:zt(e,t),commands:r(o.commands,u=>u.command),command_overrides:r(s.overrides,u=>u.command),command_handlers:r(s.handlers,u=>u.command),hooks:Tr.filter(([u])=>m[u].some(w=>a(w.name))).map(([,u])=>u),flag_commands:r(o.flags,u=>u.target_command),item_types:i(o.item_types,u=>u.types.map(w=>w.name)),item_fields:i(o.item_fields,u=>u.fields.map(w=>w.name)),..._.length>0?{relationship_kinds:_}:{},migrations:i(o.migrations,u=>typeof u.definition.id=="string"?[u.definition.id]:[]),profiles:r(o.profiles,u=>u.profile.name),importers:r(o.importers,u=>u.importer),exporters:r(o.exporters,u=>u.exporter),search_providers:r(o.search_providers,u=>u.definition.name),vector_store_adapters:r(o.vector_store_adapters,u=>u.definition.name),parser_overrides:r(c.overrides,u=>u.command),service_overrides:r(l.overrides,u=>u.service),renderer_overrides:r(p.overrides,u=>u.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:d.overrides.filter(u=>a(u.name)).length}}function fn(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import _n 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]="6fc24a7c-a359-51fd-a432-4c8037d10e9e")}catch{}})();var Te=["extensions","docs","examples","assets","prompts"],Cr=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});function Pr(e){return Te.includes(e)}function Nr(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],a=[];for(let r of n){if(typeof r!="string"||r.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,g.USAGE);a.push(r.trim())}return[...new Set(a)].sort((r,i)=>r.localeCompare(i))}function Rr(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new f("Package manifest field pm must be an object.",g.USAGE);let t={},n=e;for(let[a,r]of Object.entries(n)){if(!Pr(a))continue;let i=Nr(a,r);i.length>0&&(t[a]=i)}return t}function q(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function Ke(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,a)=>n.localeCompare(a)):void 0}function gn(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=e.url;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}}function jr(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:q(t,"docs"),npm:q(t,"npm"),repository:q(t,"repository"),report:q(t,"report")};return Object.values(n).some(a=>typeof a=="string")?n:void 0}function Dr(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:q(t,"image"),video:q(t,"video")};return Object.values(n).some(a=>typeof a=="string")?n:void 0}function Lr(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:q(t,"display_name")??q(t,"displayName"),category:q(t,"category"),summary:q(t,"summary"),links:jr(t.links),media:Dr(t.media),tags:Ke(t.tags)};return Object.values(n).some(a=>a!==void 0)?n:void 0}async function ge(e){let t=ne.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await _n.readFile(t,"utf8"))}catch(s){throw new f(`Failed to parse package manifest at "${t}": ${String(s)}`,g.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new f(`Package manifest at "${t}" must be a JSON object.`,g.USAGE);let a=n,r=a.pm,i=r!=null,o=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{};return{source:i?"pm":"convention",package_json_path:t,package_name:typeof a.name=="string"?a.name:void 0,package_version:typeof a.version=="string"?a.version:void 0,package_private:a.private===!0,package_description:typeof a.description=="string"?a.description:void 0,package_keywords:Ke(a.keywords),package_homepage:typeof a.homepage=="string"?a.homepage:void 0,package_repository_url:gn(a.repository),package_bugs_url:gn(a.bugs),aliases:Ke(o.aliases),resources:Rr(r),catalog:Lr(o.catalog)}}async function hn(e){if(!await k(e))return[];let t=await _n.readdir(e,{withFileTypes:!0}),n=[];for(let a of t){if(!a.isDirectory())continue;let r=ne.join(e,a.name);await k(ne.join(r,"manifest.json"))&&n.push(r)}return n.sort((a,r)=>a.localeCompare(r))}async function Ce(e){if(await k(ne.join(e,"manifest.json")))return[e];let n=(await ge(e)).resources.extensions??[],a=new Set;for(let r of n){if(r.includes("*")||r.startsWith("!"))throw new f(`Package extension entry "${r}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,g.USAGE);let i=ne.resolve(e,r);if(!J(e,i))throw new f(`Package extension entry "${r}" resolves outside package root.`,g.USAGE);if(await k(ne.join(i,"manifest.json"))){a.add(i);continue}for(let o of await hn(i))a.add(o)}if(n.length===0)for(let r of Cr.extensions)for(let i of await hn(ne.join(e,r)))a.add(i);return[...a].sort((r,i)=>r.localeCompare(i))}import he from"node:fs/promises";import _e from"node:path";import yn from"node:fs/promises";import Ve 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 M(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function v(e){return e.trim().toLowerCase()}function Pe(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 f("Extension manifest name must resolve to a non-empty directory name.",g.USAGE);if(r==="."||r==="..")throw new f('Extension manifest name must not resolve to "." or "..".',g.USAGE);return r}function Ye(e){return Mt(e)}async function Fr(e){try{let t=JSON.parse(await yn.readFile(Ve.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 Mr(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new f(`Extension entry file is missing at "${t}".`,g.USAGE);let a=await Fr(n.source_root),r=a.package_name?`pm install npm:${a.package_name}`:void 0,i=n.source_input??n.source_root;return new f(`Extension entry "${e.entry}" is absent from GitHub source "${i}". 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."}`,g.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 ${i}`,normalized_args:["install",i],...r?{next_best_command:r}:{}}})}async function pe(e,t={}){let n=Ve.join(e,"manifest.json");if(!await k(n))throw new f(`Extension manifest is missing at "${n}".`,g.USAGE);let a;try{a=JSON.parse(await yn.readFile(n,"utf8"))}catch(o){throw new f(`Failed to parse extension manifest at "${n}": ${Gr(o)}`,g.USAGE)}let r=Ye(a);if(!r)throw new f(`Extension manifest at "${n}" is invalid.`,g.USAGE);let i=Ve.resolve(e,r.entry);if(!J(e,i))throw new f(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await k(i))throw await Mr(r,i,t);if(!await Gt(e,i))throw new f(`Extension entry "${r.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:i,manifest:r}}function Gr(e){return e instanceof Error?e.message:String(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]="50f2e5c4-c7fe-5e29-ae2a-60b1b1957756")}catch{}})();var Xe=1,ae="2026.6.24",Jr=">=22.18.0",zr={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},vn=new Set([...Xt.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(an).map(e=>e.toLowerCase()),"scaffold"]),Ur="^6.0.0",qr="^22.0.0",xn=["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."," }"," }","}",""],B=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function wn(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function kn(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 Sn(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 Br={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},bn=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],En={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"]},Wr={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"]'},Hr={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."},Kr={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."},$n="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Vr={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 before every command to compute the migration/format gate decision \u2014","the last registered override wins. 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."]},Yr={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."]},Xr={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`."]},Qr={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 An(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 On(e,t){return e==="schema"?Xr[t]:e==="profile"?Qr[t]:Yr[t]}function Zr(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(),i=a>0&&(a===t.length||r!==void 0&&vn.has(r));return`${(vn.has(n)||i?["starter",...t]:t).join(" ")} ping`}function In(e){let t=e,n=`${e}s`,a=e.replace(/-/g,""),r=a===t?[]:[a],i=`${e.replace(/-/g,"_")}_owner`,o="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(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(i)},`,' 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(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "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 ei(e,t,n){let a=`${e}-search`,r=`${e}-vector`,i=`${e.replace(/-/g," ")} items`,o=[" 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 o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(a)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(r)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],p=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // 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(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // 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({",...In(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // 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(i)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} 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(i)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} 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"?[...o,""," // 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"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) before EVERY command \u2014 the last"," // registered override wins. 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((context) => context.decision);"]:n==="services"?[...o,""," // 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 };`," });"]:[...o,""," // 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 ti(e,t,n){let a=n==="hooks",r=n==="search",i=n==="importers",o=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",p=n==="services",m=Wr[n],_=e,y=`${e}s`,u=`${e.replace(/-/g,"_")}_note`,w=`${e}-0001-init`,h=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],b=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;",...B,"});",""]:[],x=r?Qe(e,t,"search",m):[],P=i?Qe(e,t,"importers",m):[],R=o?[`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 {",...wn(kn({extensionName:e,itemTypeName:_,itemTypeFolder:y,fieldName:u,migrationId:w,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...B,"});",""]:[],N=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 {",...wn(Sn(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...B,"});",""]:[],te=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;",...B,"});",""]:[],fe=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...B,"});",""]:[],S=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...B,"});",""]:[],D=p?[`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;",...B,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...h,'} from "@unbrained/pm-cli/sdk/testing";',...r?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...xn,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...B,"});","",...b,...x,...P,...R,...N,...te,...fe,...S,...D,`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(`
1
+ import{B as pn,C as un,K as mn,g as on,j as cn,q as dn,z as ln}from"./chunk-VCKLFEUN.js";import{a as an}from"./chunk-LN2WFEU4.js";import{s as rn}from"./chunk-SSF4PIUR.js";import{b as sn,c as Ie}from"./chunk-JC6FKIFM.js";import{a as nn}from"./chunk-A6KGKEWT.js";import{f as Zt,g as en,i as tn}from"./chunk-M72BKL5Q.js";import{A as g,Ab as Ft,Af as z,Bf as Z,C as f,Da as Ct,Hc as Bt,Jc as Wt,Kc as Ht,La as oe,Mc as Kt,Na as Pt,Oa as Nt,Qb as He,R as L,Rb as Mt,Sb as Gt,Tb as Ae,Vb as se,Xb as ce,Y as J,Z as X,_b as Jt,ac as Oe,b as k,bb as Rt,bc as zt,c as At,cc as Ut,d as Ot,g as It,j as $e,lc as qt,pb as jt,qb as Dt,rf as Qt,s as Be,sf as Q,uc as de,ud as Vt,w as Tt,xe as Xt,z as We,zb as Lt,zd as Yt}from"./chunk-GE4KCSZP.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d5e0d6f-5ffa-5302-87da-3e741b80b716")}catch{}})();var Tr=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function le(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Oe(t.extensionName));for(let u of t.extensionNames??[])n.add(Oe(u));let a=u=>n.size===0||n.has(Oe(u)),r=(u,w)=>fn(u.filter(h=>a(h.name)).map(w)),i=(u,w)=>fn(u.filter(h=>a(h.name)).flatMap(w)),{registrations:o,commands:s,parsers:c,preflight:d,services:l,renderers:p,hooks:m}=e,_=i(o.relationship_kinds??[],u=>u.definitions.map(w=>w.kind)),y=p.overrides.filter(u=>a(u.name)&&((u.commands?.length??0)>0||u.resultDiscriminator!==void 0)).map(u=>({format:u.format,commands:[...u.commands??[]],result_discriminator:u.resultDiscriminator!==void 0})).sort((u,w)=>u.format.localeCompare(w.format));return{capabilities:zt(e,t),commands:r(o.commands,u=>u.command),command_overrides:r(s.overrides,u=>u.command),command_handlers:r(s.handlers,u=>u.command),hooks:Tr.filter(([u])=>m[u].some(w=>a(w.name))).map(([,u])=>u),flag_commands:r(o.flags,u=>u.target_command),item_types:i(o.item_types,u=>u.types.map(w=>w.name)),item_fields:i(o.item_fields,u=>u.fields.map(w=>w.name)),..._.length>0?{relationship_kinds:_}:{},migrations:i(o.migrations,u=>typeof u.definition.id=="string"?[u.definition.id]:[]),profiles:r(o.profiles,u=>u.profile.name),importers:r(o.importers,u=>u.importer),exporters:r(o.exporters,u=>u.exporter),search_providers:r(o.search_providers,u=>u.definition.name),vector_store_adapters:r(o.vector_store_adapters,u=>u.definition.name),parser_overrides:r(c.overrides,u=>u.command),service_overrides:r(l.overrides,u=>u.service),renderer_overrides:r(p.overrides,u=>u.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:d.overrides.filter(u=>a(u.name)).length}}function fn(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import _n 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]="6fc24a7c-a359-51fd-a432-4c8037d10e9e")}catch{}})();var Te=["extensions","docs","examples","assets","prompts"],Cr=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});function Pr(e){return Te.includes(e)}function Nr(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],a=[];for(let r of n){if(typeof r!="string"||r.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,g.USAGE);a.push(r.trim())}return[...new Set(a)].sort((r,i)=>r.localeCompare(i))}function Rr(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new f("Package manifest field pm must be an object.",g.USAGE);let t={},n=e;for(let[a,r]of Object.entries(n)){if(!Pr(a))continue;let i=Nr(a,r);i.length>0&&(t[a]=i)}return t}function q(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function Ke(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,a)=>n.localeCompare(a)):void 0}function gn(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=e.url;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}}function jr(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:q(t,"docs"),npm:q(t,"npm"),repository:q(t,"repository"),report:q(t,"report")};return Object.values(n).some(a=>typeof a=="string")?n:void 0}function Dr(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:q(t,"image"),video:q(t,"video")};return Object.values(n).some(a=>typeof a=="string")?n:void 0}function Lr(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:q(t,"display_name")??q(t,"displayName"),category:q(t,"category"),summary:q(t,"summary"),links:jr(t.links),media:Dr(t.media),tags:Ke(t.tags)};return Object.values(n).some(a=>a!==void 0)?n:void 0}async function ge(e){let t=ne.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await _n.readFile(t,"utf8"))}catch(s){throw new f(`Failed to parse package manifest at "${t}": ${String(s)}`,g.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new f(`Package manifest at "${t}" must be a JSON object.`,g.USAGE);let a=n,r=a.pm,i=r!=null,o=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{};return{source:i?"pm":"convention",package_json_path:t,package_name:typeof a.name=="string"?a.name:void 0,package_version:typeof a.version=="string"?a.version:void 0,package_private:a.private===!0,package_description:typeof a.description=="string"?a.description:void 0,package_keywords:Ke(a.keywords),package_homepage:typeof a.homepage=="string"?a.homepage:void 0,package_repository_url:gn(a.repository),package_bugs_url:gn(a.bugs),aliases:Ke(o.aliases),resources:Rr(r),catalog:Lr(o.catalog)}}async function hn(e){if(!await k(e))return[];let t=await _n.readdir(e,{withFileTypes:!0}),n=[];for(let a of t){if(!a.isDirectory())continue;let r=ne.join(e,a.name);await k(ne.join(r,"manifest.json"))&&n.push(r)}return n.sort((a,r)=>a.localeCompare(r))}async function Ce(e){if(await k(ne.join(e,"manifest.json")))return[e];let n=(await ge(e)).resources.extensions??[],a=new Set;for(let r of n){if(r.includes("*")||r.startsWith("!"))throw new f(`Package extension entry "${r}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,g.USAGE);let i=ne.resolve(e,r);if(!J(e,i))throw new f(`Package extension entry "${r}" resolves outside package root.`,g.USAGE);if(await k(ne.join(i,"manifest.json"))){a.add(i);continue}for(let o of await hn(i))a.add(o)}if(n.length===0)for(let r of Cr.extensions)for(let i of await hn(ne.join(e,r)))a.add(i);return[...a].sort((r,i)=>r.localeCompare(i))}import he from"node:fs/promises";import _e from"node:path";import yn from"node:fs/promises";import Ve 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 M(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function v(e){return e.trim().toLowerCase()}function Pe(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 f("Extension manifest name must resolve to a non-empty directory name.",g.USAGE);if(r==="."||r==="..")throw new f('Extension manifest name must not resolve to "." or "..".',g.USAGE);return r}function Ye(e){return Mt(e)}async function Fr(e){try{let t=JSON.parse(await yn.readFile(Ve.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 Mr(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new f(`Extension entry file is missing at "${t}".`,g.USAGE);let a=await Fr(n.source_root),r=a.package_name?`pm install npm:${a.package_name}`:void 0,i=n.source_input??n.source_root;return new f(`Extension entry "${e.entry}" is absent from GitHub source "${i}". 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."}`,g.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 ${i}`,normalized_args:["install",i],...r?{next_best_command:r}:{}}})}async function pe(e,t={}){let n=Ve.join(e,"manifest.json");if(!await k(n))throw new f(`Extension manifest is missing at "${n}".`,g.USAGE);let a;try{a=JSON.parse(await yn.readFile(n,"utf8"))}catch(o){throw new f(`Failed to parse extension manifest at "${n}": ${Gr(o)}`,g.USAGE)}let r=Ye(a);if(!r)throw new f(`Extension manifest at "${n}" is invalid.`,g.USAGE);let i=Ve.resolve(e,r.entry);if(!J(e,i))throw new f(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await k(i))throw await Mr(r,i,t);if(!await Gt(e,i))throw new f(`Extension entry "${r.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:i,manifest:r}}function Gr(e){return e instanceof Error?e.message:String(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]="50f2e5c4-c7fe-5e29-ae2a-60b1b1957756")}catch{}})();var Xe=1,ae="2026.6.24",Jr=">=22.18.0",zr={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},vn=new Set([...Xt.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(an).map(e=>e.toLowerCase()),"scaffold"]),Ur="^6.0.0",qr="^22.0.0",xn=["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."," }"," }","}",""],B=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function wn(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function kn(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 Sn(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 Br={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},bn=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],En={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"]},Wr={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"]'},Hr={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."},Kr={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."},$n="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Vr={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 before every command to compute the migration/format gate decision \u2014","the last registered override wins. 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."]},Yr={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."]},Xr={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`."]},Qr={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 An(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 On(e,t){return e==="schema"?Xr[t]:e==="profile"?Qr[t]:Yr[t]}function Zr(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(),i=a>0&&(a===t.length||r!==void 0&&vn.has(r));return`${(vn.has(n)||i?["starter",...t]:t).join(" ")} ping`}function In(e){let t=e,n=`${e}s`,a=e.replace(/-/g,""),r=a===t?[]:[a],i=`${e.replace(/-/g,"_")}_owner`,o="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(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(i)},`,' 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(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "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 ei(e,t,n){let a=`${e}-search`,r=`${e}-vector`,i=`${e.replace(/-/g," ")} items`,o=[" 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 o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(a)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(r)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],p=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // 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(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // 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({",...In(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // 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(i)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} 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(i)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} 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"?[...o,""," // 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"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) before EVERY command \u2014 the last"," // registered override wins. 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((context) => context.decision);"]:n==="services"?[...o,""," // 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 };`," });"]:[...o,""," // 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 ti(e,t,n){let a=n==="hooks",r=n==="search",i=n==="importers",o=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",p=n==="services",m=Wr[n],_=e,y=`${e}s`,u=`${e.replace(/-/g,"_")}_note`,w=`${e}-0001-init`,h=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],b=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;",...B,"});",""]:[],x=r?Qe(e,t,"search",m):[],P=i?Qe(e,t,"importers",m):[],R=o?[`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 {",...wn(kn({extensionName:e,itemTypeName:_,itemTypeFolder:y,fieldName:u,migrationId:w,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...B,"});",""]:[],N=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 {",...wn(Sn(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...B,"});",""]:[],te=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;",...B,"});",""]:[],fe=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...B,"});",""]:[],S=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...B,"});",""]:[],D=p?[`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;",...B,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...h,'} from "@unbrained/pm-cli/sdk/testing";',...r?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...xn,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...B,"});","",...b,...x,...P,...R,...N,...te,...fe,...S,...D,`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(`
2
2
  `)}function ni(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 ai={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"},ri={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 ii(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 oi(e,t,n){let a=[],r=[...ii(e,t,n)],i=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,p=e.replace(/-/g,""),m=p===d?[]:[p],_=`${e.replace(/-/g,"_")}_note`,y=`${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... */ }","});"),i.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(o)},`," 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 }),","});"),i.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,","}));"),i.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(_)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(y)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),i.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({",...In(e),"});"),i.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);`," },","});"),i.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 };","});"),i.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) before EVERY command - the last registered override wins.","// 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((context) => context.decision);"),i.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 };`,"});"),i.push(" services: { output_format: outputService },");break}return{builderImports:a,definitions:r,blueprintFields:i}}function si(e,t,n){let a=oi(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...a.builderImports].sort((i,o)=>i.localeCompare(o)).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(`
3
3
  `)}function Qe(e,t,n,a){if(n==="commands")return[];let r=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${a},`," });"],m=_=>[...p," let deactivated = false;"," try {",..._.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...B];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(i)}, 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(i)},`,' 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(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' 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(o)},`,' 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(kn({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Sn(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 ci(e,t,n){let a=n==="parser",r=JSON.stringify([...En[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" };',"",...xn,`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(ae)},`," },",` target: { pmVersion: ${JSON.stringify(ae)} },`," });"," // 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;",...B,"});","",...Qe(e,t,n,r)].join(`
4
4
  `)}function di(e,t,n){let a=An(n,"package"),r=On(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 (${ai[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`.",$n,"- `.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 ${ri[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 \`${Xe}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${ae}\`. 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(`
@@ -52,4 +52,4 @@ Agent guidance check
52
52
  `),F.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
53
53
  `);let c=t?"Y/n":"y/N",d=await n.question(`Enable telemetry for this project? [${c}] `),l=hr(d,t);return F.write(`
54
54
  `),{prefix:r,preset:s,telemetry_enabled:l}}finally{n.close()}}function xc(e){return{presetFromOption:kt(e.preset),useDefaults:e.defaults===!0,authorFromOption:ur(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:gr(e.agentGuidance),typePreset:pr(e.typePreset)}}function kc(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function Sc(e,t,n,a){if(t.length===0||n)return;let r=a.discovery==="ancestor";throw new f(`${r?`No tracker exists in ${a.requested_cwd}; pm init found an ancestor tracker at ${a.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,g.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:r?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:a.tracker_root,requested_path:a.requested_cwd,suggested_path:a.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...r?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...r?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function Ec(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(St(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function $c(e){let t=await z(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=kc({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return Sc(e.settingsPath,n,e.options.force===!0,e.target),Ec({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Z(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function Ac(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,a,r=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await xr(t,We.telemetry.enabled);t=c.prefix,n=c.preset,a=c.telemetry_enabled,r=!0}let i=n??"minimal",o=vc();o.id_prefix=t,St(o,i);let s=Vt()?.trim()||void 0;return o.author_default=e.normalizedOptions.authorFromOption??s??"",a!==void 0&&(o.telemetry.enabled=a,o.telemetry.first_run_prompt_completed=!0),await Z(e.pmRoot,o),{settings:o,normalizedPrefix:t,chosenPreset:n,wizardUsed:r}}async function sr(e){return e.settingsExists?await $c(e):await Ac({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function Oc(e){let t=await or({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await Z(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function Ic(e,t){let n=[],a=[],r=await Kt(e,t.schema);for(let i of r.created_paths)n.push(i),a.push(...await de({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:a}}async function Tc(e){if(e.typePreset===void 0)return;let t=await yr(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await de({path:t.file,scope:"project",op:"init:type_preset"})),t}async function Cc(e){let n=Ct(e.settings,qt()).folders.filter(r=>!Be.includes(r)),a=await br(e.pmRoot,n);e.createdDirs.push(...a.createdDirs),e.warnings.push(...a.warnings)}function Pc(e){let t=T.resolve(e.tracker_root),n=T.dirname(t);return T.basename(t)==="pm"&&T.basename(n)===".agents"?T.dirname(n):e.workspace_root}async function Nc(e,t,n,a){if(!e)return;let r=await _t("all",{install:!0,project:!0},{...t,path:n});a.push(...r.warnings);let i=_r(r),o=i.packages.filter(s=>!s.ok).map(s=>s.alias);if(!i.installed_all||o.length>0)throw new f(`pm init --with-packages did not install all bundled packages successfully${o.length>0?`: ${o.join(", ")}`:"."}`,g.GENERIC_FAILURE);return i}function kr(e){let t=a=>Ie([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...a]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let a of e.agentGuidanceNextSteps){let r=e.target.mode==="workspace-discovery"?a:a.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(r)||n.push(r)}return n}async function Sr(e,t,n,a=dn){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let r=await a({pmRoot:e,workspaceRoot:t});r.gitattributes.changed&&n.push(`updated:merge_fence:${r.gitattributes.path}`)}catch(r){if(!(r instanceof f))throw r;n.push(`merge_fence_skipped:install_failed:${r.context.code??"pm_error"}:${r.message}:run pm merge install after resolving the Git repository error`)}}async function Mp(e,t,n={}){let a=process.cwd(),r=mr(a,t,e,n.workspace),i=r.pmRoot;e=fr(r.prefixArg,n.idPrefix);let o=xc(n);await wr(i,r.target.mode==="tracker-path",n.force===!0);let s=[],c=[],d=T.join(i,"settings.json"),l=await k(d),p;l&&(p=await sr({pmRoot:i,settingsPath:d,settingsExists:l,normalizedPrefix:Q(e),prefixArg:e,options:n,normalizedOptions:o,warnings:c,target:r.target}));let m=await br(i,Be);s.push(...m.createdDirs),c.push(...m.warnings),p??=await sr({pmRoot:i,settingsPath:d,settingsExists:l,normalizedPrefix:Q(e),prefixArg:e,options:n,normalizedOptions:o,warnings:c,target:r.target});let{settings:_}=p,y=Pc(r.target),u=await cn(y??T.dirname(i)),w=y??u,h=await Oc({pmRoot:i,cwd:w??a,agentGuidanceMode:o.agentGuidanceMode,settings:_,warnings:c}),b=await Ic(i,_);s.push(...b.createdDirs),c.push(...b.warnings);let x=await Tc({pmRoot:i,settings:_,typePreset:o.typePreset,warnings:c});if(x&&(_=await z(i)),await Cc({pmRoot:i,settings:_,createdDirs:s,warnings:c}),w&&o.agentGuidanceMode!=="status"){let N=await on(w,{pmRoot:i});N.changed&&c.push(`updated:gitignore:${N.path}`)}!l&&n.mergeFence!==!1&&o.agentGuidanceMode!=="status"&&await Sr(i,u,c);let P=await Nc(o.installBundledPackages,t,i,c),R=kr({installBundledPackages:o.installBundledPackages,registeredTypePreset:x,agentGuidanceNextSteps:h.next_steps,target:r.target});return{ok:!0,path:i,target:r.target,settings:_,created_dirs:s,warnings:c,governance_preset:_.governance.preset,wizard_used:p.wizardUsed,...x?{registered_type_preset:x}:{},...P?{installed_packages:P}:{},next_steps:R,agent_guidance:h}}export{le as a,v as b,V as c,Te as d,Cr as e,ge as f,Ce as g,bn as h,tt as i,jn as j,pd as k,wo as l,sa as m,ca as n,_t as o,Ha as p,mp as q,or as r,Lp as s,Fp as t,Mp as u};
55
- //# sourceMappingURL=chunk-377OOXUF.js.map
55
+ //# sourceMappingURL=chunk-EGJ4JTUG.js.map
@@ -1,8 +1,8 @@
1
- import{f as me,ka as le}from"./chunk-PA5XRN2A.js";import{j as fe}from"./chunk-5PZGZMPG.js";import{a as R,i as ce}from"./chunk-377OOXUF.js";import{e as se,f as ae,g as de}from"./chunk-BKMZTZYL.js";import{Dc as ie,Eb as U,Fb as V,Gb as z,Hb as W,Ib as G,Jb as Y,Kb as X,L as x,Lb as J,M as B,Mb as Q,Nb as Z,Ob as ee,Pb as re,Wb as te,Xb as ne,bc as oe,db as D,eb as H,fb as L,gb as K,nb as E,o as C,ob as q,rb as h}from"./chunk-V5K52PYW.js";(function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="60463c2e-f904-5199-87b0-8a17f0e2ee0f")}catch{}})();function Ar(r){return r}function Fr(r){return r}function ke(r,e){for(let t of e.commands??[])r.registerCommand(t);for(let[t,n]of Object.entries(e.commandOverrides??{}))r.registerCommand(t,n);for(let[t,n]of Object.entries(e.flags??{}))r.registerFlags(t,n);for(let[t,n]of Object.entries(e.parsers??{}))r.registerParser(t,n);for(let[t,n]of Object.entries(e.renderers??{}))if(typeof n=="function")r.registerRenderer(t,n);else{let{run:s,...o}=n;r.registerRenderer(t,s,o)}for(let[t,n]of Object.entries(e.services??{}))r.registerService(t,n)}function Ce(r,e){for(let o of e.preflights??[])r.registerPreflight(o);let t=e.itemTypes??[];t.length>0&&r.registerItemTypes(t);let n=e.itemFields??[];n.length>0&&r.registerItemFields(n);let s=e.relationshipKinds??[];s.length>0&&r.registerRelationshipKinds(s);for(let o of e.migrations??[])r.registerMigration(o);for(let o of e.profiles??[])r.registerProfile(o)}function Re(r,e){for(let t of e.searchProviders??[])r.registerSearchProvider(t);for(let t of e.vectorStoreAdapters??[])r.registerVectorStoreAdapter(t);for(let t of e.importers??[])r.registerImporter(t.name,t.importer,t.options);for(let t of e.exporters??[])r.registerExporter(t.name,t.exporter,t.options)}function Ne(r,e){for(let t of e.beforeCommand??[])r.hooks.beforeCommand(t);for(let t of e.beforeMutation??[])r.hooks.beforeMutation(t);for(let t of e.afterCommand??[])r.hooks.afterCommand(t);for(let t of e.onWrite??[])r.hooks.onWrite(t);for(let t of e.onRead??[])r.hooks.onRead(t);for(let t of e.onIndex??[])r.hooks.onIndex(t)}function Se(r){let t={activate:async n=>{ke(n,r),Ce(n,r),Re(n,r),Ne(n,r.hooks??{}),await r.activate?.(n)}};return r.manifest&&(t.manifest=r.manifest),r.deactivate&&(t.deactivate=r.deactivate),t}function v(r){let e=r.flatMap(t=>t??[]);return e.length>0?e:void 0}function _(r){let e=Object.assign({},...r.map(t=>t??{}));return Object.keys(e).length>0?e:void 0}function Oe(r){let e={};for(let t of r)for(let[n,s]of Object.entries(t??{}))e[n]=[...e[n]??[],...s];return Object.keys(e).length>0?e:void 0}var Ae=["beforeCommand","beforeMutation","afterCommand","onWrite","onRead","onIndex"];function Fe(r,e,t){let n=e.map(o=>o?.[t]),s=v(n);if(s!==void 0){let o=r;o[t]=s}}function Te(r){let e={};for(let t of Ae)Fe(e,r,t);return Object.keys(e).length>0?e:void 0}function Tr(...r){let e={},t=(i,a)=>{a!==void 0&&(e[i]=a)};t("commands",v(r.map(i=>i.commands))),t("commandOverrides",_(r.map(i=>i.commandOverrides))),t("flags",Oe(r.map(i=>i.flags))),t("parsers",_(r.map(i=>i.parsers))),t("renderers",_(r.map(i=>i.renderers))),t("services",_(r.map(i=>i.services))),t("preflights",v(r.map(i=>i.preflights))),t("itemTypes",v(r.map(i=>i.itemTypes))),t("itemFields",v(r.map(i=>i.itemFields))),t("relationshipKinds",v(r.map(i=>i.relationshipKinds))),t("migrations",v(r.map(i=>i.migrations))),t("profiles",v(r.map(i=>i.profiles))),t("searchProviders",v(r.map(i=>i.searchProviders))),t("vectorStoreAdapters",v(r.map(i=>i.vectorStoreAdapters))),t("importers",v(r.map(i=>i.importers))),t("exporters",v(r.map(i=>i.exporters))),t("hooks",Te(r.map(i=>i.hooks)));let n;for(let i of r)i.manifest&&(n=i.manifest);t("manifest",n);let s=r.some(i=>i.activate);t("activate",s?async i=>{for(let a of r)a.activate&&await a.activate(i)}:void 0);let o=r.some(i=>i.deactivate);return t("deactivate",o?async()=>{let i=[];for(let a of[...r].reverse())if(a.deactivate)try{await a.deactivate()}catch(d){i.push(d)}if(i.length>0)throw i.length>1?new AggregateError(i,"Multiple extension blueprint deactivate hooks failed."):i[0]}:void 0),e}var Pe=[["commands","commands"],["commandOverrides","commands"],["flags","schema"],["itemTypes","schema"],["itemFields","schema"],["relationshipKinds","schema"],["migrations","schema"],["profiles","schema"],["parsers","parser"],["renderers","renderers"],["services","services"],["preflights","preflight"],["searchProviders","search"],["vectorStoreAdapters","search"],["importers","importers"],["exporters","importers"]];function $(r){return r?Array.isArray(r)?r.length>0:Object.keys(r).length>0:!1}function N(r){let e=new Set;for(let[s,o]of Pe)$(r[s])&&e.add(o);(r.commands??[]).filter(b).some(s=>s.flags!==void 0)&&e.add("schema");let t=[...r.importers??[],...r.exporters??[]].filter(b);t.some(s=>s?.options?.flags!==void 0)&&e.add("schema"),t.some(s=>typeof s=="object")&&e.add("commands");let n=r.hooks??{};return[n.beforeCommand,n.beforeMutation,n.afterCommand,n.onWrite,n.onRead,n.onIndex].some($)&&e.add("hooks"),[...e].sort((s,o)=>s.localeCompare(o))}var Ie=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function p(r){return[...new Set(r)].sort((e,t)=>e.localeCompare(t))}function b(r){return r!=null}function S(r){return h(`${r.name} import`)}function O(r){return h(`${r.name} export`)}function Me(r,e,t){return[...r.map(n=>h(n.name)),...e.filter(n=>n.options!==void 0).map(S),...t.filter(n=>n.options!==void 0).map(O)]}function je(r,e,t,n){return[...Object.keys(r.flags??{}).map(s=>h(s)),...e.filter(s=>s.flags!==void 0).map(s=>h(s.name)),...t.filter(s=>s.options?.flags!==void 0).map(S),...n.filter(s=>s.options?.flags!==void 0).map(O)]}function Be(r){return Ie.filter(([e])=>(r[e]?.length??0)>0).map(([,e])=>e)}function De(r){let e=Object.entries(r??{}).filter(([,t])=>typeof t!="function"&&((t.commands?.length??0)>0||t.resultDiscriminator!==void 0)).map(([t,n])=>{let s=n;return{format:t,commands:p((s.commands??[]).map(o=>h(o))),result_discriminator:s.resultDiscriminator!==void 0}}).sort((t,n)=>t.format.localeCompare(n.format));return e.length>0?{renderer_ownership:e}:{}}function He(r,e,t){return{item_types:p((r.itemTypes??[]).map(n=>n.name)),item_fields:p((r.itemFields??[]).map(n=>n.name)),...(r.relationshipKinds?.length??0)>0?{relationship_kinds:p(r.relationshipKinds.map(n=>n.kind))}:{},migrations:p((r.migrations??[]).flatMap(n=>typeof n.id=="string"?[n.id]:[])),profiles:p((r.profiles??[]).map(n=>n.name)),importers:p(e.map(n=>h(n.name))),exporters:p(t.map(n=>h(n.name))),search_providers:p((r.searchProviders??[]).map(n=>n.name)),vector_store_adapters:p((r.vectorStoreAdapters??[]).map(n=>n.name)),parser_overrides:p(Object.keys(r.parsers??{}).map(n=>h(n))),service_overrides:p(Object.keys(r.services??{}).map(n=>String(n).trim().toLowerCase())),renderer_overrides:p(Object.keys(r.renderers??{}).map(n=>String(n).trim().toLowerCase())),...De(r.renderers),preflight_overrides:(r.preflights??[]).length}}function Le(r){let e=(r.commands??[]).filter(b),t=(r.importers??[]).filter(b),n=(r.exporters??[]).filter(b),s=t.map(S),o=n.map(O),i=Me(e,t,n),a=je(r,e,t,n),d=r.hooks??{},f=He(r,t,n);return{capabilities:N(r),commands:p(i),command_overrides:p(Object.keys(r.commandOverrides??{}).map(w=>h(w))),command_handlers:p([...i,...s,...o]),hooks:Be(d),flag_commands:p(a),...f}}var Ke=["commands","commandOverrides","flags","parsers","renderers","services","preflights","itemTypes","itemFields","relationshipKinds","migrations","profiles","searchProviders","vectorStoreAdapters","importers","exporters"];function qe(r){return(r.itemFields??[]).filter(e=>typeof e?.name=="string"&&ie.has(e.name.trim())).map(e=>({code:"reserved_item_field",severity:"error",message:`Item field "${e.name}" collides with reserved item metadata; rename it with an extension-specific prefix before publishing.`,field:e.name}))}function Ue(r){return[...Object.values(r.flags??{}).flat(),...(r.commands??[]).flatMap(t=>t.flags??[]),...(r.importers??[]).flatMap(t=>t.options?.flags??[]),...(r.exporters??[]).flatMap(t=>t.options?.flags??[])].flatMap(t=>{if(typeof t?.long!="string"&&typeof t?.short!="string")return[];let n=D(t.long,t.short);if(n===null)return[];let{token:s,failure:o}=n;return[{code:o,severity:"error",message:`Flag "${s}" ${H(s,o)}.`,field:s}]})}function ue(r){let e=new Set;for(let t of r){let n=q(t)??E(t);n!==null&&e.add(n)}return[...e].sort((t,n)=>t.localeCompare(n))}function Ve(r,e){let t=[];if(e===null)return r.length>0&&t.push({code:"manifest_capabilities_absent",severity:"warning",message:`Blueprint exercises ${r.length===1?"capability":"capabilities"} [${r.join(", ")}] but declares none; set capabilities to deriveExtensionCapabilities(blueprint) so the manifest grant matches.`}),t;let n=new Set(e),s=new Set(r);for(let o of r)n.has(o)||t.push({code:"capability_undeclared",severity:"error",message:`Blueprint exercises capability "${o}" but it is absent from the declared capabilities; activation throws extension_capability_missing \u2014 add "${o}" to the manifest capabilities.`,capability:o});for(let o of e)s.has(o)||t.push({code:"capability_unused",severity:"warning",message:`Capability "${o}" is declared but no blueprint surface exercises it; drop it to keep the manifest least-privilege (pm package doctor reports this as extension_capability_unused).`,capability:o});return t}function ze(r){let e=[],t=new Map;for(let s of r.commands??[]){let o=h(s.name);t.set(o,(t.get(o)??0)+1)}for(let[s,o]of t)o>1&&e.push({code:"duplicate_command",severity:"warning",message:`Command "${s}" is declared ${o} times in commands; the later registration shadows the earlier one at dispatch.`,command:s});let n=new Set(Object.keys(r.commandOverrides??{}).map(s=>h(s)));for(let s of t.keys())n.has(s)&&e.push({code:"command_override_conflict",severity:"warning",message:`Command "${s}" is declared both as a new command definition and as a command override; register one or the other.`,command:s});return e}function We(r){let e=[];for(let t of Ke)t in r&&!$(r[t])&&e.push({code:"empty_surface",severity:"warning",message:`Blueprint field "${t}" is present but empty; remove it or populate it.`,field:t});if("hooks"in r){let t=r.hooks??{};[t.beforeCommand,t.beforeMutation,t.afterCommand,t.onWrite,t.onRead,t.onIndex].some($)||e.push({code:"empty_surface",severity:"warning",message:'Blueprint field "hooks" is present but registers no lifecycle hooks; remove it or populate it.',field:"hooks"})}return e}function k(r,e={}){let t=N(r),n=e.declaredCapabilities??r.manifest?.capabilities,s=Array.isArray(n)?ue(n):null,o=[...Ve(t,s),...ze(r),...Ue(r),...qe(r),...We(r)];return{ok:o.every(i=>i.severity!=="error"),findings:o,used:t,declared:s}}function ge(r,e){let{additionalCapabilities:t,...n}=e,s=Array.isArray(t)?ue(t):[],o=[...new Set([...N(r),...s])].sort((i,a)=>i.localeCompare(a));return{...n,capabilities:o}}function Pr(r,e){let t=ge(r,e);return{module:Se({...r,manifest:t}),manifest:t}}function pe(r,e){if(r.status==="absent"||r.status==="ok")return null;let t=`${r.kind}_${r.status}`,n;switch(t){case"pm_min_version_invalid":n=`pm_min_version "${r.required}" is not a valid version; the extension is treated as incompatible and the loader skips it.`;break;case"pm_min_version_unchecked":n=`pm_min_version "${r.required}" could not be compared against pm ${e}; compatibility is unverified.`;break;case"pm_min_version_unmet":n=`Requires pm >= ${r.required} but the target is pm ${e}; the loader skips the extension.`;break;case"pm_max_version_invalid":n=`pm_max_version "${r.required}" is not a valid inclusive upper bound (version ranges are not allowed); the extension is treated as incompatible and the loader skips it.`;break;case"pm_max_version_unchecked":n=`pm_max_version "${r.required}" could not be compared against pm ${e}; compatibility is unverified.`;break;case"pm_max_version_exceeded":n=`Allows pm <= ${r.required} but the target is pm ${e}; the loader skips the extension.`;break;case"pm_max_version_exceeded_warn":n=`Target pm ${e} is newer than pm_max_version ${r.required}, but the "warn" exceeded mode lets it load with a warning.`;break}return{code:t,severity:r.allowed?"warning":"error",constraint:r.kind,required:r.required,current:e,message:n}}function A(r,e){let t=L(r.pm_min_version,e.pmVersion),n=K(r.pm_max_version,e.pmVersion,e.pmMaxVersionExceededMode??"block"),s=[],o=pe(t,e.pmVersion);o!==null&&s.push(o);let i=pe(n,e.pmVersion);return i!==null&&s.push(i),{compatible:t.allowed&&n.allowed,findings:s,pmVersion:e.pmVersion}}var Ge=new Set(["capability_undeclared","capability_unused","manifest_capabilities_absent"]);function he(r,e={}){let t=k(r,{declaredCapabilities:e.declaredCapabilities}),n=e.identity?ge(r,e.identity):null,s=e.target?A(n??r.manifest??{},e.target):null,a=[...(n!==null&&e.declaredCapabilities===void 0?t.findings.filter(d=>!Ge.has(d.code)):t.findings).map(d=>({source:"blueprint",severity:d.severity,code:d.code,message:d.message})),...(s?.findings??[]).map(d=>({source:"compatibility",severity:d.severity,code:d.code,message:d.message}))];return{ok:a.every(d=>d.severity!=="error"),capabilities:t.used,blueprint:t,manifest:n,compatibility:s,findings:a}}(function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="a09f5e0d-fccc-5a22-a6f3-0a37cbeea3b0")}catch{}})();function g(r,e){return r.name??e??""}var Ye={before_command:"beforeCommand",before_mutation:"beforeMutation",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"},F={before_command:"beforeCommand",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};function l(r){return r.trim().toLowerCase()}function ve(r){return l(r).replaceAll("-","_")}function u(r){return r?` from extension "${r}"`:""}function c(r){return[...new Set(r)].sort((e,t)=>e.localeCompare(t))}function y(r){if(typeof r!="string")throw new Error('A command name string is required. Pass it via the options object, e.g. runRegisteredCommandForTest(activation, { command: "my command" }) \u2014 positional command arguments are not supported.');return r.trim().toLowerCase().split(/\s+/).filter(e=>e.length>0).join(" ")}function m(r){return r.length>0?r.join(", "):"(none)"}function ye(r,e,t){let n=new Set(r??[]),s=c(e.filter(o=>!n.has(o)));if(s.length>0)throw new Error(`Expected package manifest ${t} to include ${s.join(", ")}; available: ${m(c(r??[]))}`)}function xe(r){let e=new Set;for(let t of r)typeof t.long=="string"&&t.long.trim().length>0&&e.add(t.long.trim()),typeof t.short=="string"&&t.short.trim().length>0&&e.add(t.short.trim());return e}function T(r){let e=x(r);if(!e)return{};let t=x(e.manifest);if(t)return t;let n=x(e.default),s=x(n?.manifest);return s||(n&&typeof e.default!="function"&&("name"in n||"capabilities"in n)?n:typeof r!="function"&&("name"in e||"capabilities"in e)?e:{})}function P(r,e){return e??(typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():"test-extension")}function be(r,e){return Array.isArray(e.capabilities)?[...e.capabilities]:Array.isArray(r.capabilities)?r.capabilities.filter(t=>typeof t=="string"):[]}function we(r,e,t){return{disabled_by_flag:!1,roots:{global:"",project:""},configured_enabled:[],configured_disabled:[],discovered:[],effective:[],warnings:[],policy:t.policy,failed:[],loaded:[{layer:t.layer,directory:"",manifest_path:"",name:t.name,version:typeof e.version=="string"?e.version:"0.0.0",entry:typeof e.entry=="string"?e.entry:"./index.js",priority:typeof e.priority=="number"?e.priority:0,entry_path:"",capabilities:t.capabilities,manifest_version:typeof e.manifest_version=="number"?e.manifest_version:void 0,pm_min_version:typeof e.pm_min_version=="string"?e.pm_min_version:void 0,pm_max_version:typeof e.pm_max_version=="string"?e.pm_max_version:void 0,engines:e.engines,trusted:e.trusted,provenance:e.provenance,sandbox_profile:e.sandbox_profile,permissions:e.permissions,activation:e.activation,module:r}]}}async function Xe(r,e={}){let t=T(r);return ne(we(r,t,{name:P(t,e.name),layer:e.layer??"project",capabilities:be(t,e),policy:e.policy??C()}))}async function Je(r,e={}){let t=T(r);return te(we(r,t,{name:P(t,e.name),layer:e.layer??"project",capabilities:be(t,{}),policy:C()}),e.activation,e.deactivateTimeoutMs===void 0?{}:{deactivate_timeout_ms:e.deactivateTimeoutMs})}async function I(r,e){let t=y(e.command);if(t.length===0)throw new Error("Expected command name must be a non-empty string");if(!r.handlers.some(a=>a.command===t)){let a=c(r.handlers.map(d=>d.command));throw new Error(`Expected a registered command handler for "${t}" to invoke. Available command handlers: ${m(a)}`)}if(e.sdk!==void 0&&e.sdkFactory!==void 0)throw new TypeError("runRegisteredCommandForTest accepts sdk or sdkFactory, not both");let s=e.pmRoot??"",o={json:!0,quiet:!0,noPager:!0,...e.global},i=e.sdk??e.sdkFactory?.({pmRoot:s,global:o})??(s.length>0?me(s,new le({pmRoot:s})):void 0);return X(r,{command:t,args:e.args?[...e.args]:[],options:e.options?{...e.options}:{},global:o,pm_root:s,...i===void 0?{}:{sdk:i}})}async function Qe(r,e){if((r.beforeMutation?.length??0)===0)throw new Error("Expected a registered before_mutation hook to invoke");await V(r,e.context)}async function Ze(r,e){let t=e.kind;if(t==="before_mutation")throw new Error("Invoke before_mutation hooks with runRegisteredMutationGuardForTest so denials and failures retain fail-closed semantics.");if((r[F[t]]?.length??0)===0){let n=c(Object.keys(F).filter(s=>(r[F[s]]?.length??0)>0));throw new Error(`Expected a registered "${t}" hook to invoke. Hook kinds with registrations: ${m(n)}`)}switch(e.kind){case"before_command":return U(r,e.context);case"after_command":return z(r,e.context);case"on_read":return G(r,e.context);case"on_write":return W(r,e.context);case"on_index":return Y(r,e.context)}}async function er(r,e){let t=y(e.command);if(!r.overrides.some(n=>n.command===t))throw new Error(`Expected a registered parser override for command "${t}" to invoke. Available parser override commands: ${m(c(r.overrides.map(n=>n.command)))}`);return J(r,e)}async function rr(r,e){if(r.overrides.length===0)throw new Error("Expected a registered preflight override to invoke, but none are registered.");return Q(r,e)}async function tr(r,e){let t=y(e.command);if(!r.overrides.some(n=>n.command===t))throw new Error(`Expected a registered command override for command "${t}" to invoke. Available command override commands: ${m(c(r.overrides.map(n=>n.command)))}`);return ee(r,e)}async function nr(r,e){if(!r.overrides.some(t=>t.format===e.format))throw new Error(`Expected a registered renderer override for format "${e.format}" to invoke. Available renderer override formats: ${m(c(r.overrides.map(t=>t.format)))}`);return re(r,e)}async function or(r,e){if(!r.overrides.some(t=>t.service===e.service))throw new Error(`Expected a registered service override for service "${e.service}" to invoke. Available service override services: ${m(c(r.overrides.map(t=>t.service)))}`);return Z(r,e)}var ir={query:["query"],embed:["embed"],embedBatch:["embedBatch","embed_batch"],queryExpansion:["queryExpansion","query_expansion"],rerank:["rerank"]};async function sr(r,e){let t=se(r,e.provider);if(!t){let o=c(r.search_providers.map(i=>i.definition.name));throw new Error(`Expected a registered search provider "${e.provider}" to invoke. Available search providers: ${m(o)}`)}let n=t.runtime_definition,s=ir[e.operation].map(o=>n[o]).find(o=>typeof o=="function");if(typeof s!="function")throw new Error(`Registered search provider "${e.provider}" does not implement the "${e.operation}" operation.`);return await s(e.context)}async function ar(r,e){let t=ae(r,e.adapter);if(!t){let s=c(r.vector_store_adapters.map(o=>o.definition.name));throw new Error(`Expected a registered vector store adapter "${e.adapter}" to invoke. Available vector store adapters: ${m(s)}`)}let n=t.runtime_definition[e.operation];if(typeof n!="function")throw new Error(`Registered vector store adapter "${e.adapter}" does not implement the "${e.operation}" operation.`);return await n(e.context)}async function dr(r,e){let t=$e(r,{migration:e.migration,extensionName:e.extensionName}),n=de(t).run;if(typeof n!="function")throw new Error(`Registered migration "${e.migration}" does not implement a run function to invoke.`);let s=t.definition.status,o={id:t.definition.id,command:"migration",layer:t.layer,extension:t.name,pm_root:e.pmRoot??"",status:(typeof s=="string"?s.trim().toLowerCase():"")||"pending"};return await n(o)}async function mr(r,e){let t=Ee(r.registrations,{importer:e.importer,extensionName:e.extensionName});return I(r.commands,{command:`${t.importer} import`,args:e.args,options:e.options,global:e.global,pmRoot:e.pmRoot})}async function cr(r,e){let t=_e(r.registrations,{exporter:e.exporter,extensionName:e.extensionName});return I(r.commands,{command:`${t.exporter} export`,args:e.args,options:e.options,global:e.global,pmRoot:e.pmRoot})}function Gr(r,e={}){let t=e.deactivated??1;if(r.deactivated!==t)throw new Error(`Expected ${t} extension${t===1?"":"s"} to deactivate cleanly, but ${r.deactivated} did.`);let n=e.failed??0;if(r.failed.length!==n){let s=r.failed.map(o=>`${o.layer}:${o.name} (${o.error})`).join(", ");throw new Error(`Expected ${n} teardown failure${n===1?"":"s"}, but observed ${r.failed.length}${s.length>0?`: ${s}`:""}.`)}return r}function Yr(r,e){if(e.packageName!==void 0&&r.package_name!==e.packageName)throw new Error(`Expected package manifest package_name to be "${e.packageName}"; received "${r.package_name??"(none)"}"`);if(e.aliases!==void 0&&ye(r.aliases,e.aliases,"aliases"),e.resources!==void 0)for(let[t,n]of Object.entries(e.resources))ye(r.resources[t],n,`pm.${t}`);return r}function fr(r,e){let t=y(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.commands.filter(i=>i.command===t),s=e.extensionName?n.find(i=>i.name===e.extensionName):n[0];if(!s){let i=r.commands.map(d=>d.command).sort((d,f)=>d.localeCompare(f)),a=e.extensionName?` from extension "${e.extensionName}"`:"";throw new Error(`Expected extension command "${t}"${a} to be registered. Available commands: ${m(i)}`)}if(e.action!==void 0&&s.action!==e.action)throw new Error(`Expected extension command "${t}" action "${e.action}", received "${s.action}"`);if(e.arguments!==void 0){let i=(s.arguments??[]).map(d=>d.name),a=e.arguments.filter(d=>!i.includes(d));if(a.length>0)throw new Error(`Expected extension command "${t}" arguments ${m(e.arguments)}; missing ${m(a)}; available ${m(i)}`)}let o=r.flags.filter(i=>i.target_command===t&&(e.extensionName===void 0||i.name===e.extensionName)).flatMap(i=>i.flags);if(e.flags!==void 0){let i=xe(o),a=e.flags.filter(d=>!i.has(d));if(a.length>0)throw new Error(`Expected extension command "${t}" flags ${m(e.flags)}; missing ${m(a)}; available ${m([...i].sort((d,f)=>d.localeCompare(f)))}`)}return{command:s,flags:o}}function lr(r,e){let t=y(g(e,e.targetCommand));if(t.length===0)throw new Error("Expected target command name must be a non-empty string");let n=r.flags.filter(o=>o.target_command===t),s;if(e.extensionName)s=n.find(o=>o.name===e.extensionName);else if(n.length===1)s=n[0];else if(n.length>1){let o=c(n.map(i=>i.name));throw new Error(`Expected flags for target command "${t}" matched multiple extensions: ${m(o)}. Specify extensionName to choose one registration.`)}if(!s){let o=c(r.flags.map(a=>a.target_command)),i=c(n.map(a=>a.name));throw new Error(`Expected flags for target command "${t}"${u(e.extensionName)} to be registered. Available flag target commands: ${m(o)}; matching extensions: ${m(i)}`)}if(e.flags!==void 0){let o=xe(s.flags),i=e.flags.filter(a=>!o.has(a));if(i.length>0)throw new Error(`Expected flags for target command "${t}" to include ${m(e.flags)}; missing ${m(i)}; available ${m([...o].sort((a,d)=>a.localeCompare(d)))}`)}return s}function pr(r,e){let t=Ye[e.kind],n=r[t]??[],s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(n.map(i=>i.name));throw new Error(`Expected a "${e.kind}" hook${u(e.extensionName)} to be registered. Available "${e.kind}" hooks: ${m(o)}`)}return s}function ur(r,e){let t=l(g(e,e.provider));if(t.length===0)throw new Error("Expected search provider name must be a non-empty string");let n=r.search_providers.filter(o=>l(o.definition.name)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.search_providers.map(i=>i.definition.name));throw new Error(`Expected search provider "${t}"${u(e.extensionName)} to be registered. Available search providers: ${m(o)}`)}return s}function gr(r,e){let t=l(g(e,e.adapter));if(t.length===0)throw new Error("Expected vector store adapter name must be a non-empty string");let n=r.vector_store_adapters.filter(o=>l(o.definition.name)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.vector_store_adapters.map(i=>i.definition.name));throw new Error(`Expected vector store adapter "${t}"${u(e.extensionName)} to be registered. Available vector store adapters: ${m(o)}`)}return s}function Ee(r,e){let t=l(g(e,e.importer));if(t.length===0)throw new Error("Expected importer name must be a non-empty string");let n=r.importers.filter(o=>l(o.importer)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.importers.map(i=>i.importer));throw new Error(`Expected importer "${t}"${u(e.extensionName)} to be registered. Available importers: ${m(o)}`)}return s}function _e(r,e){let t=l(g(e,e.exporter));if(t.length===0)throw new Error("Expected exporter name must be a non-empty string");let n=r.exporters.filter(o=>l(o.exporter)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.exporters.map(i=>i.exporter));throw new Error(`Expected exporter "${t}"${u(e.extensionName)} to be registered. Available exporters: ${m(o)}`)}return s}function hr(r,e){let t=l(g(e,e.field));if(t.length===0)throw new Error("Expected item field name must be a non-empty string");let s=r.item_fields.filter(o=>e.extensionName===void 0||o.name===e.extensionName).map(o=>({registration:o,field:o.fields.find(i=>l(i.name)===t)})).filter(o=>o.field!==void 0).find(o=>e.type===void 0||o.field.type===e.type);if(!s){let o=c(r.item_fields.flatMap(i=>i.fields.map(a=>`${a.name}:${a.type}`)));throw new Error(`Expected item field "${t}"${u(e.extensionName)} to be registered. Available item fields: ${m(o)}`)}return s}function vr(r,e){let t=l(g(e,e.itemType));if(t.length===0)throw new Error("Expected item type name must be a non-empty string");let s=r.item_types.filter(o=>e.extensionName===void 0||o.name===e.extensionName).map(o=>({registration:o,itemType:o.types.find(i=>l(i.name)===t)})).filter(o=>o.itemType!==void 0).find(o=>e.folder===void 0||o.itemType.folder===e.folder);if(!s){let o=c(r.item_types.flatMap(i=>i.types.map(a=>`${a.name}:${a.folder}`)));throw new Error(`Expected item type "${t}"${u(e.extensionName)} to be registered. Available item types: ${m(o)}`)}return s}function yr(r,e){let t=ve(g(e,e.profile));if(t.length===0)throw new Error("Expected profile name must be a non-empty string");let n=r.profiles.filter(s=>e.extensionName===void 0||s.name===e.extensionName).find(s=>ve(s.profile.name)===t);if(!n){let s=c(r.profiles.map(o=>o.profile.name));throw new Error(`Expected profile "${t}"${u(e.extensionName)} to be registered. Available profiles: ${m(s)}`)}return{registration:n,profile:n.profile}}function xr(r,e){let t=y(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.overrides.filter(o=>o.command===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.overrides.map(i=>i.command));throw new Error(`Expected command override "${t}"${u(e.extensionName)} to be registered. Available command overrides: ${m(o)}`)}return s}function br(r,e){let t=y(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.overrides.filter(o=>o.command===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.overrides.map(i=>i.command));throw new Error(`Expected parser override "${t}"${u(e.extensionName)} to be registered. Available parser overrides: ${m(o)}`)}return s}function wr(r,e={}){let t=e.extensionName?r.overrides.find(n=>n.name===e.extensionName):r.overrides[0];if(!t){let n=c(r.overrides.map(s=>s.name));throw new Error(`Expected a preflight override${u(e.extensionName)} to be registered. Available preflight overrides: ${m(n)}`)}return t}function Er(r,e){let t=l(g(e,e.format));if(t.length===0)throw new Error("Expected renderer format must be a non-empty string");let n=r.overrides.filter(o=>o.format===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.overrides.map(i=>i.format));throw new Error(`Expected renderer override "${t}"${u(e.extensionName)} to be registered. Available renderer overrides: ${m(o)}`)}return s}function _r(r,e){let t=l(g(e,e.service));if(t.length===0)throw new Error("Expected service name must be a non-empty string");let n=r.overrides.filter(o=>l(o.service)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.overrides.map(i=>i.service));throw new Error(`Expected service override "${t}"${u(e.extensionName)} to be registered. Available service overrides: ${m(o)}`)}return s}function $e(r,e){let t=l(g(e,e.migration));if(t.length===0)throw new Error("Expected migration id must be a non-empty string");let n=r.migrations.filter(a=>(e.extensionName===void 0||a.name===e.extensionName)&&typeof a.definition.id=="string"&&l(a.definition.id)===t),s=n.find(a=>e.mandatory===void 0||(a.definition.mandatory??!1)===e.mandatory);if(s)return s;let o=n[0];if(o!==void 0)throw new Error(`Expected migration "${t}"${u(e.extensionName)} to have mandatory=${e.mandatory}, but it is mandatory=${o.definition.mandatory??!1}.`);let i=c(r.migrations.map(a=>`${typeof a.definition.id=="string"&&a.definition.id.trim().length>0?a.definition.id.trim():"(unnamed)"}:${a.definition.mandatory===!0}`));throw new Error(`Expected migration "${t}"${u(e.extensionName)} to be registered. Available migrations: ${m(i)}`)}function $r(r,e){let t=(d,f)=>{let w=new Set;for(let M of d){let j=E(M);if(j===null)throw new Error(`Expected ${f} capability "${M}" to be a known extension capability. Use canonical capability names (see manifest.capabilities).`);w.add(j)}return w},n=[...t(e.declared,"declared")].sort((d,f)=>d.localeCompare(f)),s=t(e.allowUnused??[],"allowUnused"),o=oe(r,{extensionName:e.extensionName}),i=new Set(o),a=n.filter(d=>!i.has(d)&&!s.has(d));if(a.length>0){let d=u(e.extensionName);throw new Error(`Expected every declared capability${d} to be exercised, but [${a.join(", ")}] ${a.length===1?"is":"are"} declared yet never registered against. Remove ${a.length===1?"it":"them"} from manifest.capabilities for least privilege, or pass allowUnused for capabilities registered only behind a runtime flag.`)}return{declared:n,used:o,unused:a}}function Xr(r,e={}){let t=k(r,e);if(!t.ok){let n=t.findings.filter(s=>s.severity==="error");throw new Error(`Extension blueprint failed preflight with ${n.length} ${n.length===1?"error":"errors"}:
1
+ import{f as me,ka as le}from"./chunk-UN66FZRO.js";import{j as fe}from"./chunk-R546TPDE.js";import{a as R,i as ce}from"./chunk-EGJ4JTUG.js";import{e as se,f as ae,g as de}from"./chunk-A62CYISG.js";import{Dc as ie,Eb as U,Fb as V,Gb as z,Hb as W,Ib as G,Jb as Y,Kb as X,L as x,Lb as J,M as B,Mb as Q,Nb as Z,Ob as ee,Pb as re,Wb as te,Xb as ne,bc as oe,db as D,eb as H,fb as L,gb as K,nb as E,o as C,ob as q,rb as h}from"./chunk-GE4KCSZP.js";(function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="60463c2e-f904-5199-87b0-8a17f0e2ee0f")}catch{}})();function Ar(r){return r}function Fr(r){return r}function ke(r,e){for(let t of e.commands??[])r.registerCommand(t);for(let[t,n]of Object.entries(e.commandOverrides??{}))r.registerCommand(t,n);for(let[t,n]of Object.entries(e.flags??{}))r.registerFlags(t,n);for(let[t,n]of Object.entries(e.parsers??{}))r.registerParser(t,n);for(let[t,n]of Object.entries(e.renderers??{}))if(typeof n=="function")r.registerRenderer(t,n);else{let{run:s,...o}=n;r.registerRenderer(t,s,o)}for(let[t,n]of Object.entries(e.services??{}))r.registerService(t,n)}function Ce(r,e){for(let o of e.preflights??[])r.registerPreflight(o);let t=e.itemTypes??[];t.length>0&&r.registerItemTypes(t);let n=e.itemFields??[];n.length>0&&r.registerItemFields(n);let s=e.relationshipKinds??[];s.length>0&&r.registerRelationshipKinds(s);for(let o of e.migrations??[])r.registerMigration(o);for(let o of e.profiles??[])r.registerProfile(o)}function Re(r,e){for(let t of e.searchProviders??[])r.registerSearchProvider(t);for(let t of e.vectorStoreAdapters??[])r.registerVectorStoreAdapter(t);for(let t of e.importers??[])r.registerImporter(t.name,t.importer,t.options);for(let t of e.exporters??[])r.registerExporter(t.name,t.exporter,t.options)}function Ne(r,e){for(let t of e.beforeCommand??[])r.hooks.beforeCommand(t);for(let t of e.beforeMutation??[])r.hooks.beforeMutation(t);for(let t of e.afterCommand??[])r.hooks.afterCommand(t);for(let t of e.onWrite??[])r.hooks.onWrite(t);for(let t of e.onRead??[])r.hooks.onRead(t);for(let t of e.onIndex??[])r.hooks.onIndex(t)}function Se(r){let t={activate:async n=>{ke(n,r),Ce(n,r),Re(n,r),Ne(n,r.hooks??{}),await r.activate?.(n)}};return r.manifest&&(t.manifest=r.manifest),r.deactivate&&(t.deactivate=r.deactivate),t}function v(r){let e=r.flatMap(t=>t??[]);return e.length>0?e:void 0}function _(r){let e=Object.assign({},...r.map(t=>t??{}));return Object.keys(e).length>0?e:void 0}function Oe(r){let e={};for(let t of r)for(let[n,s]of Object.entries(t??{}))e[n]=[...e[n]??[],...s];return Object.keys(e).length>0?e:void 0}var Ae=["beforeCommand","beforeMutation","afterCommand","onWrite","onRead","onIndex"];function Fe(r,e,t){let n=e.map(o=>o?.[t]),s=v(n);if(s!==void 0){let o=r;o[t]=s}}function Te(r){let e={};for(let t of Ae)Fe(e,r,t);return Object.keys(e).length>0?e:void 0}function Tr(...r){let e={},t=(i,a)=>{a!==void 0&&(e[i]=a)};t("commands",v(r.map(i=>i.commands))),t("commandOverrides",_(r.map(i=>i.commandOverrides))),t("flags",Oe(r.map(i=>i.flags))),t("parsers",_(r.map(i=>i.parsers))),t("renderers",_(r.map(i=>i.renderers))),t("services",_(r.map(i=>i.services))),t("preflights",v(r.map(i=>i.preflights))),t("itemTypes",v(r.map(i=>i.itemTypes))),t("itemFields",v(r.map(i=>i.itemFields))),t("relationshipKinds",v(r.map(i=>i.relationshipKinds))),t("migrations",v(r.map(i=>i.migrations))),t("profiles",v(r.map(i=>i.profiles))),t("searchProviders",v(r.map(i=>i.searchProviders))),t("vectorStoreAdapters",v(r.map(i=>i.vectorStoreAdapters))),t("importers",v(r.map(i=>i.importers))),t("exporters",v(r.map(i=>i.exporters))),t("hooks",Te(r.map(i=>i.hooks)));let n;for(let i of r)i.manifest&&(n=i.manifest);t("manifest",n);let s=r.some(i=>i.activate);t("activate",s?async i=>{for(let a of r)a.activate&&await a.activate(i)}:void 0);let o=r.some(i=>i.deactivate);return t("deactivate",o?async()=>{let i=[];for(let a of[...r].reverse())if(a.deactivate)try{await a.deactivate()}catch(d){i.push(d)}if(i.length>0)throw i.length>1?new AggregateError(i,"Multiple extension blueprint deactivate hooks failed."):i[0]}:void 0),e}var Pe=[["commands","commands"],["commandOverrides","commands"],["flags","schema"],["itemTypes","schema"],["itemFields","schema"],["relationshipKinds","schema"],["migrations","schema"],["profiles","schema"],["parsers","parser"],["renderers","renderers"],["services","services"],["preflights","preflight"],["searchProviders","search"],["vectorStoreAdapters","search"],["importers","importers"],["exporters","importers"]];function $(r){return r?Array.isArray(r)?r.length>0:Object.keys(r).length>0:!1}function N(r){let e=new Set;for(let[s,o]of Pe)$(r[s])&&e.add(o);(r.commands??[]).filter(b).some(s=>s.flags!==void 0)&&e.add("schema");let t=[...r.importers??[],...r.exporters??[]].filter(b);t.some(s=>s?.options?.flags!==void 0)&&e.add("schema"),t.some(s=>typeof s=="object")&&e.add("commands");let n=r.hooks??{};return[n.beforeCommand,n.beforeMutation,n.afterCommand,n.onWrite,n.onRead,n.onIndex].some($)&&e.add("hooks"),[...e].sort((s,o)=>s.localeCompare(o))}var Ie=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function p(r){return[...new Set(r)].sort((e,t)=>e.localeCompare(t))}function b(r){return r!=null}function S(r){return h(`${r.name} import`)}function O(r){return h(`${r.name} export`)}function Me(r,e,t){return[...r.map(n=>h(n.name)),...e.filter(n=>n.options!==void 0).map(S),...t.filter(n=>n.options!==void 0).map(O)]}function je(r,e,t,n){return[...Object.keys(r.flags??{}).map(s=>h(s)),...e.filter(s=>s.flags!==void 0).map(s=>h(s.name)),...t.filter(s=>s.options?.flags!==void 0).map(S),...n.filter(s=>s.options?.flags!==void 0).map(O)]}function Be(r){return Ie.filter(([e])=>(r[e]?.length??0)>0).map(([,e])=>e)}function De(r){let e=Object.entries(r??{}).filter(([,t])=>typeof t!="function"&&((t.commands?.length??0)>0||t.resultDiscriminator!==void 0)).map(([t,n])=>{let s=n;return{format:t,commands:p((s.commands??[]).map(o=>h(o))),result_discriminator:s.resultDiscriminator!==void 0}}).sort((t,n)=>t.format.localeCompare(n.format));return e.length>0?{renderer_ownership:e}:{}}function He(r,e,t){return{item_types:p((r.itemTypes??[]).map(n=>n.name)),item_fields:p((r.itemFields??[]).map(n=>n.name)),...(r.relationshipKinds?.length??0)>0?{relationship_kinds:p(r.relationshipKinds.map(n=>n.kind))}:{},migrations:p((r.migrations??[]).flatMap(n=>typeof n.id=="string"?[n.id]:[])),profiles:p((r.profiles??[]).map(n=>n.name)),importers:p(e.map(n=>h(n.name))),exporters:p(t.map(n=>h(n.name))),search_providers:p((r.searchProviders??[]).map(n=>n.name)),vector_store_adapters:p((r.vectorStoreAdapters??[]).map(n=>n.name)),parser_overrides:p(Object.keys(r.parsers??{}).map(n=>h(n))),service_overrides:p(Object.keys(r.services??{}).map(n=>String(n).trim().toLowerCase())),renderer_overrides:p(Object.keys(r.renderers??{}).map(n=>String(n).trim().toLowerCase())),...De(r.renderers),preflight_overrides:(r.preflights??[]).length}}function Le(r){let e=(r.commands??[]).filter(b),t=(r.importers??[]).filter(b),n=(r.exporters??[]).filter(b),s=t.map(S),o=n.map(O),i=Me(e,t,n),a=je(r,e,t,n),d=r.hooks??{},f=He(r,t,n);return{capabilities:N(r),commands:p(i),command_overrides:p(Object.keys(r.commandOverrides??{}).map(w=>h(w))),command_handlers:p([...i,...s,...o]),hooks:Be(d),flag_commands:p(a),...f}}var Ke=["commands","commandOverrides","flags","parsers","renderers","services","preflights","itemTypes","itemFields","relationshipKinds","migrations","profiles","searchProviders","vectorStoreAdapters","importers","exporters"];function qe(r){return(r.itemFields??[]).filter(e=>typeof e?.name=="string"&&ie.has(e.name.trim())).map(e=>({code:"reserved_item_field",severity:"error",message:`Item field "${e.name}" collides with reserved item metadata; rename it with an extension-specific prefix before publishing.`,field:e.name}))}function Ue(r){return[...Object.values(r.flags??{}).flat(),...(r.commands??[]).flatMap(t=>t.flags??[]),...(r.importers??[]).flatMap(t=>t.options?.flags??[]),...(r.exporters??[]).flatMap(t=>t.options?.flags??[])].flatMap(t=>{if(typeof t?.long!="string"&&typeof t?.short!="string")return[];let n=D(t.long,t.short);if(n===null)return[];let{token:s,failure:o}=n;return[{code:o,severity:"error",message:`Flag "${s}" ${H(s,o)}.`,field:s}]})}function ue(r){let e=new Set;for(let t of r){let n=q(t)??E(t);n!==null&&e.add(n)}return[...e].sort((t,n)=>t.localeCompare(n))}function Ve(r,e){let t=[];if(e===null)return r.length>0&&t.push({code:"manifest_capabilities_absent",severity:"warning",message:`Blueprint exercises ${r.length===1?"capability":"capabilities"} [${r.join(", ")}] but declares none; set capabilities to deriveExtensionCapabilities(blueprint) so the manifest grant matches.`}),t;let n=new Set(e),s=new Set(r);for(let o of r)n.has(o)||t.push({code:"capability_undeclared",severity:"error",message:`Blueprint exercises capability "${o}" but it is absent from the declared capabilities; activation throws extension_capability_missing \u2014 add "${o}" to the manifest capabilities.`,capability:o});for(let o of e)s.has(o)||t.push({code:"capability_unused",severity:"warning",message:`Capability "${o}" is declared but no blueprint surface exercises it; drop it to keep the manifest least-privilege (pm package doctor reports this as extension_capability_unused).`,capability:o});return t}function ze(r){let e=[],t=new Map;for(let s of r.commands??[]){let o=h(s.name);t.set(o,(t.get(o)??0)+1)}for(let[s,o]of t)o>1&&e.push({code:"duplicate_command",severity:"warning",message:`Command "${s}" is declared ${o} times in commands; the later registration shadows the earlier one at dispatch.`,command:s});let n=new Set(Object.keys(r.commandOverrides??{}).map(s=>h(s)));for(let s of t.keys())n.has(s)&&e.push({code:"command_override_conflict",severity:"warning",message:`Command "${s}" is declared both as a new command definition and as a command override; register one or the other.`,command:s});return e}function We(r){let e=[];for(let t of Ke)t in r&&!$(r[t])&&e.push({code:"empty_surface",severity:"warning",message:`Blueprint field "${t}" is present but empty; remove it or populate it.`,field:t});if("hooks"in r){let t=r.hooks??{};[t.beforeCommand,t.beforeMutation,t.afterCommand,t.onWrite,t.onRead,t.onIndex].some($)||e.push({code:"empty_surface",severity:"warning",message:'Blueprint field "hooks" is present but registers no lifecycle hooks; remove it or populate it.',field:"hooks"})}return e}function k(r,e={}){let t=N(r),n=e.declaredCapabilities??r.manifest?.capabilities,s=Array.isArray(n)?ue(n):null,o=[...Ve(t,s),...ze(r),...Ue(r),...qe(r),...We(r)];return{ok:o.every(i=>i.severity!=="error"),findings:o,used:t,declared:s}}function ge(r,e){let{additionalCapabilities:t,...n}=e,s=Array.isArray(t)?ue(t):[],o=[...new Set([...N(r),...s])].sort((i,a)=>i.localeCompare(a));return{...n,capabilities:o}}function Pr(r,e){let t=ge(r,e);return{module:Se({...r,manifest:t}),manifest:t}}function pe(r,e){if(r.status==="absent"||r.status==="ok")return null;let t=`${r.kind}_${r.status}`,n;switch(t){case"pm_min_version_invalid":n=`pm_min_version "${r.required}" is not a valid version; the extension is treated as incompatible and the loader skips it.`;break;case"pm_min_version_unchecked":n=`pm_min_version "${r.required}" could not be compared against pm ${e}; compatibility is unverified.`;break;case"pm_min_version_unmet":n=`Requires pm >= ${r.required} but the target is pm ${e}; the loader skips the extension.`;break;case"pm_max_version_invalid":n=`pm_max_version "${r.required}" is not a valid inclusive upper bound (version ranges are not allowed); the extension is treated as incompatible and the loader skips it.`;break;case"pm_max_version_unchecked":n=`pm_max_version "${r.required}" could not be compared against pm ${e}; compatibility is unverified.`;break;case"pm_max_version_exceeded":n=`Allows pm <= ${r.required} but the target is pm ${e}; the loader skips the extension.`;break;case"pm_max_version_exceeded_warn":n=`Target pm ${e} is newer than pm_max_version ${r.required}, but the "warn" exceeded mode lets it load with a warning.`;break}return{code:t,severity:r.allowed?"warning":"error",constraint:r.kind,required:r.required,current:e,message:n}}function A(r,e){let t=L(r.pm_min_version,e.pmVersion),n=K(r.pm_max_version,e.pmVersion,e.pmMaxVersionExceededMode??"block"),s=[],o=pe(t,e.pmVersion);o!==null&&s.push(o);let i=pe(n,e.pmVersion);return i!==null&&s.push(i),{compatible:t.allowed&&n.allowed,findings:s,pmVersion:e.pmVersion}}var Ge=new Set(["capability_undeclared","capability_unused","manifest_capabilities_absent"]);function he(r,e={}){let t=k(r,{declaredCapabilities:e.declaredCapabilities}),n=e.identity?ge(r,e.identity):null,s=e.target?A(n??r.manifest??{},e.target):null,a=[...(n!==null&&e.declaredCapabilities===void 0?t.findings.filter(d=>!Ge.has(d.code)):t.findings).map(d=>({source:"blueprint",severity:d.severity,code:d.code,message:d.message})),...(s?.findings??[]).map(d=>({source:"compatibility",severity:d.severity,code:d.code,message:d.message}))];return{ok:a.every(d=>d.severity!=="error"),capabilities:t.used,blueprint:t,manifest:n,compatibility:s,findings:a}}(function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="a09f5e0d-fccc-5a22-a6f3-0a37cbeea3b0")}catch{}})();function g(r,e){return r.name??e??""}var Ye={before_command:"beforeCommand",before_mutation:"beforeMutation",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"},F={before_command:"beforeCommand",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};function l(r){return r.trim().toLowerCase()}function ve(r){return l(r).replaceAll("-","_")}function u(r){return r?` from extension "${r}"`:""}function c(r){return[...new Set(r)].sort((e,t)=>e.localeCompare(t))}function y(r){if(typeof r!="string")throw new Error('A command name string is required. Pass it via the options object, e.g. runRegisteredCommandForTest(activation, { command: "my command" }) \u2014 positional command arguments are not supported.');return r.trim().toLowerCase().split(/\s+/).filter(e=>e.length>0).join(" ")}function m(r){return r.length>0?r.join(", "):"(none)"}function ye(r,e,t){let n=new Set(r??[]),s=c(e.filter(o=>!n.has(o)));if(s.length>0)throw new Error(`Expected package manifest ${t} to include ${s.join(", ")}; available: ${m(c(r??[]))}`)}function xe(r){let e=new Set;for(let t of r)typeof t.long=="string"&&t.long.trim().length>0&&e.add(t.long.trim()),typeof t.short=="string"&&t.short.trim().length>0&&e.add(t.short.trim());return e}function T(r){let e=x(r);if(!e)return{};let t=x(e.manifest);if(t)return t;let n=x(e.default),s=x(n?.manifest);return s||(n&&typeof e.default!="function"&&("name"in n||"capabilities"in n)?n:typeof r!="function"&&("name"in e||"capabilities"in e)?e:{})}function P(r,e){return e??(typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():"test-extension")}function be(r,e){return Array.isArray(e.capabilities)?[...e.capabilities]:Array.isArray(r.capabilities)?r.capabilities.filter(t=>typeof t=="string"):[]}function we(r,e,t){return{disabled_by_flag:!1,roots:{global:"",project:""},configured_enabled:[],configured_disabled:[],discovered:[],effective:[],warnings:[],policy:t.policy,failed:[],loaded:[{layer:t.layer,directory:"",manifest_path:"",name:t.name,version:typeof e.version=="string"?e.version:"0.0.0",entry:typeof e.entry=="string"?e.entry:"./index.js",priority:typeof e.priority=="number"?e.priority:0,entry_path:"",capabilities:t.capabilities,manifest_version:typeof e.manifest_version=="number"?e.manifest_version:void 0,pm_min_version:typeof e.pm_min_version=="string"?e.pm_min_version:void 0,pm_max_version:typeof e.pm_max_version=="string"?e.pm_max_version:void 0,engines:e.engines,trusted:e.trusted,provenance:e.provenance,sandbox_profile:e.sandbox_profile,permissions:e.permissions,activation:e.activation,module:r}]}}async function Xe(r,e={}){let t=T(r);return ne(we(r,t,{name:P(t,e.name),layer:e.layer??"project",capabilities:be(t,e),policy:e.policy??C()}))}async function Je(r,e={}){let t=T(r);return te(we(r,t,{name:P(t,e.name),layer:e.layer??"project",capabilities:be(t,{}),policy:C()}),e.activation,e.deactivateTimeoutMs===void 0?{}:{deactivate_timeout_ms:e.deactivateTimeoutMs})}async function I(r,e){let t=y(e.command);if(t.length===0)throw new Error("Expected command name must be a non-empty string");if(!r.handlers.some(a=>a.command===t)){let a=c(r.handlers.map(d=>d.command));throw new Error(`Expected a registered command handler for "${t}" to invoke. Available command handlers: ${m(a)}`)}if(e.sdk!==void 0&&e.sdkFactory!==void 0)throw new TypeError("runRegisteredCommandForTest accepts sdk or sdkFactory, not both");let s=e.pmRoot??"",o={json:!0,quiet:!0,noPager:!0,...e.global},i=e.sdk??e.sdkFactory?.({pmRoot:s,global:o})??(s.length>0?me(s,new le({pmRoot:s})):void 0);return X(r,{command:t,args:e.args?[...e.args]:[],options:e.options?{...e.options}:{},global:o,pm_root:s,...i===void 0?{}:{sdk:i}})}async function Qe(r,e){if((r.beforeMutation?.length??0)===0)throw new Error("Expected a registered before_mutation hook to invoke");await V(r,e.context)}async function Ze(r,e){let t=e.kind;if(t==="before_mutation")throw new Error("Invoke before_mutation hooks with runRegisteredMutationGuardForTest so denials and failures retain fail-closed semantics.");if((r[F[t]]?.length??0)===0){let n=c(Object.keys(F).filter(s=>(r[F[s]]?.length??0)>0));throw new Error(`Expected a registered "${t}" hook to invoke. Hook kinds with registrations: ${m(n)}`)}switch(e.kind){case"before_command":return U(r,e.context);case"after_command":return z(r,e.context);case"on_read":return G(r,e.context);case"on_write":return W(r,e.context);case"on_index":return Y(r,e.context)}}async function er(r,e){let t=y(e.command);if(!r.overrides.some(n=>n.command===t))throw new Error(`Expected a registered parser override for command "${t}" to invoke. Available parser override commands: ${m(c(r.overrides.map(n=>n.command)))}`);return J(r,e)}async function rr(r,e){if(r.overrides.length===0)throw new Error("Expected a registered preflight override to invoke, but none are registered.");return Q(r,e)}async function tr(r,e){let t=y(e.command);if(!r.overrides.some(n=>n.command===t))throw new Error(`Expected a registered command override for command "${t}" to invoke. Available command override commands: ${m(c(r.overrides.map(n=>n.command)))}`);return ee(r,e)}async function nr(r,e){if(!r.overrides.some(t=>t.format===e.format))throw new Error(`Expected a registered renderer override for format "${e.format}" to invoke. Available renderer override formats: ${m(c(r.overrides.map(t=>t.format)))}`);return re(r,e)}async function or(r,e){if(!r.overrides.some(t=>t.service===e.service))throw new Error(`Expected a registered service override for service "${e.service}" to invoke. Available service override services: ${m(c(r.overrides.map(t=>t.service)))}`);return Z(r,e)}var ir={query:["query"],embed:["embed"],embedBatch:["embedBatch","embed_batch"],queryExpansion:["queryExpansion","query_expansion"],rerank:["rerank"]};async function sr(r,e){let t=se(r,e.provider);if(!t){let o=c(r.search_providers.map(i=>i.definition.name));throw new Error(`Expected a registered search provider "${e.provider}" to invoke. Available search providers: ${m(o)}`)}let n=t.runtime_definition,s=ir[e.operation].map(o=>n[o]).find(o=>typeof o=="function");if(typeof s!="function")throw new Error(`Registered search provider "${e.provider}" does not implement the "${e.operation}" operation.`);return await s(e.context)}async function ar(r,e){let t=ae(r,e.adapter);if(!t){let s=c(r.vector_store_adapters.map(o=>o.definition.name));throw new Error(`Expected a registered vector store adapter "${e.adapter}" to invoke. Available vector store adapters: ${m(s)}`)}let n=t.runtime_definition[e.operation];if(typeof n!="function")throw new Error(`Registered vector store adapter "${e.adapter}" does not implement the "${e.operation}" operation.`);return await n(e.context)}async function dr(r,e){let t=$e(r,{migration:e.migration,extensionName:e.extensionName}),n=de(t).run;if(typeof n!="function")throw new Error(`Registered migration "${e.migration}" does not implement a run function to invoke.`);let s=t.definition.status,o={id:t.definition.id,command:"migration",layer:t.layer,extension:t.name,pm_root:e.pmRoot??"",status:(typeof s=="string"?s.trim().toLowerCase():"")||"pending"};return await n(o)}async function mr(r,e){let t=Ee(r.registrations,{importer:e.importer,extensionName:e.extensionName});return I(r.commands,{command:`${t.importer} import`,args:e.args,options:e.options,global:e.global,pmRoot:e.pmRoot})}async function cr(r,e){let t=_e(r.registrations,{exporter:e.exporter,extensionName:e.extensionName});return I(r.commands,{command:`${t.exporter} export`,args:e.args,options:e.options,global:e.global,pmRoot:e.pmRoot})}function Gr(r,e={}){let t=e.deactivated??1;if(r.deactivated!==t)throw new Error(`Expected ${t} extension${t===1?"":"s"} to deactivate cleanly, but ${r.deactivated} did.`);let n=e.failed??0;if(r.failed.length!==n){let s=r.failed.map(o=>`${o.layer}:${o.name} (${o.error})`).join(", ");throw new Error(`Expected ${n} teardown failure${n===1?"":"s"}, but observed ${r.failed.length}${s.length>0?`: ${s}`:""}.`)}return r}function Yr(r,e){if(e.packageName!==void 0&&r.package_name!==e.packageName)throw new Error(`Expected package manifest package_name to be "${e.packageName}"; received "${r.package_name??"(none)"}"`);if(e.aliases!==void 0&&ye(r.aliases,e.aliases,"aliases"),e.resources!==void 0)for(let[t,n]of Object.entries(e.resources))ye(r.resources[t],n,`pm.${t}`);return r}function fr(r,e){let t=y(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.commands.filter(i=>i.command===t),s=e.extensionName?n.find(i=>i.name===e.extensionName):n[0];if(!s){let i=r.commands.map(d=>d.command).sort((d,f)=>d.localeCompare(f)),a=e.extensionName?` from extension "${e.extensionName}"`:"";throw new Error(`Expected extension command "${t}"${a} to be registered. Available commands: ${m(i)}`)}if(e.action!==void 0&&s.action!==e.action)throw new Error(`Expected extension command "${t}" action "${e.action}", received "${s.action}"`);if(e.arguments!==void 0){let i=(s.arguments??[]).map(d=>d.name),a=e.arguments.filter(d=>!i.includes(d));if(a.length>0)throw new Error(`Expected extension command "${t}" arguments ${m(e.arguments)}; missing ${m(a)}; available ${m(i)}`)}let o=r.flags.filter(i=>i.target_command===t&&(e.extensionName===void 0||i.name===e.extensionName)).flatMap(i=>i.flags);if(e.flags!==void 0){let i=xe(o),a=e.flags.filter(d=>!i.has(d));if(a.length>0)throw new Error(`Expected extension command "${t}" flags ${m(e.flags)}; missing ${m(a)}; available ${m([...i].sort((d,f)=>d.localeCompare(f)))}`)}return{command:s,flags:o}}function lr(r,e){let t=y(g(e,e.targetCommand));if(t.length===0)throw new Error("Expected target command name must be a non-empty string");let n=r.flags.filter(o=>o.target_command===t),s;if(e.extensionName)s=n.find(o=>o.name===e.extensionName);else if(n.length===1)s=n[0];else if(n.length>1){let o=c(n.map(i=>i.name));throw new Error(`Expected flags for target command "${t}" matched multiple extensions: ${m(o)}. Specify extensionName to choose one registration.`)}if(!s){let o=c(r.flags.map(a=>a.target_command)),i=c(n.map(a=>a.name));throw new Error(`Expected flags for target command "${t}"${u(e.extensionName)} to be registered. Available flag target commands: ${m(o)}; matching extensions: ${m(i)}`)}if(e.flags!==void 0){let o=xe(s.flags),i=e.flags.filter(a=>!o.has(a));if(i.length>0)throw new Error(`Expected flags for target command "${t}" to include ${m(e.flags)}; missing ${m(i)}; available ${m([...o].sort((a,d)=>a.localeCompare(d)))}`)}return s}function pr(r,e){let t=Ye[e.kind],n=r[t]??[],s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(n.map(i=>i.name));throw new Error(`Expected a "${e.kind}" hook${u(e.extensionName)} to be registered. Available "${e.kind}" hooks: ${m(o)}`)}return s}function ur(r,e){let t=l(g(e,e.provider));if(t.length===0)throw new Error("Expected search provider name must be a non-empty string");let n=r.search_providers.filter(o=>l(o.definition.name)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.search_providers.map(i=>i.definition.name));throw new Error(`Expected search provider "${t}"${u(e.extensionName)} to be registered. Available search providers: ${m(o)}`)}return s}function gr(r,e){let t=l(g(e,e.adapter));if(t.length===0)throw new Error("Expected vector store adapter name must be a non-empty string");let n=r.vector_store_adapters.filter(o=>l(o.definition.name)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.vector_store_adapters.map(i=>i.definition.name));throw new Error(`Expected vector store adapter "${t}"${u(e.extensionName)} to be registered. Available vector store adapters: ${m(o)}`)}return s}function Ee(r,e){let t=l(g(e,e.importer));if(t.length===0)throw new Error("Expected importer name must be a non-empty string");let n=r.importers.filter(o=>l(o.importer)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.importers.map(i=>i.importer));throw new Error(`Expected importer "${t}"${u(e.extensionName)} to be registered. Available importers: ${m(o)}`)}return s}function _e(r,e){let t=l(g(e,e.exporter));if(t.length===0)throw new Error("Expected exporter name must be a non-empty string");let n=r.exporters.filter(o=>l(o.exporter)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.exporters.map(i=>i.exporter));throw new Error(`Expected exporter "${t}"${u(e.extensionName)} to be registered. Available exporters: ${m(o)}`)}return s}function hr(r,e){let t=l(g(e,e.field));if(t.length===0)throw new Error("Expected item field name must be a non-empty string");let s=r.item_fields.filter(o=>e.extensionName===void 0||o.name===e.extensionName).map(o=>({registration:o,field:o.fields.find(i=>l(i.name)===t)})).filter(o=>o.field!==void 0).find(o=>e.type===void 0||o.field.type===e.type);if(!s){let o=c(r.item_fields.flatMap(i=>i.fields.map(a=>`${a.name}:${a.type}`)));throw new Error(`Expected item field "${t}"${u(e.extensionName)} to be registered. Available item fields: ${m(o)}`)}return s}function vr(r,e){let t=l(g(e,e.itemType));if(t.length===0)throw new Error("Expected item type name must be a non-empty string");let s=r.item_types.filter(o=>e.extensionName===void 0||o.name===e.extensionName).map(o=>({registration:o,itemType:o.types.find(i=>l(i.name)===t)})).filter(o=>o.itemType!==void 0).find(o=>e.folder===void 0||o.itemType.folder===e.folder);if(!s){let o=c(r.item_types.flatMap(i=>i.types.map(a=>`${a.name}:${a.folder}`)));throw new Error(`Expected item type "${t}"${u(e.extensionName)} to be registered. Available item types: ${m(o)}`)}return s}function yr(r,e){let t=ve(g(e,e.profile));if(t.length===0)throw new Error("Expected profile name must be a non-empty string");let n=r.profiles.filter(s=>e.extensionName===void 0||s.name===e.extensionName).find(s=>ve(s.profile.name)===t);if(!n){let s=c(r.profiles.map(o=>o.profile.name));throw new Error(`Expected profile "${t}"${u(e.extensionName)} to be registered. Available profiles: ${m(s)}`)}return{registration:n,profile:n.profile}}function xr(r,e){let t=y(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.overrides.filter(o=>o.command===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.overrides.map(i=>i.command));throw new Error(`Expected command override "${t}"${u(e.extensionName)} to be registered. Available command overrides: ${m(o)}`)}return s}function br(r,e){let t=y(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.overrides.filter(o=>o.command===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.overrides.map(i=>i.command));throw new Error(`Expected parser override "${t}"${u(e.extensionName)} to be registered. Available parser overrides: ${m(o)}`)}return s}function wr(r,e={}){let t=e.extensionName?r.overrides.find(n=>n.name===e.extensionName):r.overrides[0];if(!t){let n=c(r.overrides.map(s=>s.name));throw new Error(`Expected a preflight override${u(e.extensionName)} to be registered. Available preflight overrides: ${m(n)}`)}return t}function Er(r,e){let t=l(g(e,e.format));if(t.length===0)throw new Error("Expected renderer format must be a non-empty string");let n=r.overrides.filter(o=>o.format===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.overrides.map(i=>i.format));throw new Error(`Expected renderer override "${t}"${u(e.extensionName)} to be registered. Available renderer overrides: ${m(o)}`)}return s}function _r(r,e){let t=l(g(e,e.service));if(t.length===0)throw new Error("Expected service name must be a non-empty string");let n=r.overrides.filter(o=>l(o.service)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=c(r.overrides.map(i=>i.service));throw new Error(`Expected service override "${t}"${u(e.extensionName)} to be registered. Available service overrides: ${m(o)}`)}return s}function $e(r,e){let t=l(g(e,e.migration));if(t.length===0)throw new Error("Expected migration id must be a non-empty string");let n=r.migrations.filter(a=>(e.extensionName===void 0||a.name===e.extensionName)&&typeof a.definition.id=="string"&&l(a.definition.id)===t),s=n.find(a=>e.mandatory===void 0||(a.definition.mandatory??!1)===e.mandatory);if(s)return s;let o=n[0];if(o!==void 0)throw new Error(`Expected migration "${t}"${u(e.extensionName)} to have mandatory=${e.mandatory}, but it is mandatory=${o.definition.mandatory??!1}.`);let i=c(r.migrations.map(a=>`${typeof a.definition.id=="string"&&a.definition.id.trim().length>0?a.definition.id.trim():"(unnamed)"}:${a.definition.mandatory===!0}`));throw new Error(`Expected migration "${t}"${u(e.extensionName)} to be registered. Available migrations: ${m(i)}`)}function $r(r,e){let t=(d,f)=>{let w=new Set;for(let M of d){let j=E(M);if(j===null)throw new Error(`Expected ${f} capability "${M}" to be a known extension capability. Use canonical capability names (see manifest.capabilities).`);w.add(j)}return w},n=[...t(e.declared,"declared")].sort((d,f)=>d.localeCompare(f)),s=t(e.allowUnused??[],"allowUnused"),o=oe(r,{extensionName:e.extensionName}),i=new Set(o),a=n.filter(d=>!i.has(d)&&!s.has(d));if(a.length>0){let d=u(e.extensionName);throw new Error(`Expected every declared capability${d} to be exercised, but [${a.join(", ")}] ${a.length===1?"is":"are"} declared yet never registered against. Remove ${a.length===1?"it":"them"} from manifest.capabilities for least privilege, or pass allowUnused for capabilities registered only behind a runtime flag.`)}return{declared:n,used:o,unused:a}}function Xr(r,e={}){let t=k(r,e);if(!t.ok){let n=t.findings.filter(s=>s.severity==="error");throw new Error(`Extension blueprint failed preflight with ${n.length} ${n.length===1?"error":"errors"}:
2
2
  `+n.map(s=>` - [${s.code}] ${s.message}`).join(`
3
3
  `))}return t}function Jr(r,e={}){let t=fe(r),n=t.findings.filter(s=>s.severity==="error"||e.strict===!0&&s.severity==="warning");if(n.length>0)throw new Error(`Project profile "${t.profile}" failed lint with ${n.length} ${n.length===1?"issue":"issues"}:
4
4
  `+n.map(s=>` - ${s.severity} [${s.code}] ${s.message}`).join(`
5
5
  `));return t}function Qr(r,e){let t=Array.isArray(r.capabilities)?r.capabilities:[],n=k(e,{declaredCapabilities:t}),s=n.declared,o=new Set(s),i=new Set(n.used),a=n.used.filter(f=>!o.has(f)),d=s.filter(f=>!i.has(f));if(a.length>0||d.length>0){let f=[];throw a.length>0&&f.push(`missing [${a.join(", ")}] (the blueprint registers ${a.length===1?"a surface":"surfaces"} requiring ${a.length===1?"it":"them"}; activation throws extension_capability_missing)`),d.length>0&&f.push(`unused [${d.join(", ")}] (declared but no surface exercises ${d.length===1?"it":"them"}; drop for least privilege)`),new Error(`Manifest capabilities do not match the blueprint: ${f.join("; ")}. Set capabilities to synthesizeExtensionManifest(blueprint, identity).capabilities to stay in sync.`)}return{used:n.used,declared:s,missing:a,unused:d,findings:n.findings}}function Zr(r,e){let t=A(r,e),n=t.findings.filter(s=>s.severity==="error");if(n.length>0)throw new Error(`Extension manifest is not compatible with pm ${t.pmVersion}: ${n.map(s=>s.message).join("; ")}`);return t}function et(r,e={}){let t=he(r,e);if(!t.ok){let n=t.findings.filter(s=>s.severity==="error");throw new Error(`Extension failed preflight with ${n.length} ${n.length===1?"error":"errors"}:
6
6
  `+n.map(s=>` - [${s.source}:${s.code}] ${s.message}`).join(`
7
7
  `))}return t}function kr(r){if(!B(r))throw new Error("createExtensionTestHarness received a module with no activate export. Pass the extension module (with an activate(api) function on the module or its default export) as the first argument, and options second.")}async function rt(r,e={}){kr(r);let t=T(r),n=P(t,e.name),s=e.layer??"project",o=await Xe(r,e);if(o.failed.length>0){let i=o.failed.map(a=>{let d=a.trace?.missing_capability,f=d?`${a.error}; missing capability "${d}"`:a.error;return`${a.layer}:${a.name} (${f})`}).join(", ");throw new Error(`createExtensionTestHarness could not activate the extension cleanly: ${i}. Declare the required capability in the manifest (or pass it via options.capabilities), or use activateExtensionForTest directly to inspect a failed activation.`)}return{module:r,name:n,layer:s,activation:o,activationSummary(i){return R(o,i)},renderMarkdown(i={}){let{extensionName:a,...d}=i??{};return ce(R(o,{extensionName:a}),d)},assertCommandContract(i){return fr(o.registrations,i)},assertFlags(i){return lr(o.registrations,i)},assertItemField(i){return hr(o.registrations,i)},assertItemType(i){return vr(o.registrations,i)},assertProfile(i){return yr(o.registrations,i)},assertHook(i){return pr(o.hooks,i)},assertCommandOverride(i){return xr(o.commands,i)},assertParserOverride(i){return br(o.parsers,i)},assertPreflightOverride(i){return wr(o.preflight,i)},assertRendererOverride(i){return Er(o.renderers,i)},assertServiceOverride(i){return _r(o.services,i)},assertSearchProvider(i){return ur(o.registrations,i)},assertVectorStoreAdapter(i){return gr(o.registrations,i)},assertImporter(i){return Ee(o.registrations,i)},assertExporter(i){return _e(o.registrations,i)},assertMigration(i){return $e(o.registrations,i)},assertCapabilityUsage(i){return $r(o,i)},runCommand(i){return I(o.commands,i)},runHook(i){return Ze(o.hooks,i)},runMutationGuard(i){return Qe(o.hooks,i)},runCommandOverride(i){return tr(o.commands,i)},runParserOverride(i){return er(o.parsers,i)},runPreflightOverride(i){return rr(o.preflight,i)},runRendererOverride(i){return nr(o.renderers,i)},runServiceOverride(i){return or(o.services,i)},runSearchProvider(i){return sr(o.registrations,i)},runVectorStoreAdapter(i){return ar(o.registrations,i)},runMigration(i){return dr(o.registrations,i)},runImporter(i){return mr(o,i)},runExporter(i){return cr(o,i)},deactivate(i={}){return Je(r,{name:n,layer:s,activation:o,deactivateTimeoutMs:i.deactivateTimeoutMs})}}}export{Ar as a,Fr as b,Se as c,Tr as d,N as e,Le as f,k as g,ge as h,Pr as i,A as j,he as k,Xe as l,Je as m,I as n,Qe as o,Ze as p,er as q,rr as r,tr as s,nr as t,or as u,sr as v,ar as w,dr as x,mr as y,cr as z,Gr as A,Yr as B,fr as C,lr as D,pr as E,ur as F,gr as G,Ee as H,_e as I,hr as J,vr as K,yr as L,xr as M,br as N,wr as O,Er as P,_r as Q,$e as R,$r as S,Xr as T,Jr as U,Qr as V,Zr as W,et as X,rt as Y};
8
- //# sourceMappingURL=chunk-SULWTPQO.js.map
8
+ //# sourceMappingURL=chunk-FPBQHMFT.js.map