@unbrained/pm-cli 2026.11.4 → 2026.11.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 (219) hide show
  1. package/.agents/skills/HARNESS_COMPATIBILITY.md +1 -1
  2. package/.agents/skills/README.md +14 -14
  3. package/.agents/skills/pm-developer/SKILL.md +16 -16
  4. package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +14 -14
  5. package/.agents/skills/pm-developer/references/SCRIPTING_COMPOSITION.md +10 -10
  6. package/.agents/skills/pm-extensions/SKILL.md +13 -13
  7. package/.agents/skills/pm-extensions/references/AUTHORING.md +12 -12
  8. package/.agents/skills/pm-sdk/SKILL.md +27 -27
  9. package/.agents/skills/pm-sdk/references/SURFACE_MAP.md +32 -32
  10. package/.agents/skills/pm-test-audit/references/AUDIT.md +1 -1
  11. package/.agents/skills/pm-user/SKILL.md +35 -35
  12. package/.claude-plugin/marketplace.json +1 -1
  13. package/AGENTS.md +9 -9
  14. package/CHANGELOG.md +9 -0
  15. package/README.md +13 -13
  16. package/dist/cli/register-setup.js +1 -1
  17. package/dist/cli-bundle/bundle-manifest.json +1 -1
  18. package/dist/cli-bundle/chunks/chunk-2RPORE7M.js +31 -0
  19. package/dist/cli-bundle/chunks/{chunk-NPEDFOVQ.js → chunk-335BZ75D.js} +2 -2
  20. package/dist/cli-bundle/chunks/chunk-5GWEY4P6.js +122 -0
  21. package/dist/cli-bundle/chunks/chunk-6VRX2CM7.js +2 -0
  22. package/dist/cli-bundle/chunks/{chunk-7PGNAHNW.js → chunk-7DEKAXVA.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-3OXQGGRD.js → chunk-7ZRCYESH.js} +42 -41
  24. package/dist/cli-bundle/chunks/{chunk-BWAXA6S4.js → chunk-AUEKTX7V.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-SRDO2NJU.js → chunk-D7KYPRK4.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-ODMJ3HIB.js → chunk-DAX3AOFI.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-L4BKTPJ6.js → chunk-F6NDMKZ4.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-T56MB6SF.js → chunk-FRNMQM45.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-5S6RT5LX.js → chunk-HNGLDMSZ.js} +3 -3
  30. package/dist/cli-bundle/chunks/{chunk-QN7VCOUU.js → chunk-HRCMORE7.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-BK2XAQVC.js → chunk-HRFGFIYU.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-CERNIZLB.js → chunk-JI2GDE4I.js} +42 -42
  33. package/dist/cli-bundle/chunks/{chunk-6T2V3UIK.js → chunk-LS3GI3H4.js} +53 -53
  34. package/dist/cli-bundle/chunks/chunk-OH6WQ7VT.js +3 -0
  35. package/dist/cli-bundle/chunks/{chunk-BRIPGUAO.js → chunk-OJDMJT7Y.js} +2 -2
  36. package/dist/cli-bundle/chunks/{chunk-7RCI7AAA.js → chunk-S4LPZ4TN.js} +2 -2
  37. package/dist/cli-bundle/chunks/{chunk-AQ5UHHQS.js → chunk-UEGXWXUZ.js} +2 -2
  38. package/dist/cli-bundle/chunks/{chunk-5BVZ32G7.js → chunk-XLSHFYXZ.js} +2 -2
  39. package/dist/cli-bundle/chunks/{chunk-2GW662DP.js → chunk-YKXATU2G.js} +2 -2
  40. package/dist/cli-bundle/chunks/{item-revision-UAZOBP2Q.js → item-revision-OJJVPQY7.js} +2 -2
  41. package/dist/cli-bundle/chunks/item-transaction-QEPBUCMY.js +2 -0
  42. package/dist/cli-bundle/chunks/{mutation-admission-QZQI2NN5.js → mutation-admission-INMM3HHG.js} +2 -2
  43. package/dist/cli-bundle/chunks/{register-list-query-P3NOKQUA.js → register-list-query-5Y5JKWU5.js} +2 -2
  44. package/dist/cli-bundle/chunks/{register-mutation-A6I5K5N6.js → register-mutation-WC7OSQID.js} +2 -2
  45. package/dist/cli-bundle/chunks/{register-operations-SPKB3TNM.js → register-operations-PO63DBZH.js} +2 -2
  46. package/dist/cli-bundle/chunks/register-setup-RRFOS7IT.js +2 -0
  47. package/dist/cli-bundle/chunks/{stage-L3T725DS.js → stage-E3MMV4TV.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/chunk-5PMJOJCZ.js +44 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-TFYTTDAK.js → chunk-7KK66ISG.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-Y5GOUUYJ.js → chunk-AHWJPZSJ.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-C7UX2ZI3.js → chunk-C6P6HPCX.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-Q4OIRSKL.js → chunk-CPMSL4HS.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/chunk-CZM75DE3.js +2 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-CO2DNPH7.js → chunk-D2TBEBNW.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-E56OXRYH.js +2 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-FXFDVM5O.js → chunk-F62XGAAY.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/chunk-G4QP365K.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/{chunk-J7M52SCZ.js → chunk-G5PJCR7R.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/chunk-GS3JC5UU.js +23 -0
  60. package/dist/cli-bundle/focused-chunks/{chunk-W3CSX6GI.js → chunk-LW64TINU.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-MEJKELWC.js → chunk-M6V7UMWL.js} +3 -3
  62. package/dist/cli-bundle/focused-chunks/{chunk-CXTDEQ3N.js → chunk-MC7IE7D7.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/chunk-MG7C3JUY.js +2 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-QEVJ3Y67.js → chunk-MK4HV4JO.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-A2246ZM7.js → chunk-NQ7GYFOX.js} +54 -54
  66. package/dist/cli-bundle/focused-chunks/chunk-O7EI33NP.js +91 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-FFO7RBLN.js → chunk-RFTJZ5VB.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{chunk-PNPYQDHU.js → chunk-SNOXXRSJ.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/{chunk-JQS7TYQ6.js → chunk-UPJUTP2V.js} +2 -2
  70. package/dist/cli-bundle/focused-chunks/{chunk-SDLIUZEL.js → chunk-VWWTIX5L.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/{chunk-J6FDCAMH.js → chunk-XHOBYCVE.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/{chunk-J3YOATXR.js → chunk-YMGB2O4E.js} +25 -24
  73. package/dist/cli-bundle/focused-chunks/{item-revision-L6GVT42D.js → item-revision-CTDO4H3I.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{item-transaction-GYGP264N.js → item-transaction-AEAYVVHA.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/{mutation-admission-UWTH56OD.js → mutation-admission-4WM7TNHZ.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/{stage-WRSNJ7VI.js → stage-WV7QXR4C.js} +2 -2
  77. package/dist/cli-bundle/main.js +2 -2
  78. package/dist/cli-bundle/sdk-authoring.js +1 -1
  79. package/dist/cli-bundle/sdk-contracts.js +1 -1
  80. package/dist/cli-bundle/sdk-core.js +1 -1
  81. package/dist/cli-bundle/sdk-governance.js +1 -1
  82. package/dist/cli-bundle/sdk-graph.js +1 -1
  83. package/dist/cli-bundle/sdk-merge.js +57 -57
  84. package/dist/cli-bundle/sdk-query.js +1 -1
  85. package/dist/cli-bundle/sdk-runtime.js +1 -1
  86. package/dist/cli-bundle/sdk-testing.js +1 -1
  87. package/dist/cli-bundle/sdk.js +9 -9
  88. package/dist/core/config/positional-value.d.ts +6 -0
  89. package/dist/core/config/positional-value.js +1 -1
  90. package/dist/core/item/literal-mutation-input.d.ts +17 -0
  91. package/dist/core/item/literal-mutation-input.js +1 -1
  92. package/dist/core/item/parent-reference-policy.d.ts +8 -4
  93. package/dist/core/item/parent-reference-policy.js +1 -1
  94. package/dist/core/item/sprint-release-format.d.ts +2 -1
  95. package/dist/core/item/sprint-release-format.js +1 -1
  96. package/dist/core/output/mutation-projection.js +1 -1
  97. package/dist/core/store/item-mutation-precondition.d.ts +3 -1
  98. package/dist/core/store/item-mutation-precondition.js +1 -1
  99. package/dist/core/store/item-store.js +1 -1
  100. package/dist/core/store/settings.d.ts +14 -0
  101. package/dist/core/store/settings.js +5 -4
  102. package/dist/core/telemetry/policy.d.ts +27 -1
  103. package/dist/core/telemetry/policy.js +1 -1
  104. package/dist/core/telemetry/runtime.d.ts +18 -7
  105. package/dist/core/telemetry/runtime.js +4 -4
  106. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +8 -5
  107. package/dist/sdk/cli-contracts.d.ts +1 -1
  108. package/dist/sdk/cli-contracts.js +1 -1
  109. package/dist/sdk/config.d.ts +2 -2
  110. package/dist/sdk/config.js +1 -1
  111. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  112. package/dist/sdk/governance/health.d.ts +2 -2
  113. package/dist/sdk/governance/health.js +2 -2
  114. package/dist/sdk/index.d.ts +4 -2
  115. package/dist/sdk/index.js +1 -1
  116. package/dist/sdk/init.d.ts +4 -4
  117. package/dist/sdk/init.js +8 -8
  118. package/dist/sdk/lifecycle/claim.d.ts +4 -0
  119. package/dist/sdk/lifecycle/claim.js +1 -1
  120. package/dist/sdk/lifecycle/close.d.ts +10 -0
  121. package/dist/sdk/lifecycle/close.js +1 -1
  122. package/dist/sdk/lifecycle/create.d.ts +7 -5
  123. package/dist/sdk/lifecycle/create.js +1 -1
  124. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +628 -4
  125. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  126. package/dist/sdk/lifecycle/update.d.ts +5 -4
  127. package/dist/sdk/lifecycle/update.js +2 -2
  128. package/dist/sdk/public-surface.json +1 -1
  129. package/dist/sdk/runtime/actions.js +1 -1
  130. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  131. package/dist/sdk/runtime-input.js +1 -1
  132. package/dist/sdk/runtime-primitives.d.ts +1 -0
  133. package/dist/sdk/runtime-primitives.js +1 -1
  134. package/dist/sdk/telemetry.d.ts +1 -1
  135. package/dist/sdk/telemetry.js +2 -2
  136. package/docs/AGENT_GUIDE.md +48 -48
  137. package/docs/AGENT_OUTPUT_ENCODINGS.md +20 -20
  138. package/docs/ASSURANCE.md +10 -10
  139. package/docs/BOUNDED_CONTEXT_READS.md +3 -3
  140. package/docs/CLAUDE_CODE_PLUGIN.md +1 -1
  141. package/docs/CLI_GRAMMAR.md +2 -2
  142. package/docs/COMMANDS.md +56 -35
  143. package/docs/COMMAND_NAMESPACES.md +1 -1
  144. package/docs/CONFIGURATION.md +82 -71
  145. package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +2 -2
  146. package/docs/CONTEXT_INTEGRITY_CONTRACTS.md +5 -5
  147. package/docs/CORPUS_SHAPES.md +1 -1
  148. package/docs/DEPENDENCY_KIND_CONTRACT.md +6 -6
  149. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +5 -5
  150. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +3 -3
  151. package/docs/EXTENSION_AUTHOR_CONTRACTS.md +4 -4
  152. package/docs/HISTORY_ATTESTATION.md +1 -1
  153. package/docs/HISTORY_MAINTENANCE.md +1 -1
  154. package/docs/LIFECYCLE_COMMANDS.md +1 -1
  155. package/docs/MCP_2026_07_28.md +16 -16
  156. package/docs/MCP_2026_07_28_CONFORMANCE.md +19 -19
  157. package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +22 -22
  158. package/docs/MCP_SKILLS_AND_APPS.md +1 -1
  159. package/docs/MERGE_SAFETY.md +6 -6
  160. package/docs/MUTATION_INTEGRITY.md +5 -5
  161. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +14 -14
  162. package/docs/PACKED_FIRST_RUN.md +1 -1
  163. package/docs/QUICKSTART.md +10 -10
  164. package/docs/README.md +21 -21
  165. package/docs/READ_OUTPUT_CONTRACTS.md +9 -9
  166. package/docs/RECURRENCE_RECOVERY_CONTRACTS.md +1 -1
  167. package/docs/RELEASING.md +19 -10
  168. package/docs/SCRIPTING.md +10 -10
  169. package/docs/SDK.md +74 -38
  170. package/docs/SDK_ARTIFACT_OUTPUT.md +1 -1
  171. package/docs/SDK_PRIMITIVE_INVENTORY.md +2 -2
  172. package/docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md +7 -7
  173. package/docs/TESTING.md +1 -1
  174. package/docs/WORKFLOW_POLICIES.md +2 -2
  175. package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +8 -8
  176. package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
  177. package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -1
  178. package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -1
  179. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +1 -1
  180. package/docs/performance/cli-transport-overhead.md +7 -7
  181. package/marketplace.json +1 -1
  182. package/package.json +1 -1
  183. package/packages/pm-beads/package.json +1 -1
  184. package/packages/pm-calendar/package.json +1 -1
  185. package/packages/pm-command-kit/README.md +5 -5
  186. package/packages/pm-command-kit/package.json +1 -1
  187. package/packages/pm-digital-twin/GAP_REPORT.md +16 -16
  188. package/packages/pm-digital-twin/package.json +1 -1
  189. package/packages/pm-governance-audit/package.json +1 -1
  190. package/packages/pm-guide-shell/package.json +1 -1
  191. package/packages/pm-kanban/README.md +1 -1
  192. package/packages/pm-kanban/package.json +1 -1
  193. package/packages/pm-lifecycle-hooks/package.json +1 -1
  194. package/packages/pm-linked-test-adapters/package.json +1 -1
  195. package/packages/pm-search-advanced/package.json +1 -1
  196. package/packages/pm-templates/package.json +1 -1
  197. package/packages/pm-todos/package.json +1 -1
  198. package/packages/pm-vcs/GAP_REPORT.md +1 -1
  199. package/packages/pm-vcs/package.json +1 -1
  200. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  201. package/plugins/pm-claude/README.md +6 -6
  202. package/plugins/pm-claude/package.json +1 -1
  203. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  204. package/plugins/pm-codex/package.json +1 -1
  205. package/plugins/pm-codex/plugin.json +1 -1
  206. package/runtime-dependencies.json +1 -1
  207. package/dist/cli-bundle/chunks/chunk-5Z6LWFDL.js +0 -31
  208. package/dist/cli-bundle/chunks/chunk-DSCFJTHB.js +0 -122
  209. package/dist/cli-bundle/chunks/chunk-QQHMNUZT.js +0 -2
  210. package/dist/cli-bundle/chunks/chunk-TX2W6G37.js +0 -3
  211. package/dist/cli-bundle/chunks/item-transaction-N5F4LXYV.js +0 -2
  212. package/dist/cli-bundle/chunks/register-setup-ZZRHJ4IS.js +0 -2
  213. package/dist/cli-bundle/focused-chunks/chunk-5NGNO54M.js +0 -44
  214. package/dist/cli-bundle/focused-chunks/chunk-B6U44WPW.js +0 -2
  215. package/dist/cli-bundle/focused-chunks/chunk-BAW3DGQO.js +0 -91
  216. package/dist/cli-bundle/focused-chunks/chunk-BHNY3KPJ.js +0 -2
  217. package/dist/cli-bundle/focused-chunks/chunk-CBG67HUP.js +0 -23
  218. package/dist/cli-bundle/focused-chunks/chunk-FEPE2CE4.js +0 -2
  219. package/dist/cli-bundle/focused-chunks/chunk-PMKR4MJI.js +0 -2
@@ -1,70 +1,70 @@
1
- import{i as li,n as pi,p as mi}from"./chunk-ODMJ3HIB.js";import{Vb as Ct}from"./chunk-5S6RT5LX.js";import{Aa as Za,Ba as ae,Ca as Me,Cb as si,Da as Qa,Db as hn,Ea as se,N as Ca,Va as ti,Wa as ni,Xa as $e,Xc as ci,Ya as ai,Za as ii,ca as Se,kb as ri,qb as oi,tb as Tt,ub as Ot,wa as Ya,xa as Re,xb as Pe,ya as at,za as Xa}from"./chunk-DSCFJTHB.js";import{Ai as Ha,Bc as Ce,Ci as fn,Da as xa,Di as Ka,Ea as Sa,Ei as Va,Fa as W,Fi as xe,G as ka,Gb as T,Li as ei,Na as F,Oa as Ea,Od as I,Oi as fe,Pa as $a,Pd as V,Qa as Ia,Qd as Ga,Qe as ee,Rb as Oa,Rd as K,Sd as Q,Tc as un,Uc as Fa,Ud as Ja,Ui as A,Vc as $t,Vi as Ee,Wd as nt,Xc as be,Yd as At,Zc as ke,ad as Ma,cc as ve,cd as It,d as xt,db as H,dd as Ua,e as ya,ea as Et,ed as za,ej as Ue,f as cn,fa as pn,fb as Aa,g as dn,ga as mn,gb as oe,h as ln,j as _a,jc as Ra,k as wa,kc as Pa,kf as qa,n as va,nc as Na,oc as Da,od as J,pf as q,rf as Wa,ub as Ta,wc as ja,x as ba,yc as La,zd as B,zi as Ba}from"./chunk-3OXQGGRD.js";import{f as di}from"./chunk-RSAN2YUU.js";import{A as h,C as u,E as k,F as St,G as we,H as M,K as ue,a as fa,d as kt,m as ha,t as on,v as ga,y as sn}from"./chunk-O4ZLEN4T.js";import{mkdir as Rs,readFile as Ps}from"node:fs/promises";import fi from"node:path";import{createHash as Ns}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="24a18484-0b8b-55d7-aa23-08a23b8d78ce")}catch{}})();var gn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},hi="sdk-workspace-transaction",gi=/^[a-zA-Z0-9._-]+$/,yi=30,_i=3e3;function bn(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!gi.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function yn(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function kn(e){return{pmRoot:yn(e.pmRoot,"Transaction pmRoot"),transactionId:bn(e.transactionId,"Transaction id"),author:yn(e.author,"Transaction author")}}function Pt(e,t,n){let a=e??t;if(!Number.isInteger(a)||a<=0)throw new TypeError(`${n} must be a positive integer`);return a}function wi(e,t){return fi.join(e,"transactions","sdk",`${t}.json`)}async function ce(e,t){t.updatedAt=T();let n=wi(e,t.transactionId);await Rs(fi.dirname(n),{recursive:!0}),await ue(n,`${JSON.stringify(t,null,2)}
2
- `)}function Ds(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"&&js(e)}function js(e){let t=e.abandonment;return t===void 0?e.schemaVersion===1&&e.status!=="abandoned":e.schemaVersion!==2||t===null||typeof t!="object"||e.status==="committed"?!1:typeof t.reason=="string"&&t.reason.trim().length>0&&typeof t.author=="string"&&t.author.trim().length>0&&(t.supersededBy===void 0||typeof t.supersededBy=="string"&&gi.test(t.supersededBy)&&t.supersededBy!==e.transactionId)}function Ne(e){return Object.assign(Object.create(null),e)}function vi(e,t){try{let n=JSON.stringify(e,(a,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function _n(e,t){return e===void 0?void 0:vi(e,t)}function wn(e,t,n,a){let i=_n(n,a);i===void 0?delete e[t]:e[t]=i}function ui(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vn(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Ls(e,t){if(!vn(e.startedStepIds,t)||!vn(e.completedStepIds,t)||!ui(e.results)||!ui(e.compensationData))return!1;let n=e.startedStepIds,a=new Set(n),i=e.completedStepIds,r=new Set(i);return Object.keys(e.compensationData).some(o=>!a.has(o))||Object.keys(e.results).some(o=>!r.has(o))?!1:e.status==="committed"?t.every(o=>r.has(o)):!["compensated","abandoned"].includes(e.status??"")||r.size===0&&a.size===0}function Rt(e,t){return new u(`Workspace transaction ${e} journal is invalid (${t})`,h.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function bi(e){return new u(`Workspace transaction ${e} journal does not match the supplied plan`,h.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function Fs(e,t,n){return n===void 0||e.abandonment!==void 0||e.status==="compensated"||t.length===n.length&&t.every((a,i)=>a===n[i])}function Ms(e,t,n){let a;try{a=JSON.parse(e)}catch{throw Rt(t,"invalid JSON")}if(!a||typeof a!="object"||Array.isArray(a))throw Rt(t,"expected an object");let i=a;if(!((i.schemaVersion===1||i.schemaVersion===2)&&i.transactionId===t))throw Rt(t,"schema version or transaction id does not match the journal file");let r=i.stepIds;if(!Array.isArray(r)||!vn(r,r)||!Ls(i,r)||!Ds(i)||typeof i.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(i.status))throw Rt(t,"invalid lifecycle, metadata, status or step ids");if(!Fs(i,r,n))throw bi(t);return{...i,results:Ne(i.results),compensationData:Ne(i.compensationData)}}async function Us(e,t,n,a,i){let r=i,o=r!==void 0;if(r?.status==="compensating"&&await xn(e,r),r===void 0||r.status==="compensated"){let s=T();r={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(r?.attempt??0)+1,createdAt:r?.createdAt??s,updatedAt:s,stepIds:a,startedStepIds:[],completedStepIds:[],results:Ne(),compensationData:Ne(),...e.recoveryData===void 0?{}:{recoveryData:vi(e.recoveryData,"Transaction recovery data")}},await ce(e.pmRoot,r),await he(e,r,"prepared")}return{journal:r,recovered:o}}async function zs(e,t,n){try{await Gs(t,e.steps),await ce(e.pmRoot,t);let a=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let r of e.steps){if(a.has(r.id))continue;let o=await r.inspect(),s=_n(o.result,`Step ${r.id} result`);if(o.state!=="applied"){let c=await r.prepareCompensation?.();wn(t.compensationData,r.id,c,`Step ${r.id} compensation data`),i.add(r.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await ce(e.pmRoot,t);let d=await r.apply();s=_n(d,`Step ${r.id} result`)}await he(e,t,"step_applied",r.id),a.add(r.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>a.has(c)),wn(t.results,r.id,s,`Step ${r.id} result`),await ce(e.pmRoot,t),await he(e,t,"step_recorded",r.id)}return await he(e,t,"committing"),t.status="committed",await ce(e.pmRoot,t),await he(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Ne(t.results)}}catch(a){if(a instanceof gn||t.status==="committed")throw a;try{await xn(e,t)}catch(i){throw new AggregateError([a,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw a}}async function Nt(e,t,n){try{return Ms(await Ps(wi(e,t),"utf8"),t,n)}catch(a){if(a!==null&&typeof a=="object"&&"code"in a&&we(a))return;throw a}}async function he(e,t,n,a){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...a===void 0?{}:{stepId:a}})}async function Gs(e,t){let n=new Set,a=Ne();for(let i of t){let r=await i.inspect();r.state==="applied"&&(n.add(i.id),wn(a,i.id,r.result,`Step ${i.id} result`))}e.results=a,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function xn(e,t){t.status="compensating",await ce(e.pmRoot,t),await he(e,t,"compensating");let n=new Set(t.completedStepIds),a=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!a.has(i.id)&&!n.has(i.id))continue;let r;try{let o=(await i.inspect()).state;r=a.has(i.id)&&(o==="applied"||o==="pending"&&i.compensatePending===!0)}catch{r=a.has(i.id)}r&&(await he(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),a.delete(i.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>a.has(o)),delete t.results[i.id],delete t.compensationData[i.id],await ce(e.pmRoot,t),await he(e,t,"step_compensated",i.id)}t.status="compensated",await ce(e.pmRoot,t),await he(e,t,"compensated")}async function ki(e){let{pmRoot:t,transactionId:n,author:a}=kn(e),i=Pt(e.lockTtlSeconds,yi,"Transaction lock TTL"),r=Pt(e.lockWaitMs,_i,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(l=>{let p=bn(l.id,"Transaction step id");if(p!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return p});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:a,steps:o,lockTtlSeconds:i,lockWaitMs:r},d=await ee(t,hi,i,a,!1,!1,r);try{let l=await Nt(t,n,s);if(l?.status==="abandoned"||l?.abandonment!==void 0)throw xi(l);let p=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Ne(l.results)};let m=await Us(c,n,a,s,l);return await zs(c,m.journal,p||m.recovered)}finally{await d()}}function xi(e){let t=e.status!=="abandoned",n=e.abandonment.supersededBy,a=n===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(e.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(n)} to finish retirement of ${JSON.stringify(e.transactionId)}.`;return new u(t?`Transaction ${e.transactionId} retirement is incomplete`:`Transaction ${e.transactionId} has been abandoned`,h.CONFLICT,{code:"transaction_abandoned",required:t?a:"Use a new transactionId for the replacement plan.",why:t?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...t?{retirement:{state:"pending",superseded_by:n??null},nextSteps:[a]}:{}})}async function Nu(e,t){let n=kn({pmRoot:e,transactionId:t,author:"reader"});return Nt(n.pmRoot,n.transactionId)}function Js(e){return Ns("sha256").update(JSON.stringify(e.stepIds)).digest("hex")}async function Du(e){let t=kn(e),n=yn(e.reason,"Abandonment reason"),a=e.supersededBy===void 0?void 0:bn(e.supersededBy,"Replacement transaction id");if(a===t.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");let i=Pt(e.lockTtlSeconds,yi,"Transaction lock TTL"),r=Pt(e.lockWaitMs,_i,"Transaction lock wait"),o=await ee(t.pmRoot,hi,i,t.author,!1,!1,r);try{let s=await Nt(t.pmRoot,t.transactionId);if(s===void 0)throw new u(`Transaction ${t.transactionId} was not found`,h.NOT_FOUND);if(s.status==="committed")throw new u(`Transaction ${t.transactionId} is committed and cannot be abandoned`,h.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(s.abandonment!==void 0&&s.abandonment.supersededBy!==a)throw xi(s);if(s.status==="abandoned")return s;let c=e.resolveSteps(structuredClone(s));if(JSON.stringify(c.map(d=>d.id))!==JSON.stringify(s.stepIds))throw bi(t.transactionId);if(s.abandonment===void 0){if(a!==void 0&&await Nt(t.pmRoot,a)!==void 0)throw new u(`Replacement transaction ${a} already exists`,h.CONFLICT);s.schemaVersion=2,s.abandonment={reason:n,author:t.author,...a===void 0?{}:{supersededBy:a}},await ce(t.pmRoot,s)}return s.status!=="compensated"&&await xn({...e,...t,steps:c},s),await qs(s,t.pmRoot,i,r),s.status="abandoned",await ce(t.pmRoot,s),s}finally{await o()}}async function qs(e,t,n,a){let i=Js(e);if((await Wa(Ha(t),Ba)).some(o=>o.op==="transaction_abandon"&&o.context?.transaction_id===e.transactionId&&o.context?.attempt===e.attempt&&o.context?.plan_digest===i))return;let r=e.abandonment;await Ka({pmRoot:t,author:r.author,lockTtlSeconds:n,lockWaitMs:a,op:"transaction_abandon",message:r.reason,context:{transaction_id:e.transactionId,attempt:e.attempt,plan_digest:i,...r.supersededBy===void 0?{}:{superseded_by:r.supersededBy}}})}import Ws from"node:fs/promises";import Bs 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]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function Sn(e){return Bs.join(e,"extension-migrations.json")}function Si(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Ei(e,t){return`${e.layer}:${e.name}:${t}`}async function Hs(e){let t=Sn(e);if(!await k(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await Ws.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(a=>typeof a?.key=="string"&&(a.status==="applied"||a.status==="failed")):[]}}async function Ks(e,t){let n=await Hs(e),a=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,r)=>{let o=Si(i,r),s=a.get(Ei(i,o));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function Vs(e){let t=await Ks(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),a=[],i=!1,r=e.migrations.map((l,p)=>({migration:l,index:p})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:p}of r){let m=Si(l,p),y=Ei(l,m),g=n.get(y),_=String(l.definition.status??"pending").toLowerCase(),f=g?.status??(_==="applied"||_==="failed"?_:"pending");if(f==="applied"){a.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"skipped"});continue}if(e.dryRun===!0){a.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){a.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:f}));let E={key:y,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(y,E),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,a.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"applied"}),i=!0}catch(E){let S=E instanceof Error?E.message:String(E),C={key:y,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:S};n.set(y,C),l.definition.status="failed",l.definition.reason=S,a.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"failed",error:S}),i=!0}}if(i){let l=await A(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,y)=>m.key.localeCompare(y.key))};await xe({pmRoot:e.pmRoot,filePath:Sn(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
3
- `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let o=a.filter(l=>l.outcome==="pending").length,s=a.filter(l=>l.outcome==="applied").length,c=a.filter(l=>l.outcome==="skipped").length,d=a.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:Sn(e.pmRoot),total:a.length,pending_count:o,applied_count:s,skipped_count:c,failed_count:d,migrations:a}}async function $i(e){let t=await A(e.resolvedRoots.settings_root),n=await be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),a=await ke(n);e.warnings.push(...n.warnings,...a.warnings);let i=await Vs({pmRoot:e.resolvedRoots.pm_root,migrations:a.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:a.failed.length},i.ok)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var Ys=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function ze(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(It(t.extensionName));for(let f of t.extensionNames??[])n.add(It(f));let a=f=>n.size===0||n.has(It(f)),i=(f,w)=>Ii(f.filter(v=>a(v.name)).map(w)),r=(f,w)=>Ii(f.filter(v=>a(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:c,preflight:d,services:l,renderers:p,hooks:m}=e,y=r(o.relationship_kinds??[],f=>f.definitions.map(w=>w.kind)),g=p.overrides.filter(f=>a(f.name)&&((f.commands?.length??0)>0||f.resultDiscriminator!==void 0)).map(f=>({format:f.format,commands:[...f.commands??[]],result_discriminator:f.resultDiscriminator!==void 0})).sort((f,w)=>f.format.localeCompare(w.format)),_=i(o.assurance_providers??[],f=>f.definition.id);return{capabilities:Ua(e,t),commands:i(o.commands,f=>f.command),command_overrides:i(s.overrides,f=>f.command),command_handlers:i(s.handlers,f=>f.command),hooks:Ys.filter(([f])=>m[f].some(w=>a(w.name))).map(([,f])=>f),flag_commands:i(o.flags,f=>f.target_command),item_types:r(o.item_types,f=>f.types.map(w=>w.name)),item_fields:r(o.item_fields,f=>f.fields.map(w=>w.name)),...y.length>0?{relationship_kinds:y}:{},migrations:r(o.migrations,f=>typeof f.definition.id=="string"?[f.definition.id]:[]),profiles:i(o.profiles,f=>f.profile.name),importers:i(o.importers,f=>f.importer),exporters:i(o.exporters,f=>f.exporter),search_providers:i(o.search_providers,f=>f.definition.name),vector_store_adapters:i(o.vector_store_adapters,f=>f.definition.name),..._.length>0?{assurance_providers:_}:{},parser_overrides:i(c.overrides,f=>f.command),service_overrides:i(l.overrides,f=>f.service),renderer_overrides:i(p.overrides,f=>f.format),...g.length>0?{renderer_ownership:g}:{},preflight_overrides:d.overrides.filter(f=>a(f.name)).length,preflight_ownership:d.overrides.filter(f=>a(f.name)).map(f=>({commands:[...f.commands??[]]}))}}function Ii(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var it={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Dt={type:"array",minItems:1,maxItems:cn,items:it},Ai={...Dt,items:{...it,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},Xs={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Dt])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:it,id:it}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Ai}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Dt}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Ai,authors:Dt}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:cn,items:{type:"array",minItems:2,maxItems:2,items:it}}}}]}}},Hu={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:ya,items:Xs}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function Xu(e,t,n,a){let i=await $e(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Ti(i,t,n,a)}function Zs(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Ti(e,t,n=5,a=!1){let i=[],r=new Map,o=e.policies.filter(f=>f.rule.kind==="require_fields"),s=o.filter(f=>f.subject?.operations===void 0),c=new Set,d=0,l=0,p=0,m=0,y=0,g=va(e);for(let f of t){let w=g({operation:"",author:"",before:f,after:f,completeness_only:!0});d+=+(w.decisions.length>0),l+=w.decisions.length,w.decisions.forEach(S=>c.add(S.policy_id));let v=w.decisions.filter(S=>!S.satisfied);if(v.length===0)continue;m+=1;let E=r.get(f.type)??{items:0,violations:0,missing_fields:0};E.items+=1;for(let S of v)p+=1,E.violations+=1,E.missing_fields+=S.missing_fields.length,S.effect==="refuse"&&(y+=1),i.length<n&&i.push({id:f.id,type:f.type,status:f.status,decision:S});r.set(f.type,E)}let _=a||y>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:_,ok:_==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:l,governed_items:d,ungoverned_items:t.length-d,contract_status:Zs(o.length,t.length,d),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:p,refused_violations:y,missing_by_type:Object.fromEntries(r),violations:i,violations_truncated:i.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...a?["validate_completeness_source_incomplete"]:[]]}}import Qs 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]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function ec(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function Ri(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new u("Policy definition must be valid JSON.",h.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new u("Policy definition must be an object.",h.USAGE);return t}async function tc(e,t){let n=F(process.cwd(),e.path);await Ue(n);let a=await A(n);return{pmRoot:n,settings:a,author:q(t,a.author_default)}}function Oi(e,t,n,a){if(e==="policy-mode")return ln({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let r=dn(a.definition),o=ln({...n,policies:[...i,r].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
4
- `)>ti)throw new u("Policy registry exceeds its byte ceiling.",h.USAGE);return o}async function Ci(e,t,n,a){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:Oi(e,t,await $e(a.pmRoot),n)};let i=await Va({pmRoot:a.pmRoot,filePath:Qs.join(a.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:a.author,message:n.message,lockTtlSeconds:a.settings.locks.ttl_seconds,lockWaitMs:a.settings.locks.wait_ms,mutate(r){let o=Oi(e,t,ni(r),n);return{raw:`${JSON.stringify(o,null,2)}
5
- `,result:o}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function nc(e,t,n){let a,i=await si({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:a}),async mutate(r){let o=(await $e(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!o||o.rule.kind!=="approval")throw new u("--policy must name an approval rule.",h.USAGE);if(!o.rule.authors.includes(n.author))throw new u("This actor is not a declared approver.",h.CONFLICT);return await ai(n.pmRoot,r.metadata.id),a={policy_id:o.id,policy_fingerprint:_a(o),content_fingerprint:wa(o,{...r.metadata,body:r.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...a,warnings:i.warnings}}}function ac(e,t){let n=Ri(t),a=dn({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==a.id)throw new u("Policy id operand does not match definition.id.",h.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return a}async function hf(e,t,n={},a={}){if(!xt.includes(e))throw new u("Unknown workflow policy action.",h.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:ec()};let i=await tc(a,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await $e(i.pmRoot)};if(e==="policy-put"){let l=ac(t,n.definition);return Ci(e,l.id,{...n,definition:l},i)}if(!t?.trim())throw new u(`schema ${e} requires an operand.`,h.USAGE);if(["policy-remove","policy-mode"].includes(e))return Ci(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new u("Use policy-check to preview; policy-approve records an approval.",h.USAGE);return nc(t,n,i)}let r=W(i.settings,J()),o=await Tt(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,r.type_to_folder);if(!o)throw new u(`Item ${t} not found.`,h.NOT_FOUND);let{document:s}=await Ot(o,{schema:i.settings.schema}),c={...s.metadata,body:s.body},d=n.definition===void 0?c:{...c,...Ri(n.definition)};if(d.id!==c.id)throw new u("Policy preview cannot change the item id.",h.USAGE);return{policy_result:!0,action:e,changed:!1,result:await ii(i.pmRoot,await $e(i.pmRoot),{operation:"update",author:i.author,before:c,after:d,completeness_only:n.definition===void 0})}}import{createHash as Bi}from"node:crypto";import He from"node:fs/promises";import Ke from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1abceae0-299e-5fff-aa8c-46c015115571")}catch{}})();var ic=new Set(pn),rc=new Set(mn),Pi=new Set([...ha.filter(e=>e!=="severity"),"id","title","type","status","priority","tags","assignee","parent","description","body","created_at","updated_at","closed_at","completed_at","author","deadline","estimate","sprint","release","risk","confidence","reviewer","resolution","expected","actual"]),oc=["create","update"];function Li(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function Ni(e){return e.replaceAll("_","-")}function sc(e,t){let n=new Set;for(let a of e){let i=Li(a);i.length>0&&i!==t&&n.add(i)}return[...n].sort((a,i)=>a.localeCompare(i))}function cc(e){let t=new Set;for(let n of e??[]){let a=n.trim();a.length>0&&t.add(a)}return[...t].sort((n,a)=>n.localeCompare(a))}function dc(e){let t=new Set,n=[];for(let a of e??[]){let i=a.trim().toLowerCase();if(i.length!==0){if(!rc.has(i))throw new Error(`Invalid field command "${a}". Allowed: ${mn.join(", ")}.`);t.has(i)||(t.add(i),n.push(i))}}return e===void 0||n.length===0?[...oc]:n}function Fi(e){let t=I(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(t.includes(","))throw new Error(`Field key "${t}" must not contain commas: commas separate field names in list flags such as --unset and --fields.`);if(Pi.has(t))throw new Error(`Cannot define custom field "${t}": custom schema field "${t}" collides with built-in item metadata "${t}". Rename the custom field with a project-specific prefix. Reserved fields: ${[...Pi].sort((p,m)=>p.localeCompare(m)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!ic.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${pn.join(", ")}.`);let a=n,i=dc(e.commands),r=Li(e.cliFlag),o=r.length>0&&r!==Ni(t)?r:void 0,s=o??Ni(t),c=sc(e.aliases??[],s),d=[s,...c].find(p=>p.includes(","));if(d!==void 0)throw new Error(`Field flag "${d}" must not contain commas.`);let l=e.description?.trim();return{key:t,type:a,commands:i,description:l&&l.length>0?l:void 0,cliFlag:o,cliAliases:c,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:cc(e.requiredTypes)}}function lc(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function pc(e){let t=lc(e);if(!t)return[];let n=[];for(let a of t){if(typeof a!="object"||a===null||Array.isArray(a))continue;let i=a;typeof i.key!="string"||i.key.trim().length===0||n.push(i)}return n}function Ge(e){if(e==null||e.trim().length===0)return{fields:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/fields.json contains invalid JSON.")}return{fields:pc(t)}}function Je(e){return`${JSON.stringify({fields:e.fields},null,2)}
6
- `}function Mi(e,t){let n=e.fields.find(o=>I(o.key)===t.key),a=n!==void 0,i=e.fields.filter(o=>I(o.key)!==t.key),r={...n,key:t.key,type:t.type,commands:[...t.commands]};return Di(r,"description",t.description),Di(r,"cli_flag",t.cliFlag),t.cliAliases.length>0?r.cli_aliases=[...t.cliAliases]:delete r.cli_aliases,ji(r,"required",t.required),ji(r,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?r.allow_unset=!1:delete r.allow_unset,t.requiredTypes.length>0?r.required_types=[...t.requiredTypes]:delete r.required_types,i.push(r),i.sort((o,s)=>I(o.key).localeCompare(I(s.key))),{file:{fields:i},definition:r,replaced:a}}function Ui(e,t){let n=I(t);if(n.length===0)throw new Error("Field key must not be empty.");let a=[],i=e.fields.filter(r=>I(r.key)===n?(a.push(r),!1):!0);return a.length===0?{file:{fields:i},removed:!1}:{file:{fields:i},removed:!0,definition:a[0]}}function Di(e,t,n){let a=e;n!==void 0&&n.length>0?a[t]=n:delete a[t]}function ji(e,t,n){let a=e;n?a[t]=!0:delete a[t]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1e4c04e-0ade-5d24-95e3-b8dca3832c5a")}catch{}})();var mc=new Set(Et),De=new Set(Ga.map(e=>I(e.id)).filter(e=>e.length>0));function uc(e){let t=new Set;for(let n of e){let a=I(n);a.length>0&&t.add(a)}return[...t].sort((n,a)=>n.localeCompare(a))}function zi(e){let t=I(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(De.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...De].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let o=new Set;for(let s of e.roles){let c=typeof s=="string"?s.trim().toLowerCase():"";if(c.length!==0){if(!mc.has(c))throw new Error(`Invalid status role "${s}". Allowed roles: ${Et.join(", ")}.`);o.has(c)||(o.add(c),n.push(c))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${Et.join(", ")}.`)}let a=e.aliases===void 0?void 0:uc(e.aliases).filter(o=>o!==t),i=e.description?.trim(),r=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:a,description:i&&i.length>0?i:void 0,order:r}}function fc(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function hc(e){let t=fc(e);if(!t)return[];let n=[];for(let a of t){if(typeof a!="object"||a===null||Array.isArray(a))continue;let i=a;typeof i.id!="string"||i.id.trim().length===0||n.push(i)}return n}function qe(e){if(e==null||e.trim().length===0)return{statuses:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/statuses.json contains invalid JSON.")}return{statuses:hc(t)}}function We(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
7
- `}function Gi(e,t,n){let a=e.statuses.slice(),i=a.findIndex(s=>I(s.id)===t.id),r=i>=0?a[i]:n,o={...r,id:t.id};return t.roles!==void 0&&(t.roles.length>0?o.roles=[...t.roles]:o.roles!==void 0&&delete o.roles),t.aliases!==void 0&&(t.aliases.length>0?o.aliases=[...t.aliases]:o.aliases!==void 0&&delete o.aliases),t.description!==void 0&&(o.description=t.description),t.order!==void 0&&(o.order=t.order),i>=0?a[i]=o:a.push(o),{file:{statuses:a},definition:o,replaced:r!==void 0}}function Ji(e,t){let n=I(t);if(n.length===0)throw new Error("Status id must not be empty.");if(De.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...De].join(", ")}.`);let a=e.statuses.slice(),i=a.findIndex(o=>I(o.id)===n);if(i<0)return{file:{statuses:a},removed:!1};let[r]=a.splice(i,1);return{file:{statuses:a},removed:!0,definition:r}}function En(e,t){let n=[e.id,...e.aliases??[]];for(let a of n){let i=I(a);if(i.length===0)continue;let r=t.get(i);if(r!==void 0&&r!==e.id)throw new Error(`Status token "${i}" already belongs to status "${r}". Choose a different id/alias to avoid shadowing it.`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="09d88765-6283-5287-b293-43300251833f")}catch{}})();function ge(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Hi(e){let t=ge(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Ki(e,t){let n=In(e),a=ge(t,"migrationScope");return`auto-${Bi("sha256").update(JSON.stringify({scope:a,request:n})).digest("hex").slice(0,20)}`}function In(e){let t=e.kind==="rename-type"?{kind:e.kind,from:ge(e.from,"source"),to:ge(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:I(ge(e.from,"source")),to:I(ge(e.to,"target")),...e.type===void 0?{}:{type:ge(e.type,"type")}}:{kind:e.kind,from:I(ge(e.from,"source")),to:I(ge(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function gc(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function yc(e,t,n){let a=K(t.schema),i=gc(n);return Q(e,a.files[i],V[i])}function Vi(e,t){return Ke.join(e,"transactions","schema",`${t}-plan.json`)}function jt(e){return e.length===0?null:JSON.parse(e)}async function Be(e){let t=await M(e);return{exists:t!==null,raw:t??""}}async function Yi(e,t){t.exists?await ue(e,t.raw):await He.rm(e,{force:!0})}function _c(e,t,n){let a=ae(e),i=a.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),r=a.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(r>=0)return se(a);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);a.definitions.push({...a.definitions[i],name:t.to})}else i>=0&&a.definitions.splice(i,1);return se(a)}function wc(e,t,n){let a=Ge(e),i=a.fields.findIndex(o=>o.key===t.from),r=a.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(r>=0)return Je(a);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=a.fields[i];a.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&a.fields.splice(i,1);return Je(a)}function vc(e,t,n){let a=qe(e),i=a.statuses.findIndex(o=>o.id===t.from),r=a.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(r>=0)return We(a);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);a.statuses.push({...a.statuses[i],id:t.to})}else i>=0&&a.statuses.splice(i,1);return We(a)}function bc(e,t,n){return t.kind==="rename-type"?_c(e,t,n):t.kind==="rename-field"?wc(e,t,n):vc(e,t,n)}function Ie(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function An(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Ve(e){return Array.isArray(e)?e.map(t=>An(t)).filter(t=>t!==void 0):[]}function kc(e,t){for(let n of Ve(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(a=>Ie(a,t)));for(let n of Ve(e.type_workflows))n.type=Ie(n.type,t)}function xc(e,t){for(let a of Ve(e.definitions))a.default_status=Ie(a.default_status,t);let n=An(e.workflow);if(n)for(let[a,i]of Object.entries(n))n[a]=Ie(i,t);for(let a of Ve(e.type_workflows))Array.isArray(a.allowed_transitions)&&(a.allowed_transitions=a.allowed_transitions.map(i=>Array.isArray(i)?i.map(r=>Ie(r,t)):i))}function Sc(e,t){for(let n of Ve(e.definitions)){for(let a of["required_create_fields","required_create_repeatables"])Array.isArray(n[a])&&(n[a]=n[a].map(i=>Ie(i,t)));for(let a of["options","command_option_policies"])for(let i of Ve(n[a])){let r=a==="options"?"key":"option";i[r]=Ie(i[r],t)}}}function Ec(e,t){let n=An(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let a=t.kind==="rename-type"?"type":"status";n[a]=Ie(n[a],t)}function $n(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let a=n;return t.kind==="rename-type"?kc(a,t):t.kind==="rename-field"?Sc(a,t):xc(a,t),Ec(a,t),`${JSON.stringify(a,null,2)}
8
- `}function Xi(e,t){if(t.kind==="rename-type"){let a=ae(e).definitions;return{source:a.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:a.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let a=Ge(e).fields;return{source:a.some(i=>i.key===t.from),target:a.some(i=>i.key===t.to)}}let n=qe(e).statuses;return{source:n.some(a=>a.id===t.from),target:n.some(a=>a.id===t.to)}}function $c(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function Ic(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function Zi(e,t){let n=In(t.request),a=t.migrationId===void 0?Ki(n,t.migrationScope??"plan"):Hi(t.migrationId),i=e.map(c=>Ic(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),r=Bi("sha256").update(JSON.stringify({migrationId:a,request:n,items:i})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!o.has(c.id));return Object.freeze({migration_id:a,request:n,fingerprint:r,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function Ac(e){let t=W(e.settings,J()),n=[...new Set(Object.values(t.type_to_folder))],a=await oi(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},r=a?await ri({pmRoot:e.pmRoot,expectedSourceCursor:a.source_cursor,query:i}):null;return r?{items:r.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Pe(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Tc(e,t){let n=await M(Vi(e,t));if(n===null)return null;try{let a=JSON.parse(n);if(a.schema_version!==1||a.plan.migration_id!==t||!Array.isArray(a.plan.items))throw new TypeError("invalid plan envelope");return a.plan}catch(a){throw new u(`Stored schema migration plan "${t}" is invalid: ${Ta(a)}`,h.GENERIC_FAILURE)}}async function Oc(e,t){let n=Vi(e,t.migration_id);await He.mkdir(Ke.dirname(n),{recursive:!0});let a={schema_version:1,plan:t,created_at:new Date().toISOString()};await ue(n,`${JSON.stringify(a,null,2)}
9
- `)}function Cc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Rc(e){let t=await Tt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new u(`Schema migration item "${e.id}" no longer exists.`,h.NOT_FOUND);return(await Ot(t,{schema:e.settings.schema})).document.metadata}function qi(e,t,n){let a=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==a.toLowerCase())throw new TypeError(`Schema migration expected type "${a}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==a.toLowerCase())throw new TypeError(`Schema migration expected status "${a}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let r=e.metadata;if(Object.prototype.hasOwnProperty.call(r,i)&&!Object.prototype.hasOwnProperty.call(r,a))return[];if(!Object.prototype.hasOwnProperty.call(r,a)||Object.prototype.hasOwnProperty.call(r,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return r[i]=r[a],delete r[a],[a,i]}function Wi(e){return{id:e.id,inspect:async()=>{let t=await Be(e.filePath),n=Xi(t.raw,e.request),a=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:a?"applied":"pending",...a?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Be(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Be(e.filePath);return await ue(e.filePath,bc(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await Yi(e.filePath,{exists:t.exists,raw:t.raw})}}}function Pc(e){return{id:e.stepId,inspect:async()=>{let t=await Be(e.filePath);return{state:$n(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Be(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Be(e.filePath);return await ue(e.filePath,$n(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await Yi(e.filePath,{exists:t.exists,raw:t.raw})}}}function Nc(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await A(e.pmRoot),n=W(t,J()).type_to_folder,a=await Rc({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=$c(a,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await A(e.pmRoot),n=W(t,J()).type_to_folder,a=await hn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:qi(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:a.changedFields}},compensate:async()=>{let t=await A(e.pmRoot),n=W(t,J()).type_to_folder;await hn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(a){return{changedFields:qi(a,e.request,"reverse")}}})}}}async function Dc(e){let t=await Tc(e.pmRoot,e.migrationId);if(t){if(!Cc(t.request,e.request))throw new u(`Schema migration id "${e.migrationId}" already belongs to a different request.`,h.CONFLICT);return{plan:t,stored:!0}}let n=await Ac({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Zi(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function jc(e){let t=Xi(await M(e.schemaPath)??"",e.request);if(!t.source)throw new u(`Schema migration source "${e.request.from}" is not a custom definition.`,h.NOT_FOUND);if(t.target)throw new u(`Schema migration target "${e.request.to}" already exists.`,h.CONFLICT);await Oc(e.pmRoot,e.plan)}async function Lc(e){let t=K(e.settings.schema),n=[...new Set([["types",V.types],["fields",V.fields],["workflows",V.workflows]].map(([i,r])=>Q(e.pmRoot,t.files[i],r)).filter(i=>i!==e.schemaPath))];try{let i=Ke.join(e.pmRoot,"templates"),r=await He.readdir(i,{withFileTypes:!0});n.push(...r.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>Ke.join(i,o.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!we(i))throw i}n.sort((i,r)=>i.localeCompare(r));let a=[];for(let i of n){let r=await M(i);r!==null&&$n(r,e.request)!==r&&a.push({filePath:i,beforeRaw:r})}return{paths:n,snapshots:a}}async function Fc(e){for(let t of e.snapshots){let n=await He.readFile(t.filePath,"utf8"),a=Ke.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await fn({pmRoot:e.pmRoot,author:e.author,documentPath:a,before:jt(t.beforeRaw),after:jt(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${a}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function Mc(e,t,n){let a=In(e),i=F(process.cwd(),n.path);await Ue(i);let r=t.migrationId===void 0?Ki(a,await He.realpath(i)):Hi(t.migrationId),o=await A(i),s=q(t.author,o.author_default),c=await Dc({pmRoot:i,settings:o,migrationId:r,request:a}),d=c.plan;if(t.dryRun===!0)return{...d,action:a.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=yc(i,o,a),p=await M(l)??"";c.stored||await jc({pmRoot:i,schemaPath:l,request:a,plan:d});let m=await Lc({pmRoot:i,schemaPath:l,settings:o,request:a}),y=[Wi({id:"stage-schema",filePath:l,request:a,phase:"stage"}),...m.paths.map((w,v)=>Pc({filePath:w,request:a,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>Nc({pmRoot:i,id:w.id,request:a,author:s,force:t.force===!0})),Wi({id:"retire-source",filePath:l,request:a,phase:"retire"})],g=await ki({pmRoot:i,transactionId:`schema-${r}`,author:s,steps:y,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),_=await He.readFile(l,"utf8"),{historyPath:f}=await fn({pmRoot:i,author:s,documentPath:Ke.relative(i,l).replaceAll("\\","/"),before:jt(p),after:jt(_),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${a.kind}: ${a.from} -> ${a.to}; affected=${d.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await Fc({pmRoot:i,author:s,settings:o,request:a,plan:d,snapshots:m.snapshots}),{...d,action:a.kind,applied:!0,recovered:g.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:f}}function Uc(e){let t=e.applied?"applied":"dry-run",n=e.recovered?" (recovered)":"";return[`${e.action}: ${e.request.from} -> ${e.request.to} [${t}${n}]`,`migration_id: ${e.migration_id}`,`affected: ${e.affected_item_count}`,`pending: ${e.pending_item_count}`,`fingerprint: ${e.fingerprint}`].join(`
10
- `)}import tr from"node:fs/promises";import je 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]="74b72dd8-0877-55a4-9c80-d043f19e1f96")}catch{}})();var Lt=["extensions","docs","examples","assets","prompts"],zc=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 Gc(e){return Lt.includes(e)}function Jc(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],a=[];for(let i of n){if(typeof i!="string"||i.trim().length===0)throw new u(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);a.push(i.trim())}return[...new Set(a)].sort((i,r)=>i.localeCompare(r))}function qc(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new u("Package manifest field pm must be an object.",h.USAGE);let t={},n=e;for(let[a,i]of Object.entries(n)){if(!Gc(a))continue;let r=Jc(a,i);r.length>0&&(t[a]=r)}return t}function de(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function Tn(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 Qi(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 Wc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:de(t,"docs"),npm:de(t,"npm"),repository:de(t,"repository"),report:de(t,"report")};return Object.values(n).some(a=>typeof a=="string")?n:void 0}function Bc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:de(t,"image"),video:de(t,"video")};return Object.values(n).some(a=>typeof a=="string")?n:void 0}function Hc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:de(t,"display_name")??de(t,"displayName"),category:de(t,"category"),summary:de(t,"summary"),links:Wc(t.links),media:Bc(t.media),tags:Tn(t.tags)};return Object.values(n).some(a=>a!==void 0)?n:void 0}async function rt(e){let t=je.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await tr.readFile(t,"utf8"))}catch(s){throw new u(`Failed to parse package manifest at "${t}": ${String(s)}`,h.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new u(`Package manifest at "${t}" must be a JSON object.`,h.USAGE);let a=n,i=a.pm,r=i!=null,o=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};return{source:r?"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:Tn(a.keywords),package_homepage:typeof a.homepage=="string"?a.homepage:void 0,package_repository_url:Qi(a.repository),package_bugs_url:Qi(a.bugs),aliases:Tn(o.aliases),resources:qc(i),catalog:Hc(o.catalog)}}async function er(e){if(!await k(e))return[];let t=await tr.readdir(e,{withFileTypes:!0}),n=[];for(let a of t){if(!a.isDirectory())continue;let i=je.join(e,a.name);await k(je.join(i,"manifest.json"))&&n.push(i)}return n.sort((a,i)=>a.localeCompare(i))}async function Ft(e){if(await k(je.join(e,"manifest.json")))return[e];let t=(await rt(e)).resources.extensions??[],n=new Set;for(let a of t){if(a.includes("*")||a.startsWith("!"))throw new u(`Package extension entry "${a}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let i=je.resolve(e,a);if(!H(e,i))throw new u(`Package extension entry "${a}" resolves outside package root.`,h.USAGE);if(await k(je.join(i,"manifest.json"))){n.add(i);continue}for(let r of await er(i))n.add(r)}if(t.length===0)for(let a of zc.extensions)for(let i of await er(je.join(e,a)))n.add(i);return[...n].sort((a,i)=>a.localeCompare(i))}import{execFile as fd}from"node:child_process";import R from"node:fs/promises";import Fn from"node:os";import $ from"node:path";import{fileURLToPath as hd}from"node:url";import{promisify as gd}from"node:util";import yd from"npm-package-arg";import{extract as _d,list as wd}from"tar";import id from"node:fs/promises";import ie from"node:path";import nr from"node:fs/promises";import On from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cf5a9e7-4a66-5e72-80a2-f8a9b5b6e412")}catch{}})();function Z(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function b(e){return e.trim().toLowerCase()}function Mt(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 i=t.slice(n,a);if(i.length===0)throw new u("Extension manifest name must resolve to a non-empty directory name.",h.USAGE);if(i==="."||i==="..")throw new u('Extension manifest name must not resolve to "." or "..".',h.USAGE);return i}function Cn(e){return ja(e)}async function Kc(e){try{let t=JSON.parse(await nr.readFile(On.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 Vc(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new u(`Extension entry file is missing at "${t}".`,h.USAGE);let a=await Kc(n.source_root),i=a.package_name?`pm package install npm:${a.package_name}`:void 0,r=n.source_input??n.source_root;return new u(`Extension entry "${e.entry}" is absent from GitHub source "${r}". pm package install copies GitHub repositories without running package scripts${a.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,h.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm package install ${n.source_root}`]:[`pm package install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm package install npm:<package-name>."],recovery:{attempted_command:`pm install ${r}`,normalized_args:["install",r],...i?{next_best_command:i}:{}}})}async function Ye(e,t={}){let n=On.join(e,"manifest.json");if(!await k(n))throw new u(`Extension manifest is missing at "${n}".`,h.USAGE);let a;try{a=JSON.parse(await nr.readFile(n,"utf8"))}catch(o){throw new u(`Failed to parse extension manifest at "${n}": ${Yc(o)}`,h.USAGE)}let i=Cn(a);if(!i)throw new u(`Extension manifest at "${n}" is invalid.`,h.USAGE);let r=On.resolve(e,i.entry);if(!H(e,r))throw new u(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,h.USAGE);if(!await k(r))throw await Vc(i,r,t);if(!await Fa(e,r))throw new u(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,h.USAGE);return{directory:e,manifest_path:n,entry_path:r,manifest:i}}function Yc(e){return e instanceof Error?e.message:String(e)}import Rn from"node:fs/promises";import Xc 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]="5181479f-469f-525b-add2-914a9934afbd")}catch{}})();var Zc=".managed-extensions.json",Ut=1;function ot(e){return Xc.join(e,Zc)}function Qc(){return{version:Ut,updated_at:T(),entries:[]}}function st(e){return[...e].sort((t,n)=>{let a=t.scope.localeCompare(n.scope);if(a!==0)return a;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function ar(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function Y(e){return typeof e=="string"?e:void 0}function ed(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function td(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:Y(t.name),package:Y(t.package),version:Y(t.version),repository:Y(t.repository),owner:Y(t.owner),repo:Y(t.repo),ref:Y(t.ref),subpath:Y(t.subpath),commit:Y(t.commit)}}function nd(e){if(typeof e!="object"||e===null)return null;let t=e;if(!ed(t))return null;let n=td(t.source);if(!n)return null;let a=Ra(t.contributions);return a===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Z(t.capabilities),contributions:a,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Y(t.last_update_check_at),last_update_remote_commit:Y(t.last_update_remote_commit),last_update_remote_version:Y(t.last_update_remote_version),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Y(t.update_error)}}function ad(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Ut||!Array.isArray(t.entries))return null;let n=[];for(let a of t.entries){let i=nd(a);i&&n.push(i)}return{version:Ut,updated_at:Y(t.updated_at)??T(),entries:st(n)}}async function le(e){let t=ot(e),n=Qc();try{let a=await Rn.readFile(t,"utf8"),i=JSON.parse(a),r=ad(i);if(!r)throw new u(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:r,warnings:[]}}catch(a){if(a instanceof u)throw a;if(typeof a=="object"&&a!==null&&"code"in a&&we(a))return{path:t,state:n,warnings:[]};throw new u(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}async function Xe(e,t){let n=ot(e),a={version:Ut,updated_at:T(),entries:st(t.entries)};await Rn.mkdir(e,{recursive:!0}),await Rn.writeFile(n,`${JSON.stringify(a,null,2)}
11
- `,"utf8")}function ct(e,t){let n=e.entries.filter(a=>b(a.name)!==b(t.name)&&b(a.directory)!==b(t.directory));return n.push(t),{...e,updated_at:T(),entries:st(n)}}async function ir(e,t,n,a){let i=t.entries.find(o=>b(o.name)===b(n));if(!i)return t;let r=ct(t,{...i,contributions:a});return await Xe(e,r),r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var rd="PM_CLI_PACKAGE_ROOT",rr={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},od=new Set(["*","all"]);function Pn(){let e=[],t=process.env[rd];return typeof t=="string"&&t.trim().length>0&&e.push(ie.resolve(t.trim())),e.push(ve(import.meta.url,["../../.."])),[...new Set(e)]}async function dt(e){let t=e.trim().toLowerCase(),n=await sr(t);if(n)return n;let a=rr[t];if(!a)return null;for(let i of Pn()){let r=ie.join(i,".agents","pm","extensions",a.legacy_extension_directory);if(await k(ie.join(r,"manifest.json")))return r}return null}function or(e){return od.has(e.trim().toLowerCase())}function sd(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function cd(e,t){let n=await id.readdir(e,{withFileTypes:!0});for(let a of n){if(!a.isDirectory()||!a.name.startsWith("pm-"))continue;let i=ie.join(e,a.name);if(!await k(ie.join(i,"package.json")))continue;let r=await rt(i),o=r.aliases&&r.aliases.length>0?r.aliases:[sd(a.name)];for(let s of o){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:a.name,package_root:i,package_name:r.package_name??null})}}}async function Nn(){let e=new Map;for(let t of Pn()){let n=ie.join(t,"packages");await k(n)&&await cd(n,e)}for(let[t,n]of Object.entries(rr))if(!e.has(t))for(let a of Pn()){let i=ie.join(a,"packages",n.package_directory);if(await k(ie.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function zt(){return(await Nn()).map(e=>e.alias)}async function sr(e){let t=e.trim().toLowerCase();return(await Nn()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function cr(e){let t=await sr(e);return t?(await rt(t)).package_name??null:null}async function dr(e){let t=await dt(e);if(!t)return null;try{let n=await Ft(t);return n.length!==1?null:(await Ye(n[0])).manifest.name}catch{return null}}function dd(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function ld(e,t,n,a,i,r){let o=a==="global"?"--global":"--project",s=Object.fromEntries(Lt.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||r.has(ie.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:dd(e),media:e.catalog?.media}}}async function lr(e,t,n={}){let a=$t(F(process.cwd(),t.path),process.cwd()),i=e==="global"?a.global:a.project,r=await le(i),o=new Set(r.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>ie.resolve(m.source.location))),s=new Set(r.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),c=[],d=new Map;for(let m of await Nn()){let y=ie.resolve(m.package_root),g=d.get(y)??[];g.push(m),d.set(y,g)}for(let m of d.values()){let y=m[0],g=m.map(f=>f.alias).sort((f,w)=>f.localeCompare(w)),_=await rt(y.package_root);c.push(ld(_,y,g,e,s,o))}let l=md(n.fields),p=l?c.map(m=>ud(m,l)):c;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Lt.filter(m=>m!=="extensions"),packages:p}}var pd=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function md(e){if(e===void 0)return;let t=ci(e);if(t.length===0)throw new u("Package catalog --fields requires a comma-separated list of field names",h.USAGE);let n=t.filter(a=>!pd.has(a));if(n.length>0)throw new u(`Unknown package catalog --fields value(s): ${n.join(", ")}`,h.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function ud(e,t){let n={};for(let a of t)a==="category"?n[a]=e.catalog?.category??null:a==="display_name"?n[a]=e.catalog?.display_name??null:n[a]=e[a]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fc993281-a2a0-59e8-9f4a-e520f1b94f3b")}catch{}})();var mr=gd(fd),Jt="@unbrained/pm-cli",vd={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},Dn;async function ur(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let a=$.resolve(t);for(;;){let i=$.join(a,"node_modules",...n.split("/")),r=$.join(i,"package.json");if(await k(r))try{let s=JSON.parse(await R.readFile(r,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let o=$.dirname(a);if(o===a)return null;a=o}}function jn(e,t,n){let a=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(a.length<2)return null;let i=a[0],r=a[1].replace(/\.git$/i,"");if(i.length===0||r.length===0)return null;let o=a.slice(2),s,c;return o[0]==="tree"&&o.length>=2?(s=o[1],c=o.slice(2).join("/")):o.length>0&&(c=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:r,repository:`https://github.com/${i}/${r}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function bd(e,t,n){let a=e.slice(4).trim();if(a.length===0)throw new u('npm package source must include a package spec after "npm:".',h.USAGE);if(t)throw new u('Options "--gh/--github" cannot be combined with npm: package sources.',h.USAGE);if(n)throw new u('Option "--ref" cannot be combined with npm: package sources.',h.USAGE);return{kind:"npm",input:e,spec:a}}function lt(e,t={}){let n=e.trim();if(n.length===0)throw new u("Extension source is required for --install.",h.USAGE);let a=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return bd(n,t.forceGithub===!0,a);let i=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return jn(s,n,a)}catch{return null}})();if(i)return i;let r=n.startsWith("github.com/")?n.slice(11):null;if(r){let o=jn(r,n,a);if(!o)throw new u(`Invalid GitHub source "${n}".`,h.USAGE);return o}if(t.forceGithub){let o=jn(n,n,a);if(!o)throw new u(`Invalid GitHub shorthand "${n}".`,h.USAGE);return o}if(/^https?:\/\//i.test(n))throw new u(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,h.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function Gt(e,t=mr,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(a){let i=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr):"",r=i.trim().length>0?i.trim():a instanceof Error?a.message:String(a);throw new u(`Git command failed: git ${e.join(" ")}
12
- ${r}`,h.GENERIC_FAILURE)}}function Mn(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Un(e=process.platform){return e==="win32"}async function fr(e,t,n=mr,a=process.platform,i=process.env){let r=Mn(a),o=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));o.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(r,e,{cwd:t,encoding:"utf8",env:o,shell:Un(a)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",d=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new u(`npm command failed: ${r} ${e.join(" ")}
13
- ${d}`,h.GENERIC_FAILURE)}}function hr(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function gr(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function kd(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("npm err! code e404")||t.includes("404 not found")||t.includes("is not in this registry")}function xd(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return kd(e)||t.includes("not found")}function Sd(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Ed(e){let t=hr(e),n=Sd(t),a=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${a}`:void 0,r=i?`pm package install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:r?[r,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:r?[`Try ${r} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&r?{fallback_candidates:[{source:i,command:r,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:r}:{}}}}}function $d(e,t){if(!xd(t))return null;let n=Ed(e);return new u(n.message,h.NOT_FOUND,n.context)}async function yr(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await k(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=hd(t);return await k(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await k(t))return t}return null}async function Id(e){let t=await yr(e);if(t)return t;let n=Ad(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Ad(e,t=process.cwd()){let n="@file:",a=e.lastIndexOf(n);if(!gr(e))return e;let i=e.slice(0,a),r=e.slice(a+n.length);if(r.startsWith("//")&&!r.startsWith("///"))return e;if(!r.startsWith("/"))return`${i}@${$.resolve(t,r)}`;let o;try{o=decodeURIComponent(new URL(`file:${r}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${i}@${s}`}function pr(e,t){let n=$.resolve(e,t),a=$.relative(e,n);if(a.length===0||a===".."||a.startsWith(`..${$.sep}`)||$.isAbsolute(a))throw new u("npm pack reported a package archive outside its isolated destination.",h.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function Td(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function Od(e){return(Array.isArray(e)?e.map(t=>({value:t})):typeof e=="object"&&e!==null?Object.entries(e).map(([t,n])=>({key:t,value:n})):[]).flatMap(({key:t,value:n})=>{let a=Td(n,t);return a?[a]:[]})}function Cd(e,t){let n=t?.trim().toLowerCase(),a=n?e.filter(o=>{let s=o.name?.trim().toLowerCase();return s!==void 0?s===n:o.key?.trim().toLowerCase()===n}):[];if(a.length===1)return a[0];if(e.length!==1)return;let i=e[0],r=i.name??i.key;return n&&r!==void 0&&r.trim().toLowerCase()!==n?void 0:i}function Rd(e,t,n){let a;try{a=JSON.parse(e)}catch{let o=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!o)throw new u("npm pack did not report a tarball filename.",h.GENERIC_FAILURE);return{tarball:pr(t,o)}}let i=Od(a),r=Cd(i,n);if(!r)throw new u("npm pack --json returned an unsupported or ambiguous package receipt.",h.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:pr(t,r.filename),package:r.name??r.key,version:r.version}}async function Pd(e){return Nd(e,fr)}async function Nd(e,t){let n=await yr(e.spec);if(n){if((await R.stat(n)).isFile()&&_r(n))return Ln(n);let r=$.join(n,"package.json"),o=await k(r)?JSON.parse(await R.readFile(r,"utf8")):{};return{directory:await qt(n,e.input),package:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,cleanup:async()=>{}}}let a=await R.mkdtemp($.join(Fn.tmpdir(),"pm-npm-package-source-")),i=$.join(a,"pack");await R.mkdir(i,{recursive:!0});try{let r=await Id(e.spec),o=await t(["pack",r,"--json","--pack-destination",i]),s=Rd(o,i,gr(e.spec)?void 0:hr(e.spec));if(!await k(s.tarball))throw new u("npm pack did not create its reported package archive.",h.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await Ln(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await R.rm(a,{recursive:!0,force:!0})}}}}catch(r){throw await R.rm(a,{recursive:!0,force:!0}),$d(e.spec,r)||r}}function _r(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ye(e){throw new u(e,h.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function Dd(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&ye(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let a=e.path,i=a.split("/");(a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||i.some(r=>r===".."))&&ye(`Local package archive contains an escaping path: "${a}".`),i[0]!=="package"&&ye(`Local package archive entry "${a}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ye(`Local package archive link "${a}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ye(`Local package archive entry "${a}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ye(`Local package archive entry "${a}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&ye(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),a==="package/package.json"&&(n.packageJsonEntries+=1)}async function Ln(e,t=vd){(await R.stat(e)).size>t.maxArchiveBytes&&ye(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await R.mkdtemp($.join(Fn.tmpdir(),"pm-local-package-archive-")),a=$.join(n,"extract");await R.mkdir(a,{recursive:!0});let i={entries:0,expandedBytes:0,packageJsonEntries:0},r;try{if(await wd({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(r===void 0)try{Dd(d,t,i)}catch(l){r=l}}}),r!==void 0)throw r;i.packageJsonEntries!==1&&ye(`Local package archive must contain exactly one package/package.json entry; found ${i.packageJsonEntries}.`),await _d({file:e,cwd:a,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let o=$.join(a,"package"),s=$.join(o,"package.json"),c=JSON.parse(await R.readFile(s,"utf8"));return await jd(o),{directory:await qt(o,e),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{await R.rm(n,{recursive:!0,force:!0})}}}catch(o){throw await R.rm(n,{recursive:!0,force:!0}),o}}async function jd(e,t=fr){let n=$.join(e,"package.json");if(!await k(n))return;let a;try{a=JSON.parse(await R.readFile(n,"utf8"))}catch{return}if(typeof a!="object"||a===null)return;let i=a,r=Gd(i),o=Ld(i);if(r.length===0&&!o)return;let s={...a};delete s.devDependencies;let c={...s};Fd(c),await R.writeFile(n,`${JSON.stringify(c,null,2)}
14
- `,"utf8");try{await Promise.all([R.rm($.join(e,"package-lock.json"),{force:!0}),R.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),r.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await Md(e)}finally{await R.writeFile(n,`${JSON.stringify(s,null,2)}
15
- `,"utf8")}}function Ld(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Jt in t)return!0;return!1}function Fd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let a={...n};delete a[Jt],Object.keys(a).length===0?delete e[t]:e[t]=a}}async function Md(e){let t=ve(import.meta.url,["../../.."]),[n,a]=Jt.split("/"),i=$.join(e,"node_modules",n),r=$.join(i,a);await R.mkdir(i,{recursive:!0}),await R.rm(r,{recursive:!0,force:!0}),await R.symlink(t,r,Ud(process.platform))}function Ud(e){return e==="win32"?"junction":"dir"}function zd(e,t){if(e.startsWith("-"))throw new u(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,h.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(n=>{let a=n.charCodeAt(0);return a<=31||a===127||"&|;()`\"'".includes(n)}))throw new u(`Extension runtime dependency "${e}" has an unsafe version specifier.`,h.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{yd.resolve(e,t)}catch{throw new u(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,h.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function Gd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[a,i]of Object.entries(n)){if(a===Jt||typeof i!="string"||i.trim().length===0||t.has(a))continue;let r=i.trim();t.set(a,zd(a,r))}return[...t.values()]}async function qt(e,t){let n=await Ft(e);if(n.length===1)return n[0];if(n.length>1){let a=n.map(i=>$.relative(e,i).replaceAll($.sep,"/")).sort((i,r)=>i.localeCompare(r));throw new u(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${a.join(", ")}`,h.USAGE)}throw new u(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,h.USAGE)}async function Jd(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push($.posix.join(".agents/pm/extensions",t.subpath)),n.push($.posix.join(".custom/pm-extensions",t.subpath)),n.push($.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let r=$.resolve(e,i);if(H(e,r)&&await k($.join(r,"manifest.json")))return{directory:r,resolved_subpath:i}}if(await k($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let a=await qt(e,t.input);return{directory:a,resolved_subpath:$.relative(e,a).replaceAll($.sep,"/")}}function qd(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function Wd(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!qd(n))return new u(t,h.NOT_FOUND);let a=[];try{let r=process.env.PM_CLI_PACKAGE_ROOT,o=typeof r=="string"&&r.trim().length>0?$.resolve(r.trim()):"";Dn?.key!==o&&(Dn={key:o,aliases:await zt()}),a=Dn.aliases}catch{}let i=[`Retry with pm package install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${a.join(", ")}`];return new u(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,h.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm package install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm package install npm:${n}`}})}async function wr(e){if(e.kind==="local"){let a;try{a=await R.stat(e.absolute_path)}catch{throw await Wd(e)}if(a.isFile()&&_r(e.absolute_path)){let r=await Ln(e.absolute_path);return{source:e,directory:r.directory,source_root:$.dirname(r.directory),resolved_subpath:$.relative($.dirname(r.directory),r.directory).replaceAll($.sep,"/"),npm_package:r.package,npm_version:r.version,cleanup:r.cleanup}}if(!a.isDirectory())throw new u(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let i=await qt(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let a=await Pd(e);return{source:e,directory:a.directory,source_root:$.dirname(a.directory),cleanup:a.cleanup,resolved_subpath:$.relative($.dirname(a.directory),a.directory).replaceAll($.sep,"/"),npm_package:a.package,npm_version:a.version}}let t=await R.mkdtemp($.join(Fn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Gt(n);let a=await Gt(["-C",t,"rev-parse","HEAD"]),i=await Jd(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:a,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(a){throw await R.rm(t,{recursive:!0,force:!0}),a}}async function Ze(e,t){if(!await k(e)||!await k(t))return!1;let[n,a]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===a}import pt from"node:fs/promises";import mt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var zn=1,Le="2026.6.24",Bd=">=22.18.0",Hd={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},vr=new Set([...ka.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(ba).map(e=>e.toLowerCase()),"scaffold"]),Kd="^6.0.0",Vd="^22.0.0",xr=["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."," }"," }","}",""],pe=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function br(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Sr(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 Er(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 Yd={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},kr=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],$r={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"]},Xd={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"]'},Zd={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."},Qd={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."},Ir="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",el={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},tl={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."]},nl={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`."]},al={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 Ar(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 Tr(e,t){return e==="schema"?nl[t]:e==="profile"?al[t]:tl[t]}function il(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(o=>o.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),a=0;for(;t[a]?.toLowerCase()==="starter";)a+=1;let i=t[a]?.toLowerCase(),r=a>0&&(a===t.length||i!==void 0&&vr.has(i));return`${(vr.has(n)||r?["starter",...t]:t).join(" ")} ping`}function Or(e){let t=e,n=`${e}s`,a=e.replace(/-/g,""),i=a===t?[]:[a],r=`${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(i)},`,` 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(r)},`,' 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 rl(e,t,n){let a=`${e}-search`,i=`${e}-vector`,r=`${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(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],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({",...Or(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(r)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} 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(r)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} 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) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...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 ol(e,t,n){let a=n==="hooks",i=n==="search",r=n==="importers",o=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",p=n==="services",m=Xd[n],y=e,g=`${e}s`,_=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=a?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],E=i?Gn(e,t,"search",m):[],S=r?Gn(e,t,"importers",m):[],C=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 {",...br(Sr({extensionName:e,itemTypeName:y,itemTypeFolder:g,fieldName:_,migrationId:f,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],ne=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 {",...br(Er(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],D=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;",...pe,"});",""]:[],x=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;",...pe,"});",""]:[],G=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;",...pe,"});",""]:[],tt=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;",...pe,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...xr,`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;",...pe,"});","",...v,...E,...S,...C,...ne,...D,...x,...G,...tt,`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(`
16
- `)}function sl(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 cl={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"},dl={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 ll(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 pl(e,t,n){let a=[],i=[...ll(e,t,n)],r=[" 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],y=`${e.replace(/-/g,"_")}_note`,g=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":a.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),r.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":a.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(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 }),","});"),r.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":a.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),r.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"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(y)},`,' 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(g)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),r.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":a.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...Or(e),"});"),r.push(" profiles: [starterProfile],");break;case"renderers":a.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),r.push(" renderers: { toon: toonRenderer },");break;case"parser":a.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),r.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":a.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),r.push(" preflights: [preflightOverride],");break;case"services":a.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),r.push(" services: { output_format: outputService },");break}return{builderImports:a,definitions:i,blueprintFields:r}}function ml(e,t,n){let a=pl(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...a.builderImports].sort((i,r)=>i.localeCompare(r)).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(`
17
- `)}function Gn(e,t,n,a){if(n==="commands")return[];let i=`${e}-search`,r=`${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=y=>[...p," let deactivated = false;"," try {",...y.map(g=>g===""?g:` ${g}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(r)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(r)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(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(Sr({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Er(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 ul(e,t,n){let a=n==="parser",i=JSON.stringify([...$r[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" };',"",...xr,`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(Le)},`," },",` target: { pmVersion: ${JSON.stringify(Le)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...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;",...pe,"});","",...Gn(e,t,n,i)].join(`
18
- `)}function fl(e,t,n){let a=Ar(n,"package"),i=Tr(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 (${cl[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`.",Ir,"- `.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 ${dl[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${zn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Le}\`. 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(`
19
- `)}function hl(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function gl(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function yl(e,t,n,a){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(a.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(a.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(a.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(a.itemTypeName)},`,` folder: ${JSON.stringify(a.itemTypeFolder)},`,` aliases: ${JSON.stringify(a.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(a.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(a.itemTypeName)}, folder: ${JSON.stringify(a.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function _l(e,t,n){let a=[];return t==="renderers"&&a.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&a.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&a.push(" api.registerPreflight(preflightOverride);"),t==="services"&&a.push(' api.registerService("output_format", outputService);'),t==="hooks"&&a.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&a.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&a.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&a.push(" api.registerProfile(starterProfile);"),t==="importers"&&a.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),a}function wl(e,t,n,a="commands",i=!1){let r=`pm-${e}`,o=$r[a],s=sl(e,t,a),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:zn,pm_min_version:Le,trusted:!0,sandbox_profile:"strict",permissions:{...Hd},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
20
- `,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...rl(e,t,a),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
21
- `),l=`${JSON.stringify(Yd,null,2)}
22
- `,p=Zd[a],m=Ar(a,"package"),y=`${JSON.stringify({name:r,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Bd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Le}`},devDependencies:{"@types/node":Vd,typescript:Kd},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
23
- `,g=ol(e,t,a),_=Qd[a],f=["node_modules/","*.log","*.tsbuildinfo",""].join(`
24
- `),w=hl(e),v=["```ts",`import { ${gl(a)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...yl(e,t,a,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",..._l(t,a,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],E=[`# ${r}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,p,_,Ir,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...v,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...el[a],...Tr(a,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Le}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${zn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Le}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
25
- `);return{"package.json":y,"manifest.json":c,"index.ts":i?ml(e,t,a):d,"index.test.ts":i?ul(e,t,a):g,"tsconfig.json":l,".gitignore":f,"README.md":i?fl(r,t,a):E}}async function Cr(e,t="extension",n="commands",a=!1){let i=n.trim().toLowerCase();if(!kr.includes(i))throw new u(`Unknown scaffold capability "${n}". Supported capabilities: ${kr.join(", ")}.`,h.USAGE);let r=i;if(a&&t!=="package")throw new u("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",h.USAGE);let o=a?"declarative":"imperative",s=e.trim(),c=mt.resolve(process.cwd(),s),d=Mt(mt.basename(c)).replace(/^(?:pm-)+/u,""),l=il(d),p=wl(d,l,t,r,a),m=!1;if(await k(c)){if(!(await pt.stat(c)).isDirectory())throw new u(`Scaffold target "${c}" exists and is not a directory.`,h.CONFLICT)}else await pt.mkdir(c,{recursive:!0}),m=!0;for(let[g,_]of Object.entries(p)){let f=mt.join(c,g);if(await k(f)&&await pt.readFile(f,"utf8")!==_)throw new u(`Scaffold file "${g}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,h.CONFLICT)}let y=[];for(let[g,_]of Object.entries(p)){let f=mt.join(c,g);if(await k(f)){y.push({path:g,status:"unchanged"});continue}await pt.mkdir(mt.dirname(f),{recursive:!0}),await pt.writeFile(f,_,"utf8"),y.push({path:g,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:r,style:o,target_path:c,created_directory:m,files:y}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3984f1ef-1703-5a83-a4fa-ec1cdc738572")}catch{}})();var Rr=[["commands","Commands"],["command_overrides","Command overrides"],["flag_commands","Flag commands"],["item_types","Item types"],["item_fields","Item fields"],["migrations","Migrations"],["profiles","Profiles"],["importers","Importers"],["exporters","Exporters"],["search_providers","Search providers"],["vector_store_adapters","Vector store adapters"],["assurance_providers","Assurance measurement providers"],["hooks","Lifecycle hooks"],["parser_overrides","Parser overrides"],["service_overrides","Service overrides"],["renderer_overrides","Renderer overrides"]];function Jn(e){return"#".repeat(e)}function Pr(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let r of e)n=r==="`"?n+1:0,t=Math.max(t,n);let a="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${a}${i}${e}${i}${a}`}function vl(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(Pr).join(", ")}`}function bl(e,t,n){let a=[`${Jn(t)} ${e}`,""];return n.length===0?(a.push("_None._",""),a):(a.push(...n.map(i=>`- ${Pr(i)}`),""),a)}function kl(e,t,n){return e===0&&!n?[]:[`${Jn(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function qn(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<1||n>6)throw new RangeError(`headingLevel must be an integer in [1, 6], received ${String(t.headingLevel)}`);let a=Math.min(n+1,6),i=t.includeEmpty===!0,r=t.title??"Extension surfaces",o=[`${Jn(n)} ${r}`,""];(i||e.capabilities.length>0)&&o.push(vl(e.capabilities),"");for(let[s,c]of Rr){let d=e[s]??[];d.length===0&&!i||o.push(...bl(c,a,d))}return o.push(...kl(e.preflight_overrides,a,i)),!(e.preflight_overrides>0||Rr.some(([s])=>(e[s]?.length??0)>0))&&!i&&o.push("_This extension registers no surfaces._",""),`${o.join(`
1
+ import{i as mi,n as ui,p as fi}from"./chunk-DAX3AOFI.js";import{Vb as Rt}from"./chunk-HNGLDMSZ.js";import{$a as ai,Ba as Xa,Ca as Pe,Cb as Ne,Da as it,Ea as Za,Fa as Qa,Ga as ae,Ha as Ue,Hb as ci,Ia as ei,Ib as gn,Ja as se,Q as Ra,_a as ni,ab as $e,bb as ii,cb as ri,ed as li,ha as Ee,nc as di,pb as oi,vb as si,yb as Ot,zb as Ct}from"./chunk-5GWEY4P6.js";import{Ad as B,Ai as Ha,Bc as Re,Bi as Ka,Da as Ea,Di as fn,Ea as $a,Ei as Va,Fa as W,Fi as Ya,G as Sa,Gb as T,Gi as Se,Mi as ti,Na as F,Oa as Ia,Pa as Ce,Pd as A,Pi as fe,Qa as Aa,Qd as V,Rb as Ca,Rd as Ja,Re as ee,Ri as hn,Sd as K,Td as Q,Uc as un,Vc as Ma,Vd as qa,Vi as I,Wc as It,Wi as he,Xd as at,Yc as ke,Zd as Tt,_c as xe,bd as Ua,cc as be,d as St,db as H,dd as At,e as wa,ea as $t,ed as za,f as cn,fa as pn,fb as Ta,fd as Ga,fj as ze,g as dn,ga as mn,gb as oe,h as ln,j as va,jc as Pa,k as ba,kc as Na,lf as Wa,n as ka,nc as Da,oc as ja,pd as J,qf as q,sf as Ba,ub as Oa,wc as La,x as xa,yc as Fa}from"./chunk-7ZRCYESH.js";import{f as pi}from"./chunk-RSAN2YUU.js";import{A as h,C as u,E as k,F as Et,G as ve,H as M,K as ue,a as ha,d as xt,m as ga,t as sn,v as ya,y as _a}from"./chunk-O4ZLEN4T.js";import{mkdir as Ds,readFile as js}from"node:fs/promises";import gi from"node:path";import{createHash as Ls}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="24a18484-0b8b-55d7-aa23-08a23b8d78ce")}catch{}})();var yn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},yi="sdk-workspace-transaction",_i=/^[a-zA-Z0-9._-]+$/,wi=30,vi=3e3;function kn(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!_i.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function _n(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function xn(e){return{pmRoot:_n(e.pmRoot,"Transaction pmRoot"),transactionId:kn(e.transactionId,"Transaction id"),author:_n(e.author,"Transaction author")}}function Nt(e,t,n){let a=e??t;if(!Number.isInteger(a)||a<=0)throw new TypeError(`${n} must be a positive integer`);return a}function bi(e,t){return gi.join(e,"transactions","sdk",`${t}.json`)}async function ce(e,t){t.updatedAt=T();let n=bi(e,t.transactionId);await Ds(gi.dirname(n),{recursive:!0}),await ue(n,`${JSON.stringify(t,null,2)}
2
+ `)}function Fs(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"&&Ms(e)}function Ms(e){let t=e.abandonment;return t===void 0?e.schemaVersion===1&&e.status!=="abandoned":e.schemaVersion!==2||t===null||typeof t!="object"||e.status==="committed"?!1:typeof t.reason=="string"&&t.reason.trim().length>0&&typeof t.author=="string"&&t.author.trim().length>0&&(t.supersededBy===void 0||typeof t.supersededBy=="string"&&_i.test(t.supersededBy)&&t.supersededBy!==e.transactionId)}function De(e){return Object.assign(Object.create(null),e)}function ki(e,t){try{let n=JSON.stringify(e,(a,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function wn(e,t){return e===void 0?void 0:ki(e,t)}function vn(e,t,n,a){let i=wn(n,a);i===void 0?delete e[t]:e[t]=i}function hi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bn(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Us(e,t){if(!bn(e.startedStepIds,t)||!bn(e.completedStepIds,t)||!hi(e.results)||!hi(e.compensationData))return!1;let n=e.startedStepIds,a=new Set(n),i=e.completedStepIds,r=new Set(i);return Object.keys(e.compensationData).some(o=>!a.has(o))||Object.keys(e.results).some(o=>!r.has(o))?!1:e.status==="committed"?t.every(o=>r.has(o)):!["compensated","abandoned"].includes(e.status??"")||r.size===0&&a.size===0}function Pt(e,t){return new u(`Workspace transaction ${e} journal is invalid (${t})`,h.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function xi(e){return new u(`Workspace transaction ${e} journal does not match the supplied plan`,h.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function zs(e,t,n){return n===void 0||e.abandonment!==void 0||e.status==="compensated"||t.length===n.length&&t.every((a,i)=>a===n[i])}function Gs(e,t,n){let a;try{a=JSON.parse(e)}catch{throw Pt(t,"invalid JSON")}if(!a||typeof a!="object"||Array.isArray(a))throw Pt(t,"expected an object");let i=a;if(!((i.schemaVersion===1||i.schemaVersion===2)&&i.transactionId===t))throw Pt(t,"schema version or transaction id does not match the journal file");let r=i.stepIds;if(!Array.isArray(r)||!bn(r,r)||!Us(i,r)||!Fs(i)||typeof i.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(i.status))throw Pt(t,"invalid lifecycle, metadata, status or step ids");if(!zs(i,r,n))throw xi(t);return{...i,results:De(i.results),compensationData:De(i.compensationData)}}async function Js(e,t,n,a,i){let r=i,o=r!==void 0;if(r?.status==="compensating"&&await Sn(e,r),r===void 0||r.status==="compensated"){let s=T();r={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(r?.attempt??0)+1,createdAt:r?.createdAt??s,updatedAt:s,stepIds:a,startedStepIds:[],completedStepIds:[],results:De(),compensationData:De(),...e.recoveryData===void 0?{}:{recoveryData:ki(e.recoveryData,"Transaction recovery data")}},await ce(e.pmRoot,r),await ge(e,r,"prepared")}return{journal:r,recovered:o}}async function qs(e,t,n){try{await Ws(t,e.steps),await ce(e.pmRoot,t);let a=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let r of e.steps){if(a.has(r.id))continue;let o=await r.inspect(),s=wn(o.result,`Step ${r.id} result`);if(o.state!=="applied"){let d=await r.prepareCompensation?.();vn(t.compensationData,r.id,d,`Step ${r.id} compensation data`),i.add(r.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await ce(e.pmRoot,t);let c=await r.apply();s=wn(c,`Step ${r.id} result`)}await ge(e,t,"step_applied",r.id),a.add(r.id),t.completedStepIds=e.steps.map(d=>d.id).filter(d=>a.has(d)),vn(t.results,r.id,s,`Step ${r.id} result`),await ce(e.pmRoot,t),await ge(e,t,"step_recorded",r.id)}return await ge(e,t,"committing"),t.status="committed",await ce(e.pmRoot,t),await ge(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:De(t.results)}}catch(a){if(a instanceof yn||t.status==="committed")throw a;try{await Sn(e,t)}catch(i){throw new AggregateError([a,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw a}}async function Dt(e,t,n){try{return Gs(await js(bi(e,t),"utf8"),t,n)}catch(a){if(a!==null&&typeof a=="object"&&"code"in a&&ve(a))return;throw a}}async function ge(e,t,n,a){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...a===void 0?{}:{stepId:a}})}async function Ws(e,t){let n=new Set,a=De();for(let i of t){let r=await i.inspect();r.state==="applied"&&(n.add(i.id),vn(a,i.id,r.result,`Step ${i.id} result`))}e.results=a,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function Sn(e,t){t.status="compensating",await ce(e.pmRoot,t),await ge(e,t,"compensating");let n=new Set(t.completedStepIds),a=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!a.has(i.id)&&!n.has(i.id))continue;let r;try{let o=(await i.inspect()).state;r=a.has(i.id)&&(o==="applied"||o==="pending"&&i.compensatePending===!0)}catch{r=a.has(i.id)}r&&(await ge(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),a.delete(i.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>a.has(o)),delete t.results[i.id],delete t.compensationData[i.id],await ce(e.pmRoot,t),await ge(e,t,"step_compensated",i.id)}t.status="compensated",await ce(e.pmRoot,t),await ge(e,t,"compensated")}async function Si(e){let{pmRoot:t,transactionId:n,author:a}=xn(e),i=Nt(e.lockTtlSeconds,wi,"Transaction lock TTL"),r=Nt(e.lockWaitMs,vi,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(l=>{let p=kn(l.id,"Transaction step id");if(p!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return p});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let d={...e,pmRoot:t,transactionId:n,author:a,steps:o,lockTtlSeconds:i,lockWaitMs:r},c=await ee(t,yi,i,a,!1,!1,r);try{let l=await Dt(t,n,s);if(l?.status==="abandoned"||l?.abandonment!==void 0)throw Ei(l);let p=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:De(l.results)};let m=await Js(d,n,a,s,l);return await qs(d,m.journal,p||m.recovered)}finally{await c()}}function Ei(e){let t=e.status!=="abandoned",n=e.abandonment.supersededBy,a=n===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(e.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(n)} to finish retirement of ${JSON.stringify(e.transactionId)}.`;return new u(t?`Transaction ${e.transactionId} retirement is incomplete`:`Transaction ${e.transactionId} has been abandoned`,h.CONFLICT,{code:"transaction_abandoned",required:t?a:"Use a new transactionId for the replacement plan.",why:t?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...t?{retirement:{state:"pending",superseded_by:n??null},nextSteps:[a]}:{}})}async function Uu(e,t){let n=xn({pmRoot:e,transactionId:t,author:"reader"});return Dt(n.pmRoot,n.transactionId)}function Bs(e){return Ls("sha256").update(JSON.stringify(e.stepIds)).digest("hex")}async function zu(e){let t=xn(e),n=_n(e.reason,"Abandonment reason"),a=e.supersededBy===void 0?void 0:kn(e.supersededBy,"Replacement transaction id");if(a===t.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");let i=Nt(e.lockTtlSeconds,wi,"Transaction lock TTL"),r=Nt(e.lockWaitMs,vi,"Transaction lock wait"),o=await ee(t.pmRoot,yi,i,t.author,!1,!1,r);try{let s=await Dt(t.pmRoot,t.transactionId);if(s===void 0)throw new u(`Transaction ${t.transactionId} was not found`,h.NOT_FOUND);if(s.status==="committed")throw new u(`Transaction ${t.transactionId} is committed and cannot be abandoned`,h.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(s.abandonment!==void 0&&s.abandonment.supersededBy!==a)throw Ei(s);if(s.status==="abandoned")return s;let d=e.resolveSteps(structuredClone(s));if(JSON.stringify(d.map(c=>c.id))!==JSON.stringify(s.stepIds))throw xi(t.transactionId);if(s.abandonment===void 0){if(a!==void 0&&await Dt(t.pmRoot,a)!==void 0)throw new u(`Replacement transaction ${a} already exists`,h.CONFLICT);s.schemaVersion=2,s.abandonment={reason:n,author:t.author,...a===void 0?{}:{supersededBy:a}},await ce(t.pmRoot,s)}return s.status!=="compensated"&&await Sn({...e,...t,steps:d},s),await Hs(s,t.pmRoot,i,r),s.status="abandoned",await ce(t.pmRoot,s),s}finally{await o()}}async function Hs(e,t,n,a){let i=Bs(e);if((await Ba(Ka(t),Ha)).some(o=>o.op==="transaction_abandon"&&o.context?.transaction_id===e.transactionId&&o.context?.attempt===e.attempt&&o.context?.plan_digest===i))return;let r=e.abandonment;await Va({pmRoot:t,author:r.author,lockTtlSeconds:n,lockWaitMs:a,op:"transaction_abandon",message:r.reason,context:{transaction_id:e.transactionId,attempt:e.attempt,plan_digest:i,...r.supersededBy===void 0?{}:{superseded_by:r.supersededBy}}})}import Ks from"node:fs/promises";import Vs 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]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function En(e){return Vs.join(e,"extension-migrations.json")}function $i(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Ii(e,t){return`${e.layer}:${e.name}:${t}`}async function Ys(e){let t=En(e);if(!await k(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await Ks.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(a=>typeof a?.key=="string"&&(a.status==="applied"||a.status==="failed")):[]}}async function Xs(e,t){let n=await Ys(e),a=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,r)=>{let o=$i(i,r),s=a.get(Ii(i,o));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function Zs(e){let t=await Xs(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),a=[],i=!1,r=e.migrations.map((l,p)=>({migration:l,index:p})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:p}of r){let m=$i(l,p),y=Ii(l,m),g=n.get(y),_=String(l.definition.status??"pending").toLowerCase(),f=g?.status??(_==="applied"||_==="failed"?_:"pending");if(f==="applied"){a.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"skipped"});continue}if(e.dryRun===!0){a.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){a.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:f}));let E={key:y,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(y,E),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,a.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"applied"}),i=!0}catch(E){let S=E instanceof Error?E.message:String(E),C={key:y,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:S};n.set(y,C),l.definition.status="failed",l.definition.reason=S,a.push({key:y,layer:l.layer,extension:l.name,id:m,before:f,outcome:"failed",error:S}),i=!0}}if(i){let l=await I(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,y)=>m.key.localeCompare(y.key))};await Se({pmRoot:e.pmRoot,filePath:En(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
3
+ `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let o=a.filter(l=>l.outcome==="pending").length,s=a.filter(l=>l.outcome==="applied").length,d=a.filter(l=>l.outcome==="skipped").length,c=a.filter(l=>l.outcome==="failed").length;return{ok:c===0,dry_run:e.dryRun===!0,state_path:En(e.pmRoot),total:a.length,pending_count:o,applied_count:s,skipped_count:d,failed_count:c,migrations:a}}async function Ai(e){let t=await I(e.resolvedRoots.settings_root),n=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),a=await xe(n);e.warnings.push(...n.warnings,...a.warnings);let i=await Zs({pmRoot:e.resolvedRoots.pm_root,migrations:a.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:a.failed.length},i.ok)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var Qs=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Ge(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(At(t.extensionName));for(let f of t.extensionNames??[])n.add(At(f));let a=f=>n.size===0||n.has(At(f)),i=(f,w)=>Ti(f.filter(v=>a(v.name)).map(w)),r=(f,w)=>Ti(f.filter(v=>a(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:d,preflight:c,services:l,renderers:p,hooks:m}=e,y=r(o.relationship_kinds??[],f=>f.definitions.map(w=>w.kind)),g=p.overrides.filter(f=>a(f.name)&&((f.commands?.length??0)>0||f.resultDiscriminator!==void 0)).map(f=>({format:f.format,commands:[...f.commands??[]],result_discriminator:f.resultDiscriminator!==void 0})).sort((f,w)=>f.format.localeCompare(w.format)),_=i(o.assurance_providers??[],f=>f.definition.id);return{capabilities:za(e,t),commands:i(o.commands,f=>f.command),command_overrides:i(s.overrides,f=>f.command),command_handlers:i(s.handlers,f=>f.command),hooks:Qs.filter(([f])=>m[f].some(w=>a(w.name))).map(([,f])=>f),flag_commands:i(o.flags,f=>f.target_command),item_types:r(o.item_types,f=>f.types.map(w=>w.name)),item_fields:r(o.item_fields,f=>f.fields.map(w=>w.name)),...y.length>0?{relationship_kinds:y}:{},migrations:r(o.migrations,f=>typeof f.definition.id=="string"?[f.definition.id]:[]),profiles:i(o.profiles,f=>f.profile.name),importers:i(o.importers,f=>f.importer),exporters:i(o.exporters,f=>f.exporter),search_providers:i(o.search_providers,f=>f.definition.name),vector_store_adapters:i(o.vector_store_adapters,f=>f.definition.name),..._.length>0?{assurance_providers:_}:{},parser_overrides:i(d.overrides,f=>f.command),service_overrides:i(l.overrides,f=>f.service),renderer_overrides:i(p.overrides,f=>f.format),...g.length>0?{renderer_ownership:g}:{},preflight_overrides:c.overrides.filter(f=>a(f.name)).length,preflight_ownership:c.overrides.filter(f=>a(f.name)).map(f=>({commands:[...f.commands??[]]}))}}function Ti(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var rt={type:"string",minLength:1,maxLength:128,pattern:"\\S"},jt={type:"array",minItems:1,maxItems:cn,items:rt},Oi={...jt,items:{...rt,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},ec={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,jt])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:rt,id:rt}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Oi}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:jt}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Oi,authors:jt}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:cn,items:{type:"array",minItems:2,maxItems:2,items:rt}}}}]}}},Qu={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:wa,items:ec}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function af(e,t,n,a){let i=await $e(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Ci(i,t,n,a)}function tc(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Ci(e,t,n=5,a=!1){let i=[],r=new Map,o=e.policies.filter(f=>f.rule.kind==="require_fields"),s=o.filter(f=>f.subject?.operations===void 0),d=new Set,c=0,l=0,p=0,m=0,y=0,g=ka(e);for(let f of t){let w=g({operation:"",author:"",before:f,after:f,completeness_only:!0});c+=+(w.decisions.length>0),l+=w.decisions.length,w.decisions.forEach(S=>d.add(S.policy_id));let v=w.decisions.filter(S=>!S.satisfied);if(v.length===0)continue;m+=1;let E=r.get(f.type)??{items:0,violations:0,missing_fields:0};E.items+=1;for(let S of v)p+=1,E.violations+=1,E.missing_fields+=S.missing_fields.length,S.effect==="refuse"&&(y+=1),i.length<n&&i.push({id:f.id,type:f.type,status:f.status,decision:S});r.set(f.type,E)}let _=a||y>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:_,ok:_==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:d.size,requirement_application_count:l,governed_items:c,ungoverned_items:t.length-c,contract_status:tc(o.length,t.length,c),applied_policy_ids:[...d].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:d.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:p,refused_violations:y,missing_by_type:Object.fromEntries(r),violations:i,violations_truncated:i.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...a?["validate_completeness_source_incomplete"]:[]]}}import nc 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]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function ac(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function Ni(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new u("Policy definition must be valid JSON.",h.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new u("Policy definition must be an object.",h.USAGE);return t}async function ic(e,t){let n=F(process.cwd(),e.path);await ze(n);let a=await I(n);return{pmRoot:n,settings:a,author:q(t,a.author_default)}}function Ri(e,t,n,a){if(e==="policy-mode")return ln({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let r=dn(a.definition),o=ln({...n,policies:[...i,r].sort((s,d)=>s.id.localeCompare(d.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
4
+ `)>ni)throw new u("Policy registry exceeds its byte ceiling.",h.USAGE);return o}async function Pi(e,t,n,a){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:Ri(e,t,await $e(a.pmRoot),n)};let i=await Ya({pmRoot:a.pmRoot,filePath:nc.join(a.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:a.author,message:n.message,lockTtlSeconds:a.settings.locks.ttl_seconds,lockWaitMs:a.settings.locks.wait_ms,mutate(r){let o=Ri(e,t,ai(r),n);return{raw:`${JSON.stringify(o,null,2)}
5
+ `,result:o}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function rc(e,t,n){let a,i=await ci({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:a}),async mutate(r){let o=(await $e(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!o||o.rule.kind!=="approval")throw new u("--policy must name an approval rule.",h.USAGE);if(!o.rule.authors.includes(n.author))throw new u("This actor is not a declared approver.",h.CONFLICT);return await ii(n.pmRoot,r.metadata.id),a={policy_id:o.id,policy_fingerprint:va(o),content_fingerprint:ba(o,{...r.metadata,body:r.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...a,warnings:i.warnings}}}function oc(e,t){let n=Ni(t),a=dn({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==a.id)throw new u("Policy id operand does not match definition.id.",h.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return a}async function bf(e,t,n={},a={}){if(!St.includes(e))throw new u("Unknown workflow policy action.",h.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:ac()};let i=await ic(a,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await $e(i.pmRoot)};if(e==="policy-put"){let l=oc(t,n.definition);return Pi(e,l.id,{...n,definition:l},i)}if(!t?.trim())throw new u(`schema ${e} requires an operand.`,h.USAGE);if(["policy-remove","policy-mode"].includes(e))return Pi(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new u("Use policy-check to preview; policy-approve records an approval.",h.USAGE);return rc(t,n,i)}let r=W(i.settings,J()),o=await Ot(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,r.type_to_folder);if(!o)throw new u(`Item ${t} not found.`,h.NOT_FOUND);let{document:s}=await Ct(o,{schema:i.settings.schema}),d={...s.metadata,body:s.body},c=n.definition===void 0?d:{...d,...Ni(n.definition)};if(c.id!==d.id)throw new u("Policy preview cannot change the item id.",h.USAGE);return{policy_result:!0,action:e,changed:!1,result:await ri(i.pmRoot,await $e(i.pmRoot),{operation:"update",author:i.author,before:d,after:c,completeness_only:n.definition===void 0})}}import{createHash as Ki}from"node:crypto";import Ke 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]="1abceae0-299e-5fff-aa8c-46c015115571")}catch{}})();var sc=new Set(pn),cc=new Set(mn),Di=new Set([...ga.filter(e=>e!=="severity"),"id","title","type","status","priority","tags","assignee","parent","description","body","created_at","updated_at","closed_at","completed_at","author","deadline","estimate","sprint","release","risk","confidence","reviewer","resolution","expected","actual"]),dc=["create","update"];function Mi(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function ji(e){return e.replaceAll("_","-")}function lc(e,t){let n=new Set;for(let a of e){let i=Mi(a);i.length>0&&i!==t&&n.add(i)}return[...n].sort((a,i)=>a.localeCompare(i))}function pc(e){let t=new Set;for(let n of e??[]){let a=n.trim();a.length>0&&t.add(a)}return[...t].sort((n,a)=>n.localeCompare(a))}function mc(e){let t=new Set,n=[];for(let a of e??[]){let i=a.trim().toLowerCase();if(i.length!==0){if(!cc.has(i))throw new Error(`Invalid field command "${a}". Allowed: ${mn.join(", ")}.`);t.has(i)||(t.add(i),n.push(i))}}return e===void 0||n.length===0?[...dc]:n}function Ui(e){let t=A(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(t.includes(","))throw new Error(`Field key "${t}" must not contain commas: commas separate field names in list flags such as --unset and --fields.`);if(Di.has(t))throw new Error(`Cannot define custom field "${t}": custom schema field "${t}" collides with built-in item metadata "${t}". Rename the custom field with a project-specific prefix. Reserved fields: ${[...Di].sort((p,m)=>p.localeCompare(m)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!sc.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${pn.join(", ")}.`);let a=n,i=mc(e.commands),r=Mi(e.cliFlag),o=r.length>0&&r!==ji(t)?r:void 0,s=o??ji(t),d=lc(e.aliases??[],s),c=[s,...d].find(p=>p.includes(","));if(c!==void 0)throw new Error(`Field flag "${c}" must not contain commas.`);let l=e.description?.trim();return{key:t,type:a,commands:i,description:l&&l.length>0?l:void 0,cliFlag:o,cliAliases:d,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:pc(e.requiredTypes)}}function uc(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function fc(e){let t=uc(e);if(!t)return[];let n=[];for(let a of t){if(typeof a!="object"||a===null||Array.isArray(a))continue;let i=a;typeof i.key!="string"||i.key.trim().length===0||n.push(i)}return n}function Je(e){if(e==null||e.trim().length===0)return{fields:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/fields.json contains invalid JSON.")}return{fields:fc(t)}}function qe(e){return`${JSON.stringify({fields:e.fields},null,2)}
6
+ `}function zi(e,t){let n=e.fields.find(o=>A(o.key)===t.key),a=n!==void 0,i=e.fields.filter(o=>A(o.key)!==t.key),r={...n,key:t.key,type:t.type,commands:[...t.commands]};return Li(r,"description",t.description),Li(r,"cli_flag",t.cliFlag),t.cliAliases.length>0?r.cli_aliases=[...t.cliAliases]:delete r.cli_aliases,Fi(r,"required",t.required),Fi(r,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?r.allow_unset=!1:delete r.allow_unset,t.requiredTypes.length>0?r.required_types=[...t.requiredTypes]:delete r.required_types,i.push(r),i.sort((o,s)=>A(o.key).localeCompare(A(s.key))),{file:{fields:i},definition:r,replaced:a}}function Gi(e,t){let n=A(t);if(n.length===0)throw new Error("Field key must not be empty.");let a=[],i=e.fields.filter(r=>A(r.key)===n?(a.push(r),!1):!0);return a.length===0?{file:{fields:i},removed:!1}:{file:{fields:i},removed:!0,definition:a[0]}}function Li(e,t,n){let a=e;n!==void 0&&n.length>0?a[t]=n:delete a[t]}function Fi(e,t,n){let a=e;n?a[t]=!0:delete a[t]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1e4c04e-0ade-5d24-95e3-b8dca3832c5a")}catch{}})();var hc=new Set($t),je=new Set(Ja.map(e=>A(e.id)).filter(e=>e.length>0));function gc(e){let t=new Set;for(let n of e){let a=A(n);a.length>0&&t.add(a)}return[...t].sort((n,a)=>n.localeCompare(a))}function Ji(e){let t=A(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(je.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...je].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let o=new Set;for(let s of e.roles){let d=typeof s=="string"?s.trim().toLowerCase():"";if(d.length!==0){if(!hc.has(d))throw new Error(`Invalid status role "${s}". Allowed roles: ${$t.join(", ")}.`);o.has(d)||(o.add(d),n.push(d))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${$t.join(", ")}.`)}let a=e.aliases===void 0?void 0:gc(e.aliases).filter(o=>o!==t),i=e.description?.trim(),r=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:a,description:i&&i.length>0?i:void 0,order:r}}function yc(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function _c(e){let t=yc(e);if(!t)return[];let n=[];for(let a of t){if(typeof a!="object"||a===null||Array.isArray(a))continue;let i=a;typeof i.id!="string"||i.id.trim().length===0||n.push(i)}return n}function We(e){if(e==null||e.trim().length===0)return{statuses:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/statuses.json contains invalid JSON.")}return{statuses:_c(t)}}function Be(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
7
+ `}function qi(e,t,n){let a=e.statuses.slice(),i=a.findIndex(s=>A(s.id)===t.id),r=i>=0?a[i]:n,o={...r,id:t.id};return t.roles!==void 0&&(t.roles.length>0?o.roles=[...t.roles]:o.roles!==void 0&&delete o.roles),t.aliases!==void 0&&(t.aliases.length>0?o.aliases=[...t.aliases]:o.aliases!==void 0&&delete o.aliases),t.description!==void 0&&(o.description=t.description),t.order!==void 0&&(o.order=t.order),i>=0?a[i]=o:a.push(o),{file:{statuses:a},definition:o,replaced:r!==void 0}}function Wi(e,t){let n=A(t);if(n.length===0)throw new Error("Status id must not be empty.");if(je.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...je].join(", ")}.`);let a=e.statuses.slice(),i=a.findIndex(o=>A(o.id)===n);if(i<0)return{file:{statuses:a},removed:!1};let[r]=a.splice(i,1);return{file:{statuses:a},removed:!0,definition:r}}function $n(e,t){let n=[e.id,...e.aliases??[]];for(let a of n){let i=A(a);if(i.length===0)continue;let r=t.get(i);if(r!==void 0&&r!==e.id)throw new Error(`Status token "${i}" already belongs to status "${r}". Choose a different id/alias to avoid shadowing it.`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="09d88765-6283-5287-b293-43300251833f")}catch{}})();function ye(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Vi(e){let t=ye(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Yi(e,t){let n=An(e),a=ye(t,"migrationScope");return`auto-${Ki("sha256").update(JSON.stringify({scope:a,request:n})).digest("hex").slice(0,20)}`}function An(e){let t=e.kind==="rename-type"?{kind:e.kind,from:ye(e.from,"source"),to:ye(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:A(ye(e.from,"source")),to:A(ye(e.to,"target")),...e.type===void 0?{}:{type:ye(e.type,"type")}}:{kind:e.kind,from:A(ye(e.from,"source")),to:A(ye(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function wc(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function vc(e,t,n){let a=K(t.schema),i=wc(n);return Q(e,a.files[i],V[i])}function Xi(e,t){return Ve.join(e,"transactions","schema",`${t}-plan.json`)}function Lt(e){return e.length===0?null:JSON.parse(e)}async function He(e){let t=await M(e);return{exists:t!==null,raw:t??""}}async function Zi(e,t){t.exists?await ue(e,t.raw):await Ke.rm(e,{force:!0})}function bc(e,t,n){let a=ae(e),i=a.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),r=a.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(r>=0)return se(a);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);a.definitions.push({...a.definitions[i],name:t.to})}else i>=0&&a.definitions.splice(i,1);return se(a)}function kc(e,t,n){let a=Je(e),i=a.fields.findIndex(o=>o.key===t.from),r=a.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(r>=0)return qe(a);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=a.fields[i];a.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&a.fields.splice(i,1);return qe(a)}function xc(e,t,n){let a=We(e),i=a.statuses.findIndex(o=>o.id===t.from),r=a.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(r>=0)return Be(a);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);a.statuses.push({...a.statuses[i],id:t.to})}else i>=0&&a.statuses.splice(i,1);return Be(a)}function Sc(e,t,n){return t.kind==="rename-type"?bc(e,t,n):t.kind==="rename-field"?kc(e,t,n):xc(e,t,n)}function Ie(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Tn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Ye(e){return Array.isArray(e)?e.map(t=>Tn(t)).filter(t=>t!==void 0):[]}function Ec(e,t){for(let n of Ye(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(a=>Ie(a,t)));for(let n of Ye(e.type_workflows))n.type=Ie(n.type,t)}function $c(e,t){for(let a of Ye(e.definitions))a.default_status=Ie(a.default_status,t);let n=Tn(e.workflow);if(n)for(let[a,i]of Object.entries(n))n[a]=Ie(i,t);for(let a of Ye(e.type_workflows))Array.isArray(a.allowed_transitions)&&(a.allowed_transitions=a.allowed_transitions.map(i=>Array.isArray(i)?i.map(r=>Ie(r,t)):i))}function Ic(e,t){for(let n of Ye(e.definitions)){for(let a of["required_create_fields","required_create_repeatables"])Array.isArray(n[a])&&(n[a]=n[a].map(i=>Ie(i,t)));for(let a of["options","command_option_policies"])for(let i of Ye(n[a])){let r=a==="options"?"key":"option";i[r]=Ie(i[r],t)}}}function Ac(e,t){let n=Tn(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let a=t.kind==="rename-type"?"type":"status";n[a]=Ie(n[a],t)}function In(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let a=n;return t.kind==="rename-type"?Ec(a,t):t.kind==="rename-field"?Ic(a,t):$c(a,t),Ac(a,t),`${JSON.stringify(a,null,2)}
8
+ `}function Qi(e,t){if(t.kind==="rename-type"){let a=ae(e).definitions;return{source:a.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:a.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let a=Je(e).fields;return{source:a.some(i=>i.key===t.from),target:a.some(i=>i.key===t.to)}}let n=We(e).statuses;return{source:n.some(a=>a.id===t.from),target:n.some(a=>a.id===t.to)}}function Tc(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function Oc(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function er(e,t){let n=An(t.request),a=t.migrationId===void 0?Yi(n,t.migrationScope??"plan"):Vi(t.migrationId),i=e.map(d=>Oc(d,n)).filter(d=>d!==null).sort((d,c)=>d.id.localeCompare(c.id)),r=Ki("sha256").update(JSON.stringify({migrationId:a,request:n,items:i})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(d=>d.trim()).filter(d=>d.length>0)),s=i.filter(d=>!o.has(d.id));return Object.freeze({migration_id:a,request:n,fingerprint:r,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function Cc(e){let t=W(e.settings,J()),n=[...new Set(Object.values(t.type_to_folder))],a=await si(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},r=a?await oi({pmRoot:e.pmRoot,expectedSourceCursor:a.source_cursor,query:i}):null;return r?{items:r.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Ne(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Rc(e,t){let n=await M(Xi(e,t));if(n===null)return null;try{let a=JSON.parse(n);if(a.schema_version!==1||a.plan.migration_id!==t||!Array.isArray(a.plan.items))throw new TypeError("invalid plan envelope");return a.plan}catch(a){throw new u(`Stored schema migration plan "${t}" is invalid: ${Oa(a)}`,h.GENERIC_FAILURE)}}async function Pc(e,t){let n=Xi(e,t.migration_id);await Ke.mkdir(Ve.dirname(n),{recursive:!0});let a={schema_version:1,plan:t,created_at:new Date().toISOString()};await ue(n,`${JSON.stringify(a,null,2)}
9
+ `)}function Nc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Dc(e){let t=await Ot(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new u(`Schema migration item "${e.id}" no longer exists.`,h.NOT_FOUND);return(await Ct(t,{schema:e.settings.schema})).document.metadata}function Bi(e,t,n){let a=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==a.toLowerCase())throw new TypeError(`Schema migration expected type "${a}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==a.toLowerCase())throw new TypeError(`Schema migration expected status "${a}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let r=e.metadata;if(Object.prototype.hasOwnProperty.call(r,i)&&!Object.prototype.hasOwnProperty.call(r,a))return[];if(!Object.prototype.hasOwnProperty.call(r,a)||Object.prototype.hasOwnProperty.call(r,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return r[i]=r[a],delete r[a],[a,i]}function Hi(e){return{id:e.id,inspect:async()=>{let t=await He(e.filePath),n=Qi(t.raw,e.request),a=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:a?"applied":"pending",...a?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await He(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await He(e.filePath);return await ue(e.filePath,Sc(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await Zi(e.filePath,{exists:t.exists,raw:t.raw})}}}function jc(e){return{id:e.stepId,inspect:async()=>{let t=await He(e.filePath);return{state:In(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await He(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await He(e.filePath);return await ue(e.filePath,In(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await Zi(e.filePath,{exists:t.exists,raw:t.raw})}}}function Lc(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await I(e.pmRoot),n=W(t,J()).type_to_folder,a=await Dc({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=Tc(a,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await I(e.pmRoot),n=W(t,J()).type_to_folder,a=await gn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:Bi(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:a.changedFields}},compensate:async()=>{let t=await I(e.pmRoot),n=W(t,J()).type_to_folder;await gn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(a){return{changedFields:Bi(a,e.request,"reverse")}}})}}}async function Fc(e){let t=await Rc(e.pmRoot,e.migrationId);if(t){if(!Nc(t.request,e.request))throw new u(`Schema migration id "${e.migrationId}" already belongs to a different request.`,h.CONFLICT);return{plan:t,stored:!0}}let n=await Cc({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...er(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Mc(e){let t=Qi(await M(e.schemaPath)??"",e.request);if(!t.source)throw new u(`Schema migration source "${e.request.from}" is not a custom definition.`,h.NOT_FOUND);if(t.target)throw new u(`Schema migration target "${e.request.to}" already exists.`,h.CONFLICT);await Pc(e.pmRoot,e.plan)}async function Uc(e){let t=K(e.settings.schema),n=[...new Set([["types",V.types],["fields",V.fields],["workflows",V.workflows]].map(([i,r])=>Q(e.pmRoot,t.files[i],r)).filter(i=>i!==e.schemaPath))];try{let i=Ve.join(e.pmRoot,"templates"),r=await Ke.readdir(i,{withFileTypes:!0});n.push(...r.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>Ve.join(i,o.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!ve(i))throw i}n.sort((i,r)=>i.localeCompare(r));let a=[];for(let i of n){let r=await M(i);r!==null&&In(r,e.request)!==r&&a.push({filePath:i,beforeRaw:r})}return{paths:n,snapshots:a}}async function zc(e){for(let t of e.snapshots){let n=await Ke.readFile(t.filePath,"utf8"),a=Ve.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await fn({pmRoot:e.pmRoot,author:e.author,documentPath:a,before:Lt(t.beforeRaw),after:Lt(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${a}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function Gc(e,t,n){let a=An(e),i=F(process.cwd(),n.path);await ze(i);let r=t.migrationId===void 0?Yi(a,await Ke.realpath(i)):Vi(t.migrationId),o=await I(i),s=q(t.author,o.author_default),d=await Fc({pmRoot:i,settings:o,migrationId:r,request:a}),c=d.plan;if(t.dryRun===!0)return{...c,action:a.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=vc(i,o,a),p=await M(l)??"";d.stored||await Mc({pmRoot:i,schemaPath:l,request:a,plan:c});let m=await Uc({pmRoot:i,schemaPath:l,settings:o,request:a}),y=[Hi({id:"stage-schema",filePath:l,request:a,phase:"stage"}),...m.paths.map((w,v)=>jc({filePath:w,request:a,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...c.items.map(w=>Lc({pmRoot:i,id:w.id,request:a,author:s,force:t.force===!0})),Hi({id:"retire-source",filePath:l,request:a,phase:"retire"})],g=await Si({pmRoot:i,transactionId:`schema-${r}`,author:s,steps:y,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),_=await Ke.readFile(l,"utf8"),{historyPath:f}=await fn({pmRoot:i,author:s,documentPath:Ve.relative(i,l).replaceAll("\\","/"),before:Lt(p),after:Lt(_),op:"schema_migration",idempotencyKey:`${c.migration_id}:${c.fingerprint}`,message:`${a.kind}: ${a.from} -> ${a.to}; affected=${c.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await zc({pmRoot:i,author:s,settings:o,request:a,plan:c,snapshots:m.snapshots}),{...c,action:a.kind,applied:!0,recovered:g.recovered,migrated_item_count:c.affected_item_count,workspace_history_path:f}}function Jc(e){let t=e.applied?"applied":"dry-run",n=e.recovered?" (recovered)":"";return[`${e.action}: ${e.request.from} -> ${e.request.to} [${t}${n}]`,`migration_id: ${e.migration_id}`,`affected: ${e.affected_item_count}`,`pending: ${e.pending_item_count}`,`fingerprint: ${e.fingerprint}`].join(`
10
+ `)}import ar from"node:fs/promises";import Le 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]="74b72dd8-0877-55a4-9c80-d043f19e1f96")}catch{}})();var Ft=["extensions","docs","examples","assets","prompts"],qc=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 Wc(e){return Ft.includes(e)}function Bc(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],a=[];for(let i of n){if(typeof i!="string"||i.trim().length===0)throw new u(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);a.push(i.trim())}return[...new Set(a)].sort((i,r)=>i.localeCompare(r))}function Hc(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new u("Package manifest field pm must be an object.",h.USAGE);let t={},n=e;for(let[a,i]of Object.entries(n)){if(!Wc(a))continue;let r=Bc(a,i);r.length>0&&(t[a]=r)}return t}function de(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function On(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 tr(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 Kc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:de(t,"docs"),npm:de(t,"npm"),repository:de(t,"repository"),report:de(t,"report")};return Object.values(n).some(a=>typeof a=="string")?n:void 0}function Vc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:de(t,"image"),video:de(t,"video")};return Object.values(n).some(a=>typeof a=="string")?n:void 0}function Yc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:de(t,"display_name")??de(t,"displayName"),category:de(t,"category"),summary:de(t,"summary"),links:Kc(t.links),media:Vc(t.media),tags:On(t.tags)};return Object.values(n).some(a=>a!==void 0)?n:void 0}async function ot(e){let t=Le.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await ar.readFile(t,"utf8"))}catch(s){throw new u(`Failed to parse package manifest at "${t}": ${String(s)}`,h.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new u(`Package manifest at "${t}" must be a JSON object.`,h.USAGE);let a=n,i=a.pm,r=i!=null,o=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};return{source:r?"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:On(a.keywords),package_homepage:typeof a.homepage=="string"?a.homepage:void 0,package_repository_url:tr(a.repository),package_bugs_url:tr(a.bugs),aliases:On(o.aliases),resources:Hc(i),catalog:Yc(o.catalog)}}async function nr(e){if(!await k(e))return[];let t=await ar.readdir(e,{withFileTypes:!0}),n=[];for(let a of t){if(!a.isDirectory())continue;let i=Le.join(e,a.name);await k(Le.join(i,"manifest.json"))&&n.push(i)}return n.sort((a,i)=>a.localeCompare(i))}async function Mt(e){if(await k(Le.join(e,"manifest.json")))return[e];let t=(await ot(e)).resources.extensions??[],n=new Set;for(let a of t){if(a.includes("*")||a.startsWith("!"))throw new u(`Package extension entry "${a}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let i=Le.resolve(e,a);if(!H(e,i))throw new u(`Package extension entry "${a}" resolves outside package root.`,h.USAGE);if(await k(Le.join(i,"manifest.json"))){n.add(i);continue}for(let r of await nr(i))n.add(r)}if(t.length===0)for(let a of qc.extensions)for(let i of await nr(Le.join(e,a)))n.add(i);return[...n].sort((a,i)=>a.localeCompare(i))}import{execFile as yd}from"node:child_process";import R from"node:fs/promises";import Mn from"node:os";import $ from"node:path";import{fileURLToPath as _d}from"node:url";import{promisify as wd}from"node:util";import vd from"npm-package-arg";import{extract as bd,list as kd}from"tar";import sd from"node:fs/promises";import ie from"node:path";import ir from"node:fs/promises";import Cn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cf5a9e7-4a66-5e72-80a2-f8a9b5b6e412")}catch{}})();function Z(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function b(e){return e.trim().toLowerCase()}function Ut(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 i=t.slice(n,a);if(i.length===0)throw new u("Extension manifest name must resolve to a non-empty directory name.",h.USAGE);if(i==="."||i==="..")throw new u('Extension manifest name must not resolve to "." or "..".',h.USAGE);return i}function Rn(e){return La(e)}async function Xc(e){try{let t=JSON.parse(await ir.readFile(Cn.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 Zc(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new u(`Extension entry file is missing at "${t}".`,h.USAGE);let a=await Xc(n.source_root),i=a.package_name?`pm package install npm:${a.package_name}`:void 0,r=n.source_input??n.source_root;return new u(`Extension entry "${e.entry}" is absent from GitHub source "${r}". pm package install copies GitHub repositories without running package scripts${a.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,h.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm package install ${n.source_root}`]:[`pm package install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm package install npm:<package-name>."],recovery:{attempted_command:`pm install ${r}`,normalized_args:["install",r],...i?{next_best_command:i}:{}}})}async function Xe(e,t={}){let n=Cn.join(e,"manifest.json");if(!await k(n))throw new u(`Extension manifest is missing at "${n}".`,h.USAGE);let a;try{a=JSON.parse(await ir.readFile(n,"utf8"))}catch(o){throw new u(`Failed to parse extension manifest at "${n}": ${Qc(o)}`,h.USAGE)}let i=Rn(a);if(!i)throw new u(`Extension manifest at "${n}" is invalid.`,h.USAGE);let r=Cn.resolve(e,i.entry);if(!H(e,r))throw new u(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,h.USAGE);if(!await k(r))throw await Zc(i,r,t);if(!await Ma(e,r))throw new u(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,h.USAGE);return{directory:e,manifest_path:n,entry_path:r,manifest:i}}function Qc(e){return e instanceof Error?e.message:String(e)}import Pn from"node:fs/promises";import ed 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]="5181479f-469f-525b-add2-914a9934afbd")}catch{}})();var td=".managed-extensions.json",zt=1;function st(e){return ed.join(e,td)}function nd(){return{version:zt,updated_at:T(),entries:[]}}function ct(e){return[...e].sort((t,n)=>{let a=t.scope.localeCompare(n.scope);if(a!==0)return a;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function rr(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function Y(e){return typeof e=="string"?e:void 0}function ad(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function id(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:Y(t.name),package:Y(t.package),version:Y(t.version),repository:Y(t.repository),owner:Y(t.owner),repo:Y(t.repo),ref:Y(t.ref),subpath:Y(t.subpath),commit:Y(t.commit)}}function rd(e){if(typeof e!="object"||e===null)return null;let t=e;if(!ad(t))return null;let n=id(t.source);if(!n)return null;let a=Pa(t.contributions);return a===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Z(t.capabilities),contributions:a,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Y(t.last_update_check_at),last_update_remote_commit:Y(t.last_update_remote_commit),last_update_remote_version:Y(t.last_update_remote_version),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:Y(t.update_error)}}function od(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==zt||!Array.isArray(t.entries))return null;let n=[];for(let a of t.entries){let i=rd(a);i&&n.push(i)}return{version:zt,updated_at:Y(t.updated_at)??T(),entries:ct(n)}}async function le(e){let t=st(e),n=nd();try{let a=await Pn.readFile(t,"utf8"),i=JSON.parse(a),r=od(i);if(!r)throw new u(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:r,warnings:[]}}catch(a){if(a instanceof u)throw a;if(typeof a=="object"&&a!==null&&"code"in a&&ve(a))return{path:t,state:n,warnings:[]};throw new u(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}async function Ze(e,t){let n=st(e),a={version:zt,updated_at:T(),entries:ct(t.entries)};await Pn.mkdir(e,{recursive:!0}),await Pn.writeFile(n,`${JSON.stringify(a,null,2)}
11
+ `,"utf8")}function dt(e,t){let n=e.entries.filter(a=>b(a.name)!==b(t.name)&&b(a.directory)!==b(t.directory));return n.push(t),{...e,updated_at:T(),entries:ct(n)}}async function or(e,t,n,a){let i=t.entries.find(o=>b(o.name)===b(n));if(!i)return t;let r=dt(t,{...i,contributions:a});return await Ze(e,r),r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var cd="PM_CLI_PACKAGE_ROOT",sr={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},dd=new Set(["*","all"]);function Nn(){let e=[],t=process.env[cd];return typeof t=="string"&&t.trim().length>0&&e.push(ie.resolve(t.trim())),e.push(be(import.meta.url,["../../.."])),[...new Set(e)]}async function lt(e){let t=e.trim().toLowerCase(),n=await dr(t);if(n)return n;let a=sr[t];if(!a)return null;for(let i of Nn()){let r=ie.join(i,".agents","pm","extensions",a.legacy_extension_directory);if(await k(ie.join(r,"manifest.json")))return r}return null}function cr(e){return dd.has(e.trim().toLowerCase())}function ld(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function pd(e,t){let n=await sd.readdir(e,{withFileTypes:!0});for(let a of n){if(!a.isDirectory()||!a.name.startsWith("pm-"))continue;let i=ie.join(e,a.name);if(!await k(ie.join(i,"package.json")))continue;let r=await ot(i),o=r.aliases&&r.aliases.length>0?r.aliases:[ld(a.name)];for(let s of o){let d=s.trim().toLowerCase();d.length===0||t.has(d)||t.set(d,{alias:d,package_directory:a.name,package_root:i,package_name:r.package_name??null})}}}async function Dn(){let e=new Map;for(let t of Nn()){let n=ie.join(t,"packages");await k(n)&&await pd(n,e)}for(let[t,n]of Object.entries(sr))if(!e.has(t))for(let a of Nn()){let i=ie.join(a,"packages",n.package_directory);if(await k(ie.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Gt(){return(await Dn()).map(e=>e.alias)}async function dr(e){let t=e.trim().toLowerCase();return(await Dn()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function lr(e){let t=await dr(e);return t?(await ot(t)).package_name??null:null}async function pr(e){let t=await lt(e);if(!t)return null;try{let n=await Mt(t);return n.length!==1?null:(await Xe(n[0])).manifest.name}catch{return null}}function md(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function ud(e,t,n,a,i,r){let o=a==="global"?"--global":"--project",s=Object.fromEntries(Ft.filter(d=>d!=="extensions").map(d=>[d,e.resources[d]??[]]).filter(([,d])=>Array.isArray(d)&&d.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(d=>i.has(d))||r.has(ie.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:md(e),media:e.catalog?.media}}}async function mr(e,t,n={}){let a=It(F(process.cwd(),t.path),process.cwd()),i=e==="global"?a.global:a.project,r=await le(i),o=new Set(r.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>ie.resolve(m.source.location))),s=new Set(r.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),d=[],c=new Map;for(let m of await Dn()){let y=ie.resolve(m.package_root),g=c.get(y)??[];g.push(m),c.set(y,g)}for(let m of c.values()){let y=m[0],g=m.map(f=>f.alias).sort((f,w)=>f.localeCompare(w)),_=await ot(y.package_root);d.push(ud(_,y,g,e,s,o))}let l=hd(n.fields),p=l?d.map(m=>gd(m,l)):d;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Ft.filter(m=>m!=="extensions"),packages:p}}var fd=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function hd(e){if(e===void 0)return;let t=li(e);if(t.length===0)throw new u("Package catalog --fields requires a comma-separated list of field names",h.USAGE);let n=t.filter(a=>!fd.has(a));if(n.length>0)throw new u(`Unknown package catalog --fields value(s): ${n.join(", ")}`,h.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function gd(e,t){let n={};for(let a of t)a==="category"?n[a]=e.catalog?.category??null:a==="display_name"?n[a]=e.catalog?.display_name??null:n[a]=e[a]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fc993281-a2a0-59e8-9f4a-e520f1b94f3b")}catch{}})();var fr=wd(yd),qt="@unbrained/pm-cli",xd={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},jn;async function hr(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let a=$.resolve(t);for(;;){let i=$.join(a,"node_modules",...n.split("/")),r=$.join(i,"package.json");if(await k(r))try{let s=JSON.parse(await R.readFile(r,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let o=$.dirname(a);if(o===a)return null;a=o}}function Ln(e,t,n){let a=e.split("/").map(c=>c.trim()).filter(c=>c.length>0);if(a.length<2)return null;let i=a[0],r=a[1].replace(/\.git$/i,"");if(i.length===0||r.length===0)return null;let o=a.slice(2),s,d;return o[0]==="tree"&&o.length>=2?(s=o[1],d=o.slice(2).join("/")):o.length>0&&(d=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:r,repository:`https://github.com/${i}/${r}.git`,ref:s,subpath:d&&d.length>0?d:void 0}}function Sd(e,t,n){let a=e.slice(4).trim();if(a.length===0)throw new u('npm package source must include a package spec after "npm:".',h.USAGE);if(t)throw new u('Options "--gh/--github" cannot be combined with npm: package sources.',h.USAGE);if(n)throw new u('Option "--ref" cannot be combined with npm: package sources.',h.USAGE);return{kind:"npm",input:e,spec:a}}function pt(e,t={}){let n=e.trim();if(n.length===0)throw new u("Extension source is required for --install.",h.USAGE);let a=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Sd(n,t.forceGithub===!0,a);let i=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return Ln(s,n,a)}catch{return null}})();if(i)return i;let r=n.startsWith("github.com/")?n.slice(11):null;if(r){let o=Ln(r,n,a);if(!o)throw new u(`Invalid GitHub source "${n}".`,h.USAGE);return o}if(t.forceGithub){let o=Ln(n,n,a);if(!o)throw new u(`Invalid GitHub shorthand "${n}".`,h.USAGE);return o}if(/^https?:\/\//i.test(n))throw new u(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,h.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function Jt(e,t=fr,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(a){let i=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr):"",r=i.trim().length>0?i.trim():a instanceof Error?a.message:String(a);throw new u(`Git command failed: git ${e.join(" ")}
12
+ ${r}`,h.GENERIC_FAILURE)}}function Un(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function zn(e=process.platform){return e==="win32"}async function gr(e,t,n=fr,a=process.platform,i=process.env){let r=Un(a),o=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));o.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(r,e,{cwd:t,encoding:"utf8",env:o,shell:zn(a)})).stdout??"").trim()}catch(s){let d=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",c=d.trim().length>0?d.trim():s instanceof Error?s.message:String(s);throw new u(`npm command failed: ${r} ${e.join(" ")}
13
+ ${c}`,h.GENERIC_FAILURE)}}function yr(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function _r(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function Ed(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("npm err! code e404")||t.includes("404 not found")||t.includes("is not in this registry")}function $d(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return Ed(e)||t.includes("not found")}function Id(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Ad(e){let t=yr(e),n=Id(t),a=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${a}`:void 0,r=i?`pm package install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:r?[r,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:r?[`Try ${r} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&r?{fallback_candidates:[{source:i,command:r,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:r}:{}}}}}function Td(e,t){if(!$d(t))return null;let n=Ad(e);return new u(n.message,h.NOT_FOUND,n.context)}async function wr(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await k(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=_d(t);return await k(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await k(t))return t}return null}async function Od(e){let t=await wr(e);if(t)return t;let n=Cd(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Cd(e,t=process.cwd()){let n="@file:",a=e.lastIndexOf(n);if(!_r(e))return e;let i=e.slice(0,a),r=e.slice(a+n.length);if(r.startsWith("//")&&!r.startsWith("///"))return e;if(!r.startsWith("/"))return`${i}@${$.resolve(t,r)}`;let o;try{o=decodeURIComponent(new URL(`file:${r}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${i}@${s}`}function ur(e,t){let n=$.resolve(e,t),a=$.relative(e,n);if(a.length===0||a===".."||a.startsWith(`..${$.sep}`)||$.isAbsolute(a))throw new u("npm pack reported a package archive outside its isolated destination.",h.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function Rd(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function Pd(e){return(Array.isArray(e)?e.map(t=>({value:t})):typeof e=="object"&&e!==null?Object.entries(e).map(([t,n])=>({key:t,value:n})):[]).flatMap(({key:t,value:n})=>{let a=Rd(n,t);return a?[a]:[]})}function Nd(e,t){let n=t?.trim().toLowerCase(),a=n?e.filter(o=>{let s=o.name?.trim().toLowerCase();return s!==void 0?s===n:o.key?.trim().toLowerCase()===n}):[];if(a.length===1)return a[0];if(e.length!==1)return;let i=e[0],r=i.name??i.key;return n&&r!==void 0&&r.trim().toLowerCase()!==n?void 0:i}function Dd(e,t,n){let a;try{a=JSON.parse(e)}catch{let o=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!o)throw new u("npm pack did not report a tarball filename.",h.GENERIC_FAILURE);return{tarball:ur(t,o)}}let i=Pd(a),r=Nd(i,n);if(!r)throw new u("npm pack --json returned an unsupported or ambiguous package receipt.",h.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:ur(t,r.filename),package:r.name??r.key,version:r.version}}async function jd(e){return Ld(e,gr)}async function Ld(e,t){let n=await wr(e.spec);if(n){if((await R.stat(n)).isFile()&&vr(n))return Fn(n);let r=$.join(n,"package.json"),o=await k(r)?JSON.parse(await R.readFile(r,"utf8")):{};return{directory:await Wt(n,e.input),package:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,cleanup:async()=>{}}}let a=await R.mkdtemp($.join(Mn.tmpdir(),"pm-npm-package-source-")),i=$.join(a,"pack");await R.mkdir(i,{recursive:!0});try{let r=await Od(e.spec),o=await t(["pack",r,"--json","--pack-destination",i]),s=Dd(o,i,_r(e.spec)?void 0:yr(e.spec));if(!await k(s.tarball))throw new u("npm pack did not create its reported package archive.",h.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let d=await Fn(s.tarball);return{directory:d.directory,package:s.package??d.package,version:s.version??d.version,cleanup:async()=>{try{await d.cleanup()}finally{await R.rm(a,{recursive:!0,force:!0})}}}}catch(r){throw await R.rm(a,{recursive:!0,force:!0}),Td(e.spec,r)||r}}function vr(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function _e(e){throw new u(e,h.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function Fd(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&_e(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let a=e.path,i=a.split("/");(a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||i.some(r=>r===".."))&&_e(`Local package archive contains an escaping path: "${a}".`),i[0]!=="package"&&_e(`Local package archive entry "${a}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&_e(`Local package archive link "${a}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&_e(`Local package archive entry "${a}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&_e(`Local package archive entry "${a}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&_e(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),a==="package/package.json"&&(n.packageJsonEntries+=1)}async function Fn(e,t=xd){(await R.stat(e)).size>t.maxArchiveBytes&&_e(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await R.mkdtemp($.join(Mn.tmpdir(),"pm-local-package-archive-")),a=$.join(n,"extract");await R.mkdir(a,{recursive:!0});let i={entries:0,expandedBytes:0,packageJsonEntries:0},r;try{if(await kd({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:c=>{if(r===void 0)try{Fd(c,t,i)}catch(l){r=l}}}),r!==void 0)throw r;i.packageJsonEntries!==1&&_e(`Local package archive must contain exactly one package/package.json entry; found ${i.packageJsonEntries}.`),await bd({file:e,cwd:a,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let o=$.join(a,"package"),s=$.join(o,"package.json"),d=JSON.parse(await R.readFile(s,"utf8"));return await Md(o),{directory:await Wt(o,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await R.rm(n,{recursive:!0,force:!0})}}}catch(o){throw await R.rm(n,{recursive:!0,force:!0}),o}}async function Md(e,t=gr){let n=$.join(e,"package.json");if(!await k(n))return;let a;try{a=JSON.parse(await R.readFile(n,"utf8"))}catch{return}if(typeof a!="object"||a===null)return;let i=a,r=Wd(i),o=Ud(i);if(r.length===0&&!o)return;let s={...a};delete s.devDependencies;let d={...s};zd(d),await R.writeFile(n,`${JSON.stringify(d,null,2)}
14
+ `,"utf8");try{await Promise.all([R.rm($.join(e,"package-lock.json"),{force:!0}),R.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),r.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await Gd(e)}finally{await R.writeFile(n,`${JSON.stringify(s,null,2)}
15
+ `,"utf8")}}function Ud(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&qt in t)return!0;return!1}function zd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let a={...n};delete a[qt],Object.keys(a).length===0?delete e[t]:e[t]=a}}async function Gd(e){let t=be(import.meta.url,["../../.."]),[n,a]=qt.split("/"),i=$.join(e,"node_modules",n),r=$.join(i,a);await R.mkdir(i,{recursive:!0}),await R.rm(r,{recursive:!0,force:!0}),await R.symlink(t,r,Jd(process.platform))}function Jd(e){return e==="win32"?"junction":"dir"}function qd(e,t){if(e.startsWith("-"))throw new u(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,h.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(n=>{let a=n.charCodeAt(0);return a<=31||a===127||"&|;()`\"'".includes(n)}))throw new u(`Extension runtime dependency "${e}" has an unsafe version specifier.`,h.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{vd.resolve(e,t)}catch{throw new u(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,h.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function Wd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[a,i]of Object.entries(n)){if(a===qt||typeof i!="string"||i.trim().length===0||t.has(a))continue;let r=i.trim();t.set(a,qd(a,r))}return[...t.values()]}async function Wt(e,t){let n=await Mt(e);if(n.length===1)return n[0];if(n.length>1){let a=n.map(i=>$.relative(e,i).replaceAll($.sep,"/")).sort((i,r)=>i.localeCompare(r));throw new u(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${a.join(", ")}`,h.USAGE)}throw new u(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,h.USAGE)}async function Bd(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push($.posix.join(".agents/pm/extensions",t.subpath)),n.push($.posix.join(".custom/pm-extensions",t.subpath)),n.push($.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let r=$.resolve(e,i);if(H(e,r)&&await k($.join(r,"manifest.json")))return{directory:r,resolved_subpath:i}}if(await k($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let a=await Wt(e,t.input);return{directory:a,resolved_subpath:$.relative(e,a).replaceAll($.sep,"/")}}function Hd(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function Kd(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Hd(n))return new u(t,h.NOT_FOUND);let a=[];try{let r=process.env.PM_CLI_PACKAGE_ROOT,o=typeof r=="string"&&r.trim().length>0?$.resolve(r.trim()):"";jn?.key!==o&&(jn={key:o,aliases:await Gt()}),a=jn.aliases}catch{}let i=[`Retry with pm package install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${a.join(", ")}`];return new u(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,h.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm package install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm package install npm:${n}`}})}async function br(e){if(e.kind==="local"){let a;try{a=await R.stat(e.absolute_path)}catch{throw await Kd(e)}if(a.isFile()&&vr(e.absolute_path)){let r=await Fn(e.absolute_path);return{source:e,directory:r.directory,source_root:$.dirname(r.directory),resolved_subpath:$.relative($.dirname(r.directory),r.directory).replaceAll($.sep,"/"),npm_package:r.package,npm_version:r.version,cleanup:r.cleanup}}if(!a.isDirectory())throw new u(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let i=await Wt(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let a=await jd(e);return{source:e,directory:a.directory,source_root:$.dirname(a.directory),cleanup:a.cleanup,resolved_subpath:$.relative($.dirname(a.directory),a.directory).replaceAll($.sep,"/"),npm_package:a.package,npm_version:a.version}}let t=await R.mkdtemp($.join(Mn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Jt(n);let a=await Jt(["-C",t,"rev-parse","HEAD"]),i=await Bd(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:a,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(a){throw await R.rm(t,{recursive:!0,force:!0}),a}}async function Qe(e,t){if(!await k(e)||!await k(t))return!1;let[n,a]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===a}import mt from"node:fs/promises";import ut 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]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var Gn=1,Fe="2026.6.24",Vd=">=22.18.0",Yd={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},kr=new Set([...Sa.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(xa).map(e=>e.toLowerCase()),"scaffold"]),Xd="^6.0.0",Zd="^22.0.0",Er=["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."," }"," }","}",""],pe=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function xr(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function $r(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 Ir(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 Qd={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Sr=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Ar={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"]},el={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"]'},tl={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."},nl={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."},Tr="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",al={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},il={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."]},rl={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`."]},ol={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 Or(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 Cr(e,t){return e==="schema"?rl[t]:e==="profile"?ol[t]:il[t]}function sl(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(o=>o.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),a=0;for(;t[a]?.toLowerCase()==="starter";)a+=1;let i=t[a]?.toLowerCase(),r=a>0&&(a===t.length||i!==void 0&&kr.has(i));return`${(kr.has(n)||r?["starter",...t]:t).join(" ")} ping`}function Rr(e){let t=e,n=`${e}s`,a=e.replace(/-/g,""),i=a===t?[]:[a],r=`${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(i)},`,` 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(r)},`,' 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 cl(e,t,n){let a=`${e}-search`,i=`${e}-vector`,r=`${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(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,d=`${e}s`,c=e.replace(/-/g,""),l=c===s?[]:[c],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(d)},`,` 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({",...Rr(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(r)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} 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(r)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} 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) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...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 dl(e,t,n){let a=n==="hooks",i=n==="search",r=n==="importers",o=n==="schema",s=n==="profile",d=n==="renderers",c=n==="parser",l=n==="preflight",p=n==="services",m=el[n],y=e,g=`${e}s`,_=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=a?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],E=i?Jn(e,t,"search",m):[],S=r?Jn(e,t,"importers",m):[],C=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 {",...xr($r({extensionName:e,itemTypeName:y,itemTypeFolder:g,fieldName:_,migrationId:f,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],ne=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 {",...xr(Ir(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});",""]:[],j=d?[`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;",...pe,"});",""]:[],x=c?[`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;",...pe,"});",""]:[],G=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;",...pe,"});",""]:[],nt=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;",...pe,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Er,`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)},`,...c?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe,"});","",...v,...E,...S,...C,...ne,...j,...x,...G,...nt,`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(`
16
+ `)}function ll(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 pl={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"},ml={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 ul(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 fl(e,t,n){let a=[],i=[...ul(e,t,n)],r=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,d=`${e.replace(/-/g," ")} items`,c=e,l=`${e}s`,p=e.replace(/-/g,""),m=p===c?[]:[p],y=`${e.replace(/-/g,"_")}_note`,g=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":a.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),r.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":a.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(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 }),","});"),r.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":a.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),r.push(" importers: ["," {",` name: ${JSON.stringify(d)},`," importer,"," options: {",` action: ${JSON.stringify(`${d} 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(d)},`," exporter,"," options: {",` action: ${JSON.stringify(`${d} 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"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(y)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(c)},`," // 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(g)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),r.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":a.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...Rr(e),"});"),r.push(" profiles: [starterProfile],");break;case"renderers":a.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),r.push(" renderers: { toon: toonRenderer },");break;case"parser":a.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),r.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":a.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),r.push(" preflights: [preflightOverride],");break;case"services":a.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),r.push(" services: { output_format: outputService },");break}return{builderImports:a,definitions:i,blueprintFields:r}}function hl(e,t,n){let a=fl(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...a.builderImports].sort((i,r)=>i.localeCompare(r)).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(`
17
+ `)}function Jn(e,t,n,a){if(n==="commands")return[];let i=`${e}-search`,r=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,d=`${e}s`,c=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${a},`," });"],m=y=>[...p," let deactivated = false;"," try {",...y.map(g=>g===""?g:` ${g}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...pe];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(r)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(r)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(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($r({extensionName:e,itemTypeName:s,itemTypeFolder:d,fieldName:c,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Ir(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 gl(e,t,n){let a=n==="parser",i=JSON.stringify([...Ar[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" };',"",...Er,`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(Fe)},`," },",` target: { pmVersion: ${JSON.stringify(Fe)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...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;",...pe,"});","",...Jn(e,t,n,i)].join(`
18
+ `)}function yl(e,t,n){let a=Or(n,"package"),i=Cr(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 (${pl[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`.",Tr,"- `.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 ${ml[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Gn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Fe}\`. 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(`
19
+ `)}function _l(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function wl(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function vl(e,t,n,a){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(a.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(a.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(a.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(a.itemTypeName)},`,` folder: ${JSON.stringify(a.itemTypeFolder)},`,` aliases: ${JSON.stringify(a.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(a.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(a.itemTypeName)}, folder: ${JSON.stringify(a.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function bl(e,t,n){let a=[];return t==="renderers"&&a.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&a.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&a.push(" api.registerPreflight(preflightOverride);"),t==="services"&&a.push(' api.registerService("output_format", outputService);'),t==="hooks"&&a.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&a.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&a.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&a.push(" api.registerProfile(starterProfile);"),t==="importers"&&a.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),a}function kl(e,t,n,a="commands",i=!1){let r=`pm-${e}`,o=Ar[a],s=ll(e,t,a),d=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Gn,pm_min_version:Fe,trusted:!0,sandbox_profile:"strict",permissions:{...Yd},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
20
+ `,c=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...cl(e,t,a),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
21
+ `),l=`${JSON.stringify(Qd,null,2)}
22
+ `,p=tl[a],m=Or(a,"package"),y=`${JSON.stringify({name:r,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Vd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Fe}`},devDependencies:{"@types/node":Zd,typescript:Xd},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
23
+ `,g=dl(e,t,a),_=nl[a],f=["node_modules/","*.log","*.tsbuildinfo",""].join(`
24
+ `),w=_l(e),v=["```ts",`import { ${wl(a)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...vl(e,t,a,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...bl(t,a,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],E=[`# ${r}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,p,_,Tr,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...v,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...al[a],...Cr(a,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Fe}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Gn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Fe}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
25
+ `);return{"package.json":y,"manifest.json":d,"index.ts":i?hl(e,t,a):c,"index.test.ts":i?gl(e,t,a):g,"tsconfig.json":l,".gitignore":f,"README.md":i?yl(r,t,a):E}}async function Pr(e,t="extension",n="commands",a=!1){let i=n.trim().toLowerCase();if(!Sr.includes(i))throw new u(`Unknown scaffold capability "${n}". Supported capabilities: ${Sr.join(", ")}.`,h.USAGE);let r=i;if(a&&t!=="package")throw new u("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",h.USAGE);let o=a?"declarative":"imperative",s=e.trim(),d=ut.resolve(process.cwd(),s),c=Ut(ut.basename(d)).replace(/^(?:pm-)+/u,""),l=sl(c),p=kl(c,l,t,r,a),m=!1;if(await k(d)){if(!(await mt.stat(d)).isDirectory())throw new u(`Scaffold target "${d}" exists and is not a directory.`,h.CONFLICT)}else await mt.mkdir(d,{recursive:!0}),m=!0;for(let[g,_]of Object.entries(p)){let f=ut.join(d,g);if(await k(f)&&await mt.readFile(f,"utf8")!==_)throw new u(`Scaffold file "${g}" already exists with different content in "${d}". Choose a new target path or remove conflicting files.`,h.CONFLICT)}let y=[];for(let[g,_]of Object.entries(p)){let f=ut.join(d,g);if(await k(f)){y.push({path:g,status:"unchanged"});continue}await mt.mkdir(ut.dirname(f),{recursive:!0}),await mt.writeFile(f,_,"utf8"),y.push({path:g,status:"created"})}return{extension_name:c,package_name:`pm-${c}`,command_name:l,invocation_command:`pm ${l}`,capability:r,style:o,target_path:d,created_directory:m,files:y}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3984f1ef-1703-5a83-a4fa-ec1cdc738572")}catch{}})();var Nr=[["commands","Commands"],["command_overrides","Command overrides"],["flag_commands","Flag commands"],["item_types","Item types"],["item_fields","Item fields"],["migrations","Migrations"],["profiles","Profiles"],["importers","Importers"],["exporters","Exporters"],["search_providers","Search providers"],["vector_store_adapters","Vector store adapters"],["assurance_providers","Assurance measurement providers"],["hooks","Lifecycle hooks"],["parser_overrides","Parser overrides"],["service_overrides","Service overrides"],["renderer_overrides","Renderer overrides"]];function qn(e){return"#".repeat(e)}function Dr(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let r of e)n=r==="`"?n+1:0,t=Math.max(t,n);let a="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${a}${i}${e}${i}${a}`}function xl(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(Dr).join(", ")}`}function Sl(e,t,n){let a=[`${qn(t)} ${e}`,""];return n.length===0?(a.push("_None._",""),a):(a.push(...n.map(i=>`- ${Dr(i)}`),""),a)}function El(e,t,n){return e===0&&!n?[]:[`${qn(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function Wn(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<1||n>6)throw new RangeError(`headingLevel must be an integer in [1, 6], received ${String(t.headingLevel)}`);let a=Math.min(n+1,6),i=t.includeEmpty===!0,r=t.title??"Extension surfaces",o=[`${qn(n)} ${r}`,""];(i||e.capabilities.length>0)&&o.push(xl(e.capabilities),"");for(let[s,d]of Nr){let c=e[s]??[];c.length===0&&!i||o.push(...Sl(d,a,c))}return o.push(...El(e.preflight_overrides,a,i)),!(e.preflight_overrides>0||Nr.some(([s])=>(e[s]?.length??0)>0))&&!i&&o.push("_This extension registers no surfaces._",""),`${o.join(`
26
26
  `).trimEnd()}
27
- `}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function Nr(e,t){return`${e}:${b(t)}`}function xl(e,t){let n=[];for(let[a,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let r=new Map;for(let o of i){let s=r.get(o.command)??[];r.set(o.command,[...s,o])}for(let[o,s]of r){if(t!==null&&!s.some(d=>t.has(b(d.name))))continue;let c=s.at(-1);n.push({command:o,surface:a,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((a,i)=>a.command.localeCompare(i.command)||a.surface.localeCompare(i.surface))}function Dr(e,t,n){let a=new Set(n.failed.map(d=>Nr(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:a.has(Nr(d.layer,d.name))?"failed":"ok",surfaces:ze(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:ze(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),r=typeof e=="string"?b(e):null,o=r===null?null:new Set(t.loaded.filter(d=>b(d.name)===r||typeof d.source_package=="string"&&b(d.source_package)===r||(d.source_aliases??[]).some(l=>b(l)===r)).map(d=>b(d.name)).concat(r)),s=o===null?i:i.filter(d=>o.has(b(d.name))),c=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:ze(n,c),command_ownership:xl(n,o)}}var Sl={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function dg(e,t){let n=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(n.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),n.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){n.push("## Command ownership","");for(let a of e.command_ownership){let i=a.claimants.find(o=>o.winner),r=a.claimants.map(o=>`${o.layer}:${o.name}`).join(", ");n.push(`- \`${a.command}\` (${a.surface}): ${i.layer}:${i.name}; policy=${a.policy}; collision=${String(a.collision)}; claimants=${r}`)}n.push("")}if(e.extensions.length===0)return n.push(`_No ${t}s are loaded._`,""),`${n.join(`
27
+ `}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function jr(e,t){return`${e}:${b(t)}`}function $l(e,t){let n=[];for(let[a,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let r=new Map;for(let o of i){let s=r.get(o.command)??[];r.set(o.command,[...s,o])}for(let[o,s]of r){if(t!==null&&!s.some(c=>t.has(b(c.name))))continue;let d=s.at(-1);n.push({command:o,surface:a,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(c=>({name:c.name,layer:c.layer,winner:c===d}))})}}return n.sort((a,i)=>a.command.localeCompare(i.command)||a.surface.localeCompare(i.surface))}function Lr(e,t,n){let a=new Set(n.failed.map(c=>jr(c.layer,c.name))),i=[...t.loaded.map(c=>({name:c.name,layer:c.layer,version:c.version,activation_status:a.has(jr(c.layer,c.name))?"failed":"ok",surfaces:Ge(n,{extensionName:c.name})})),...t.failed.map(c=>({name:c.name,layer:c.layer,version:"unknown",activation_status:"not_loaded",surfaces:Ge(n,{extensionName:c.name})}))].sort((c,l)=>c.name.localeCompare(l.name)||c.layer.localeCompare(l.layer)),r=typeof e=="string"?b(e):null,o=r===null?null:new Set(t.loaded.filter(c=>b(c.name)===r||typeof c.source_package=="string"&&b(c.source_package)===r||(c.source_aliases??[]).some(l=>b(l)===r)).map(c=>b(c.name)).concat(r)),s=o===null?i:i.filter(c=>o.has(b(c.name))),d=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Ge(n,d),command_ownership:$l(n,o)}}var Il={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function hg(e,t){let n=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(n.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),n.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){n.push("## Command ownership","");for(let a of e.command_ownership){let i=a.claimants.find(o=>o.winner),r=a.claimants.map(o=>`${o.layer}:${o.name}`).join(", ");n.push(`- \`${a.command}\` (${a.surface}): ${i.layer}:${i.name}; policy=${a.policy}; collision=${String(a.collision)}; claimants=${r}`)}n.push("")}if(e.extensions.length===0)return n.push(`_No ${t}s are loaded._`,""),`${n.join(`
28
28
  `).trimEnd()}
29
- `;for(let a of e.extensions){let i=`${a.name} (${a.layer} v${a.version}, ${Sl[a.activation_status]})`;n.push(qn(a.surfaces,{title:i,headingLevel:2}))}return e.extensions.length>1&&n.push(qn(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${n.join(`
29
+ `;for(let a of e.extensions){let i=`${a.name} (${a.layer} v${a.version}, ${Il[a.activation_status]})`;n.push(Wn(a.surfaces,{title:i,headingLevel:2}))}return e.extensions.length>1&&n.push(Wn(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${n.join(`
30
30
  `).trimEnd()}
31
- `}import Ht from"node:fs/promises";import Bt from"node:path";import jr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function ut(e,t,n,a){let i=jr.relative(e,n);if(i!==""&&!H(e,n)||n===t||H(t,n))return!1;let r=i.split(jr.sep);return r.includes(".git")?!1:a?!r.some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as El}from"node:crypto";import L from"node:fs/promises";import $l from"node:os";import N from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var Lr=3,Il=120,Fr=250,Al=12e4,Tl=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Mr=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Ur=e=>Tl.has(String(Mr(e))),Wt=(e,t)=>Mr(e)===t,zr=e=>new Promise(t=>{setTimeout(t,e)}),Gr=async e=>{let t=N.join(e,"package.json");await k(t)||await L.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
32
- `,"utf8")},Jr=async e=>{let t=ve(import.meta.url,["../../.."]),n=N.join(e,"node_modules","@unbrained"),a=N.join(n,"pm-cli");await L.mkdir(n,{recursive:!0}),await L.rm(a,{recursive:!0,force:!0}),await L.symlink(t,a,process.platform==="win32"?"junction":"dir")},ft=async e=>{let t=N.resolve(e),n=N.dirname(t),a=N.parse(n).root,i=await L.realpath(a).catch(()=>a),r=N.relative(a,n),o=r===""?[]:r.split(N.sep);for(let[s,c]of o.entries()){let d=N.join(i,c);try{i=await L.realpath(d)}catch{i=N.join(i,...o.slice(s));break}}return N.join(i,N.basename(t))},qr=async(e,t,n,a=$l.tmpdir())=>Ce("extension_install_copy",async()=>{let i=N.resolve(e),r=await L.realpath(i).catch(()=>i),o=await ft(t);if(r===o)return;if(!H(r,o)){await n(r,t,{recursive:!0,force:!0,filter:p=>ut(r,o,N.resolve(p),!1)});return}let s=await L.realpath(N.resolve(a)).catch(()=>ft(a)),c=H(r,s)?N.dirname(r):s;if(H(r,c))throw new u(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,h.USAGE,{code:"extension_install_source_contains_destination"});let d=await L.mkdtemp(N.join(c,"pm-extension-copy-")),l=N.join(d,"extension");try{await n(r,l,{recursive:!0,force:!0,filter:p=>ut(r,o,N.resolve(p),!0)}),await n(l,t,{recursive:!0,force:!0})}finally{await L.rm(d,{recursive:!0,force:!0})}}),Wr=async(e,t,n=L.cp)=>{for(let a=1;a<=Lr;a+=1)try{await Ce("extension_install_copy",async()=>{await L.rm(t,{recursive:!0,force:!0}),await qr(e,t,n)});return}catch(i){if(!Ur(i)||a===Lr)throw i;await zr(Fr)}},Wn=async e=>{let t;try{t=await L.readFile(N.join(e,"owner.json"),"utf8")}catch(i){if(!St(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let a=n.token;return typeof a=="string"&&a.length>0?a:null},Br=async(e,t)=>await Wn(e)!==t?!1:(await L.rm(e,{recursive:!0,force:!0}),!0),Ol=async(e,t)=>{let n;try{n=await L.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let a=await Wn(e);return a===null?(await L.rm(e,{recursive:!0,force:!0}),!0):Br(e,a)},Cl=(e,t,n)=>{let a=Promise.resolve(),i=setInterval(()=>{a=a.then(async()=>{if(await Wn(e)!==t)return;let r=new Date;await L.utimes(e,r,r)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await a}},Rl=async(e,t)=>{await L.mkdir(e);try{await L.writeFile(N.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
33
- `,"utf8")}catch(n){throw await L.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Pl=async(e,t,n,a,i)=>{for(let r=1;r<=n;r+=1)try{return await Rl(e,t),!0}catch(o){if(!Wt(o,"EEXIST"))throw o;await Ol(e,i)?r-=1:await zr(a)}return!1},Bn=async(e,t,n,a)=>Ce("extension_install",async()=>{let i=N.join(e,"runtime","extension-install-locks"),r=N.join(i,"scope.lock");await L.mkdir(i,{recursive:!0});let{attempts:o=Il,delay_ms:s=Fr,stale_ms:c=Al,heartbeat_ms:d}=a??{};if(![o,s,c,d].filter(w=>w!==void 0).every(Number.isFinite))throw new u("Extension install lock timings must be finite numbers.",h.USAGE);let l=Math.max(1,Math.floor(o)),p=Math.max(0,Math.floor(s)),m=Math.floor(c),y=Math.floor(d??m/3);if(m<=0||y<=0||y>=m)throw new u("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",h.USAGE);let g={pid:process.pid,token:El(),created_at:T(),destination:t};if(!await Pl(r,g,l,p,m))throw new u(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let _=Cl(r,g.token,y),f=!1;try{let w=await n();return f=!0,w}finally{await _(),await Br(r,g.token).catch(w=>{if(f)throw w})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var Nl=new Set(["node_modules",".git","dist","build","coverage"]);async function Hr(e,t,n,a){let i=e.source.kind==="local"?await Ht.stat(e.source.absolute_path):void 0,r=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,o=await Dl(e.directory,t,a),s={source_mode:r,...r==="archive"?{archive_bytes:i.size}:{},copy:o},c=e.source_root??e.directory;if(r==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await k(Bt.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),r==="directory"&&!o.complete){let d=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new u(`Local extension source scan stopped at ${d}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,h.USAGE,{code:"extension_install_incomplete_source_scan",reason:o.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function Dl(e,t,n={}){let{maxEntries:a=1e4,maxDepth:i=64,signal:r}=n;if(![a,i].every(p=>Number.isSafeInteger(p)&&p>0))throw new u("maxEntries and maxDepth must be positive safe integers.",h.USAGE);r?.throwIfAborted();let o=await Ht.realpath(e),s=await ft(t),c=await Ze(o,s);r?.throwIfAborted();let d=c?"in_place":H(o,s)?"nested_filtered_snapshot":"directory_snapshot",l={copy_scope:d,source_directory:o,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:a,max_depth:i};return d==="in_place"||await Kr(o,0,l,r),l}async function Kr(e,t,n,a){a?.throwIfAborted();let i=await Ht.opendir(e);for await(let r of i){if(a?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=Bt.join(e,r.name);if(!ut(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(Bt.relative(n.source_directory,o).split(Bt.sep).some(s=>Nl.has(s))&&(n.development_entries+=1),await jl(o,t,n,a),!n.complete)return}}async function jl(e,t,n,a){let i=await Ht.lstat(e);if(a?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await Kr(e,t+1,n,a)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import Ll from"node:fs/promises";import Fl from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bef4424-f5b8-511b-91f7-0b39cf11f515")}catch{}})();async function Ml(e,t){if(e.kind!=="local"||e.input.startsWith(".")||e.input.includes("\\")||e.input.includes("/")&&!/^@[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/u.test(e.input))return e;try{return await Ll.lstat(e.absolute_path),e}catch(r){if(!we(r))throw r}let n=e.input.trim(),a=t.filter(r=>r.source.kind==="npm"),i=(a.find(r=>r.name===n)??a.find(r=>r.directory===n)??a.find(r=>r.source.package===n))?.source.package;if(i===void 0)return e;try{let r=Fl(i);if(!r.registry||r.name!==i)return e}catch{return e}return lt(`npm:${i}`,{})}async function Vr(e,t,n,a=[]){let i=typeof t=="string"?null:await dt(e),r=i===null?null:e.trim().toLowerCase(),o=r===null?null:await cr(r),s=await Ml(lt(i??e,{forceGithub:typeof t=="string",ref:n}),a),c=r===null?null:await ur(e);return{bundledAliasName:r,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:r===null?s.kind:"builtin",input:r??s.input,...o===null?{}:{package:o}},ambiguous:c!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...r===null?[]:[{kind:"builtin",input:r,...o===null?{}:{package:o},command:`pm install ${r}`}],...c===null?[]:[{kind:"npm",input:`npm:${c.package}`,package:c.package,...c.version===void 0?{}:{version:c.version},directory:c.directory,command:`pm install npm:${c.package}`}]]}}}import et from"node:fs/promises";import te from"node:path";import ql from"node:path";import{mkdir as Wl}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="abb182c9-6d6c-5be4-a2ad-c91b00a098d0")}catch{}})();var ht=["agile","ops","research"],Ul={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function Kt(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${ht.join(", ")}.`)}function gt(e){return Ul[e].map(t=>at(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var zl=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Gl(e){let t=zl.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Jl(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Yr(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,a=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let c=Gl(s);if(c===void 0)continue;let d=i.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<a&&d.examples.push(s),i.set(c,d)}let r=[];for(let[o,s]of i.entries()){if(s.count<n)continue;let c=Jl(o);r.push({name:c,prefix:o,count:s.count,examples:s.examples,shadows_builtin:Ya(c)!==void 0})}return r.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var yy=[...xt,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Vt="schema-types",Xr="schema-statuses",Zr="schema-fields";function Ae(e){return xe({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function vy(e,t,n){let a=F(process.cwd(),n.path);await _e(a);let i;try{i=at({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(y){throw new u(y instanceof Error?y.message:String(y),h.USAGE)}let r=await A(a),o=K(r.schema),s=Q(a,o.files.types,V.types),c=[],d=q(t.author,r.author_default),l=fe(r),p=await ee(a,Vt,r.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),m;try{let y=await M(s),g;try{g=ae(y)}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}try{Xa(i,g);let _=new Map,f=W(r,J());for(let[w,v]of Object.entries(f.type_to_folder)){let E=v.trim().toLowerCase();E.length>0&&!_.has(E)&&_.set(E,w)}Za(i,g,_)}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}m=Me(g,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await Ae({pmRoot:a,filePath:s,raw:se(m.file),op:"schema:add-type",author:d,settings:r}),await yt(a,[m.definition],c,"schema:add-type-folder"),c.push(...await B({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await Qr(a,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Te(c),generated_at:T()}}async function _e(e){await Ue(e)}async function Qr(e,t){try{let n=await pi(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Te(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Bl(e,t,n,a){let i=W(t,J()),r=a.trim().toLowerCase();return(await Pe(e,t.item_format,i.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===r).length}async function Hl(e,t,n,a){let i=W(t,J()),r=nt(n),o=I(a);return(await Pe(e,t.item_format,i.type_to_folder,[],n)).filter(s=>{let c=typeof s.status=="string"?s.status:"";return(r.alias_to_id.get(I(c))??I(c))===o}).length}async function Kl(e,t,n,a,i){if(i.length===0||De.has(i))return;let r=await Hl(t,n,a,i);r>0&&e.push(`items_using_status:${r}`);let o=eo(a.workflow,i);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function eo(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&I(n)===t).map(([n])=>n)}async function by(e,t,n){let a=F(process.cwd(),n.path);await _e(a);let i=await A(a),r=K(i.schema),o=Q(a,r.files.types,V.types),s=[],c=q(t.author,i.author_default),d=fe(i),l=await ee(a,Vt,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),p;try{let m=await M(o),y;try{y=ae(m)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=Qa(y,e)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=(p.definition?.name??e??"").trim();if(g.length>0){let _=await Bl(a,i,r,g);_>0&&s.push(`items_using_type:${_}`)}await Ae({pmRoot:a,filePath:o,raw:se(p.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await B({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return p.removed&&await Qr(a,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:o,definitions:p.file.definitions.length},warnings:Te(s),generated_at:T()}}function Hn(e,t){return Q(e,t.files.statuses,V.statuses)}function Yt(e,t){return Q(e,t.files.fields,V.fields)}function to(e,t){return Q(e,t.files.types,V.types)}async function yt(e,t,n,a){for(let i of t){let r=Sa(i.folder??xa(i.name)),o=ql.join(e,r);await k(o)||(await Wl(o,{recursive:!0}),n.push(...await B({path:o,scope:"project",op:a})))}}function Kn(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function Vl(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Yl(e){let t=new Map;for(let n of e){let a=I(n.id);if(a.length!==0){t.set(a,a);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let r=I(i);r.length>0&&!t.has(r)&&t.set(r,a)}}}return t}async function ky(e,t,n){let a=F(process.cwd(),n.path);await _e(a);let i;try{i=zi({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}let r=await A(a),o=K(r.schema),s=Hn(a,o),c=nt(o);try{En(i,c.alias_to_id)}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}let d=Vl(c.by_id.get(i.id));if((i.roles??d?.roles??[]).length===0)throw new u(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,h.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Re(i.id)}" --role active`,`pm schema add-status "${Re(i.id)}" --role blocked`]});let l=[],p=q(t.author,r.author_default),m=fe(r),y=await ee(a,Xr,r.locks.ttl_seconds,p,!!t.force,m.force_required_for_stale_lock,r.locks.wait_ms),g;try{let _=await M(s),f;try{f=qe(_)}catch(v){throw new u(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=Yl(f.statuses);try{En(i,w)}catch(v){throw new u(v instanceof Error?v.message:String(v),h.USAGE)}g=Gi(f,i,d),await Ae({pmRoot:a,filePath:s,raw:We(g.file),op:"schema:add-status",author:p,settings:r}),l.push(...await B({path:s,scope:"project",op:"schema:add-status"}))}finally{await y()}return{action:"add-status",registered:!0,replaced:g.replaced,status:g.definition,file:{path:s,statuses:g.file.statuses.length},warnings:Te(l),generated_at:T()}}async function xy(e,t,n){let a=F(process.cwd(),n.path);await _e(a);let i=await A(a),r=K(i.schema),o=Hn(a,r),s=[],c=q(t.author,i.author_default),d=fe(i),l=await ee(a,Xr,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),p;try{let m=await M(o),y;try{y=qe(m)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=Ji(y,e)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=I(p.definition?.id??e);await Kl(s,a,i,r,g),await Ae({pmRoot:a,filePath:o,raw:We(p.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await B({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:o,statuses:p.file.statuses.length},warnings:Te(s),generated_at:T()}}function no(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function Xl(e,t,n){return{...no(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function ao(e){return{id:e.id,source:De.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function io(e,t,n){let a=e.toLowerCase();return n.has(a)?"extension":t.has(a)?"custom":"builtin"}function Zl(){let e=new Map,t=J();for(let n of t?.item_types??[]){let a=n.types;if(Array.isArray(a))for(let i of a){if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i.name;typeof r=="string"&&r.trim().length>0&&e.set(r.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function Ql(e){let t=nt(e),n=[],a=[];for(let i of t.definitions){let r=ao(i);r.source==="builtin"?n.push(r):a.push(r)}return{builtin:n,custom:a}}async function _t(e){let t=F(process.cwd(),e.path);await _e(t);let n=await A(t),a=K(n.schema),i=Q(t,a.files.types,V.types),r=Hn(t,a),o=W(n,J()),s=Zl(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:i,statusesPath:r,byType:o.by_type,customNames:c,extensionProvenance:s,schema:a}}async function Sy(e){let t=await _t(e),n=[],a=[],i=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=io(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=no(s);c==="extension"?i.push(d):c==="custom"?a.push(d):n.push(d)}let r=Ql(t.schema),o=At(t.schema).definitions.map(Kn);return{action:"list",builtin:n,custom:a,extension:i,counts:{builtin:n.length,custom:a.length,extension:i.length,total:n.length+a.length+i.length},statuses:{builtin:r.builtin,custom:r.custom,counts:{builtin:r.builtin.length,custom:r.custom.length,total:r.builtin.length+r.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:T()}}async function Ey(e,t){let n=(e??"").trim();if(n.length===0)throw new u("Type name must not be empty.",h.USAGE);let a=await _t(t),i=Object.values(a.byType).find(r=>r.name.toLowerCase()===n.toLowerCase()||r.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!i)throw new u(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Re(n)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Xl(i,io(i.name,a.customNames,new Set(a.extensionProvenance.keys())),a.extensionProvenance.get(i.name.toLowerCase())),file:{path:a.typesPath},generated_at:T()}}async function $y(e,t){let n=I(e);if(n.length===0)throw new u("Status id must not be empty.",h.USAGE);let a=await _t(t),i=nt(a.schema),r=i.alias_to_id.get(n)??n,o=i.by_id.get(r);if(!o)throw new u(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Re(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:ao(o),file:{path:a.statusesPath},generated_at:T()}}async function Iy(e,t,n){let a=F(process.cwd(),n.path);await _e(a);let i;try{i=Fi({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}let r=await A(a),o=K(r.schema),s=Yt(a,o),c=[],d=Ct(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=q(t.author,r.author_default),p=fe(r),m=await ee(a,Zr,r.locks.ttl_seconds,l,!!t.force,p.force_required_for_stale_lock,r.locks.wait_ms),y;try{let g=await M(s),_;try{_=Ge(g)}catch(f){throw new u(f instanceof Error?f.message:String(f),h.GENERIC_FAILURE)}y=Mi(_,i),await Ae({pmRoot:a,filePath:s,raw:Je(y.file),op:"schema:add-field",author:l,settings:r}),c.push(...await B({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:y.replaced,field:y.definition,file:{path:s,fields:y.file.fields.length},warnings:Te(c),generated_at:T()}}async function ep(e,t,n,a){let i=W(t,J());return(await Pe(e,t.item_format,i.type_to_folder,[],n)).filter(r=>{let o=r[a];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function Ay(e,t,n){let a=F(process.cwd(),n.path);await _e(a);let i=await A(a),r=K(i.schema),o=Yt(a,r),s=[],c=q(t.author,i.author_default),d=fe(i),l=await ee(a,Zr,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),p;try{let m=await M(o),y;try{y=Ge(m)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=Ui(y,e)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=I(p.definition?.key??e),_=I(p.definition?.metadata_key??p.definition?.front_matter_key??g);if(_.length>0){let f=await ep(a,i,r,_);f>0&&s.push(`items_using_field:${f}`)}await Ae({pmRoot:a,filePath:o,raw:Je(p.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await B({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:o,fields:p.file.fields.length},warnings:Te(s),generated_at:T()}}async function Ty(e){let t=await _t(e),n=At(t.schema).definitions.map(Kn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Yt(t.pmRoot,t.schema)},generated_at:T()}}async function Oy(e,t){let n=I(e);if(n.length===0)throw new u("Field key must not be empty.",h.USAGE);let a=await _t(t),i=At(a.schema).by_key.get(n);if(!i)throw new u(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Re(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Kn(i),file:{path:Yt(a.pmRoot,a.schema)},generated_at:T()}}async function Cy(e,t,n){let a=F(process.cwd(),n.path);await _e(a);let i;try{let _=Kt(e);if(_===void 0)throw new Error(`Type preset name is required. Allowed: ${ht.join(", ")}.`);i=_}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}let r=await A(a),o=K(r.schema),s=to(a,o),c=[],d=q(t.author,r.author_default),l=fe(r),p=[],m=[],y,g=await ee(a,Vt,r.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms);try{let _=await M(s),f;try{f=ae(_)}catch(v){throw new u(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=f;for(let v of gt(i)){let E=Me(w,v);w=E.file,(E.replaced?m:p).push(E.definition.name)}y=w.definitions.length,await Ae({pmRoot:a,filePath:s,raw:se(w),op:"schema:apply-preset",author:d,settings:r}),await yt(a,gt(i),c,"schema:apply-preset-folder"),c.push(...await B({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await g()}return{action:"apply-preset",preset:i,registered:p,replaced:m,file:{path:s,definitions:y},warnings:Te(c),generated_at:T()}}function tp(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new u("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function Ry(e,t){let n=F(process.cwd(),t.path);await _e(n);let a=await A(n),i=K(a.schema),r=to(n,i),o=tp(e.minCount),s=W(a,J()),c=(await Pe(n,a.item_format,s.type_to_folder,[],i)).map(v=>typeof v.title=="string"?v.title:""),d=Yr(c,{minCount:o}),l=[],p=[],m=[],y=[],g;if(!e.apply){let v;try{v=ae(await M(r))}catch(E){throw new u(E instanceof Error?E.message:String(E),h.GENERIC_FAILURE)}return g=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:d,registered:p,replaced:m,skipped:y,file:{path:r,definitions:g},warnings:l,generated_at:T()}}let _=q(e.author,a.author_default),f=fe(a),w=await ee(n,Vt,a.locks.ttl_seconds,_,!!e.force,f.force_required_for_stale_lock,a.locks.wait_ms);try{let v=await M(r),E;try{E=ae(v)}catch(C){throw new u(C instanceof Error?C.message:String(C),h.GENERIC_FAILURE)}let S=E;for(let C of d){if(C.shadows_builtin){y.push({name:C.name,reason:"shadows_builtin"});continue}let ne;try{ne=at({name:C.name})}catch{y.push({name:C.name,reason:"invalid_type_token"});continue}let D=Me(S,ne);S=D.file,(D.replaced?m:p).push(D.definition.name)}g=S.definitions.length,await Ae({pmRoot:n,filePath:r,raw:se(S),op:"schema:infer-types",author:_,settings:a}),await yt(n,S.definitions.filter(C=>p.includes(C.name)||m.includes(C.name)),l,"schema:infer-types-folder"),l.push(...await B({path:r,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:o,candidates:d,registered:p,replaced:m,skipped:y,file:{path:r,definitions:g},warnings:Te(l),generated_at:T()}}function Py(e){let t=e.replaced?"Updated":"Registered",n=e.type.aliases&&e.type.aliases.length>0?` (aliases: ${e.type.aliases.join(", ")})`:"";return`${t} custom item type "${e.type.name}"${n} in ${e.file.path}. Run: pm create "${Re(e.type.name)}" "<title>"`}function Ny(e){return e.removed?`Removed custom item type "${e.type?.name??"(unknown)"}" from ${e.file.path}.`:`No custom item type matched; nothing removed from ${e.file.path}.`}function Dy(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",a=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${a} in ${e.file.path}.`}function jy(e){return e.removed?`Removed custom status "${e.status?.id??"(unknown)"}" from ${e.file.path}.`:`No custom status matched; nothing removed from ${e.file.path}.`}function Ly(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,a]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])a.length!==0&&t.push(`${n}: ${a.map(i=>i.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,a]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])a.length!==0&&t.push(`${n}: ${a.map(i=>i.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(n=>`${n.key} (${n.type}, ${n.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
34
- `)}function Fy(e){let t=[`type: ${e.type.name}`,`source: ${e.type.source}`,`folder: ${e.type.folder}`];return e.type.default_status&&t.push(`default_status: ${e.type.default_status}`),e.type.aliases.length>0&&t.push(`aliases: ${e.type.aliases.join(", ")}`),e.type.description&&t.push(`description: ${e.type.description}`),e.type.options.length>0&&t.push(`options: ${e.type.options.map(n=>n.key).join(", ")}`),t.join(`
35
- `)}function My(e){let t=[`status: ${e.status.id}`,`source: ${e.status.source}`];return e.status.roles.length>0&&t.push(`roles: ${e.status.roles.join(", ")}`),e.status.aliases.length>0&&t.push(`aliases: ${e.status.aliases.join(", ")}`),e.status.description&&t.push(`description: ${e.status.description}`),typeof e.status.order=="number"&&t.push(`order: ${e.status.order}`),t.join(`
36
- `)}function np(e){let t=[];e.required&&t.push("required"),e.required_on_create&&t.push("required_on_create"),e.allow_unset||t.push("no_unset");let n=t.length>0?` [${t.join(", ")}]`:"";return`${e.key} (${e.type}) ${e.cli_flag} commands=${e.commands.join("/")}${n}`}function Uy(e){return`${e.replaced?"Updated":"Registered"} custom field "${e.field.key}" in ${e.file.path}. Use it: pm create "<title>" --${(e.field.cli_flag??e.field.key).replaceAll("_","-")} <value>`}function zy(e){return e.removed?`Removed custom field "${e.field?.key??"(unknown)"}" from ${e.file.path}.`:`No custom field matched; nothing removed from ${e.file.path}.`}function Gy(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${np(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
37
- `)}function Jy(e){let t=e.field,n=[`field: ${t.key}`,`type: ${t.type}`,`cli_flag: ${t.cli_flag}`,`commands: ${t.commands.join(", ")}`];return t.cli_aliases.length>0&&n.push(`cli_aliases: ${t.cli_aliases.join(", ")}`),t.description&&n.push(`description: ${t.description}`),t.required&&n.push("required: true"),t.required_on_create&&n.push("required_on_create: true"),t.allow_unset||n.push("allow_unset: false"),t.required_types.length>0&&n.push(`required_types: ${t.required_types.join(", ")}`),n.join(`
38
- `)}function qy(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",a=[t,n].filter(i=>i.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${a.length>0?` (${a})`:""}.`}function Wy(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;let t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(let n of e.candidates){let a=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${a}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
39
- `)}var By={workflowSlotsReferencing:eo};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a8289336-e833-5617-9a32-0a21f28f294e")}catch{}})();function ro(e){let t=/^extension_(disabled_)?pm_(min|max)_version_([a-z_]+):(project|global):([^:]+):(.+)$/u.exec(e);if(!t)return;let[,n,a,i,r,o,s]=t,c=s.split(":")[0].replace(a==="min"?"required=":"allowed=",""),d=i==="invalid"?`a valid pm_${a}_version instead of ${c}`:`pm ${a==="min"?">=":"<="} ${c}`;return n?`Package ${o} is disabled and requires ${d} before activation. After satisfying the bound, run ${oe(["package","activate",o,`--${r}`])}.`:`Package ${o} requires ${d}. Use a compatible host or package version, or keep it disabled with ${oe(["package","deactivate",o,`--${r}`])}.`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="573b0fd6-f003-55d8-8f49-c2a5e81cbc31")}catch{}})();function Vn(e){return e.map(({layer:t,name:n,error:a})=>({layer:t,name:n,error:a}))}function Xt(e,t,n){let a=b(t),i=n.trim();if(a.length===0||i.length===0)return;let r=e.get(a)??new Set;r.add(i),e.set(a,r)}function ap(e){let t=new Map,n=new Map;for(let a of e.registrations.commands)Xt(t,a.name,a.command),Xt(n,a.name,a.action);for(let a of e.commands.handlers)Xt(t,a.name,a.command);for(let a of e.commands.overrides)Xt(t,a.name,a.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function oo(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function ip(e){let{enabled:t,normalizedName:n,loadedNames:a,loadFailedNames:i,activationFailedNames:r}=e;return t?i.has(n)||r.has(n)?{runtime_active:!1,activation_status:"failed"}:a.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function Zt(e,t,n){let a=new Set(t.loaded.map(c=>b(c.name))),i=new Set(t.failed.map(c=>b(c.name))),r=new Set(n.failed.map(c=>b(c.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=ap(n);return e.map(c=>{let d=b(c.name),l=oo(o.get(d)),p=oo(s.get(d)),m={...l?{command_paths:l}:{},...p?{action_paths:p}:{}},y=ip({enabled:c.enabled,normalizedName:d,loadedNames:a,loadFailedNames:i,activationFailedNames:r});return{...c,...y,...m}})}function rp(e){let t=0,n=0,a=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(a+=1)}return{warning_count:t,violation_count:n,blocked_count:a}}function U(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var lo=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function op(e){return lo.has(go(e))}function so(e){return e==="project"||e==="global"}function po(e){let t=e.split(":"),n=t[0];if(!n||!lo.has(n))return null;let a=t.at(-4),i=t.at(-3)?.trim(),r=t.at(-2),o=t.at(-1)?.trim();return!so(a)||!so(r)||!i||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:a,name:i},displaced:{layer:r,name:o}}}function sp(e){let t=new Set;for(let n of e){let a=po(n);a&&(t.add(a.winner.name),t.add(a.displaced.name))}return[...t].sort((n,a)=>n.localeCompare(a))}function cp(e,t){let n=e.filter(op);if(n.length===0)return null;let a=sp(n);return`Extension registration collisions or handler/override overlaps detected.${a.length>0?` Conflicting extensions: ${a.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function dp(e,t,n,a){let i=t.map(p=>po(p)).filter(p=>p!==null).sort((p,m)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let r=e==="global"?"--global":"--project",o=U(a,"deactivate"),s=`${U(a,"doctor")} ${r} --detail deep --trace`,c=new Map(n.map(p=>[b(p.name),p])),d=new Map;for(let p of i)for(let m of[p.winner.name,p.displaced.name]){let y=b(m);d.set(y,(d.get(y)??0)+1)}let l=[...d.entries()].map(([p,m])=>{let y=c.get(p),g=y?.name??p,_=y?.command_paths??[],f=y?.action_paths??[];return{action:"deactivate",extension:g,command:`${o} ${g} ${r}`,affected_collisions:m,feature_loss:{command_paths:[..._].sort((w,v)=>w.localeCompare(v)),action_paths:[...f].sort((w,v)=>w.localeCompare(v))}}}).sort((p,m)=>{let y=m.affected_collisions-p.affected_collisions;if(y!==0)return y;let g=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,_=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return g!==_?g-_:p.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:d.size,next_best_command:s,collisions:i,remediation_candidates:l}}function mo(e){let t=[];for(let n of e){let a=n.error.toLowerCase();(a.includes("cannot find package '@unbrained/pm-cli'")||a.includes('cannot find module "@unbrained/pm-cli"')||a.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(a.includes("cannot use import statement outside a module")||a.includes("to load an es module")||a.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,a)=>n.localeCompare(a))}function uo(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let a of t){if(!a||typeof a.name!="string")continue;let i=a.trace?.missing_capability??a.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${a.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((a,i)=>a.localeCompare(i))}function fo(e,t){let n=[];for(let a of za(e.loaded,t))for(let i of a.unused)n.push(`extension_capability_unused:${a.layer}:${a.name}:${i}`);return[...new Set(n)].sort((a,i)=>a.localeCompare(i))}var lp=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${U(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${fa.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${U(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${U(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${U(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function pp(e){let{normalizedWarnings:t,options:n,scope:a,scopeFlag:i,updateCheckFailedTotal:r,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,p=t.map(ro).filter(y=>y!==void 0),m={options:n,scope:a,scopeFlag:i,updateCheckFailedTotal:r,policyWarningCount:o};if(t.length>0){let y=cp(t,{deactivate:`${U(n,"deactivate")} <name> ${i}`,doctor:`${U(n,"doctor")} ${i} --detail deep --trace`});y&&p.push(y);for(let g of lp)g.matches(t,m)&&p.push(g.build(m))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${U(n,"manage")} ${i} --fix-managed-state (or ${U(n,"adopt-all")} ${i}, ${U(n,"adopt")} <name> ${i}, or reinstall via ${U(n,"install")} ${i} <source>).`),d>0&&p.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${U(n,"manage")} ${i} to request update checks.`),l>0&&p.push(`Update available managed extensions via ${U(n,"install")} ${i} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${U(n,"manage")} ${i} after extension changes.`),p}function Qt(e,t,n,a={}){let i=[...new Set(t)].sort((x,G)=>x.localeCompare(G)),r=n.filter(x=>x.managed).length,o=n.filter(x=>x.enabled).length,s=n.filter(x=>x.active).length,c=n.filter(x=>x.update_check_status==="checked"&&x.update_available===!0).length,d=n.filter(x=>x.managed===!1),l=d.filter(x=>co(x)).map(x=>x.name).sort((x,G)=>x.localeCompare(G)),p=d.filter(x=>!co(x)).map(x=>x.name).sort((x,G)=>x.localeCompare(G)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let x of n)m[x.update_check_status]+=1;let y=m.failed,g=n.filter(x=>x.update_check_status==="skipped_non_github"&&x.source?.kind!=="builtin").length,_=Object.entries({skipped_unmanaged:p.length,skipped_non_github:g,failed:y,not_checked:m.not_checked}).filter(([,x])=>x>0).map(([x,G])=>`extension_update_health_partial_coverage:${x}:${G}`),f=_.length>0,w=f?"partial":"full",v=[...new Set([...i,..._])].sort((x,G)=>x.localeCompare(G)),E=[...new Set(v.map(x=>go(x)))].sort((x,G)=>x.localeCompare(G)),S=rp(v),C=e==="global"?"--global":"--project",ne=dp(e,i,n,a),D=pp({normalizedWarnings:v,options:a,scope:e,scopeFlag:C,updateCheckFailedTotal:y,policyWarningCount:S.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:g,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:E,warnings:v,policy_warning_count:S.warning_count,policy_violation_count:S.violation_count,policy_blocked_count:S.blocked_count,total_extensions:n.length,managed_total:r,enabled_total:o,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:f,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(x=>x.name).sort((x,G)=>x.localeCompare(G)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:m,update_check_failed_total:y,top_warnings:v.slice(0,8),remediation:D,...ne?{collision_plan:ne}:{}}}function ho(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new u(`Invalid --detail value "${e}". Expected summary or deep.`,h.USAGE)}function go(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function yo(e){let t=new Set,n=[];for(let a of e){let i=(()=>{let r=Na(a);return r?[r]:Da(a)})();for(let r of i){let o=`${r.layer}:${r.name}:${r.capability}`;t.has(o)||(t.add(o),n.push(r))}}return n}function _o(){return{version:kt.version,capabilities:[...kt.capabilities],legacy_aliases:{...kt.legacy_aliases}}}function co(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function wo(e,t,n,a,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let r=[...new Set(t.filter(d=>d.active).map(d=>b(d.name)))].sort((d,l)=>d.localeCompare(l)),o=[...new Set(n.filter(d=>d.layer==="project").map(d=>b(d.name)))].sort((d,l)=>d.localeCompare(l)),s=new Set(a.map(d=>b(d.name))),c=r.filter(d=>!o.includes(d)&&!s.has(d)).sort((d,l)=>d.localeCompare(l));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:r.length,loaded_project_count:o.length,active_project_names:r,loaded_project_names:o,missing_active_project_names:c}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var Yn=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let a=new Array(e.length),i=0,r=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,a[o]=await n(e[o])}});return await Promise.all(r),a};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function vo(e,t){let n=b(e),a=t.find(i=>b(i.name)===n);return{command_paths:[...a?.command_paths??[]].sort((i,r)=>i.localeCompare(r)),action_paths:[...a?.action_paths??[]].sort((i,r)=>i.localeCompare(r))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function bo(e,t){let n=new Set((t?.loaded??[]).flatMap(r=>(r.activation?.commands?.length??0)>0?[`${r.layer}:${b(r.name)}`]:[])),a=e.services.overrides.filter(r=>r.service==="output_format").filter(r=>r.passThrough!==!0).filter(r=>!n.has(`${r.layer}:${b(r.name)}`)).map(r=>`extension_output_service_override_global:${r.service}:${r.layer}:${r.name}`),i=e.renderers.overrides.filter(r=>(r.commands?.length??0)===0&&r.resultDiscriminator===void 0).map(r=>`extension_output_renderer_override_global:${r.format}:${r.layer}:${r.name}`);return[...new Set([...a,...i])].sort((r,o)=>r.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var ko=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Ct(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,a)=>a.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{execFile as mp}from"node:child_process";import{promisify as up}from"node:util";import fp from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b67e46f9-51ff-501b-98da-74353b4c66d9")}catch{}})();var hp=up(mp),So=1e4;function xo(e,t,n){if(typeof t=="string")try{let a=fp.resolve(e,t);if(a.type==="version")return a.fetchSpec}catch{}throw new Error(n)}async function gp(e,t){try{return(await hp(Mn(),e,{encoding:"utf8",timeout:t,maxBuffer:65536,shell:Un(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function Eo(e,t=gp){let n=T();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let a=xo(e.package,e.version,"missing_or_invalid_installed_npm_version"),i=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],So),r;try{r=JSON.parse(i)}catch{throw new Error("invalid_npm_registry_metadata")}let o=Array.isArray(r)&&r.length===1?r[0]:r,s=xo(e.package,o,"invalid_npm_registry_version");return{checked_at:n,available:s!==a,remote_version:s}}catch(a){return{checked_at:n,available:null,error:a instanceof Error?a.message:String(a)}}}var yp=(e,t,n)=>{let a=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c=""]=o.split(/\s+/);return{commit:s,ref:c}}),i=a.find(o=>o.ref.endsWith("^{}"))??a[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let r=t?.trim();return r?{checked_at:n,remote_commit:i.commit,available:i.commit!==r}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},Xn=async(e,t=Gt)=>{let n=T();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let a=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,a,`${a}^{}`],void 0,So);return yp(i,e.commit,n)}catch(a){return{checked_at:n,available:null,error:a instanceof Error?a.message:String(a)}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d34e2cc0-5e58-5534-8480-a9ab47ec4a88")}catch{}})();var _p=4;async function $o(e,t=!1){let n=await Yn(e.entries,_p,async a=>{if(!["github","npm"].includes(a.source.kind))return a;if(t)return{...a,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0};let i=a.source.kind==="github"?await Xn(a.source):await Eo(a.source);return{...a,last_update_check_at:i.checked_at,last_update_remote_commit:"remote_commit"in i?i.remote_commit:void 0,last_update_remote_version:"remote_version"in i?i.remote_version:void 0,update_available:i.available,update_error:i.error}});return{...e,entries:st(n)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17cca82e-e9f9-5633-8d91-bc6c2b560d5f")}catch{}})();function Io(e,t){let n=e.filter(a=>a.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:a,result:i})=>{let r=i.details;return{alias:a,ok:i.ok,extension:r.extension,source:r.source,source_resolution:r.source_resolution,install_plan:r.install_plan,dry_run:r.dry_run,destination_path:r.destination_path,activated:r.activated,settings_changed:r.settings_changed,previous_state_preserved:r.previous_state_preserved,rollback:r.rollback,command_paths:r.command_paths,action_paths:r.action_paths,command_discovery:r.command_discovery,verification:r.verification,runtime_activation_status:r.runtime_activation_status,activation_diagnostics:r.activation_diagnostics,warnings:i.warnings}})}}import wp from"node:fs/promises";import vp 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]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function bp(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function kp(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function xp(e){let t=vp.join(e,"manifest.json"),n;try{n=await wp.readFile(t,"utf8")}catch(s){if(St(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let a;try{a=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof a!="object"||a===null||Array.isArray(a))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=a,r=La(i),o=bp(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:r.findings,warnings:r.findings.map(s=>kp(o,s)),remediation:r.findings.map(s=>s.message)}}function Ao(e){return xp(Ea(e))}import re from"node:fs/promises";import Qe 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]="7c06c702-29ea-5552-aadc-52dfc9c238ef")}catch{}})();var Zn=async e=>re.readFile(e).catch(t=>{if(Wt(t,"ENOENT"))return null;throw t}),Sp=async(e,t,n,a,i)=>Ce("extension_install_backup",async()=>{let r=ot(e),o=Ia(t),[s,c]=await Promise.all([Zn(r),Zn(o)]);return a&&await re.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:a,managedStatePath:r,managedStateContents:s,settingsPath:o,settingsContents:c}}),To=async e=>Ce("extension_install_rollback",async()=>{await re.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await re.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])if(n===null)await re.rm(t,{force:!0});else if(t===e.settingsPath){let a=Qe.dirname(e.settingsPath),i=await A(a);try{await xe({pmRoot:a,filePath:t,raw:n.toString("utf8"),op:"extension:install:rollback",author:q(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms})}finally{ei(a)}}else await re.mkdir(Qe.dirname(t),{recursive:!0}),await re.writeFile(t,n)});async function Oo(e,t){let n=await k(e.destinationDirectory),a=await Ze(e.sourceDirectory,e.destinationDirectory);await re.mkdir(e.selectedRoot,{recursive:!0});let i=Qe.join(Qe.dirname(e.selectedRoot),"runtime","extension-installs");await re.mkdir(i,{recursive:!0});let r=await re.mkdtemp(Qe.join(i,".pm-extension-install-backup-")),o=Qe.join(r,"destination"),s=["package","install",o,`--${e.scope}`],c=oe(s),d=!1;try{let l=await Sp(e.selectedRoot,e.settingsRoot,e.destinationDirectory,n,o),p;try{p=await t()}catch(m){try{await To(l)}catch(y){d=!0;let g=new u(`Extension install failed: ${String(m)}; rollback failed: ${String(y)}`,h.GENERIC_FAILURE,{code:"extension_install_rollback_failed",original_code:m instanceof u?m.code:void 0,required:"Restore the previous package before retrying the replacement. Previous state was not preserved.",nextSteps:[n?c:"Repair the reported metadata write failure, then retry the original install."],...n?{recovery:{suggested_retry:c,suggested_retry_args:s}}:{}});throw Object.defineProperty(g,"cause",{value:m,configurable:!0,writable:!0}),g}throw m}if(p.ok)return p;if(!n||a)return{...p,details:{...p.details,previous_state_preserved:!1}};try{await To(l)}catch(m){return d=!0,{...p,details:{...p.details,previous_state_preserved:!1,rollback:{status:"failed",error:String(m),backup_directory:o,recovery_command:c,recovery_args:s}}}}return{...p,details:{...p.details,overwritten:!1,settings_changed:!1,previous_state_preserved:!0,rollback:{status:"restored"}}}}finally{d||await re.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ae11424-9de8-5bce-91b4-e8901459fb5f")}catch{}})();var No=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],Ep=No.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),$p={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},Ip="__pm_native_output",Ap=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Do=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Tp=["disabled","require_trusted","require_provenance"],jo={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},Op=e=>{let t=e??jo,n={};for(let a of Ap)n[a]=Z(t[a]??[]);return n},Cp=(e,t)=>{for(let n of Do)t[n].length>0&&(e[n]=t[n]);return e},Rp=(e,t)=>{for(let n of Tp)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Pp=e=>{let t={};for(let n of Do)t[n]=Z(e[n]??[]);return t},Np=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Cp(Rp({name:t},e),Pp(e))},Dp=e=>(e??[]).map(t=>Np(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),jp=e=>{let t=Object.assign({},jo,e??{}),n=Op(e),a=Dp(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:a}},Lo=async(e,t)=>{let n=[t],a=await dr(t);a&&n.push(a);let i=[...new Set(n.map(r=>b(r)).filter(r=>r.length>0))];for(let r of i){let o=e.find(c=>b(c.name)===r);if(o)return o;let s=e.find(c=>b(c.directory)===r);if(s)return s}},Fo=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled));return new Set(Z(e.extensions.disabled)).has(n)?!1:a.size===0?!0:a.has(n)},Mo=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled)),i=new Set(Z(e.extensions.disabled)),r=[...a],o=[...i];return i.delete(n),a.size>0&&a.add(n),e.extensions.enabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Lp=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled)),i=new Set(Z(e.extensions.disabled)),r=[...a],o=[...i];return a.delete(n),i.add(n),e.extensions.enabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Fp=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled)),i=new Set(Z(e.extensions.disabled)),r=[...a],o=[...i];return a.delete(n),i.delete(n),e.extensions.enabled=[...a].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Mp=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),a=No.map(([i,r,o])=>({action:r,flag:o,distance:Oa(t,i,n)})).filter(i=>i.distance!==null).sort((i,r)=>i.distance-r.distance)[0];return a?{action:a.action,flag:a.flag}:null},Up=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=Mp(e);if(!a)return new u(`One action flag is required. Use one of: ${Ep}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let i=`pm ${n} ${a.flag}`;return Ca({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(Uo),retry_command:i,message_suffix:`. Did you mean "${a.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},zp=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],Uo={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Gp=e=>Uo[e]??null,Jp=(e,t)=>{let n=[...new Set(zp.filter(([a])=>t[a]===!0).map(([,a])=>a))];if(n.length===0){if(e===void 0)return"explore";let a=Gp(e.trim().toLowerCase());if(a)return a;throw Up(e,t)}if(n.length>1)throw new u("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},qp=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new u('Options "--project/--local" and "--global" are mutually exclusive.',h.USAGE);return n?"global":"project"},Wp=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],zo=e=>{for(let t of Wp){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Go=(e,t,n,a)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,last_update_remote_version:i.last_update_remote_version,update_error:i.update_error,update_check_status:a.status,update_check_reason:a.reason}},Bp=(e,t,n,a)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},a),r=a?Fo(n,a.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Go({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:r},t,a,zo(a))}},Hp=async(e,t,n,a,i,r)=>{let o=te.join(e,t),s=te.join(o,"manifest.json"),c=r.get(b(t));if(!await k(s))return Bp(t,n,a,c);let d=Symbol("invalid-extension-manifest-json"),l=await et.readFile(s,"utf8").then(y=>JSON.parse(y)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Cn(l);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(b(p.name))??r.get(b(t));return{summary:Go({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:Fo(a,p.name)},n,m,zo(m))}},me=async(e,t,n,a)=>{if(!await k(e))return{extensions:[],warnings:[]};let i=(await et.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,l)=>d.localeCompare(l)),r=new Map(a.entries.map(d=>[b(d.name),d])),o=new Map(a.entries.map(d=>[b(d.directory),d])),s=[],c=[];for(let d of i){let l=await Hp(e,d,t,n,r,o);l.warning&&s.push(l.warning),l.summary&&c.push(l.summary)}return{extensions:c.sort((d,l)=>d.name.localeCompare(l.name)),warnings:s.sort((d,l)=>d.localeCompare(l))}},Kp=Ma(),Vp=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Yp=(e,t,n,a)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),r=a?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return r&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Vp(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:o,...r?{sdk_dependency_status:"missing"}:{}}},Xp=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,a])=>a!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},Jo=e=>e.map(t=>Xp(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),qo=(e,t,n)=>{let a=b(e);return t.find(i=>(n===void 0||i.layer===n)&&b(i.name)===a)},Zp=(e,t,n,a)=>n.find(i=>i.scope===t&&b(i.name)===b(e))?.activation_status??(a?"failed":"unknown"),Wo=(e,t,n,a,i)=>Kp.enqueue(async()=>{let r=process.env.PM_CLI_PACKAGE_ROOT,o=await et.mkdtemp(te.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=ve(import.meta.url,["../.."]);try{let s=await be({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:un(),cache_bust:!0,module_graph_snapshot_root:o}),c=await ke({...s}),d=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...Jo(c.failed)],l=Object.fromEntries(s.loaded.map(p=>[b(p.name),Pa(ze(c,{extensionName:p.name}))]));return{installed:Zt(a,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await et.rm(o,{recursive:!0,force:!0}),r===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=r}}),ea=async(e,t,n,a)=>{let i=n.filter(c=>!c.managed),r=[...i].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),o=a,s=[];for(let c of r){let d=te.join(e,c.directory),l=await Ye(d),p=T(),m={kind:"local",input:c.name,location:d};o=ct(o,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:p,updated_at:p,source:m}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return s.length>0&&await Xe(e,o),{state:o,adopted_entries:s,unmanaged_candidates:r,already_managed_count:n.length-i.length}},Qp=(e,t)=>{let n=F(process.cwd(),t.path),a=$t(n,process.cwd()),i=e==="global"?$a(process.cwd()):n,r=e==="global"?a.global:a.project;return{pm_root:n,scope:e,settings_root:i,selected_root:r,roots:a}},en=e=>{let t=[e.gh,e.github].filter(a=>typeof a=="string").map(a=>a.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new u('Options "--gh" and "--github" must match when both are provided.',h.USAGE);return n[0]},em=e=>$p[e],tm=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=e==="install"?"source":"name",i=`${n} ${a}`,r=em(e),o=`<${a}>`,s=`pm ${n} ${r} ${o}`;throw new u(`Action "${e}" requires ${i} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${a} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${a} target`}]}})},tn=(e,t,n={})=>{let a=e?.trim();if(a)return a;if(t==="init")throw new u('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',h.USAGE);return tm(t,n)},nm=(e,t)=>{let n=new Set([...t.registrations.item_types.map(a=>({entry:a,count:a.types.length})),...t.registrations.item_fields.map(a=>({entry:a,count:a.fields.length}))].filter(({count:a})=>a>0).map(({entry:a})=>`${a.layer}:${b(a.name)}`));return e.loaded.filter(a=>(a.activation?.commands??[]).length>0).filter(a=>n.has(`${a.layer}:${b(a.name)}`)).map(a=>`extension_schema_narrow_activation:${a.layer}:${a.name}`).filter((a,i,r)=>r.indexOf(a)===i).sort((a,i)=>a.localeCompare(i))},am=(e,t)=>{let n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(a=>a.triggered&&!a.allowed);if(n)throw new u(n.message,h.USAGE)},im=(e,t,n)=>{let a=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(a)?void 0:e},rm=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},om=(e,t,n)=>{let a={ok:n,action:e.action,scope:e.scope,roots:rm(e),warnings:[...new Set(e.warnings)].sort((i,r)=>i.localeCompare(r)),details:t};return e.action==="doctor"&&Object.defineProperty(a,Ip,{value:!0,enumerable:!1,configurable:!1}),a},ta=async(e,t,n)=>{let a=Jp(e,t);am(a,t);let i=im(e,a,t),r=qp(t),o=Qp(r,n),s={action:a,normalizedTarget:i,scope:r,resolvedRoots:o,warnings:[],options:t,global:n},c={...s,withResult:(d,l=!0)=>om(s,d,l)};return await Mm(c)},sm=(e,t)=>{let n=t.vocabulary??"extension",a=e.target_path.replace(/\\/g,"/"),i=Aa(a),r={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[r[n],...s,`Install the scaffold: ${oe(n==="package"?["install","--project",a]:["extension","--install","--project",a])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},cm=async e=>{let{action:t,normalizedTarget:n,options:a,withResult:i}=e;if([en(a),a.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new u('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let r=tn(n,t,a),o=await Cr(r,a.vocabulary??"extension",a.capability,a.declarative===!0);return i({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:sm(o,a)})},dm=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:a,options:i,global:r,withResult:o}=e;if(t!==void 0)throw new u('Action "reload" does not accept a target argument.',h.USAGE);let s=await A(n.settings_root),c=un(),d=await be({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:r.noExtensions,reload_token:c,cache_bust:!0});a.push(...d.warnings);let l=await ke(d);a.push(...l.warnings);let p={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&a.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(p)},lm=async e=>{let{normalizedTarget:t,scope:n,options:a,global:i,withResult:r}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new u('Action "catalog" does not accept a package target.',h.USAGE);return r(await lr(n,i,a))},pm=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),mm=e=>({kind:"local",input:e.input,location:e.absolute_path}),um=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),fm=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),hm=(e,t,n,a)=>e?pm(e,t):n.kind==="local"?mm(n):n.kind==="npm"?um(n,a):fm(n,a),gm=(e,t,n,a)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:a}:ar(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:a}:{installed_at:a,updated_at:a},ym=async(e,t)=>{let{scope:n,resolvedRoots:a,warnings:i}=e,{validated:r,destinationDirectoryName:o}=t,s=await A(a.settings_root),c=await le(a.selected_root);i.push(...c.warnings);let d=te.join(a.selected_root,o),l=await k(d),p=await Ze(r.directory,d);await et.mkdir(a.selected_root,{recursive:!0});let m=hm(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),y=c.state.entries.find(w=>b(w.name)===b(r.manifest.name)),g=gm(y,r.manifest.version,m,T()),_=ct(c.state,{name:r.manifest.name,directory:o,scope:n,manifest_version:r.manifest.version,manifest_entry:r.manifest.entry,capabilities:[...r.manifest.capabilities],contributions:r.manifest.contributions,...g,source:m}),f=Mo(s,r.manifest.name);return p||await Wr(r.directory,d),await Gr(d),await Jr(d),await Xe(a.selected_root,_),f&&await Ee(a.settings_root,s,"settings:write"),{settings:s,managedState:_,sourceRecord:m,destinationDirectory:d,destinationExists:l,installInPlace:p,activationChanged:f}},_m=async(e,t,n)=>{let a=n.filter(i=>b(i.name)===b(t)).flatMap(i=>i.types.map(r=>({name:r.name,folder:r.folder})));return e.scope==="project"&&a.length>0&&await yt(e.resolvedRoots.pm_root,a,e.warnings,"install:type-folder"),a},wm=(e,t,n,a,i)=>{let r=qo(t,n.activation_failures,e.scope),o=Zp(t,e.scope,n.installed,r),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:r,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:a.command_paths,registered_actions:a.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},vm=async(e,t)=>{let{scope:n,resolvedRoots:a,warnings:i,global:r,withResult:o}=e,{validated:s,destinationDirectoryName:c}=t;return Oo({selectedRoot:a.selected_root,settingsRoot:a.settings_root,destinationDirectory:te.join(a.selected_root,c),sourceDirectory:s.directory,scope:n},async()=>{let d=await ym(e,t),l=await me(a.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let p=await Wo(a.pm_root,te.dirname(a.selected_root),d.settings,l.extensions,r);i.push(...p.warnings);let m=await _m(e,s.manifest.name,p.item_type_registrations),y=vo(s.manifest.name,p.installed),g=wm(e,s.manifest.name,p,y,m),_=p.contribution_inventories[b(s.manifest.name)];return _&&(d.managedState=await ir(a.selected_root,d.managedState,s.manifest.name,_)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:g.activated,settings_changed:d.activationChanged,runtime_activation_status:g.status,command_paths:y.command_paths,action_paths:y.action_paths,contributions:_,command_discovery:Yp(s.manifest.name,d.sourceRecord,y,g.failure),verification:g.verification,activation_diagnostics:{failed_count:p.activation_failures.length,failed:p.activation_failures,installed_extension_failed:g.failure??null}},g.activated)})},bm=async e=>{let{options:t,global:n,warnings:a,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new u('Action "install all" does not accept --ref.',h.USAGE);let r=[],o=new Map;for(let s of await zt()){let c=await dt(s),d=te.resolve(c),l=o.get(d);l===void 0&&(l=await ta(s,{...t,install:!0},n),o.set(d,l)),r.push({alias:s,result:l})}return a.push(...r.flatMap(s=>s.result.warnings)),i(Io(r,t.dryRun===!0),r.every(s=>s.result.ok))},km=async(e,t,n)=>{let{resolvedRoots:a}=e,{bundledAliasName:i,bundledPackageName:r,installSource:o,sourceResolution:s}=await Vr(t,n,e.options.ref,(await le(a.selected_root)).state.entries);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${d.package}`)}let c=await wr(o);try{let d=await Ye(c.directory,{source_kind:o.kind,source_input:o.input,source_root:c.source_root}),l=Mt(d.manifest.name),p=e.options.dryRun===!0||o.kind==="local"&&i===null?await Hr(c,te.join(a.selected_root,l),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:d.manifest.name,version:d.manifest.version},source_resolution:s,install_plan:p}):await Bn(a.settings_root,l,()=>vm(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:r,sourceResolution:s,installSource:o,resolvedSource:c,installPlan:p}))}finally{c.cleanup&&await c.cleanup()}},xm=async e=>{let t=en(e.options),n=t??tn(e.normalizedTarget,e.action,e.options);return[t===void 0,or(n)].every(Boolean)?bm(e):km(e,n,t)},Sm=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:i,options:r,withResult:o}=e;if(t!==void 0)throw new u('Action "adopt-all" does not accept a target argument.',h.USAGE);if(en(r)!==void 0||typeof r.ref=="string"&&r.ref.trim().length>0)throw new u('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let s=await A(a.settings_root),c=await le(a.selected_root);i.push(...c.warnings);let d=await me(a.selected_root,n,s,c.state);i.push(...d.warnings);let l=await ea(a.selected_root,n,d.extensions,c.state),p=await me(a.selected_root,n,s,l.state);i.push(...p.warnings);let m=Qt(n,i,p.extensions,r);i.push(...m.warnings);let y=new Map(p.extensions.map(f=>[`${b(f.name)}:${b(f.directory)}`,f])),g=new Map(p.extensions.map(f=>[b(f.directory),f])),_=l.adopted_entries.map(f=>{let w=b(f.directory),v=y.get(`${b(f.name)}:${w}`)??g.get(w);return{...f,...Bo(v)}});return o({adopted_all:_.length>0,adopted_count:_.length,already_managed_count:l.already_managed_count,extensions:_,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},Bo=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Em=(e,t,n,a)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=lt(e,{forceGithub:!0,ref:a});if(i.kind!=="github")throw new u(`Invalid GitHub shorthand "${e}".`,h.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},$m=async e=>{let{action:t,normalizedTarget:n,scope:a,resolvedRoots:i,warnings:r,options:o,withResult:s}=e,c=tn(n,t,o),d=en(o),l=await A(i.settings_root),p=await le(i.selected_root);r.push(...p.warnings);let m=await me(i.selected_root,a,l,p.state);r.push(...m.warnings);let y=await Lo(m.extensions,c);if(!y)throw new u(`Installed extension "${c}" was not found in ${a} scope.`,h.NOT_FOUND);if(y.managed)return s({adopted:!1,already_managed:!0,extension:{name:y.name,directory:y.directory}});let g=te.join(i.selected_root,y.directory),_=await Ye(g),f=T(),w=Em(d,c,g,o.ref),v=ct(p.state,{name:_.manifest.name,directory:y.directory,scope:a,manifest_version:_.manifest.version,manifest_entry:_.manifest.entry,capabilities:[..._.manifest.capabilities],contributions:_.manifest.contributions,installed_at:f,updated_at:f,source:w});await Xe(i.selected_root,v);let E=await me(i.selected_root,a,l,v);r.push(...E.warnings);let S=E.extensions.find(C=>b(C.name)===b(_.manifest.name))??E.extensions.find(C=>b(C.directory)===b(y.directory));return s({adopted:!0,extension:{name:_.manifest.name,directory:y.directory,version:_.manifest.version,entry:_.manifest.entry},source:w,...Bo(S)})},Ho=async e=>{let{action:t,normalizedTarget:n,scope:a,resolvedRoots:i,warnings:r,options:o}=e,s=tn(n,t,o),c=await A(i.settings_root),d=await le(i.selected_root);r.push(...d.warnings);let l=await me(i.selected_root,a,c,d.state);r.push(...l.warnings);let p=await Lo(l.extensions,s);if(!p)throw new u(`Installed extension "${s}" was not found in ${a} scope.`,h.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:p}},Im=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:a,managedStateRead:i,candidate:r}=await Ho(e),o=te.join(t.selected_root,r.directory);await et.rm(o,{recursive:!0,force:!0});let s={...i.state,updated_at:T(),entries:i.state.entries.filter(d=>b(d.name)!==b(r.name)&&b(d.directory)!==b(r.directory))};await Xe(t.selected_root,s);let c=Fp(a,r.name);return c&&await Ee(t.settings_root,a,"settings:write"),n({removed:!0,extension:{name:r.name,directory:r.directory},destination_path:o,settings_changed:c})},Co=async e=>{let{action:t,resolvedRoots:n,warnings:a,global:i,withResult:r}=e,{settings:o,candidate:s}=await Ho(e),c=t==="activate"?Mo(o,s.name):Lp(o,s.name);c&&await Ee(n.settings_root,o,"settings:write");let d=t==="activate"?await Wo(n.pm_root,te.dirname(n.selected_root),o,[s],i).then(l=>(a.push(...l.warnings),qo(s.name,l.activation_failures,e.scope))):void 0;return d&&a.push(`extension_activate_failed:${e.scope}:${s.name}`),r({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},d===void 0)},Am=(e,t,n,a,i,r)=>{let o=a==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],c=i?.adopted_entries.length??0,d=[[r!==null,r??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},Qn=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Tm=(e,t,n,a)=>{if(e!=="project"||t||!Qn(a))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Om=(e,t,n)=>{if(String(e??"").trim().length>0)throw new u('Action "doctor" does not accept a target argument.',h.USAGE);let a=[n.isolated,n.ignoreGlobal].includes(!0);if([a,t==="global"].every(Boolean))throw new u("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let i=ho(n.detail),r=n.trace===!0;if([r,i!=="deep"].every(Boolean))throw new u("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:a,detailMode:i,includeTrace:r}},Cm=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let a=await ea(e.resolvedRoots.selected_root,e.scope,t,n);return{state:a.state,fix:a}},Rm=(e,t,n,a)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:Qn(a),rerun_command:null,pm_global_path_recipe:null};let r=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:Qn(a),rerun_command:t?null:r,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},Pm=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:i,options:r,global:o,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=Om(t,n,r),p=await A(a.settings_root),m=await le(a.selected_root);i.push(...m.warnings);let y=await me(a.selected_root,n,p,m.state);i.push(...y.warnings);let{state:g,fix:_}=await Cm(e,y.extensions,m.state),f=await me(a.selected_root,n,p,g);i.push(...f.warnings);let w=await be({pmRoot:a.pm_root,settings:p,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:c}),v=await ke({...w,loaded:w.loaded}),E=await Ao(a.pm_root);i.push(...E.warnings,...w.warnings),i.push(...mo(w.failed)),i.push(...v.warnings),i.push(...uo(v.failed)),i.push(...fo(w,v)),i.push(...bo(v,w)),i.push(...nm(w,v)),i.push(...ko(v));let S=Zt(f.extensions,w,v),C=wo(n,S,w.loaded.map(O=>({layer:O.layer,name:O.name})),w.failed.map(O=>({name:O.name})),w.disabled_by_flag);i.push(...C.warnings);let ne=S.filter(O=>O.update_check_status==="failed").map(O=>`extension_update_check_failed:${O.name}`);i.push(...ne);let D=Qt(n,i,S,r);i.push(...D.warnings);let x=[...D.warnings],G={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},tt=yo(x),an=_o(),ma=D.warning_codes,Is=Tm(n,c,r.vocabulary,w),As=Am(D.remediation,w.failed.length,v.failed.length,r.vocabulary,_,Is),ua=Rm(n,c,r.vocabulary,w),Ts={status:D.status,scope:n,warning_count:D.warning_count,warning_codes:ma,total_extensions:S.length,managed_total:S.filter(O=>O.managed).length,enabled_total:S.filter(O=>O.enabled).length,active_total:S.filter(O=>O.active).length,unmanaged_loaded_extension_count:D.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:D.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:D.unmanaged_expected_extension_count,runtime_active_total:S.filter(O=>O.runtime_active===!0).length,activation_status_totals:{ok:S.filter(O=>O.activation_status==="ok").length,failed:S.filter(O=>O.activation_status==="failed").length,not_loaded:S.filter(O=>O.activation_status==="not_loaded").length,unknown:S.filter(O=>O.activation_status==="unknown").length},unknown_capability_count:tt.length,capability_contract_version:an.version,update_available_total:D.update_available_total,update_check_status_totals:D.update_check_status_totals,update_health_coverage:D.update_health_coverage,update_health_partial:D.update_health_partial,update_check_failed_total:S.filter(O=>O.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Vn(w.failed),activation_failures:Vn(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:C.warnings.length,trace_enabled:l,isolation:ua,policy:G,remediation:As},Os=_?{requested:!0,applied:_.adopted_entries.length>0,adopted_count:_.adopted_entries.length,already_managed_count:_.already_managed_count,adopted_extensions:_.adopted_entries.map(O=>O.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:f.extensions.filter(O=>O.managed).length,adopted_extensions:[]},rn={mode:d,summary:Ts,triage:D,trace_enabled:l,capability_contract:an,capability_guidance:tt,managed_state_fix:Os,author_manifest:E,isolation:ua,policy:w.policy};if(d==="deep"){let O=l?v.failed:v.failed.map(P=>{let{trace:xu,...Cs}=P;return Cs});rn.deep={warnings:x,warning_codes:ma,capability_contract:an,capability_guidance:tt,trace_enabled:l,managed_state:{path:m.path,count:g.entries.length,entries:g.entries},installed_extensions:S,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(P=>({layer:P.layer,directory:P.directory,name:P.name,version:P.version,entry:P.entry,priority:P.priority}))},activation:{failed:O,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:C.summary},l&&(rn.deep.trace={activation_failures:v.failed.filter(P=>P.trace!==void 0).map(P=>({layer:P.layer,name:P.name,entry_path:P.entry_path,error:P.error,method:P.trace.method,command:P.trace.command,capability:P.trace.capability,missing_capability:P.trace.missing_capability,registration_index:P.trace.registration_index,expected_schema:P.trace.expected_schema,hint:P.trace.hint,received:P.trace.received}))})}return s(rn)},Nm=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:i,options:r,global:o,withResult:s}=e,c=await A(a.settings_root),d=await be({pmRoot:a.pm_root,settings:c,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),l=await ke(d);i.push(...d.warnings),i.push(...l.warnings);let p=Dr(t,d,l);if(t!==void 0&&p.extensions.length===0){let m=r.vocabulary==="package"?"package":"extension",y=[...new Set(d.loaded.map(_=>r.vocabulary==="package"&&typeof _.source_package=="string"&&_.source_package.trim().length>0?_.source_package.trim():_.name))].sort((_,f)=>_.localeCompare(f)),g=y.length>0?` Loaded ${m} names: ${y.join(", ")}.`:"";throw new u(`No loaded ${m} named "${t}" was found in ${n} scope.${g} Run pm ${m} explore to list discovered ${m}s.`,h.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},Dm=async(e,t,n)=>{let a=n,i=null;return[e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await ea(e.resolvedRoots.selected_root,e.scope,t,n),a=i.state),e.action==="manage"&&(a=await $o(a,e.options.offline)),{state:a,fix:i}},jm=async(e,t,n)=>{let a=await be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await ke({...a,loaded:a.loaded});return e.warnings.push(...a.warnings,...i.warnings),{installed:Zt(n,a,i),failures:Jo(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:a.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...a.warnings,...i.warnings])].length,policy:a.policy}}},Lm=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},Ro=async e=>{let{action:t,scope:n,resolvedRoots:a,warnings:i,options:r,withResult:o}=e,s=await A(a.settings_root),c=jp(s.extensions.policy),d=await le(a.selected_root);i.push(...d.warnings);let l=await me(a.selected_root,n,s,d.state);i.push(...l.warnings);let{state:p,fix:m}=await Dm(e,l.extensions,d.state),y=await me(a.selected_root,n,s,p);if(i.push(...y.warnings),t==="manage"&&r.offline===!0)for(let v of y.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=y.extensions.filter(E=>E.update_check_status==="failed").map(E=>`extension_update_check_failed:${E.name}`);i.push(...v)}let g=await jm(e,s,y.extensions),_=g.installed,f=Qt(n,i,_,r);i.push(...f.warnings);let w={total:_.length,managed_total:_.filter(v=>v.managed).length,enabled_total:_.filter(v=>v.enabled).length,active_total:_.filter(v=>v.active).length,extensions:_,triage:f,policy:c};return g.failures!==void 0&&(w.activation_diagnostics={failed_count:g.failures.length,failed:g.failures}),t==="explore"&&(w.runtime_probe=g.summary),t==="manage"&&(w.runtime_probe=g.summary,w.managed_state_fix=Lm(m,_)),o(w)},Po={init:cm,install:xm,uninstall:Im,explore:Ro,manage:Ro,describe:Nm,reload:dm,doctor:Pm,catalog:lm,adopt:$m,"adopt-all":Sm,activate:Co,deactivate:Co,migrate:$i},Fm=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Mm=e=>Fm(e)?Bn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Po[e.action](e)):Po[e.action](e);import ia from"node:fs/promises";import z from"node:path";import Ko from"node:readline/promises";import{stdin as Vo,stdout as wt}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bb8a4985-8bc0-5290-a6f9-310d940cf4d7")}catch{}})();var Yo=["ask","add","skip","status"],Um=["AGENTS.md","CLAUDE.md"],zm=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Gm=8,ra=1,Jm="<!-- pm-cli:agent-guidance:start:",qm=`<!-- pm-cli:agent-guidance:start:v${ra} -->`,na="<!-- pm-cli:agent-guidance:end -->",bt="Add workflow guidance later: pm init --agent-guidance add",Nw={toPortableRelativePath:Fe,ensureTrailingNewline:aa,detectLineEnding:Zo,findGuidanceBlockRange:oa,buildAgentGuidanceBlock:Qo,upsertAgentGuidanceBlock:sa,resolveProjectRoot:ts,resolveTargetGuidancePath:ns,parsePromptChoice:as,pushUnique:Oe,promptForGuidanceWrite:is,normalizeAgentGuidanceState:ca,applyAgentGuidanceState:os,writeGuidanceFile:da,setAgentGuidanceReadlineFactoryForTests:Wm},Xo=()=>Ko.createInterface({input:Vo,output:wt});function Wm(e){Xo=e??(()=>Ko.createInterface({input:Vo,output:wt}))}function Fe(e,t){let n=z.relative(e,t);return n.length===0?z.basename(t):n.split(z.sep).join("/")}function aa(e){return e.endsWith(`
31
+ `}import Kt from"node:fs/promises";import Ht from"node:path";import Fr 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]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function ft(e,t,n,a){let i=Fr.relative(e,n);if(i!==""&&!H(e,n)||n===t||H(t,n))return!1;let r=i.split(Fr.sep);return r.includes(".git")?!1:a?!r.some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as Al}from"node:crypto";import L from"node:fs/promises";import Tl from"node:os";import D 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]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var Mr=3,Ol=120,Ur=250,Cl=12e4,Rl=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),zr=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Gr=e=>Rl.has(String(zr(e))),Bt=(e,t)=>zr(e)===t,Jr=e=>new Promise(t=>{setTimeout(t,e)}),qr=async e=>{let t=D.join(e,"package.json");await k(t)||await L.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
32
+ `,"utf8")},Wr=async e=>{let t=be(import.meta.url,["../../.."]),n=D.join(e,"node_modules","@unbrained"),a=D.join(n,"pm-cli");await L.mkdir(n,{recursive:!0}),await L.rm(a,{recursive:!0,force:!0}),await L.symlink(t,a,process.platform==="win32"?"junction":"dir")},ht=async e=>{let t=D.resolve(e),n=D.dirname(t),a=D.parse(n).root,i=await L.realpath(a).catch(()=>a),r=D.relative(a,n),o=r===""?[]:r.split(D.sep);for(let[s,d]of o.entries()){let c=D.join(i,d);try{i=await L.realpath(c)}catch{i=D.join(i,...o.slice(s));break}}return D.join(i,D.basename(t))},Br=async(e,t,n,a=Tl.tmpdir())=>Re("extension_install_copy",async()=>{let i=D.resolve(e),r=await L.realpath(i).catch(()=>i),o=await ht(t);if(r===o)return;if(!H(r,o)){await n(r,t,{recursive:!0,force:!0,filter:p=>ft(r,o,D.resolve(p),!1)});return}let s=await L.realpath(D.resolve(a)).catch(()=>ht(a)),d=H(r,s)?D.dirname(r):s;if(H(r,d))throw new u(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,h.USAGE,{code:"extension_install_source_contains_destination"});let c=await L.mkdtemp(D.join(d,"pm-extension-copy-")),l=D.join(c,"extension");try{await n(r,l,{recursive:!0,force:!0,filter:p=>ft(r,o,D.resolve(p),!0)}),await n(l,t,{recursive:!0,force:!0})}finally{await L.rm(c,{recursive:!0,force:!0})}}),Hr=async(e,t,n=L.cp)=>{for(let a=1;a<=Mr;a+=1)try{await Re("extension_install_copy",async()=>{await L.rm(t,{recursive:!0,force:!0}),await Br(e,t,n)});return}catch(i){if(!Gr(i)||a===Mr)throw i;await Jr(Ur)}},Bn=async e=>{let t;try{t=await L.readFile(D.join(e,"owner.json"),"utf8")}catch(i){if(!Et(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let a=n.token;return typeof a=="string"&&a.length>0?a:null},Kr=async(e,t)=>await Bn(e)!==t?!1:(await L.rm(e,{recursive:!0,force:!0}),!0),Pl=async(e,t)=>{let n;try{n=await L.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let a=await Bn(e);return a===null?(await L.rm(e,{recursive:!0,force:!0}),!0):Kr(e,a)},Nl=(e,t,n)=>{let a=Promise.resolve(),i=setInterval(()=>{a=a.then(async()=>{if(await Bn(e)!==t)return;let r=new Date;await L.utimes(e,r,r)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await a}},Dl=async(e,t)=>{await L.mkdir(e);try{await L.writeFile(D.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
33
+ `,"utf8")}catch(n){throw await L.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},jl=async(e,t,n,a,i)=>{for(let r=1;r<=n;r+=1)try{return await Dl(e,t),!0}catch(o){if(!Bt(o,"EEXIST"))throw o;await Pl(e,i)?r-=1:await Jr(a)}return!1},Hn=async(e,t,n,a)=>Re("extension_install",async()=>{let i=D.join(e,"runtime","extension-install-locks"),r=D.join(i,"scope.lock");await L.mkdir(i,{recursive:!0});let{attempts:o=Ol,delay_ms:s=Ur,stale_ms:d=Cl,heartbeat_ms:c}=a??{};if(![o,s,d,c].filter(w=>w!==void 0).every(Number.isFinite))throw new u("Extension install lock timings must be finite numbers.",h.USAGE);let l=Math.max(1,Math.floor(o)),p=Math.max(0,Math.floor(s)),m=Math.floor(d),y=Math.floor(c??m/3);if(m<=0||y<=0||y>=m)throw new u("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",h.USAGE);let g={pid:process.pid,token:Al(),created_at:T(),destination:t};if(!await jl(r,g,l,p,m))throw new u(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let _=Nl(r,g.token,y),f=!1;try{let w=await n();return f=!0,w}finally{await _(),await Kr(r,g.token).catch(w=>{if(f)throw w})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var Ll=new Set(["node_modules",".git","dist","build","coverage"]);async function Vr(e,t,n,a){let i=e.source.kind==="local"?await Kt.stat(e.source.absolute_path):void 0,r=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,o=await Fl(e.directory,t,a),s={source_mode:r,...r==="archive"?{archive_bytes:i.size}:{},copy:o},d=e.source_root??e.directory;if(r==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await k(Ht.join(d,"package.json"))&&(s.packed_alternative={cwd:d,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),r==="directory"&&!o.complete){let c=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new u(`Local extension source scan stopped at ${c}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,h.USAGE,{code:"extension_install_incomplete_source_scan",reason:o.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function Fl(e,t,n={}){let{maxEntries:a=1e4,maxDepth:i=64,signal:r}=n;if(![a,i].every(p=>Number.isSafeInteger(p)&&p>0))throw new u("maxEntries and maxDepth must be positive safe integers.",h.USAGE);r?.throwIfAborted();let o=await Kt.realpath(e),s=await ht(t),d=await Qe(o,s);r?.throwIfAborted();let c=d?"in_place":H(o,s)?"nested_filtered_snapshot":"directory_snapshot",l={copy_scope:c,source_directory:o,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:a,max_depth:i};return c==="in_place"||await Yr(o,0,l,r),l}async function Yr(e,t,n,a){a?.throwIfAborted();let i=await Kt.opendir(e);for await(let r of i){if(a?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=Ht.join(e,r.name);if(!ft(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(Ht.relative(n.source_directory,o).split(Ht.sep).some(s=>Ll.has(s))&&(n.development_entries+=1),await Ml(o,t,n,a),!n.complete)return}}async function Ml(e,t,n,a){let i=await Kt.lstat(e);if(a?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await Yr(e,t+1,n,a)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import Ul from"node:fs/promises";import zl from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bef4424-f5b8-511b-91f7-0b39cf11f515")}catch{}})();async function Gl(e,t){if(e.kind!=="local"||e.input.startsWith(".")||e.input.includes("\\")||e.input.includes("/")&&!/^@[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/u.test(e.input))return e;try{return await Ul.lstat(e.absolute_path),e}catch(r){if(!ve(r))throw r}let n=e.input.trim(),a=t.filter(r=>r.source.kind==="npm"),i=(a.find(r=>r.name===n)??a.find(r=>r.directory===n)??a.find(r=>r.source.package===n))?.source.package;if(i===void 0)return e;try{let r=zl(i);if(!r.registry||r.name!==i)return e}catch{return e}return pt(`npm:${i}`,{})}async function Xr(e,t,n,a=[]){let i=typeof t=="string"?null:await lt(e),r=i===null?null:e.trim().toLowerCase(),o=r===null?null:await lr(r),s=await Gl(pt(i??e,{forceGithub:typeof t=="string",ref:n}),a),d=r===null?null:await hr(e);return{bundledAliasName:r,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:r===null?s.kind:"builtin",input:r??s.input,...o===null?{}:{package:o}},ambiguous:d!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...r===null?[]:[{kind:"builtin",input:r,...o===null?{}:{package:o},command:`pm install ${r}`}],...d===null?[]:[{kind:"npm",input:`npm:${d.package}`,package:d.package,...d.version===void 0?{}:{version:d.version},directory:d.directory,command:`pm install npm:${d.package}`}]]}}}import tt from"node:fs/promises";import te from"node:path";import Hl from"node:path";import{mkdir as Kl}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="abb182c9-6d6c-5be4-a2ad-c91b00a098d0")}catch{}})();var gt=["agile","ops","research"],Jl={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function Vt(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${gt.join(", ")}.`)}function yt(e){return Jl[e].map(t=>it(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var ql=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Wl(e){let t=ql.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Bl(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Zr(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,a=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let d=Wl(s);if(d===void 0)continue;let c=i.get(d)??{count:0,examples:[]};c.count+=1,c.examples.length<a&&c.examples.push(s),i.set(d,c)}let r=[];for(let[o,s]of i.entries()){if(s.count<n)continue;let d=Bl(o);r.push({name:d,prefix:o,count:s.count,examples:s.examples,shadows_builtin:Xa(d)!==void 0})}return r.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var xy=[...St,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Yt="schema-types",Qr="schema-statuses",eo="schema-fields";function Ae(e){return Se({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function $y(e,t,n){let a=F(process.cwd(),n.path);await we(a);let i;try{i=it({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(y){throw new u(y instanceof Error?y.message:String(y),h.USAGE)}let r=await I(a),o=K(r.schema),s=Q(a,o.files.types,V.types),d=[],c=q(t.author,r.author_default),l=fe(r),p=await ee(a,Yt,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),m;try{let y=await M(s),g;try{g=ae(y)}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}try{Za(i,g);let _=new Map,f=W(r,J());for(let[w,v]of Object.entries(f.type_to_folder)){let E=v.trim().toLowerCase();E.length>0&&!_.has(E)&&_.set(E,w)}Qa(i,g,_)}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}m=Ue(g,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&d.push(`type_recased:${m.previousName}->${m.definition.name}`),await Ae({pmRoot:a,filePath:s,raw:se(m.file),op:"schema:add-type",author:c,settings:r}),await _t(a,[m.definition],d,"schema:add-type-folder"),d.push(...await B({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await to(a,d),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Te(d),generated_at:T()}}async function we(e){await ze(e)}async function to(e,t){try{let n=await ui(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Te(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Vl(e,t,n,a){let i=W(t,J()),r=a.trim().toLowerCase();return(await Ne(e,t.item_format,i.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===r).length}async function Yl(e,t,n,a){let i=W(t,J()),r=at(n),o=A(a);return(await Ne(e,t.item_format,i.type_to_folder,[],n)).filter(s=>{let d=typeof s.status=="string"?s.status:"";return(r.alias_to_id.get(A(d))??A(d))===o}).length}async function Xl(e,t,n,a,i){if(i.length===0||je.has(i))return;let r=await Yl(t,n,a,i);r>0&&e.push(`items_using_status:${r}`);let o=no(a.workflow,i);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function no(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&A(n)===t).map(([n])=>n)}async function Iy(e,t,n){let a=F(process.cwd(),n.path);await we(a);let i=await I(a),r=K(i.schema),o=Q(a,r.files.types,V.types),s=[],d=q(t.author,i.author_default),c=fe(i),l=await ee(a,Yt,i.locks.ttl_seconds,d,!!t.force,c.force_required_for_stale_lock,i.locks.wait_ms),p;try{let m=await M(o),y;try{y=ae(m)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=ei(y,e)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=(p.definition?.name??e??"").trim();if(g.length>0){let _=await Vl(a,i,r,g);_>0&&s.push(`items_using_type:${_}`)}await Ae({pmRoot:a,filePath:o,raw:se(p.file),op:"schema:remove-type",author:d,settings:i}),s.push(...await B({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return p.removed&&await to(a,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:o,definitions:p.file.definitions.length},warnings:Te(s),generated_at:T()}}function Kn(e,t){return Q(e,t.files.statuses,V.statuses)}function Xt(e,t){return Q(e,t.files.fields,V.fields)}function ao(e,t){return Q(e,t.files.types,V.types)}async function _t(e,t,n,a){for(let i of t){let r=$a(i.folder??Ea(i.name)),o=Hl.join(e,r);await k(o)||(await Kl(o,{recursive:!0}),n.push(...await B({path:o,scope:"project",op:a})))}}function Vn(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function Zl(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Ql(e){let t=new Map;for(let n of e){let a=A(n.id);if(a.length!==0){t.set(a,a);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let r=A(i);r.length>0&&!t.has(r)&&t.set(r,a)}}}return t}async function Ay(e,t,n){let a=F(process.cwd(),n.path);await we(a);let i;try{i=Ji({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}let r=await I(a),o=K(r.schema),s=Kn(a,o),d=at(o);try{$n(i,d.alias_to_id)}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}let c=Zl(d.by_id.get(i.id));if((i.roles??c?.roles??[]).length===0)throw new u(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,h.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Pe(i.id)}" --role active`,`pm schema add-status "${Pe(i.id)}" --role blocked`]});let l=[],p=q(t.author,r.author_default),m=fe(r),y=await ee(a,Qr,r.locks.ttl_seconds,p,!!t.force,m.force_required_for_stale_lock,r.locks.wait_ms),g;try{let _=await M(s),f;try{f=We(_)}catch(v){throw new u(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=Ql(f.statuses);try{$n(i,w)}catch(v){throw new u(v instanceof Error?v.message:String(v),h.USAGE)}g=qi(f,i,c),await Ae({pmRoot:a,filePath:s,raw:Be(g.file),op:"schema:add-status",author:p,settings:r}),l.push(...await B({path:s,scope:"project",op:"schema:add-status"}))}finally{await y()}return{action:"add-status",registered:!0,replaced:g.replaced,status:g.definition,file:{path:s,statuses:g.file.statuses.length},warnings:Te(l),generated_at:T()}}async function Ty(e,t,n){let a=F(process.cwd(),n.path);await we(a);let i=await I(a),r=K(i.schema),o=Kn(a,r),s=[],d=q(t.author,i.author_default),c=fe(i),l=await ee(a,Qr,i.locks.ttl_seconds,d,!!t.force,c.force_required_for_stale_lock,i.locks.wait_ms),p;try{let m=await M(o),y;try{y=We(m)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=Wi(y,e)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=A(p.definition?.id??e);await Xl(s,a,i,r,g),await Ae({pmRoot:a,filePath:o,raw:Be(p.file),op:"schema:remove-status",author:d,settings:i}),s.push(...await B({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:o,statuses:p.file.statuses.length},warnings:Te(s),generated_at:T()}}function io(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function ep(e,t,n){return{...io(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function ro(e){return{id:e.id,source:je.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function oo(e,t,n){let a=e.toLowerCase();return n.has(a)?"extension":t.has(a)?"custom":"builtin"}function tp(){let e=new Map,t=J();for(let n of t?.item_types??[]){let a=n.types;if(Array.isArray(a))for(let i of a){if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i.name;typeof r=="string"&&r.trim().length>0&&e.set(r.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function np(e){let t=at(e),n=[],a=[];for(let i of t.definitions){let r=ro(i);r.source==="builtin"?n.push(r):a.push(r)}return{builtin:n,custom:a}}async function wt(e){let t=F(process.cwd(),e.path);await we(t);let n=await I(t),a=K(n.schema),i=Q(t,a.files.types,V.types),r=Kn(t,a),o=W(n,J()),s=tp(),d=new Set((n.item_types?.definitions??[]).map(c=>c.name.trim().toLowerCase()).filter(c=>c.length>0&&!s.has(c)));return{pmRoot:t,typesPath:i,statusesPath:r,byType:o.by_type,customNames:d,extensionProvenance:s,schema:a}}async function Oy(e){let t=await wt(e),n=[],a=[],i=[];for(let s of Object.values(t.byType).sort((d,c)=>d.name.localeCompare(c.name))){let d=oo(s.name,t.customNames,new Set(t.extensionProvenance.keys())),c=io(s);d==="extension"?i.push(c):d==="custom"?a.push(c):n.push(c)}let r=np(t.schema),o=Tt(t.schema).definitions.map(Vn);return{action:"list",builtin:n,custom:a,extension:i,counts:{builtin:n.length,custom:a.length,extension:i.length,total:n.length+a.length+i.length},statuses:{builtin:r.builtin,custom:r.custom,counts:{builtin:r.builtin.length,custom:r.custom.length,total:r.builtin.length+r.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:T()}}async function Cy(e,t){let n=(e??"").trim();if(n.length===0)throw new u("Type name must not be empty.",h.USAGE);let a=await wt(t),i=Object.values(a.byType).find(r=>r.name.toLowerCase()===n.toLowerCase()||r.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!i)throw new u(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Pe(n)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:ep(i,oo(i.name,a.customNames,new Set(a.extensionProvenance.keys())),a.extensionProvenance.get(i.name.toLowerCase())),file:{path:a.typesPath},generated_at:T()}}async function Ry(e,t){let n=A(e);if(n.length===0)throw new u("Status id must not be empty.",h.USAGE);let a=await wt(t),i=at(a.schema),r=i.alias_to_id.get(n)??n,o=i.by_id.get(r);if(!o)throw new u(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Pe(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:ro(o),file:{path:a.statusesPath},generated_at:T()}}async function Py(e,t,n){let a=F(process.cwd(),n.path);await we(a);let i;try{i=Ui({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}let r=await I(a),o=K(r.schema),s=Xt(a,o),d=[],c=Rt(i.key);c&&d.push(`custom_field_mcp_input_collision:${c.field}:${c.property}:${c.owner}:use=${c.nested_path}`);let l=q(t.author,r.author_default),p=fe(r),m=await ee(a,eo,r.locks.ttl_seconds,l,!!t.force,p.force_required_for_stale_lock,r.locks.wait_ms),y;try{let g=await M(s),_;try{_=Je(g)}catch(f){throw new u(f instanceof Error?f.message:String(f),h.GENERIC_FAILURE)}y=zi(_,i),await Ae({pmRoot:a,filePath:s,raw:qe(y.file),op:"schema:add-field",author:l,settings:r}),d.push(...await B({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:y.replaced,field:y.definition,file:{path:s,fields:y.file.fields.length},warnings:Te(d),generated_at:T()}}async function ap(e,t,n,a){let i=W(t,J());return(await Ne(e,t.item_format,i.type_to_folder,[],n)).filter(r=>{let o=r[a];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function Ny(e,t,n){let a=F(process.cwd(),n.path);await we(a);let i=await I(a),r=K(i.schema),o=Xt(a,r),s=[],d=q(t.author,i.author_default),c=fe(i),l=await ee(a,eo,i.locks.ttl_seconds,d,!!t.force,c.force_required_for_stale_lock,i.locks.wait_ms),p;try{let m=await M(o),y;try{y=Je(m)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=Gi(y,e)}catch(g){throw new u(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=A(p.definition?.key??e),_=A(p.definition?.metadata_key??p.definition?.front_matter_key??g);if(_.length>0){let f=await ap(a,i,r,_);f>0&&s.push(`items_using_field:${f}`)}await Ae({pmRoot:a,filePath:o,raw:qe(p.file),op:"schema:remove-field",author:d,settings:i}),s.push(...await B({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:o,fields:p.file.fields.length},warnings:Te(s),generated_at:T()}}async function Dy(e){let t=await wt(e),n=Tt(t.schema).definitions.map(Vn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Xt(t.pmRoot,t.schema)},generated_at:T()}}async function jy(e,t){let n=A(e);if(n.length===0)throw new u("Field key must not be empty.",h.USAGE);let a=await wt(t),i=Tt(a.schema).by_key.get(n);if(!i)throw new u(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Pe(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Vn(i),file:{path:Xt(a.pmRoot,a.schema)},generated_at:T()}}async function Ly(e,t,n){let a=F(process.cwd(),n.path);await we(a);let i;try{let _=Vt(e);if(_===void 0)throw new Error(`Type preset name is required. Allowed: ${gt.join(", ")}.`);i=_}catch(_){throw new u(_ instanceof Error?_.message:String(_),h.USAGE)}let r=await I(a),o=K(r.schema),s=ao(a,o),d=[],c=q(t.author,r.author_default),l=fe(r),p=[],m=[],y,g=await ee(a,Yt,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms);try{let _=await M(s),f;try{f=ae(_)}catch(v){throw new u(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=f;for(let v of yt(i)){let E=Ue(w,v);w=E.file,(E.replaced?m:p).push(E.definition.name)}y=w.definitions.length,await Ae({pmRoot:a,filePath:s,raw:se(w),op:"schema:apply-preset",author:c,settings:r}),await _t(a,yt(i),d,"schema:apply-preset-folder"),d.push(...await B({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await g()}return{action:"apply-preset",preset:i,registered:p,replaced:m,file:{path:s,definitions:y},warnings:Te(d),generated_at:T()}}function ip(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new u("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function Fy(e,t){let n=F(process.cwd(),t.path);await we(n);let a=await I(n),i=K(a.schema),r=ao(n,i),o=ip(e.minCount),s=W(a,J()),d=(await Ne(n,a.item_format,s.type_to_folder,[],i)).map(v=>typeof v.title=="string"?v.title:""),c=Zr(d,{minCount:o}),l=[],p=[],m=[],y=[],g;if(!e.apply){let v;try{v=ae(await M(r))}catch(E){throw new u(E instanceof Error?E.message:String(E),h.GENERIC_FAILURE)}return g=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:c,registered:p,replaced:m,skipped:y,file:{path:r,definitions:g},warnings:l,generated_at:T()}}let _=q(e.author,a.author_default),f=fe(a),w=await ee(n,Yt,a.locks.ttl_seconds,_,!!e.force,f.force_required_for_stale_lock,a.locks.wait_ms);try{let v=await M(r),E;try{E=ae(v)}catch(C){throw new u(C instanceof Error?C.message:String(C),h.GENERIC_FAILURE)}let S=E;for(let C of c){if(C.shadows_builtin){y.push({name:C.name,reason:"shadows_builtin"});continue}let ne;try{ne=it({name:C.name})}catch{y.push({name:C.name,reason:"invalid_type_token"});continue}let j=Ue(S,ne);S=j.file,(j.replaced?m:p).push(j.definition.name)}g=S.definitions.length,await Ae({pmRoot:n,filePath:r,raw:se(S),op:"schema:infer-types",author:_,settings:a}),await _t(n,S.definitions.filter(C=>p.includes(C.name)||m.includes(C.name)),l,"schema:infer-types-folder"),l.push(...await B({path:r,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:o,candidates:c,registered:p,replaced:m,skipped:y,file:{path:r,definitions:g},warnings:Te(l),generated_at:T()}}function My(e){let t=e.replaced?"Updated":"Registered",n=e.type.aliases&&e.type.aliases.length>0?` (aliases: ${e.type.aliases.join(", ")})`:"";return`${t} custom item type "${e.type.name}"${n} in ${e.file.path}. Run: pm create "${Pe(e.type.name)}" "<title>"`}function Uy(e){return e.removed?`Removed custom item type "${e.type?.name??"(unknown)"}" from ${e.file.path}.`:`No custom item type matched; nothing removed from ${e.file.path}.`}function zy(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",a=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${a} in ${e.file.path}.`}function Gy(e){return e.removed?`Removed custom status "${e.status?.id??"(unknown)"}" from ${e.file.path}.`:`No custom status matched; nothing removed from ${e.file.path}.`}function Jy(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,a]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])a.length!==0&&t.push(`${n}: ${a.map(i=>i.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,a]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])a.length!==0&&t.push(`${n}: ${a.map(i=>i.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(n=>`${n.key} (${n.type}, ${n.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
34
+ `)}function qy(e){let t=[`type: ${e.type.name}`,`source: ${e.type.source}`,`folder: ${e.type.folder}`];return e.type.default_status&&t.push(`default_status: ${e.type.default_status}`),e.type.aliases.length>0&&t.push(`aliases: ${e.type.aliases.join(", ")}`),e.type.description&&t.push(`description: ${e.type.description}`),e.type.options.length>0&&t.push(`options: ${e.type.options.map(n=>n.key).join(", ")}`),t.join(`
35
+ `)}function Wy(e){let t=[`status: ${e.status.id}`,`source: ${e.status.source}`];return e.status.roles.length>0&&t.push(`roles: ${e.status.roles.join(", ")}`),e.status.aliases.length>0&&t.push(`aliases: ${e.status.aliases.join(", ")}`),e.status.description&&t.push(`description: ${e.status.description}`),typeof e.status.order=="number"&&t.push(`order: ${e.status.order}`),t.join(`
36
+ `)}function rp(e){let t=[];e.required&&t.push("required"),e.required_on_create&&t.push("required_on_create"),e.allow_unset||t.push("no_unset");let n=t.length>0?` [${t.join(", ")}]`:"";return`${e.key} (${e.type}) ${e.cli_flag} commands=${e.commands.join("/")}${n}`}function By(e){return`${e.replaced?"Updated":"Registered"} custom field "${e.field.key}" in ${e.file.path}. Use it: pm create "<title>" --${(e.field.cli_flag??e.field.key).replaceAll("_","-")} <value>`}function Hy(e){return e.removed?`Removed custom field "${e.field?.key??"(unknown)"}" from ${e.file.path}.`:`No custom field matched; nothing removed from ${e.file.path}.`}function Ky(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${rp(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
37
+ `)}function Vy(e){let t=e.field,n=[`field: ${t.key}`,`type: ${t.type}`,`cli_flag: ${t.cli_flag}`,`commands: ${t.commands.join(", ")}`];return t.cli_aliases.length>0&&n.push(`cli_aliases: ${t.cli_aliases.join(", ")}`),t.description&&n.push(`description: ${t.description}`),t.required&&n.push("required: true"),t.required_on_create&&n.push("required_on_create: true"),t.allow_unset||n.push("allow_unset: false"),t.required_types.length>0&&n.push(`required_types: ${t.required_types.join(", ")}`),n.join(`
38
+ `)}function Yy(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",a=[t,n].filter(i=>i.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${a.length>0?` (${a})`:""}.`}function Xy(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;let t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(let n of e.candidates){let a=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${a}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
39
+ `)}var Zy={workflowSlotsReferencing:no};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a8289336-e833-5617-9a32-0a21f28f294e")}catch{}})();function so(e){let t=/^extension_(disabled_)?pm_(min|max)_version_([a-z_]+):(project|global):([^:]+):(.+)$/u.exec(e);if(!t)return;let[,n,a,i,r,o,s]=t,d=s.split(":")[0].replace(a==="min"?"required=":"allowed=",""),c=i==="invalid"?`a valid pm_${a}_version instead of ${d}`:`pm ${a==="min"?">=":"<="} ${d}`;return n?`Package ${o} is disabled and requires ${c} before activation. After satisfying the bound, run ${oe(["package","activate",o,`--${r}`])}.`:`Package ${o} requires ${c}. Use a compatible host or package version, or keep it disabled with ${oe(["package","deactivate",o,`--${r}`])}.`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="573b0fd6-f003-55d8-8f49-c2a5e81cbc31")}catch{}})();function Yn(e){return e.map(({layer:t,name:n,error:a})=>({layer:t,name:n,error:a}))}function Zt(e,t,n){let a=b(t),i=n.trim();if(a.length===0||i.length===0)return;let r=e.get(a)??new Set;r.add(i),e.set(a,r)}function op(e){let t=new Map,n=new Map;for(let a of e.registrations.commands)Zt(t,a.name,a.command),Zt(n,a.name,a.action);for(let a of e.commands.handlers)Zt(t,a.name,a.command);for(let a of e.commands.overrides)Zt(t,a.name,a.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function co(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function sp(e){let{enabled:t,normalizedName:n,loadedNames:a,loadFailedNames:i,activationFailedNames:r}=e;return t?i.has(n)||r.has(n)?{runtime_active:!1,activation_status:"failed"}:a.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function Qt(e,t,n){let a=new Set(t.loaded.map(d=>b(d.name))),i=new Set(t.failed.map(d=>b(d.name))),r=new Set(n.failed.map(d=>b(d.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=op(n);return e.map(d=>{let c=b(d.name),l=co(o.get(c)),p=co(s.get(c)),m={...l?{command_paths:l}:{},...p?{action_paths:p}:{}},y=sp({enabled:d.enabled,normalizedName:c,loadedNames:a,loadFailedNames:i,activationFailedNames:r});return{...d,...y,...m}})}function cp(e){let t=0,n=0,a=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(a+=1)}return{warning_count:t,violation_count:n,blocked_count:a}}function U(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var mo=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function dp(e){return mo.has(_o(e))}function lo(e){return e==="project"||e==="global"}function uo(e){let t=e.split(":"),n=t[0];if(!n||!mo.has(n))return null;let a=t.at(-4),i=t.at(-3)?.trim(),r=t.at(-2),o=t.at(-1)?.trim();return!lo(a)||!lo(r)||!i||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:a,name:i},displaced:{layer:r,name:o}}}function lp(e){let t=new Set;for(let n of e){let a=uo(n);a&&(t.add(a.winner.name),t.add(a.displaced.name))}return[...t].sort((n,a)=>n.localeCompare(a))}function pp(e,t){let n=e.filter(dp);if(n.length===0)return null;let a=lp(n);return`Extension registration collisions or handler/override overlaps detected.${a.length>0?` Conflicting extensions: ${a.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function mp(e,t,n,a){let i=t.map(p=>uo(p)).filter(p=>p!==null).sort((p,m)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let r=e==="global"?"--global":"--project",o=U(a,"deactivate"),s=`${U(a,"doctor")} ${r} --detail deep --trace`,d=new Map(n.map(p=>[b(p.name),p])),c=new Map;for(let p of i)for(let m of[p.winner.name,p.displaced.name]){let y=b(m);c.set(y,(c.get(y)??0)+1)}let l=[...c.entries()].map(([p,m])=>{let y=d.get(p),g=y?.name??p,_=y?.command_paths??[],f=y?.action_paths??[];return{action:"deactivate",extension:g,command:`${o} ${g} ${r}`,affected_collisions:m,feature_loss:{command_paths:[..._].sort((w,v)=>w.localeCompare(v)),action_paths:[...f].sort((w,v)=>w.localeCompare(v))}}}).sort((p,m)=>{let y=m.affected_collisions-p.affected_collisions;if(y!==0)return y;let g=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,_=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return g!==_?g-_:p.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:c.size,next_best_command:s,collisions:i,remediation_candidates:l}}function fo(e){let t=[];for(let n of e){let a=n.error.toLowerCase();(a.includes("cannot find package '@unbrained/pm-cli'")||a.includes('cannot find module "@unbrained/pm-cli"')||a.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(a.includes("cannot use import statement outside a module")||a.includes("to load an es module")||a.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,a)=>n.localeCompare(a))}function ho(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let a of t){if(!a||typeof a.name!="string")continue;let i=a.trace?.missing_capability??a.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${a.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((a,i)=>a.localeCompare(i))}function go(e,t){let n=[];for(let a of Ga(e.loaded,t))for(let i of a.unused)n.push(`extension_capability_unused:${a.layer}:${a.name}:${i}`);return[...new Set(n)].sort((a,i)=>a.localeCompare(i))}var up=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${U(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${ha.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${U(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${U(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${U(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function fp(e){let{normalizedWarnings:t,options:n,scope:a,scopeFlag:i,updateCheckFailedTotal:r,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:d,skippedNonGithubTotal:c,updateAvailableTotal:l}=e,p=t.map(so).filter(y=>y!==void 0),m={options:n,scope:a,scopeFlag:i,updateCheckFailedTotal:r,policyWarningCount:o};if(t.length>0){let y=pp(t,{deactivate:`${U(n,"deactivate")} <name> ${i}`,doctor:`${U(n,"doctor")} ${i} --detail deep --trace`});y&&p.push(y);for(let g of up)g.matches(t,m)&&p.push(g.build(m))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${U(n,"manage")} ${i} --fix-managed-state (or ${U(n,"adopt-all")} ${i}, ${U(n,"adopt")} <name> ${i}, or reinstall via ${U(n,"install")} ${i} <source>).`),c>0&&p.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),d>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${U(n,"manage")} ${i} to request update checks.`),l>0&&p.push(`Update available managed extensions via ${U(n,"install")} ${i} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${U(n,"manage")} ${i} after extension changes.`),p}function en(e,t,n,a={}){let i=[...new Set(t)].sort((x,G)=>x.localeCompare(G)),r=n.filter(x=>x.managed).length,o=n.filter(x=>x.enabled).length,s=n.filter(x=>x.active).length,d=n.filter(x=>x.update_check_status==="checked"&&x.update_available===!0).length,c=n.filter(x=>x.managed===!1),l=c.filter(x=>po(x)).map(x=>x.name).sort((x,G)=>x.localeCompare(G)),p=c.filter(x=>!po(x)).map(x=>x.name).sort((x,G)=>x.localeCompare(G)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let x of n)m[x.update_check_status]+=1;let y=m.failed,g=n.filter(x=>x.update_check_status==="skipped_non_github"&&x.source?.kind!=="builtin").length,_=Object.entries({skipped_unmanaged:p.length,skipped_non_github:g,failed:y,not_checked:m.not_checked}).filter(([,x])=>x>0).map(([x,G])=>`extension_update_health_partial_coverage:${x}:${G}`),f=_.length>0,w=f?"partial":"full",v=[...new Set([...i,..._])].sort((x,G)=>x.localeCompare(G)),E=[...new Set(v.map(x=>_o(x)))].sort((x,G)=>x.localeCompare(G)),S=cp(v),C=e==="global"?"--global":"--project",ne=mp(e,i,n,a),j=fp({normalizedWarnings:v,options:a,scope:e,scopeFlag:C,updateCheckFailedTotal:y,policyWarningCount:S.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:g,updateAvailableTotal:d});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:E,warnings:v,policy_warning_count:S.warning_count,policy_violation_count:S.violation_count,policy_blocked_count:S.blocked_count,total_extensions:n.length,managed_total:r,enabled_total:o,active_total:s,update_available_total:d,update_health_coverage:w,update_health_partial:f,unmanaged_loaded_extension_count:c.length,unmanaged_loaded_extensions:c.map(x=>x.name).sort((x,G)=>x.localeCompare(G)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:m,update_check_failed_total:y,top_warnings:v.slice(0,8),remediation:j,...ne?{collision_plan:ne}:{}}}function yo(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new u(`Invalid --detail value "${e}". Expected summary or deep.`,h.USAGE)}function _o(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function wo(e){let t=new Set,n=[];for(let a of e){let i=(()=>{let r=Da(a);return r?[r]:ja(a)})();for(let r of i){let o=`${r.layer}:${r.name}:${r.capability}`;t.has(o)||(t.add(o),n.push(r))}}return n}function vo(){return{version:xt.version,capabilities:[...xt.capabilities],legacy_aliases:{...xt.legacy_aliases}}}function po(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function bo(e,t,n,a,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let r=[...new Set(t.filter(c=>c.active).map(c=>b(c.name)))].sort((c,l)=>c.localeCompare(l)),o=[...new Set(n.filter(c=>c.layer==="project").map(c=>b(c.name)))].sort((c,l)=>c.localeCompare(l)),s=new Set(a.map(c=>b(c.name))),d=r.filter(c=>!o.includes(c)&&!s.has(c)).sort((c,l)=>c.localeCompare(l));return{warnings:d.length>0?[`extension_doctor_consistency_active_not_loaded:${d.join(",")}`]:[],summary:{active_project_count:r.length,loaded_project_count:o.length,active_project_names:r,loaded_project_names:o,missing_active_project_names:d}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var Xn=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let a=new Array(e.length),i=0,r=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,a[o]=await n(e[o])}});return await Promise.all(r),a};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function ko(e,t){let n=b(e),a=t.find(i=>b(i.name)===n);return{command_paths:[...a?.command_paths??[]].sort((i,r)=>i.localeCompare(r)),action_paths:[...a?.action_paths??[]].sort((i,r)=>i.localeCompare(r))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function xo(e,t){let n=new Set((t?.loaded??[]).flatMap(r=>(r.activation?.commands?.length??0)>0?[`${r.layer}:${b(r.name)}`]:[])),a=e.services.overrides.filter(r=>r.service==="output_format").filter(r=>r.passThrough!==!0).filter(r=>!n.has(`${r.layer}:${b(r.name)}`)).map(r=>`extension_output_service_override_global:${r.service}:${r.layer}:${r.name}`),i=e.renderers.overrides.filter(r=>(r.commands?.length??0)===0&&r.resultDiscriminator===void 0).map(r=>`extension_output_renderer_override_global:${r.format}:${r.layer}:${r.name}`);return[...new Set([...a,...i])].sort((r,o)=>r.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var So=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Rt(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,a)=>a.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{execFile as hp}from"node:child_process";import{promisify as gp}from"node:util";import yp from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b67e46f9-51ff-501b-98da-74353b4c66d9")}catch{}})();var _p=gp(hp),$o=1e4;function Eo(e,t,n){if(typeof t=="string")try{let a=yp.resolve(e,t);if(a.type==="version")return a.fetchSpec}catch{}throw new Error(n)}async function wp(e,t){try{return(await _p(Un(),e,{encoding:"utf8",timeout:t,maxBuffer:65536,shell:zn(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function Io(e,t=wp){let n=T();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let a=Eo(e.package,e.version,"missing_or_invalid_installed_npm_version"),i=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],$o),r;try{r=JSON.parse(i)}catch{throw new Error("invalid_npm_registry_metadata")}let o=Array.isArray(r)&&r.length===1?r[0]:r,s=Eo(e.package,o,"invalid_npm_registry_version");return{checked_at:n,available:s!==a,remote_version:s}}catch(a){return{checked_at:n,available:null,error:a instanceof Error?a.message:String(a)}}}var vp=(e,t,n)=>{let a=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,d=""]=o.split(/\s+/);return{commit:s,ref:d}}),i=a.find(o=>o.ref.endsWith("^{}"))??a[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let r=t?.trim();return r?{checked_at:n,remote_commit:i.commit,available:i.commit!==r}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},Zn=async(e,t=Jt)=>{let n=T();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let a=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,a,`${a}^{}`],void 0,$o);return vp(i,e.commit,n)}catch(a){return{checked_at:n,available:null,error:a instanceof Error?a.message:String(a)}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d34e2cc0-5e58-5534-8480-a9ab47ec4a88")}catch{}})();var bp=4;async function Ao(e,t=!1){let n=await Xn(e.entries,bp,async a=>{if(!["github","npm"].includes(a.source.kind))return a;if(t)return{...a,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0};let i=a.source.kind==="github"?await Zn(a.source):await Io(a.source);return{...a,last_update_check_at:i.checked_at,last_update_remote_commit:"remote_commit"in i?i.remote_commit:void 0,last_update_remote_version:"remote_version"in i?i.remote_version:void 0,update_available:i.available,update_error:i.error}});return{...e,entries:ct(n)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17cca82e-e9f9-5633-8d91-bc6c2b560d5f")}catch{}})();function To(e,t){let n=e.filter(a=>a.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:a,result:i})=>{let r=i.details;return{alias:a,ok:i.ok,extension:r.extension,source:r.source,source_resolution:r.source_resolution,install_plan:r.install_plan,dry_run:r.dry_run,destination_path:r.destination_path,activated:r.activated,settings_changed:r.settings_changed,previous_state_preserved:r.previous_state_preserved,rollback:r.rollback,command_paths:r.command_paths,action_paths:r.action_paths,command_discovery:r.command_discovery,verification:r.verification,runtime_activation_status:r.runtime_activation_status,activation_diagnostics:r.activation_diagnostics,warnings:i.warnings}})}}import kp from"node:fs/promises";import xp 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]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function Sp(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Ep(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function $p(e){let t=xp.join(e,"manifest.json"),n;try{n=await kp.readFile(t,"utf8")}catch(s){if(Et(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let a;try{a=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof a!="object"||a===null||Array.isArray(a))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=a,r=Fa(i),o=Sp(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:r.findings,warnings:r.findings.map(s=>Ep(o,s)),remediation:r.findings.map(s=>s.message)}}function Oo(e){return $p(Ia(e))}import re from"node:fs/promises";import et 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]="7c06c702-29ea-5552-aadc-52dfc9c238ef")}catch{}})();var Qn=async e=>re.readFile(e).catch(t=>{if(Bt(t,"ENOENT"))return null;throw t}),Ip=async(e,t,n,a,i)=>Re("extension_install_backup",async()=>{let r=st(e),o=Aa(t),[s,d]=await Promise.all([Qn(r),Qn(o)]);return a&&await re.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:a,managedStatePath:r,managedStateContents:s,settingsPath:o,settingsContents:d}}),Co=async e=>Re("extension_install_rollback",async()=>{await re.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await re.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])if(n===null)await re.rm(t,{force:!0});else if(t===e.settingsPath){let a=et.dirname(e.settingsPath),i=await I(a);try{await Se({pmRoot:a,filePath:t,raw:n.toString("utf8"),op:"extension:install:rollback",author:q(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms})}finally{ti(a)}}else await re.mkdir(et.dirname(t),{recursive:!0}),await re.writeFile(t,n)});async function Ro(e,t){let n=await k(e.destinationDirectory),a=await Qe(e.sourceDirectory,e.destinationDirectory);await re.mkdir(e.selectedRoot,{recursive:!0});let i=et.join(et.dirname(e.selectedRoot),"runtime","extension-installs");await re.mkdir(i,{recursive:!0});let r=await re.mkdtemp(et.join(i,".pm-extension-install-backup-")),o=et.join(r,"destination"),s=["package","install",o,`--${e.scope}`],d=oe(s),c=!1;try{let l=await Ip(e.selectedRoot,e.settingsRoot,e.destinationDirectory,n,o),p;try{p=await t()}catch(m){try{await Co(l)}catch(y){c=!0;let g=new u(`Extension install failed: ${String(m)}; rollback failed: ${String(y)}`,h.GENERIC_FAILURE,{code:"extension_install_rollback_failed",original_code:m instanceof u?m.code:void 0,required:"Restore the previous package before retrying the replacement. Previous state was not preserved.",nextSteps:[n?d:"Repair the reported metadata write failure, then retry the original install."],...n?{recovery:{suggested_retry:d,suggested_retry_args:s}}:{}});throw Object.defineProperty(g,"cause",{value:m,configurable:!0,writable:!0}),g}throw m}if(p.ok)return p;if(!n||a)return{...p,details:{...p.details,previous_state_preserved:!1}};try{await Co(l)}catch(m){return c=!0,{...p,details:{...p.details,previous_state_preserved:!1,rollback:{status:"failed",error:String(m),backup_directory:o,recovery_command:d,recovery_args:s}}}}return{...p,details:{...p.details,overwritten:!1,settings_changed:!1,previous_state_preserved:!0,rollback:{status:"restored"}}}}finally{c||await re.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ae11424-9de8-5bce-91b4-e8901459fb5f")}catch{}})();var jo=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],Ap=jo.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Tp={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},Op="__pm_native_output",Cp=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Lo=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Rp=["disabled","require_trusted","require_provenance"],Fo={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},Pp=e=>{let t=e??Fo,n={};for(let a of Cp)n[a]=Z(t[a]??[]);return n},Np=(e,t)=>{for(let n of Lo)t[n].length>0&&(e[n]=t[n]);return e},Dp=(e,t)=>{for(let n of Rp)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},jp=e=>{let t={};for(let n of Lo)t[n]=Z(e[n]??[]);return t},Lp=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Np(Dp({name:t},e),jp(e))},Fp=e=>(e??[]).map(t=>Lp(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Mp=e=>{let t=Object.assign({},Fo,e??{}),n=Pp(e),a=Fp(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:a}},Mo=async(e,t)=>{let n=[t],a=await pr(t);a&&n.push(a);let i=[...new Set(n.map(r=>b(r)).filter(r=>r.length>0))];for(let r of i){let o=e.find(d=>b(d.name)===r);if(o)return o;let s=e.find(d=>b(d.directory)===r);if(s)return s}},Uo=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled));return new Set(Z(e.extensions.disabled)).has(n)?!1:a.size===0?!0:a.has(n)},zo=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled)),i=new Set(Z(e.extensions.disabled)),r=[...a],o=[...i];return i.delete(n),a.size>0&&a.add(n),e.extensions.enabled=[...a].sort((s,d)=>s.localeCompare(d)),e.extensions.disabled=[...i].sort((s,d)=>s.localeCompare(d)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Up=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled)),i=new Set(Z(e.extensions.disabled)),r=[...a],o=[...i];return a.delete(n),i.add(n),e.extensions.enabled=[...a].sort((s,d)=>s.localeCompare(d)),e.extensions.disabled=[...i].sort((s,d)=>s.localeCompare(d)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},zp=(e,t)=>{let n=t.trim(),a=new Set(Z(e.extensions.enabled)),i=new Set(Z(e.extensions.disabled)),r=[...a],o=[...i];return a.delete(n),i.delete(n),e.extensions.enabled=[...a].sort((s,d)=>s.localeCompare(d)),e.extensions.disabled=[...i].sort((s,d)=>s.localeCompare(d)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Gp=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),a=jo.map(([i,r,o])=>({action:r,flag:o,distance:Ca(t,i,n)})).filter(i=>i.distance!==null).sort((i,r)=>i.distance-r.distance)[0];return a?{action:a.action,flag:a.flag}:null},Jp=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=Gp(e);if(!a)return new u(`One action flag is required. Use one of: ${Ap}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let i=`pm ${n} ${a.flag}`;return Ra({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(Go),retry_command:i,message_suffix:`. Did you mean "${a.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},qp=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],Go={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Wp=e=>Go[e]??null,Bp=(e,t)=>{let n=[...new Set(qp.filter(([a])=>t[a]===!0).map(([,a])=>a))];if(n.length===0){if(e===void 0)return"explore";let a=Wp(e.trim().toLowerCase());if(a)return a;throw Jp(e,t)}if(n.length>1)throw new u("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},Hp=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new u('Options "--project/--local" and "--global" are mutually exclusive.',h.USAGE);return n?"global":"project"},Kp=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],Jo=e=>{for(let t of Kp){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},qo=(e,t,n,a)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,last_update_remote_version:i.last_update_remote_version,update_error:i.update_error,update_check_status:a.status,update_check_reason:a.reason}},Vp=(e,t,n,a)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},a),r=a?Uo(n,a.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:qo({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:r},t,a,Jo(a))}},Yp=async(e,t,n,a,i,r)=>{let o=te.join(e,t),s=te.join(o,"manifest.json"),d=r.get(b(t));if(!await k(s))return Vp(t,n,a,d);let c=Symbol("invalid-extension-manifest-json"),l=await tt.readFile(s,"utf8").then(y=>JSON.parse(y)).catch(()=>c);if(l===c)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Rn(l);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(b(p.name))??r.get(b(t));return{summary:qo({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:Uo(a,p.name)},n,m,Jo(m))}},me=async(e,t,n,a)=>{if(!await k(e))return{extensions:[],warnings:[]};let i=(await tt.readdir(e,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name).sort((c,l)=>c.localeCompare(l)),r=new Map(a.entries.map(c=>[b(c.name),c])),o=new Map(a.entries.map(c=>[b(c.directory),c])),s=[],d=[];for(let c of i){let l=await Yp(e,c,t,n,r,o);l.warning&&s.push(l.warning),l.summary&&d.push(l.summary)}return{extensions:d.sort((c,l)=>c.name.localeCompare(l.name)),warnings:s.sort((c,l)=>c.localeCompare(l))}},Xp=Ua(),Zp=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Qp=(e,t,n,a)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),r=a?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return r&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Zp(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:o,...r?{sdk_dependency_status:"missing"}:{}}},em=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,a])=>a!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},Wo=e=>e.map(t=>em(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),Bo=(e,t,n)=>{let a=b(e);return t.find(i=>(n===void 0||i.layer===n)&&b(i.name)===a)},tm=(e,t,n,a)=>n.find(i=>i.scope===t&&b(i.name)===b(e))?.activation_status??(a?"failed":"unknown"),Ho=(e,t,n,a,i)=>Xp.enqueue(async()=>{let r=process.env.PM_CLI_PACKAGE_ROOT,o=await tt.mkdtemp(te.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=be(import.meta.url,["../.."]);try{let s=await ke({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:un(),cache_bust:!0,module_graph_snapshot_root:o}),d=await xe({...s}),c=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...Wo(d.failed)],l=Object.fromEntries(s.loaded.map(p=>[b(p.name),Na(Ge(d,{extensionName:p.name}))]));return{installed:Qt(a,s,d),warnings:[...s.warnings,...d.warnings],activation_failures:c,extensions_disabled:s.disabled_by_flag,item_type_registrations:d.registrations.item_types,contribution_inventories:l}}finally{await tt.rm(o,{recursive:!0,force:!0}),r===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=r}}),ta=async(e,t,n,a)=>{let i=n.filter(d=>!d.managed),r=[...i].sort((d,c)=>{let l=d.name.localeCompare(c.name);return l!==0?l:d.directory.localeCompare(c.directory)}),o=a,s=[];for(let d of r){let c=te.join(e,d.directory),l=await Xe(c),p=T(),m={kind:"local",input:d.name,location:c};o=dt(o,{name:l.manifest.name,directory:d.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:p,updated_at:p,source:m}),s.push({name:l.manifest.name,directory:d.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return s.length>0&&await Ze(e,o),{state:o,adopted_entries:s,unmanaged_candidates:r,already_managed_count:n.length-i.length}},nm=(e,t)=>{let n=F(process.cwd(),t.path),a=It(n,process.cwd()),i=e==="global"?Ce(process.cwd()):n,r=e==="global"?a.global:a.project;return{pm_root:n,scope:e,settings_root:i,selected_root:r,roots:a}},tn=e=>{let t=[e.gh,e.github].filter(a=>typeof a=="string").map(a=>a.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new u('Options "--gh" and "--github" must match when both are provided.',h.USAGE);return n[0]},am=e=>Tp[e],im=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=e==="install"?"source":"name",i=`${n} ${a}`,r=am(e),o=`<${a}>`,s=`pm ${n} ${r} ${o}`;throw new u(`Action "${e}" requires ${i} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${a} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${a} target`}]}})},nn=(e,t,n={})=>{let a=e?.trim();if(a)return a;if(t==="init")throw new u('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',h.USAGE);return im(t,n)},rm=(e,t)=>{let n=new Set([...t.registrations.item_types.map(a=>({entry:a,count:a.types.length})),...t.registrations.item_fields.map(a=>({entry:a,count:a.fields.length}))].filter(({count:a})=>a>0).map(({entry:a})=>`${a.layer}:${b(a.name)}`));return e.loaded.filter(a=>(a.activation?.commands??[]).length>0).filter(a=>n.has(`${a.layer}:${b(a.name)}`)).map(a=>`extension_schema_narrow_activation:${a.layer}:${a.name}`).filter((a,i,r)=>r.indexOf(a)===i).sort((a,i)=>a.localeCompare(i))},om=(e,t)=>{let n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(a=>a.triggered&&!a.allowed);if(n)throw new u(n.message,h.USAGE)},sm=(e,t,n)=>{let a=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(a)?void 0:e},cm=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},dm=(e,t,n)=>{let a={ok:n,action:e.action,scope:e.scope,roots:cm(e),warnings:[...new Set(e.warnings)].sort((i,r)=>i.localeCompare(r)),details:t};return e.action==="doctor"&&Object.defineProperty(a,Op,{value:!0,enumerable:!1,configurable:!1}),a},na=async(e,t,n)=>{let a=Bp(e,t);om(a,t);let i=sm(e,a,t),r=Hp(t),o=nm(r,n),s={action:a,normalizedTarget:i,scope:r,resolvedRoots:o,warnings:[],options:t,global:n},d={...s,withResult:(c,l=!0)=>dm(s,c,l)};return await Gm(d)},lm=(e,t)=>{let n=t.vocabulary??"extension",a=e.target_path.replace(/\\/g,"/"),i=Ta(a),r={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[r[n],...s,`Install the scaffold: ${oe(n==="package"?["install","--project",a]:["extension","--install","--project",a])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},pm=async e=>{let{action:t,normalizedTarget:n,options:a,withResult:i}=e;if([tn(a),a.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new u('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let r=nn(n,t,a),o=await Pr(r,a.vocabulary??"extension",a.capability,a.declarative===!0);return i({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:lm(o,a)})},mm=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:a,options:i,global:r,withResult:o}=e;if(t!==void 0)throw new u('Action "reload" does not accept a target argument.',h.USAGE);let s=await I(n.settings_root),d=un(),c=await ke({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:r.noExtensions,reload_token:d,cache_bust:!0});a.push(...c.warnings);let l=await xe(c);a.push(...l.warnings);let p={reload:{token:d,cache_bust:!0,watch:i.watch===!0},loaded_count:c.loaded.length,failed_count:c.failed.length,activated_count:Math.max(0,c.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:c.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:c.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&a.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(p)},um=async e=>{let{normalizedTarget:t,scope:n,options:a,global:i,withResult:r}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new u('Action "catalog" does not accept a package target.',h.USAGE);return r(await mr(n,i,a))},fm=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),hm=e=>({kind:"local",input:e.input,location:e.absolute_path}),gm=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),ym=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),_m=(e,t,n,a)=>e?fm(e,t):n.kind==="local"?hm(n):n.kind==="npm"?gm(n,a):ym(n,a),wm=(e,t,n,a)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:a}:rr(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:a}:{installed_at:a,updated_at:a},vm=async(e,t)=>{let{scope:n,resolvedRoots:a,warnings:i}=e,{validated:r,destinationDirectoryName:o}=t,s=await I(a.settings_root),d=await le(a.selected_root);i.push(...d.warnings);let c=te.join(a.selected_root,o),l=await k(c),p=await Qe(r.directory,c);await tt.mkdir(a.selected_root,{recursive:!0});let m=_m(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),y=d.state.entries.find(w=>b(w.name)===b(r.manifest.name)),g=wm(y,r.manifest.version,m,T()),_=dt(d.state,{name:r.manifest.name,directory:o,scope:n,manifest_version:r.manifest.version,manifest_entry:r.manifest.entry,capabilities:[...r.manifest.capabilities],contributions:r.manifest.contributions,...g,source:m}),f=zo(s,r.manifest.name);return p||await Hr(r.directory,c),await qr(c),await Wr(c),await Ze(a.selected_root,_),f&&await he(a.settings_root,s,"settings:write"),{settings:s,managedState:_,sourceRecord:m,destinationDirectory:c,destinationExists:l,installInPlace:p,activationChanged:f}},bm=async(e,t,n)=>{let a=n.filter(i=>b(i.name)===b(t)).flatMap(i=>i.types.map(r=>({name:r.name,folder:r.folder})));return e.scope==="project"&&a.length>0&&await _t(e.resolvedRoots.pm_root,a,e.warnings,"install:type-folder"),a},km=(e,t,n,a,i)=>{let r=Bo(t,n.activation_failures,e.scope),o=tm(t,e.scope,n.installed,r),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let d={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:r,verification:{status:d[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:a.command_paths,registered_actions:a.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:d[String(s)]}}},xm=async(e,t)=>{let{scope:n,resolvedRoots:a,warnings:i,global:r,withResult:o}=e,{validated:s,destinationDirectoryName:d}=t;return Ro({selectedRoot:a.selected_root,settingsRoot:a.settings_root,destinationDirectory:te.join(a.selected_root,d),sourceDirectory:s.directory,scope:n},async()=>{let c=await vm(e,t),l=await me(a.selected_root,n,c.settings,c.managedState);i.push(...l.warnings);let p=await Ho(a.pm_root,te.dirname(a.selected_root),c.settings,l.extensions,r);i.push(...p.warnings);let m=await bm(e,s.manifest.name,p.item_type_registrations),y=ko(s.manifest.name,p.installed),g=km(e,s.manifest.name,p,y,m),_=p.contribution_inventories[b(s.manifest.name)];return _&&(c.managedState=await or(a.selected_root,c.managedState,s.manifest.name,_)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:d},source:c.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:c.destinationDirectory,overwritten:[c.destinationExists,!c.installInPlace].every(Boolean),installed_in_place:c.installInPlace,activated:g.activated,settings_changed:c.activationChanged,runtime_activation_status:g.status,command_paths:y.command_paths,action_paths:y.action_paths,contributions:_,command_discovery:Qp(s.manifest.name,c.sourceRecord,y,g.failure),verification:g.verification,activation_diagnostics:{failed_count:p.activation_failures.length,failed:p.activation_failures,installed_extension_failed:g.failure??null}},g.activated)})},Sm=async e=>{let{options:t,global:n,warnings:a,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new u('Action "install all" does not accept --ref.',h.USAGE);let r=[],o=new Map;for(let s of await Gt()){let d=await lt(s),c=te.resolve(d),l=o.get(c);l===void 0&&(l=await na(s,{...t,install:!0},n),o.set(c,l)),r.push({alias:s,result:l})}return a.push(...r.flatMap(s=>s.result.warnings)),i(To(r,t.dryRun===!0),r.every(s=>s.result.ok))},Em=async(e,t,n)=>{let{resolvedRoots:a}=e,{bundledAliasName:i,bundledPackageName:r,installSource:o,sourceResolution:s}=await Xr(t,n,e.options.ref,(await le(a.selected_root)).state.entries);if(s.ambiguous){let c=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${c.package}`)}let d=await br(o);try{let c=await Xe(d.directory,{source_kind:o.kind,source_input:o.input,source_root:d.source_root}),l=Ut(c.manifest.name),p=e.options.dryRun===!0||o.kind==="local"&&i===null?await Vr(d,te.join(a.selected_root,l),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:c.manifest.name,version:c.manifest.version},source_resolution:s,install_plan:p}):await Hn(a.settings_root,l,()=>xm(e,{validated:c,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:r,sourceResolution:s,installSource:o,resolvedSource:d,installPlan:p}))}finally{d.cleanup&&await d.cleanup()}},$m=async e=>{let t=tn(e.options),n=t??nn(e.normalizedTarget,e.action,e.options);return[t===void 0,cr(n)].every(Boolean)?Sm(e):Em(e,n,t)},Im=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:i,options:r,withResult:o}=e;if(t!==void 0)throw new u('Action "adopt-all" does not accept a target argument.',h.USAGE);if(tn(r)!==void 0||typeof r.ref=="string"&&r.ref.trim().length>0)throw new u('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let s=await I(a.settings_root),d=await le(a.selected_root);i.push(...d.warnings);let c=await me(a.selected_root,n,s,d.state);i.push(...c.warnings);let l=await ta(a.selected_root,n,c.extensions,d.state),p=await me(a.selected_root,n,s,l.state);i.push(...p.warnings);let m=en(n,i,p.extensions,r);i.push(...m.warnings);let y=new Map(p.extensions.map(f=>[`${b(f.name)}:${b(f.directory)}`,f])),g=new Map(p.extensions.map(f=>[b(f.directory),f])),_=l.adopted_entries.map(f=>{let w=b(f.directory),v=y.get(`${b(f.name)}:${w}`)??g.get(w);return{...f,...Ko(v)}});return o({adopted_all:_.length>0,adopted_count:_.length,already_managed_count:l.already_managed_count,extensions:_,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},Ko=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Am=(e,t,n,a)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=pt(e,{forceGithub:!0,ref:a});if(i.kind!=="github")throw new u(`Invalid GitHub shorthand "${e}".`,h.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},Tm=async e=>{let{action:t,normalizedTarget:n,scope:a,resolvedRoots:i,warnings:r,options:o,withResult:s}=e,d=nn(n,t,o),c=tn(o),l=await I(i.settings_root),p=await le(i.selected_root);r.push(...p.warnings);let m=await me(i.selected_root,a,l,p.state);r.push(...m.warnings);let y=await Mo(m.extensions,d);if(!y)throw new u(`Installed extension "${d}" was not found in ${a} scope.`,h.NOT_FOUND);if(y.managed)return s({adopted:!1,already_managed:!0,extension:{name:y.name,directory:y.directory}});let g=te.join(i.selected_root,y.directory),_=await Xe(g),f=T(),w=Am(c,d,g,o.ref),v=dt(p.state,{name:_.manifest.name,directory:y.directory,scope:a,manifest_version:_.manifest.version,manifest_entry:_.manifest.entry,capabilities:[..._.manifest.capabilities],contributions:_.manifest.contributions,installed_at:f,updated_at:f,source:w});await Ze(i.selected_root,v);let E=await me(i.selected_root,a,l,v);r.push(...E.warnings);let S=E.extensions.find(C=>b(C.name)===b(_.manifest.name))??E.extensions.find(C=>b(C.directory)===b(y.directory));return s({adopted:!0,extension:{name:_.manifest.name,directory:y.directory,version:_.manifest.version,entry:_.manifest.entry},source:w,...Ko(S)})},Vo=async e=>{let{action:t,normalizedTarget:n,scope:a,resolvedRoots:i,warnings:r,options:o}=e,s=nn(n,t,o),d=await I(i.settings_root),c=await le(i.selected_root);r.push(...c.warnings);let l=await me(i.selected_root,a,d,c.state);r.push(...l.warnings);let p=await Mo(l.extensions,s);if(!p)throw new u(`Installed extension "${s}" was not found in ${a} scope.`,h.NOT_FOUND);return{settings:d,managedStateRead:c,candidate:p}},Om=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:a,managedStateRead:i,candidate:r}=await Vo(e),o=te.join(t.selected_root,r.directory);await tt.rm(o,{recursive:!0,force:!0});let s={...i.state,updated_at:T(),entries:i.state.entries.filter(c=>b(c.name)!==b(r.name)&&b(c.directory)!==b(r.directory))};await Ze(t.selected_root,s);let d=zp(a,r.name);return d&&await he(t.settings_root,a,"settings:write"),n({removed:!0,extension:{name:r.name,directory:r.directory},destination_path:o,settings_changed:d})},Po=async e=>{let{action:t,resolvedRoots:n,warnings:a,global:i,withResult:r}=e,{settings:o,candidate:s}=await Vo(e),d=t==="activate"?zo(o,s.name):Up(o,s.name);d&&await he(n.settings_root,o,"settings:write");let c=t==="activate"?await Ho(n.pm_root,te.dirname(n.selected_root),o,[s],i).then(l=>(a.push(...l.warnings),Bo(s.name,l.activation_failures,e.scope))):void 0;return c&&a.push(`extension_activate_failed:${e.scope}:${s.name}`),r({extension:{name:s.name,directory:s.directory},active:t==="activate"&&c===void 0,runtime_active:t==="activate"&&c===void 0,activation_failure:c??null,settings_changed:d,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},c===void 0)},Cm=(e,t,n,a,i,r)=>{let o=a==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],d=i?.adopted_entries.length??0,c=[[r!==null,r??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[d>0,`Managed-state fix adopted ${d} extension(s).`]];return[...new Set([...e,...c.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},ea=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Rm=(e,t,n,a)=>{if(e!=="project"||t||!ea(a))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Pm=(e,t,n)=>{if(String(e??"").trim().length>0)throw new u('Action "doctor" does not accept a target argument.',h.USAGE);let a=[n.isolated,n.ignoreGlobal].includes(!0);if([a,t==="global"].every(Boolean))throw new u("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let i=yo(n.detail),r=n.trace===!0;if([r,i!=="deep"].every(Boolean))throw new u("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:a,detailMode:i,includeTrace:r}},Nm=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let a=await ta(e.resolvedRoots.selected_root,e.scope,t,n);return{state:a.state,fix:a}},Dm=(e,t,n,a)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:ea(a),rerun_command:null,pm_global_path_recipe:null};let r=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:ea(a),rerun_command:t?null:r,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},jm=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:i,options:r,global:o,withResult:s}=e,{isolated:d,detailMode:c,includeTrace:l}=Pm(t,n,r),p=await I(a.settings_root),m=await le(a.selected_root);i.push(...m.warnings);let y=await me(a.selected_root,n,p,m.state);i.push(...y.warnings);let{state:g,fix:_}=await Nm(e,y.extensions,m.state),f=await me(a.selected_root,n,p,g);i.push(...f.warnings);let w=await ke({pmRoot:a.pm_root,settings:p,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:d}),v=await xe({...w,loaded:w.loaded}),E=await Oo(a.pm_root);i.push(...E.warnings,...w.warnings),i.push(...fo(w.failed)),i.push(...v.warnings),i.push(...ho(v.failed)),i.push(...go(w,v)),i.push(...xo(v,w)),i.push(...rm(w,v)),i.push(...So(v));let S=Qt(f.extensions,w,v),C=bo(n,S,w.loaded.map(O=>({layer:O.layer,name:O.name})),w.failed.map(O=>({name:O.name})),w.disabled_by_flag);i.push(...C.warnings);let ne=S.filter(O=>O.update_check_status==="failed").map(O=>`extension_update_check_failed:${O.name}`);i.push(...ne);let j=en(n,i,S,r);i.push(...j.warnings);let x=[...j.warnings],G={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},nt=wo(x),rn=vo(),ua=j.warning_codes,Os=Rm(n,d,r.vocabulary,w),Cs=Cm(j.remediation,w.failed.length,v.failed.length,r.vocabulary,_,Os),fa=Dm(n,d,r.vocabulary,w),Rs={status:j.status,scope:n,warning_count:j.warning_count,warning_codes:ua,total_extensions:S.length,managed_total:S.filter(O=>O.managed).length,enabled_total:S.filter(O=>O.enabled).length,active_total:S.filter(O=>O.active).length,unmanaged_loaded_extension_count:j.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:j.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:j.unmanaged_expected_extension_count,runtime_active_total:S.filter(O=>O.runtime_active===!0).length,activation_status_totals:{ok:S.filter(O=>O.activation_status==="ok").length,failed:S.filter(O=>O.activation_status==="failed").length,not_loaded:S.filter(O=>O.activation_status==="not_loaded").length,unknown:S.filter(O=>O.activation_status==="unknown").length},unknown_capability_count:nt.length,capability_contract_version:rn.version,update_available_total:j.update_available_total,update_check_status_totals:j.update_check_status_totals,update_health_coverage:j.update_health_coverage,update_health_partial:j.update_health_partial,update_check_failed_total:S.filter(O=>O.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Yn(w.failed),activation_failures:Yn(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:C.warnings.length,trace_enabled:l,isolation:fa,policy:G,remediation:Cs},Ps=_?{requested:!0,applied:_.adopted_entries.length>0,adopted_count:_.adopted_entries.length,already_managed_count:_.already_managed_count,adopted_extensions:_.adopted_entries.map(O=>O.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:f.extensions.filter(O=>O.managed).length,adopted_extensions:[]},on={mode:c,summary:Rs,triage:j,trace_enabled:l,capability_contract:rn,capability_guidance:nt,managed_state_fix:Ps,author_manifest:E,isolation:fa,policy:w.policy};if(c==="deep"){let O=l?v.failed:v.failed.map(N=>{let{trace:Tu,...Ns}=N;return Ns});on.deep={warnings:x,warning_codes:ua,capability_contract:rn,capability_guidance:nt,trace_enabled:l,managed_state:{path:m.path,count:g.entries.length,entries:g.entries},installed_extensions:S,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(N=>({layer:N.layer,directory:N.directory,name:N.name,version:N.version,entry:N.entry,priority:N.priority}))},activation:{failed:O,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:C.summary},l&&(on.deep.trace={activation_failures:v.failed.filter(N=>N.trace!==void 0).map(N=>({layer:N.layer,name:N.name,entry_path:N.entry_path,error:N.error,method:N.trace.method,command:N.trace.command,capability:N.trace.capability,missing_capability:N.trace.missing_capability,registration_index:N.trace.registration_index,expected_schema:N.trace.expected_schema,hint:N.trace.hint,received:N.trace.received}))})}return s(on)},Lm=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:i,options:r,global:o,withResult:s}=e,d=await I(a.settings_root),c=await ke({pmRoot:a.pm_root,settings:d,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),l=await xe(c);i.push(...c.warnings),i.push(...l.warnings);let p=Lr(t,c,l);if(t!==void 0&&p.extensions.length===0){let m=r.vocabulary==="package"?"package":"extension",y=[...new Set(c.loaded.map(_=>r.vocabulary==="package"&&typeof _.source_package=="string"&&_.source_package.trim().length>0?_.source_package.trim():_.name))].sort((_,f)=>_.localeCompare(f)),g=y.length>0?` Loaded ${m} names: ${y.join(", ")}.`:"";throw new u(`No loaded ${m} named "${t}" was found in ${n} scope.${g} Run pm ${m} explore to list discovered ${m}s.`,h.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},Fm=async(e,t,n)=>{let a=n,i=null;return[e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await ta(e.resolvedRoots.selected_root,e.scope,t,n),a=i.state),e.action==="manage"&&(a=await Ao(a,e.options.offline)),{state:a,fix:i}},Mm=async(e,t,n)=>{let a=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await xe({...a,loaded:a.loaded});return e.warnings.push(...a.warnings,...i.warnings),{installed:Qt(n,a,i),failures:Wo(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:a.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...a.warnings,...i.warnings])].length,policy:a.policy}}},Um=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},No=async e=>{let{action:t,scope:n,resolvedRoots:a,warnings:i,options:r,withResult:o}=e,s=await I(a.settings_root),d=Mp(s.extensions.policy),c=await le(a.selected_root);i.push(...c.warnings);let l=await me(a.selected_root,n,s,c.state);i.push(...l.warnings);let{state:p,fix:m}=await Fm(e,l.extensions,c.state),y=await me(a.selected_root,n,s,p);if(i.push(...y.warnings),t==="manage"&&r.offline===!0)for(let v of y.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=y.extensions.filter(E=>E.update_check_status==="failed").map(E=>`extension_update_check_failed:${E.name}`);i.push(...v)}let g=await Mm(e,s,y.extensions),_=g.installed,f=en(n,i,_,r);i.push(...f.warnings);let w={total:_.length,managed_total:_.filter(v=>v.managed).length,enabled_total:_.filter(v=>v.enabled).length,active_total:_.filter(v=>v.active).length,extensions:_,triage:f,policy:d};return g.failures!==void 0&&(w.activation_diagnostics={failed_count:g.failures.length,failed:g.failures}),t==="explore"&&(w.runtime_probe=g.summary),t==="manage"&&(w.runtime_probe=g.summary,w.managed_state_fix=Um(m,_)),o(w)},Do={init:pm,install:$m,uninstall:Om,explore:No,manage:No,describe:Lm,reload:mm,doctor:jm,catalog:um,adopt:Tm,"adopt-all":Im,activate:Po,deactivate:Po,migrate:Ai},zm=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Gm=e=>zm(e)?Hn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Do[e.action](e)):Do[e.action](e);import ra from"node:fs/promises";import z from"node:path";import Yo from"node:readline/promises";import{stdin as Xo,stdout as vt}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bb8a4985-8bc0-5290-a6f9-310d940cf4d7")}catch{}})();var Zo=["ask","add","skip","status"],Jm=["AGENTS.md","CLAUDE.md"],qm=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Wm=8,oa=1,Bm="<!-- pm-cli:agent-guidance:start:",Hm=`<!-- pm-cli:agent-guidance:start:v${oa} -->`,aa="<!-- pm-cli:agent-guidance:end -->",kt="Add workflow guidance later: pm init --agent-guidance add",Uw={toPortableRelativePath:Me,ensureTrailingNewline:ia,detectLineEnding:es,findGuidanceBlockRange:sa,buildAgentGuidanceBlock:ts,upsertAgentGuidanceBlock:ca,resolveProjectRoot:as,resolveTargetGuidancePath:is,parsePromptChoice:rs,pushUnique:Oe,promptForGuidanceWrite:os,normalizeAgentGuidanceState:da,applyAgentGuidanceState:cs,writeGuidanceFile:la,setAgentGuidanceReadlineFactoryForTests:Km},Qo=()=>Yo.createInterface({input:Xo,output:vt});function Km(e){Qo=e??(()=>Yo.createInterface({input:Xo,output:vt}))}function Me(e,t){let n=z.relative(e,t);return n.length===0?z.basename(t):n.split(z.sep).join("/")}function ia(e){return e.endsWith(`
40
40
  `)?e:`${e}
41
- `}function Zo(e){return e.includes(`\r
41
+ `}function es(e){return e.includes(`\r
42
42
  `)?`\r
43
43
  `:`
44
- `}function oa(e){let t=e.indexOf(Jm);if(t===-1)return null;let n=e.indexOf(na,t);return n===-1?null:{start_index:t,end_index:n+na.length}}function Bm(e){return oa(e)!==null}function Qo(e,t="<your project test command>"){return[qm,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and start: `pm claim <id> --start`, or `pm claim --next --start` to take the next available item in one write.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",na,""].join(e)}function sa(e,t="<your project test command>"){let n=Zo(e),a=Qo(n,t),i=oa(e);if(i){let s=e.slice(i.end_index),c=s.startsWith(`\r
44
+ `}function sa(e){let t=e.indexOf(Bm);if(t===-1)return null;let n=e.indexOf(aa,t);return n===-1?null:{start_index:t,end_index:n+aa.length}}function Vm(e){return sa(e)!==null}function ts(e,t="<your project test command>"){return[Hm,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and start: `pm claim <id> --start`, or `pm claim --next --start` to take the next available item in one write.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",aa,""].join(e)}function ca(e,t="<your project test command>"){let n=es(e),a=ts(n,t),i=sa(e);if(i){let s=e.slice(i.end_index),d=s.startsWith(`\r
45
45
  `)?s.slice(2):s.startsWith(`
46
- `)?s.slice(1):s,d=aa(`${e.slice(0,i.start_index)}${a}${c}`);return{next_content:d,changed:d!==e}}let r=e.length===0?"":e.endsWith(`
46
+ `)?s.slice(1):s,c=ia(`${e.slice(0,i.start_index)}${a}${d}`);return{next_content:c,changed:c!==e}}let r=e.length===0?"":e.endsWith(`
47
47
  `)?`
48
48
  `:`
49
49
 
50
- `,o=aa(`${e}${r}${a}`);return{next_content:o,changed:o!==e}}async function es(e){if(await k(z.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await ia.readFile(z.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=Hm(t);if(n===void 0)return"<your project test command>";let a=n.packageManager?.split("@")[0];return a==="pnpm"?"pnpm test":a==="bun"?"bun run test":a==="yarn"?"yarn test":a==="npm"?"npm test":await k(z.join(e,"pnpm-lock.yaml"))?"pnpm test":await k(z.join(e,"bun.lock"))||await k(z.join(e,"bun.lockb"))?"bun run test":await k(z.join(e,"yarn.lock"))?"yarn test":"npm test"}function Hm(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function ts(e,t){let n=z.dirname(e);return z.basename(e)==="pm"&&z.basename(n)===".agents"?z.dirname(n):z.resolve(t,e)}function ns(e,t){let n=e.find(i=>z.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let a=e.find(i=>i.exists);return a?a.file_path:z.join(t,"AGENTS.md")}function as(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function is(e){let t=Xo();try{wt.write(`
50
+ `,o=ia(`${e}${r}${a}`);return{next_content:o,changed:o!==e}}async function ns(e){if(await k(z.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await ra.readFile(z.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=Ym(t);if(n===void 0)return"<your project test command>";let a=n.packageManager?.split("@")[0];return a==="pnpm"?"pnpm test":a==="bun"?"bun run test":a==="yarn"?"yarn test":a==="npm"?"npm test":await k(z.join(e,"pnpm-lock.yaml"))?"pnpm test":await k(z.join(e,"bun.lock"))||await k(z.join(e,"bun.lockb"))?"bun run test":await k(z.join(e,"yarn.lock"))?"yarn test":"npm test"}function Ym(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function as(e,t){let n=z.dirname(e);return z.basename(e)==="pm"&&z.basename(n)===".agents"?z.dirname(n):z.resolve(t,e)}function is(e,t){let n=e.find(i=>z.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let a=e.find(i=>i.exists);return a?a.file_path:z.join(t,"AGENTS.md")}function rs(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function os(e){let t=Qo();try{vt.write(`
51
51
  Agent guidance check
52
- `),wt.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
53
- `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return wt.write(`
54
- `),as(n,!0)}finally{t.close()}}function ca(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:ra,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,a)=>n.localeCompare(a)):[]}}async function rs(e){let t=[],n=await es(e);for(let a of Um){let i=z.join(e,a),r=await k(i);if(!r){t.push({file_path:i,exists:r,has_guidance:!1,has_marker:!1});continue}let o=await ia.readFile(i,"utf8"),s=o.toLowerCase(),c=zm.filter(l=>s.includes(l)),d=Bm(o);t.push({file_path:i,exists:r,has_guidance:d||c.length>=Gm,has_marker:d,outdated:d&&sa(o,n).changed})}return t}function Oe(e,t){e.includes(t)||e.push(t)}function os(e,t){let n=ca(e),a=JSON.stringify(n)!==JSON.stringify(t);return a&&(e.agent_guidance=t),{changed:a,state:t}}async function da(e,t=z.dirname(e)){let n=await k(e)?await ia.readFile(e,"utf8"):"",a=sa(n,await es(t));return a.changed?(await ue(e,a.next_content),{changed:!0,warnings:await B({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function Km(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Fe(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Fe(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Fe(e.projectRoot,t.file_path))}}async function Vm(e,t,n){return e?await rs(n):t}function vt(e,t,n){e.state={...e.state,...n,template_version:ra,last_checked_files:t}}async function ss(e,t){if(t.presentBefore)return;let n=await da(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Ym(e,t){t||(e.warnings.push("agent_guidance:missing"),Oe(e.nextSteps,bt))}function Xm(e,t){e.skipped=!0,vt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Oe(e.nextSteps,bt)}async function Zm(e,t){await ss(e,t),vt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Qm(e,t){e.state.declined&&vt(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function eu(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Oe(e.nextSteps,bt)}async function tu(e,t){if(e.prompted=!0,await is(t.targetRelativePath)){await ss(e,t),vt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,vt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Oe(e.nextSteps,bt)}function nu(e){e.warnings.push("agent_guidance:missing_non_interactive"),Oe(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Oe(e.nextSteps,bt)}async function au(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Ym(n,t.presentBefore),n):t.mode==="skip"?(Xm(n,t.checkedFiles),n):t.mode==="add"?(await Zm(n,t),n):t.presentBefore?(Qm(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(eu(n),n):t.interactive?(await tu(n,t),n):(nu(n),n)}async function cs(e){let t=ts(e.pm_root,e.cwd),n=await rs(t),a=ns(n,t),i=Fe(t,a),r=n.map(l=>Fe(t,l.file_path)),o=n.some(l=>l.has_guidance),s=await au(ca(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:a,targetRelativePath:i,checkedFiles:r,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let l of n.filter(p=>p.outdated)){let p=await da(l.file_path,t);s.applied||=p.changed,s.warnings.push(...p.warnings)}let c=os(e.settings,s.state);n=await Vm(s.applied,n,t);let d=n.filter(l=>l.outdated).map(l=>Fe(t,l.file_path));return d.length>0&&(s.warnings.push(`agent_guidance_outdated:${d.join(",")}`),Oe(s.nextSteps,"pm init --agent-guidance add")),{summary:Km({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import iu from"node:fs/promises";import j from"node:path";import ls from"node:readline/promises";import{stdin as ps,stdout as X}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ffab1407-659d-5bc4-95ff-5efe52baf522")}catch{}})();var ru=Symbol.for("pm.sdk.init-invocation-cwd");function iv(e,t=!1){if(t){let n=e.warnings.filter(i=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(i)),a=n.includes("agent_guidance:missing_non_interactive")?e.next_steps.filter(i=>i.includes("--agent-guidance")):[];return{ok:e.ok,path:e.path,governance_preset:e.governance_preset,telemetry:`${e.settings.telemetry.enabled?"enabled":"disabled"} (${e.settings.telemetry.capture_level})`,created_count:e.created_dirs.length,next_steps:[...a,...e.next_steps.filter(i=>!a.includes(i))].slice(0,3),...n.length>0?{warnings:n.join("; ")}:{},details:`${oe(["--pm-path",e.path,"init","--verbose"])} for full setup details and notices (or --json)`}}return{ok:e.ok,path:e.path,target:e.target,id_prefix:e.settings.id_prefix,governance_preset:e.governance_preset,telemetry:{enabled:e.settings.telemetry.enabled,capture_level:e.settings.telemetry.capture_level},output_format:e.settings.output.default_format,created_dirs_count:e.created_dirs.length,created_dirs:e.created_dirs,warnings:e.warnings,wizard_used:e.wizard_used,...e.registered_type_preset?{registered_type_preset:e.registered_type_preset}:{},...e.installed_packages?{installed_packages:e.installed_packages}:{},next_steps:e.next_steps,agent_guidance:e.agent_guidance,hint:"Re-run with --verbose for the full settings tree."}}var rv={normalizeInitGovernancePreset:la,normalizeInitTypePreset:us,normalizeOptionalInitAuthor:fs,normalizeInitAgentGuidanceMode:ys,isPathLikeInitTarget:nn,resolveInitInvocation:hs,resolveInitPrefixInput:gs,parseYesNoChoice:_s,applyGovernancePreset:pa,runInitWizard:Ss,setInitReadlineFactoryForTests:ou,summarizeInstalledPackages:ws,buildInitNextSteps:Es,registerInitTypePreset:vs,assertExplicitTrackerPathIsNotWorkspaceRoot:ks,isLikelyWorkspaceRoot:bs,installInitMergeFence:$s},ms=()=>ls.createInterface({input:ps,output:X});function ou(e){ms=e??(()=>ls.createInterface({input:ps,output:X}))}function su(){return structuredClone(sn)}var cu=["minimal","default","strict"];function la(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new u("--preset must not be empty",h.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new u(`Invalid --preset value "${e}". Allowed: ${cu.join(", ")}`,h.USAGE)}function us(e){if(e!==void 0){if(e.trim().length===0)throw new u("--type-preset must not be empty",h.USAGE);try{return Kt(e)}catch{throw new u(`Invalid --type-preset value "${e}". Allowed: ${ht.join(", ")}`,h.USAGE)}}}function fs(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new u("--author must not be empty",h.USAGE);return t}function nn(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:j.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function hs(e,t,n,a){let i=a?.trim();if(a!==void 0&&i?.length===0)throw new u("--workspace must not be empty",h.USAGE);if(i!==void 0){if(t.path!==void 0||nn(n))throw new u("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",h.USAGE);let d=j.resolve(e,i),l=j.join(d,".agents","pm");return{pmRoot:l,prefixArg:n,target:{mode:"workspace-path",tracker_root:l,workspace_root:d}}}if(t.path===void 0&&nn(n)){let d=j.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let r=F(e,t.path),o=j.join(j.resolve(e),".agents","pm"),s=j.dirname(j.dirname(r)),c=j.resolve(r)===o?"current":"ancestor";return{pmRoot:r,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:r,workspace_root:s,discovery:c,requested_cwd:j.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:o}:{}}:{mode:"tracker-path",tracker_root:r}}}function gs(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new u("--id-prefix must not be empty",h.USAGE);if(nn(t))throw new u(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,h.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&Se(e)!==Se(t))throw new u(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,h.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Se(e)}`,`pm init --id-prefix ${Se(t)}`]});return t}function ys(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new u("--agent-guidance must not be empty",h.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new u(`Invalid --agent-guidance value "${e}". Allowed: ${Yo.join(", ")}`,h.USAGE)}function _s(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function pa(e,t){let n=ga[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function du(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ws(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(du).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function vs(e,t,n){let a=K(t.schema),i=Q(e,a.files.types,V.types),r=ae(await M(i)),o=[],s=[];for(let c of gt(n)){let d=Me(r,c);r=d.file,(d.replaced?s:o).push(d.definition.name)}return await xe({pmRoot:e,filePath:i,raw:se(r),op:"init:type-preset",author:q(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:o,updated:s,file:i}}async function bs(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",j.join(".agents","pm")];for(let n of t)if(await k(j.join(e,n)))return!0;return!1}async function ks(e,t,n){if(!t||n||await k(j.join(e,"settings.json"))||!await bs(e))return;let a=j.join(e,".agents","pm");throw new u(`Refusing to initialize tracker files directly in workspace root "${e}".`,h.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${a} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${a} init --yes`}})}async function xs(e,t){let n=[],a=[];for(let i of t){let r=i?j.join(e,i):e,o=await k(r);await iu.mkdir(r,{recursive:!0}),o?a.push(`already_exists:${r}`):n.push(r),a.push(...await B({path:r,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:a}}async function Ss(e,t){let n=ms();try{X.write(`pm init setup wizard (agent-optimized)
52
+ `),vt.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
53
+ `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return vt.write(`
54
+ `),rs(n,!0)}finally{t.close()}}function da(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:oa,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,a)=>n.localeCompare(a)):[]}}async function ss(e){let t=[],n=await ns(e);for(let a of Jm){let i=z.join(e,a),r=await k(i);if(!r){t.push({file_path:i,exists:r,has_guidance:!1,has_marker:!1});continue}let o=await ra.readFile(i,"utf8"),s=o.toLowerCase(),d=qm.filter(l=>s.includes(l)),c=Vm(o);t.push({file_path:i,exists:r,has_guidance:c||d.length>=Wm,has_marker:c,outdated:c&&ca(o,n).changed})}return t}function Oe(e,t){e.includes(t)||e.push(t)}function cs(e,t){let n=da(e),a=JSON.stringify(n)!==JSON.stringify(t);return a&&(e.agent_guidance=t),{changed:a,state:t}}async function la(e,t=z.dirname(e)){let n=await k(e)?await ra.readFile(e,"utf8"):"",a=ca(n,await ns(t));return a.changed?(await ue(e,a.next_content),{changed:!0,warnings:await B({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function Xm(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Me(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Me(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Me(e.projectRoot,t.file_path))}}async function Zm(e,t,n){return e?await ss(n):t}function bt(e,t,n){e.state={...e.state,...n,template_version:oa,last_checked_files:t}}async function ds(e,t){if(t.presentBefore)return;let n=await la(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Qm(e,t){t||(e.warnings.push("agent_guidance:missing"),Oe(e.nextSteps,kt))}function eu(e,t){e.skipped=!0,bt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Oe(e.nextSteps,kt)}async function tu(e,t){await ds(e,t),bt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function nu(e,t){e.state.declined&&bt(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function au(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Oe(e.nextSteps,kt)}async function iu(e,t){if(e.prompted=!0,await os(t.targetRelativePath)){await ds(e,t),bt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,bt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Oe(e.nextSteps,kt)}function ru(e){e.warnings.push("agent_guidance:missing_non_interactive"),Oe(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Oe(e.nextSteps,kt)}async function ou(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Qm(n,t.presentBefore),n):t.mode==="skip"?(eu(n,t.checkedFiles),n):t.mode==="add"?(await tu(n,t),n):t.presentBefore?(nu(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(au(n),n):t.interactive?(await iu(n,t),n):(ru(n),n)}async function ls(e){let t=as(e.pm_root,e.cwd),n=await ss(t),a=is(n,t),i=Me(t,a),r=n.map(l=>Me(t,l.file_path)),o=n.some(l=>l.has_guidance),s=await ou(da(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:a,targetRelativePath:i,checkedFiles:r,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let l of n.filter(p=>p.outdated)){let p=await la(l.file_path,t);s.applied||=p.changed,s.warnings.push(...p.warnings)}let d=cs(e.settings,s.state);n=await Zm(s.applied,n,t);let c=n.filter(l=>l.outdated).map(l=>Me(t,l.file_path));return c.length>0&&(s.warnings.push(`agent_guidance_outdated:${c.join(",")}`),Oe(s.nextSteps,"pm init --agent-guidance add")),{summary:Xm({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:d.changed}}import su from"node:fs/promises";import P from"node:path";import ms from"node:readline/promises";import{stdin as us,stdout as X}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0bfdfae5-a153-5cc1-9946-aa2ef215aa85")}catch{}})();var cu=Symbol.for("pm.sdk.init-invocation-cwd");function pv(e,t=!1){if(t){let n=e.warnings.filter(i=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(i)),a=n.includes("agent_guidance:missing_non_interactive")?e.next_steps.filter(i=>i.includes("--agent-guidance")):[];return{ok:e.ok,path:e.path,governance_preset:e.governance_preset,telemetry:`${e.settings.telemetry.enabled?"enabled":"disabled"} (${e.settings.telemetry.capture_level})`,created_count:e.created_dirs.length,next_steps:[...a,...e.next_steps.filter(i=>!a.includes(i))].slice(0,3),...n.length>0?{warnings:n.join("; ")}:{},details:`${oe(["--pm-path",e.path,"init","--verbose"])} for full setup details and notices (or --json)`}}return{ok:e.ok,path:e.path,target:e.target,id_prefix:e.settings.id_prefix,governance_preset:e.governance_preset,telemetry:{enabled:e.settings.telemetry.enabled,capture_level:e.settings.telemetry.capture_level},output_format:e.settings.output.default_format,created_dirs_count:e.created_dirs.length,created_dirs:e.created_dirs,warnings:e.warnings,wizard_used:e.wizard_used,...e.registered_type_preset?{registered_type_preset:e.registered_type_preset}:{},...e.installed_packages?{installed_packages:e.installed_packages}:{},next_steps:e.next_steps,agent_guidance:e.agent_guidance,hint:"Re-run with --verbose for the full settings tree."}}var mv={normalizeInitGovernancePreset:pa,normalizeInitTypePreset:hs,normalizeOptionalInitAuthor:gs,normalizeInitAgentGuidanceMode:ws,isPathLikeInitTarget:an,resolveInitInvocation:ys,resolveInitPrefixInput:_s,parseYesNoChoice:vs,applyGovernancePreset:ma,runInitWizard:$s,setInitReadlineFactoryForTests:du,summarizeInstalledPackages:bs,buildInitNextSteps:As,registerInitTypePreset:ks,assertExplicitTrackerPathIsNotWorkspaceRoot:Ss,isLikelyWorkspaceRoot:xs,installInitMergeFence:Ts},fs=()=>ms.createInterface({input:us,output:X});function du(e){fs=e??(()=>ms.createInterface({input:us,output:X}))}function lu(){return structuredClone(_a)}var pu=["minimal","default","strict"];function pa(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new u("--preset must not be empty",h.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new u(`Invalid --preset value "${e}". Allowed: ${pu.join(", ")}`,h.USAGE)}function hs(e){if(e!==void 0){if(e.trim().length===0)throw new u("--type-preset must not be empty",h.USAGE);try{return Vt(e)}catch{throw new u(`Invalid --type-preset value "${e}". Allowed: ${gt.join(", ")}`,h.USAGE)}}}function gs(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new u("--author must not be empty",h.USAGE);return t}function an(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:P.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function ys(e,t,n,a){let i=a?.trim();if(a!==void 0&&i?.length===0)throw new u("--workspace must not be empty",h.USAGE);if(i!==void 0){if(t.path!==void 0||an(n))throw new u("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",h.USAGE);let c=P.resolve(e,i),l=P.join(c,".agents","pm");return{pmRoot:l,prefixArg:n,target:{mode:"workspace-path",tracker_root:l,workspace_root:c}}}if(t.path===void 0&&an(n)){let c=P.resolve(e,n.trim());return{pmRoot:c,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:c}}}let r=F(e,t.path),o=P.join(P.resolve(e),".agents","pm"),s=P.dirname(P.dirname(r)),d=P.resolve(r)===o?"current":"ancestor";return{pmRoot:r,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:r,workspace_root:s,discovery:d,requested_cwd:P.resolve(e),...d==="ancestor"?{suggested_current_tracker_root:o}:{}}:{mode:"tracker-path",tracker_root:r}}}function _s(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new u("--id-prefix must not be empty",h.USAGE);if(an(t))throw new u(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,h.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&Ee(e)!==Ee(t))throw new u(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,h.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Ee(e)}`,`pm init --id-prefix ${Ee(t)}`]});return t}function ws(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new u("--agent-guidance must not be empty",h.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new u(`Invalid --agent-guidance value "${e}". Allowed: ${Zo.join(", ")}`,h.USAGE)}function vs(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function ma(e,t){let n=ya[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bs(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(mu).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function ks(e,t,n){let a=K(t.schema),i=Q(e,a.files.types,V.types),r=ae(await M(i)),o=[],s=[];for(let d of yt(n)){let c=Ue(r,d);r=c.file,(c.replaced?s:o).push(c.definition.name)}return await Se({pmRoot:e,filePath:i,raw:se(r),op:"init:type-preset",author:q(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:o,updated:s,file:i}}async function xs(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",P.join(".agents","pm")];for(let n of t)if(await k(P.join(e,n)))return!0;return!1}async function Ss(e,t,n){if(!t||n||await k(P.join(e,"settings.json"))||!await xs(e))return;let a=P.join(e,".agents","pm");throw new u(`Refusing to initialize tracker files directly in workspace root "${e}".`,h.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${a} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${a} init --yes`}})}async function Es(e,t){let n=[],a=[];for(let i of t){let r=i?P.join(e,i):e,o=await k(r);await su.mkdir(r,{recursive:!0}),o?a.push(`already_exists:${r}`):n.push(r),a.push(...await B({path:r,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:a}}async function $s(e,t){let n=fs(),a=t===void 0?2:3;try{X.write(`pm init setup wizard (agent-optimized)
55
55
  `),X.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
56
56
 
57
- `),X.write(`1/3 Item ID prefix
57
+ `),X.write(`1/${a} Item ID prefix
58
58
  `),X.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
59
- `);let a=await n.question(`Item ID prefix [${e}]: `),i=a.trim().length>0?Se(a):e;X.write(`
60
- 2/3 Governance preset
59
+ `);let i=await n.question(`Item ID prefix [${e}]: `),r=i.trim().length>0?Ee(i):e;X.write(`
60
+ 2/${a} Governance preset
61
61
  `),X.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
62
62
  `),X.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
63
63
  `),X.write(`strict: ownership blocking, strict create defaults, close validation strict.
64
- `);let r=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),o=r.trim().length>0?r.trim():"minimal",s="minimal";try{s=la(o)}catch{X.write(`Unrecognized governance preset "${o}"; using minimal.
65
- `)}X.write(`
66
- 3/3 Project telemetry
67
- `),X.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
68
- `);let c=t?"Y/n":"y/N",d=await n.question(`Enable telemetry for this project? [${c}] `),l=_s(d,t);return X.write(`
69
- `),{prefix:i,preset:s,telemetry_enabled:l}}finally{n.close()}}function lu(e){return{presetFromOption:la(e.preset),useDefaults:e.defaults===!0,authorFromOption:fs(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:ys(e.agentGuidance),typePreset:us(e.typePreset)}}function pu(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 mu(e,t,n,a){if(t.length===0||n)return;let i=a.discovery==="ancestor";throw new u(`${i?`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.`,h.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:i?"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",...i?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...i?['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 uu(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&&(pa(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 fu(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=pu({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return mu(e.settingsPath,n,e.options.force===!0,e.target),uu({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Ee(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function hu(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,a,i=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await Ss(t,sn.telemetry.enabled);t=c.prefix,n=c.preset,a=c.telemetry_enabled,i=!0}let r=n??"minimal",o=su();o.id_prefix=t,pa(o,r);let s=qa()?.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 Ee(e.pmRoot,o),{settings:o,normalizedPrefix:t,chosenPreset:n,wizardUsed:i}}async function ds(e){return e.settingsExists?await fu(e):await hu({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function gu(e){let t=await cs({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 Ee(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function yu(e,t){let n=[],a=[],i=await Ja(e,t.schema);for(let r of i.created_paths)n.push(r),a.push(...await B({path:r,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:a}}async function _u(e){if(e.typePreset===void 0)return;let t=await vs(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await B({path:t.file,scope:"project",op:"init:type_preset"})),t}async function wu(e){let t=W(e.settings,J()).folders.filter(a=>!on.includes(a)),n=await xs(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function vu(e){let t=j.resolve(e.tracker_root),n=j.dirname(t);return j.basename(t)==="pm"&&j.basename(n)===".agents"?j.dirname(n):e.workspace_root}async function bu(e,t,n,a){if(!e)return;let i=await ta("all",{install:!0,project:!0},{...t,path:n});a.push(...i.warnings);let r=ws(i),o=r.packages.filter(s=>!s.ok).map(s=>s.alias);if(!r.installed_all||o.length>0)throw new u(`pm init --with-packages did not install all bundled packages successfully${o.length>0?`: ${o.join(", ")}`:"."}`,h.GENERIC_FAILURE);return r}function Es(e){let t=a=>oe([...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 i=e.target.mode==="workspace-discovery"?a:a.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(i)||n.push(i)}return n}async function $s(e,t,n,a=mi){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 i=await a({pmRoot:e,workspaceRoot:t});i.gitattributes.changed&&n.push(`updated:merge_fence:${i.gitattributes.path}`)}catch(i){if(!(i instanceof u))throw i;n.push(`merge_fence_skipped:install_failed:${i.context.code??"pm_error"}:${i.message}:run pm merge install after resolving the Git repository error`)}}async function ku(e,t,n,a){if(e==null||n==="status")return;let i=await di(e,{pmRoot:t});i.changed&&a.push(`updated:gitignore:${i.path}`)}async function ov(e,t,n={}){let a=t[ru],i=typeof a=="string"?a:process.cwd(),r=hs(i,t,e,n.workspace),o=r.pmRoot;e=gs(r.prefixArg,n.idPrefix);let s=lu(n);await ks(o,r.target.mode==="tracker-path",n.force===!0);let c=[],d=[],l=j.join(o,"settings.json"),p=await k(l),m;p&&(m=await ds({pmRoot:o,settingsPath:l,settingsExists:p,normalizedPrefix:Se(e),prefixArg:e,options:n,normalizedOptions:s,warnings:d,target:r.target}));let y=await xs(o,on);c.push(...y.createdDirs),d.push(...y.warnings),m??=await ds({pmRoot:o,settingsPath:l,settingsExists:p,normalizedPrefix:Se(e),prefixArg:e,options:n,normalizedOptions:s,warnings:d,target:r.target});let{settings:g}=m,_=vu(r.target),f=await li(_??j.dirname(o)),w=_??f,v=await gu({pmRoot:o,cwd:w??i,agentGuidanceMode:s.agentGuidanceMode,settings:g,warnings:d}),E=await yu(o,g);c.push(...E.createdDirs),d.push(...E.warnings);let S=await _u({pmRoot:o,settings:g,typePreset:s.typePreset,warnings:d});S&&(g=await A(o)),await wu({pmRoot:o,settings:g,createdDirs:c,warnings:d}),await ku(w,o,s.agentGuidanceMode,d),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await $s(o,f,d);let C=await bu(s.installBundledPackages,t,o,d),ne=Es({installBundledPackages:s.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:v.next_steps,target:r.target});return{ok:!0,path:o,target:r.target,settings:g,created_dirs:c,warnings:d,governance_preset:g.governance.preset,wizard_used:m.wizardUsed,...S?{registered_type_preset:S}:{},...C?{installed_packages:C}:{},next_steps:ne,agent_guidance:v}}export{gn as a,kn as b,ki as c,Nu as d,Js as e,Du as f,Sn as g,Hs as h,Ks as i,Vs as j,$i as k,Ul as l,ze as m,zi as n,qe as o,We as p,Gi as q,Fi as r,Ge as s,Je as t,Mi as u,Xs as v,Hu as w,Xu as x,Ti as y,ec as z,hf as A,Ki as B,Zi as C,Mc as D,Uc as E,yy as F,vy as G,by as H,yt as I,ky as J,xy as K,Sy as L,Ey as M,$y as N,Iy as O,Ay as P,Ty as Q,Oy as R,Cy as S,Ry as T,Py as U,Ny as V,Dy as W,jy as X,Ly as Y,Fy as Z,My as _,Uy as $,zy as aa,Gy as ba,Jy as ca,qy as da,Wy as ea,By as fa,Z as ga,b as ha,Cn as ia,ad as ja,le as ka,Lt as la,zc as ma,rt as na,Ft as oa,ur as pa,kr as qa,qn as ra,Dr as sa,dg as ta,ro as ua,cp as va,yo as wa,_o as xa,Yn as ya,Hr as za,Dl as Aa,xp as Ba,Vr as Ca,ta as Da,Yo as Ea,Nw as Fa,cs as Ga,ru as Ha,iv as Ia,rv as Ja,ov as Ka};
70
- //# sourceMappingURL=chunk-6T2V3UIK.js.map
64
+ `);let o=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),s=o.trim().length>0?o.trim():"minimal",d="minimal";try{d=pa(s)}catch{X.write(`Unrecognized governance preset "${s}"; using minimal.
65
+ `)}let c;if(t!==void 0){X.write(`
66
+ 3/3 Telemetry
67
+ `),X.write(`Telemetry helps improve reliability. The choice applies to this CLI install; change it with pm config global set telemetry-tracking.
68
+ `);let l=await n.question(`Enable telemetry for this CLI install? [${t?"Y/n":"y/N"}] `);c=vs(l,t)}return X.write(`
69
+ `),{prefix:r,preset:d,telemetry_enabled:c}}finally{n.close()}}function uu(e){return{presetFromOption:pa(e.preset),useDefaults:e.defaults===!0,authorFromOption:gs(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:ws(e.agentGuidance),typePreset:hs(e.typePreset)}}function fu(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 hu(e,t,n,a){if(t.length===0||n)return;let i=a.discovery==="ancestor";throw new u(`${i?`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.`,h.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:i?"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",...i?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...i?['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 gu(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&&(ma(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 yu(e){let t=await I(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=fu({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return hu(e.settingsPath,n,e.options.force===!0,e.target),gu({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await he(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function _u(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,a,i=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await $s(t,await wu());t=c.prefix,n=c.preset,a=c.telemetry_enabled,i=!0}let r=n??"minimal",o=lu();o.id_prefix=t,ma(o,r);let s=Wa()?.trim()||void 0;o.author_default=e.normalizedOptions.authorFromOption??s??"";let d=Is(e.pmRoot);return a!==void 0&&(o.telemetry.enabled=a,o.telemetry.first_run_prompt_completed=!0),await he(e.pmRoot,o,void 0,d),a!==void 0&&d.omitSections&&await vu(a,e.warnings),{settings:o,normalizedPrefix:t,chosenPreset:n,wizardUsed:i}}function Is(e){return P.resolve(e)===P.resolve(Ce(process.cwd()))?{}:{omitSections:["telemetry"]}}async function wu(){let e=await I(Ce(process.cwd()));if(!(di().telemetry_disabled||e.telemetry.first_run_prompt_completed||hn(e)))return e.telemetry.enabled}async function vu(e,t){let n=Ce(process.cwd()),a=await I(n);if(hn(a)){t.push("telemetry_consent_not_recorded:global_settings_unreadable");return}let i=!1;a.telemetry.enabled=e,a.telemetry.first_run_prompt_completed=!0,await he(n,a,"telemetry:first_run_prompt",{skipIfStored:r=>i=r.telemetry?.first_run_prompt_completed===!0}),i&&t.push("telemetry_consent_kept:recorded_while_prompting")}async function bu(e){let{telemetry:t}=await I(Ce(process.cwd()));return{...e,telemetry:{...e.telemetry,enabled:t.enabled,first_run_prompt_completed:t.first_run_prompt_completed,capture_level:t.capture_level}}}async function ps(e){return e.settingsExists?await yu(e):await _u({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions,warnings:e.warnings})}async function ku(e){let t=await ls({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 he(e.pmRoot,e.settings,void 0,Is(e.pmRoot)),{...t.summary,next_steps:t.next_steps}}async function xu(e,t){let n=[],a=[],i=await qa(e,t.schema);for(let r of i.created_paths)n.push(r),a.push(...await B({path:r,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:a}}async function Su(e){if(e.typePreset===void 0)return;let t=await ks(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await B({path:t.file,scope:"project",op:"init:type_preset"})),t}async function Eu(e){let t=W(e.settings,J()).folders.filter(a=>!sn.includes(a)),n=await Es(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function $u(e){let t=P.resolve(e.tracker_root),n=P.dirname(t);return P.basename(t)==="pm"&&P.basename(n)===".agents"?P.dirname(n):e.workspace_root}async function Iu(e,t,n,a){if(!e)return;let i=await na("all",{install:!0,project:!0},{...t,path:n});a.push(...i.warnings);let r=bs(i),o=r.packages.filter(s=>!s.ok).map(s=>s.alias);if(!r.installed_all||o.length>0)throw new u(`pm init --with-packages did not install all bundled packages successfully${o.length>0?`: ${o.join(", ")}`:"."}`,h.GENERIC_FAILURE);return r}function As(e){let t=a=>oe([...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 i=e.target.mode==="workspace-discovery"?a:a.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(i)||n.push(i)}return n}async function Ts(e,t,n,a=fi){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 i=await a({pmRoot:e,workspaceRoot:t});i.gitattributes.changed&&n.push(`updated:merge_fence:${i.gitattributes.path}`)}catch(i){if(!(i instanceof u))throw i;n.push(`merge_fence_skipped:install_failed:${i.context.code??"pm_error"}:${i.message}:run pm merge install after resolving the Git repository error`)}}async function Au(e,t,n,a){if(e==null||n==="status")return;let i=await pi(e,{pmRoot:t});i.changed&&a.push(`updated:gitignore:${i.path}`)}async function uv(e,t,n={}){let a=t[cu],i=typeof a=="string"?a:process.cwd(),r=ys(i,t,e,n.workspace),o=r.pmRoot;e=_s(r.prefixArg,n.idPrefix);let s=uu(n);await Ss(o,r.target.mode==="tracker-path",n.force===!0);let d=[],c=[],l=P.join(o,"settings.json"),p=await k(l),m;p&&(m=await ps({pmRoot:o,settingsPath:l,settingsExists:p,normalizedPrefix:Ee(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:r.target}));let y=await Es(o,sn);d.push(...y.createdDirs),c.push(...y.warnings),m??=await ps({pmRoot:o,settingsPath:l,settingsExists:p,normalizedPrefix:Ee(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:r.target});let{settings:g}=m,_=$u(r.target),f=await mi(_??P.dirname(o)),w=_??f,v=await ku({pmRoot:o,cwd:w??i,agentGuidanceMode:s.agentGuidanceMode,settings:g,warnings:c}),E=await xu(o,g);d.push(...E.createdDirs),c.push(...E.warnings);let S=await Su({pmRoot:o,settings:g,typePreset:s.typePreset,warnings:c});S&&(g=await I(o)),await Eu({pmRoot:o,settings:g,createdDirs:d,warnings:c}),await Au(w,o,s.agentGuidanceMode,c),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await Ts(o,f,c);let C=await Iu(s.installBundledPackages,t,o,c),ne=As({installBundledPackages:s.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:v.next_steps,target:r.target});return{ok:!0,path:o,target:r.target,settings:await bu(g),created_dirs:d,warnings:c,governance_preset:g.governance.preset,wizard_used:m.wizardUsed,...S?{registered_type_preset:S}:{},...C?{installed_packages:C}:{},next_steps:ne,agent_guidance:v}}export{yn as a,xn as b,Si as c,Uu as d,Bs as e,zu as f,En as g,Ys as h,Xs as i,Zs as j,Ai as k,Jl as l,Ge as m,Ji as n,We as o,Be as p,qi as q,Ui as r,Je as s,qe as t,zi as u,ec as v,Qu as w,af as x,Ci as y,ac as z,bf as A,Yi as B,er as C,Gc as D,Jc as E,xy as F,$y as G,Iy as H,_t as I,Ay as J,Ty as K,Oy as L,Cy as M,Ry as N,Py as O,Ny as P,Dy as Q,jy as R,Ly as S,Fy as T,My as U,Uy as V,zy as W,Gy as X,Jy as Y,qy as Z,Wy as _,By as $,Hy as aa,Ky as ba,Vy as ca,Yy as da,Xy as ea,Zy as fa,Z as ga,b as ha,Rn as ia,od as ja,le as ka,Ft as la,qc as ma,ot as na,Mt as oa,hr as pa,Sr as qa,Wn as ra,Lr as sa,hg as ta,so as ua,pp as va,wo as wa,vo as xa,Xn as ya,Vr as za,Fl as Aa,$p as Ba,Xr as Ca,na as Da,Zo as Ea,Uw as Fa,ls as Ga,cu as Ha,pv as Ia,mv as Ja,uv as Ka};
70
+ //# sourceMappingURL=chunk-LS3GI3H4.js.map