@unbrained/pm-cli 2026.9.6 → 2026.9.8

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 (719) hide show
  1. package/.agents/skills/pm-developer/SKILL.md +12 -4
  2. package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +19 -10
  3. package/.agents/skills/pm-extensions/SKILL.md +6 -0
  4. package/.agents/skills/pm-sdk/SKILL.md +11 -2
  5. package/.agents/skills/pm-user/SKILL.md +5 -0
  6. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +95 -0
  7. package/.claude-plugin/marketplace.json +2 -2
  8. package/CHANGELOG.md +218 -182
  9. package/dist/cli/after-command-context-usage.js +1 -48
  10. package/dist/cli/argv-utils.js +1 -40
  11. package/dist/cli/bootstrap-args.js +1 -9
  12. package/dist/cli/bundle-integrity.js +2 -110
  13. package/dist/cli/commander-usage.js +11 -771
  14. package/dist/cli/commands/activity.js +1 -9
  15. package/dist/cli/commands/aggregate.js +1 -5
  16. package/dist/cli/commands/append.js +1 -5
  17. package/dist/cli/commands/claim.js +1 -5
  18. package/dist/cli/commands/close-many.js +1 -5
  19. package/dist/cli/commands/close.js +1 -9
  20. package/dist/cli/commands/comments.js +1 -5
  21. package/dist/cli/commands/config.js +1 -9
  22. package/dist/cli/commands/context.js +1 -9
  23. package/dist/cli/commands/contracts.js +1 -5
  24. package/dist/cli/commands/copy.js +1 -9
  25. package/dist/cli/commands/create.js +1 -9
  26. package/dist/cli/commands/delete.js +1 -9
  27. package/dist/cli/commands/deps.js +1 -9
  28. package/dist/cli/commands/docs.js +1 -9
  29. package/dist/cli/commands/duplicates.js +1 -9
  30. package/dist/cli/commands/eval.js +1 -9
  31. package/dist/cli/commands/extension/describe.js +1 -5
  32. package/dist/cli/commands/extension/scaffold.js +1 -5
  33. package/dist/cli/commands/extension/shared.js +1 -5
  34. package/dist/cli/commands/extension.js +1 -9
  35. package/dist/cli/commands/files.js +1 -9
  36. package/dist/cli/commands/focus.js +1 -9
  37. package/dist/cli/commands/gc.js +1 -9
  38. package/dist/cli/commands/get.js +1 -9
  39. package/dist/cli/commands/graph.js +1 -10
  40. package/dist/cli/commands/health.js +1 -9
  41. package/dist/cli/commands/history-compact.js +1 -10
  42. package/dist/cli/commands/history-redact.js +1 -11
  43. package/dist/cli/commands/history-repair.js +1 -10
  44. package/dist/cli/commands/history.js +1 -5
  45. package/dist/cli/commands/index.js +1 -58
  46. package/dist/cli/commands/init-agent-guidance.js +1 -9
  47. package/dist/cli/commands/init.js +1 -9
  48. package/dist/cli/commands/learnings.js +1 -5
  49. package/dist/cli/commands/lifecycle-transitions.js +1 -5
  50. package/dist/cli/commands/list.js +1 -9
  51. package/dist/cli/commands/merge.js +1 -11
  52. package/dist/cli/commands/next.js +1 -9
  53. package/dist/cli/commands/notes.js +1 -5
  54. package/dist/cli/commands/plan.js +1 -9
  55. package/dist/cli/commands/profile.js +1 -9
  56. package/dist/cli/commands/restore.js +1 -9
  57. package/dist/cli/commands/scheduling-shortcuts.js +1 -9
  58. package/dist/cli/commands/schema.js +1 -10
  59. package/dist/cli/commands/search.js +1 -9
  60. package/dist/cli/commands/stats.js +1 -9
  61. package/dist/cli/commands/telemetry.js +1 -9
  62. package/dist/cli/commands/test-all.js +1 -9
  63. package/dist/cli/commands/test-runs.js +1 -9
  64. package/dist/cli/commands/test.js +1 -9
  65. package/dist/cli/commands/update-many.js +1 -5
  66. package/dist/cli/commands/update.js +1 -9
  67. package/dist/cli/commands/upgrade.js +1 -5
  68. package/dist/cli/commands/validate.js +1 -15
  69. package/dist/cli/context-intent-invocation.js +1 -20
  70. package/dist/cli/description-stdin.js +1 -17
  71. package/dist/cli/error-guidance.js +1 -1353
  72. package/dist/cli/extension-command-help.js +5 -636
  73. package/dist/cli/extension-command-options.js +1 -427
  74. package/dist/cli/extension-recovery.js +1 -126
  75. package/dist/cli/help-content.js +2 -1001
  76. package/dist/cli/help-json-payload.js +4 -570
  77. package/dist/cli/main.d.ts +4 -0
  78. package/dist/cli/main.js +5 -2573
  79. package/dist/cli/migration-gates.js +1 -289
  80. package/dist/cli/public.js +1 -20
  81. package/dist/cli/register-annotations.js +1 -270
  82. package/dist/cli/register-assurance.js +1 -62
  83. package/dist/cli/register-files-lookup.js +1 -56
  84. package/dist/cli/register-history-activity.d.ts +8 -0
  85. package/dist/cli/register-history-activity.js +2 -0
  86. package/dist/cli/register-history-author.js +1 -38
  87. package/dist/cli/register-history-maintenance.d.ts +9 -0
  88. package/dist/cli/register-history-maintenance.js +2 -0
  89. package/dist/cli/register-list-query.js +10 -943
  90. package/dist/cli/register-mutation-options.js +1 -9
  91. package/dist/cli/register-mutation.js +19 -1893
  92. package/dist/cli/register-operations.js +1 -920
  93. package/dist/cli/register-setup.js +1 -716
  94. package/dist/cli/register-structured-mutation.js +1 -196
  95. package/dist/cli/registration-helpers.js +1 -5
  96. package/dist/cli/runtime-compatibility-boundary.js +4 -42
  97. package/dist/cli/schema-registration-helpers.js +1 -73
  98. package/dist/cli/search-refresh.js +1 -13
  99. package/dist/cli/stats-analytics-json.js +1 -68
  100. package/dist/cli/telemetry-flush.js +1 -10
  101. package/dist/cli-bundle/bundle-manifest.json +164 -156
  102. package/dist/cli-bundle/chunks/chunk-3BZZA6A3.js +5 -0
  103. package/dist/cli-bundle/chunks/chunk-AMRDVX36.js +235 -0
  104. package/dist/cli-bundle/chunks/chunk-DAM4CBBR.js +2202 -0
  105. package/dist/cli-bundle/chunks/{chunk-WYRZZ5ZE.js → chunk-DEZPZOQ7.js} +2 -2
  106. package/dist/cli-bundle/chunks/chunk-FLDWYEND.js +77 -0
  107. package/dist/cli-bundle/chunks/{chunk-NPN5I67J.js → chunk-G5ADGQ2D.js} +3 -3
  108. package/dist/cli-bundle/chunks/chunk-JAAEYHUA.js +2 -0
  109. package/dist/cli-bundle/chunks/{chunk-JX4DH4WC.js → chunk-KR3RP4FH.js} +3 -3
  110. package/dist/cli-bundle/chunks/chunk-LEZOUXG6.js +2 -0
  111. package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +2 -0
  112. package/dist/cli-bundle/chunks/chunk-QOEKOECV.js +29 -0
  113. package/dist/cli-bundle/chunks/chunk-RHSFOMHU.js +2 -0
  114. package/dist/cli-bundle/chunks/chunk-XOD2PCB6.js +20 -0
  115. package/dist/cli-bundle/chunks/{chunk-JT6XF6GE.js → chunk-YVEQ2AMO.js} +4 -4
  116. package/dist/cli-bundle/chunks/register-list-query-KSK3R63M.js +11 -0
  117. package/dist/cli-bundle/chunks/register-mutation-IQ5C7U6O.js +20 -0
  118. package/dist/cli-bundle/chunks/{register-operations-I5W3KMGB.js → register-operations-DWVHR2NC.js} +2 -2
  119. package/dist/cli-bundle/chunks/register-setup-BQ5SVD4B.js +2 -0
  120. package/dist/cli-bundle/focused-chunks/chunk-3WRPWLA7.js +3 -0
  121. package/dist/cli-bundle/focused-chunks/chunk-7MBUII7U.js +2 -0
  122. package/dist/cli-bundle/focused-chunks/chunk-COPBO5HW.js +8 -0
  123. package/dist/cli-bundle/focused-chunks/chunk-DUN4IXYN.js +20 -0
  124. package/dist/cli-bundle/focused-chunks/{chunk-LIJIA4TY.js → chunk-EE5QSM4Z.js} +3 -3
  125. package/dist/cli-bundle/focused-chunks/chunk-HJVARYM3.js +6 -0
  126. package/dist/cli-bundle/focused-chunks/chunk-IAUOUGVR.js +177 -0
  127. package/dist/cli-bundle/focused-chunks/chunk-KOOMJ54F.js +2 -0
  128. package/dist/cli-bundle/focused-chunks/chunk-MZDXX7JY.js +56 -0
  129. package/dist/cli-bundle/focused-chunks/{chunk-M6PBRFSH.js → chunk-OPFHFGDD.js} +2 -2
  130. package/dist/cli-bundle/focused-chunks/chunk-QHNETP77.js +9 -0
  131. package/dist/cli-bundle/focused-chunks/{chunk-3BZEOXLT.js → chunk-RMWES4M6.js} +2 -2
  132. package/dist/cli-bundle/focused-chunks/chunk-RXT4P5QH.js +10 -0
  133. package/dist/cli-bundle/focused-chunks/chunk-SDOL6FM2.js +12 -0
  134. package/dist/cli-bundle/focused-chunks/chunk-SQV4AAUC.js +2 -0
  135. package/dist/cli-bundle/focused-chunks/{chunk-PEFABF7E.js → chunk-WE3IUNIW.js} +3 -3
  136. package/dist/cli-bundle/focused-chunks/chunk-YALOUBWJ.js +2 -0
  137. package/dist/cli-bundle/main.js +20 -20
  138. package/dist/cli-bundle/sdk-authoring.js +1 -1
  139. package/dist/cli-bundle/sdk-contracts.js +2 -2
  140. package/dist/cli-bundle/sdk-core.js +29 -29
  141. package/dist/cli-bundle/sdk-governance.js +1 -1
  142. package/dist/cli-bundle/sdk-graph.js +1 -1
  143. package/dist/cli-bundle/sdk-merge.js +42 -42
  144. package/dist/cli-bundle/sdk-query.js +1 -1
  145. package/dist/cli-bundle/sdk-runtime.js +1 -1
  146. package/dist/cli-bundle/sdk-testing.js +1 -1
  147. package/dist/cli-bundle/sdk.js +11 -11
  148. package/dist/cli.js +1 -104
  149. package/dist/core/checkpoint/checkpoint-gc.js +1 -169
  150. package/dist/core/checkpoint/mutation-checkpoint.js +2 -133
  151. package/dist/core/config/nested-settings.js +1 -534
  152. package/dist/core/config/positional-value.js +1 -109
  153. package/dist/core/diagnostics/remediation.js +1 -506
  154. package/dist/core/extensions/activation-summary-markdown.js +2 -145
  155. package/dist/core/extensions/activation-summary.js +1 -92
  156. package/dist/core/extensions/activation-transaction.js +1 -46
  157. package/dist/core/extensions/capability-usage.js +1 -173
  158. package/dist/core/extensions/command-hook-context.js +1 -13
  159. package/dist/core/extensions/command-metadata-contract.js +1 -22
  160. package/dist/core/extensions/command-visibility-tier.js +1 -29
  161. package/dist/core/extensions/contribution-inventory.js +1 -173
  162. package/dist/core/extensions/exporter-output-contract.js +1 -66
  163. package/dist/core/extensions/extension-candidate.js +1 -18
  164. package/dist/core/extensions/extension-capability-aliases.js +1 -158
  165. package/dist/core/extensions/extension-hook-runtime.js +1 -699
  166. package/dist/core/extensions/extension-policy.js +1 -599
  167. package/dist/core/extensions/extension-registries.js +1 -62
  168. package/dist/core/extensions/extension-runtime-helpers.js +1 -33
  169. package/dist/core/extensions/extension-types.js +1 -102
  170. package/dist/core/extensions/flag-definition-validation.js +1 -52
  171. package/dist/core/extensions/flag-value-types.js +1 -64
  172. package/dist/core/extensions/index.js +1 -526
  173. package/dist/core/extensions/item-field-types.js +1 -39
  174. package/dist/core/extensions/item-fields.js +1 -261
  175. package/dist/core/extensions/loader.js +1 -2223
  176. package/dist/core/extensions/manifest-schema.js +1 -69
  177. package/dist/core/extensions/module-graph-snapshot.js +1 -33
  178. package/dist/core/extensions/preflight-ownership.js +1 -41
  179. package/dist/core/extensions/registration-validation.js +1 -82
  180. package/dist/core/extensions/registration-values.js +1 -209
  181. package/dist/core/extensions/reserved-host-flags.js +1 -36
  182. package/dist/core/extensions/runtime-registrations.js +1 -67
  183. package/dist/core/extensions/service-ownership.js +1 -19
  184. package/dist/core/extensions/version-compat.js +1 -216
  185. package/dist/core/fs/fs-utils.js +2 -158
  186. package/dist/core/fs/host-environment-errors.js +1 -141
  187. package/dist/core/fs/index.js +1 -9
  188. package/dist/core/fs/path-utils.js +1 -17
  189. package/dist/core/governance/content-fields.js +1 -160
  190. package/dist/core/governance/issue-codes.js +1 -151
  191. package/dist/core/governance/metadata-coverage.js +1 -358
  192. package/dist/core/history/drift-cache.js +3 -72
  193. package/dist/core/history/drift-scan.js +1 -342
  194. package/dist/core/history/event-classification.js +1 -109
  195. package/dist/core/history/event-index.js +8 -784
  196. package/dist/core/history/history-compact-bulk.js +1 -104
  197. package/dist/core/history/history-diff.js +1 -158
  198. package/dist/core/history/history-rewrite.d.ts +6 -1
  199. package/dist/core/history/history-rewrite.js +1 -107
  200. package/dist/core/history/history-storage-stats.js +1 -102
  201. package/dist/core/history/history-stream-policy.js +1 -62
  202. package/dist/core/history/history.js +2 -617
  203. package/dist/core/history/identity.js +1 -30
  204. package/dist/core/history/index.js +1 -9
  205. package/dist/core/history/projection.js +1 -196
  206. package/dist/core/history/read.d.ts +9 -0
  207. package/dist/core/history/read.js +1 -57
  208. package/dist/core/history/replay.js +2 -439
  209. package/dist/core/history/version-address.js +1 -32
  210. package/dist/core/history/workspace-history.js +2 -433
  211. package/dist/core/io/body-file.js +1 -62
  212. package/dist/core/io/bulk-ids-input.js +1 -112
  213. package/dist/core/item/actionability.js +1 -327
  214. package/dist/core/item/dependency-reference.js +1 -20
  215. package/dist/core/item/id.js +1 -112
  216. package/dist/core/item/index.js +1 -12
  217. package/dist/core/item/item-format-version.js +1 -78
  218. package/dist/core/item/item-format.js +5 -1473
  219. package/dist/core/item/item-record.js +1 -23
  220. package/dist/core/item/item-type-definition.js +1 -133
  221. package/dist/core/item/parent-reference-policy.js +1 -57
  222. package/dist/core/item/parse.js +2 -603
  223. package/dist/core/item/plan-lifecycle.js +1 -19
  224. package/dist/core/item/priority.js +1 -61
  225. package/dist/core/item/sprint-release-format.js +1 -38
  226. package/dist/core/item/status-filter.js +1 -115
  227. package/dist/core/item/status.js +1 -43
  228. package/dist/core/item/toon-decode.js +1 -29
  229. package/dist/core/item/type-registry.js +1 -715
  230. package/dist/core/item/type-synonyms.js +1 -38
  231. package/dist/core/lock/index.js +1 -9
  232. package/dist/core/lock/lock-gc.js +1 -240
  233. package/dist/core/lock/lock.js +3 -590
  234. package/dist/core/output/mutation-projection.js +1 -217
  235. package/dist/core/output/output-control.js +1 -25
  236. package/dist/core/output/output.js +11 -494
  237. package/dist/core/output/query-summary.js +1 -58
  238. package/dist/core/output/tabular.js +1 -77
  239. package/dist/core/packages/manifest.js +1 -244
  240. package/dist/core/packages/root.js +1 -84
  241. package/dist/core/profile/profile-describe.js +1 -83
  242. package/dist/core/profile/profile-lint.js +1 -415
  243. package/dist/core/profile/profile-plan.js +0 -0
  244. package/dist/core/profile/profile-presets.js +1 -370
  245. package/dist/core/reproducibility/context.js +1 -82
  246. package/dist/core/schema/fields-file.js +2 -288
  247. package/dist/core/schema/item-types-file.js +2 -296
  248. package/dist/core/schema/runtime-field-filters.js +1 -49
  249. package/dist/core/schema/runtime-field-values.js +1 -313
  250. package/dist/core/schema/runtime-schema.js +2 -826
  251. package/dist/core/schema/status-defs-file.js +2 -227
  252. package/dist/core/schema/status-token.js +1 -31
  253. package/dist/core/schema/type-inference.js +1 -95
  254. package/dist/core/schema/type-presets.js +1 -87
  255. package/dist/core/schema/type-workflows.js +1 -104
  256. package/dist/core/search/background-refresh.js +2 -286
  257. package/dist/core/search/bm25.js +1 -146
  258. package/dist/core/search/cache.js +2 -534
  259. package/dist/core/search/corpus.js +1 -311
  260. package/dist/core/search/embedding-batches.js +1 -163
  261. package/dist/core/search/eval.js +1 -225
  262. package/dist/core/search/http-client.js +1 -75
  263. package/dist/core/search/providers.js +1 -242
  264. package/dist/core/search/relevance.js +1 -244
  265. package/dist/core/search/semantic-defaults.js +1 -199
  266. package/dist/core/search/staleness.js +1 -30
  267. package/dist/core/search/vector-stores.js +2 -664
  268. package/dist/core/search/vectorization-metadata.js +1 -81
  269. package/dist/core/sentry/helpers.js +1 -272
  270. package/dist/core/sentry/instrument.js +1 -387
  271. package/dist/core/session/session-state.js +1 -260
  272. package/dist/core/shared/agent-session-context.js +1 -133
  273. package/dist/core/shared/author.js +1 -1172
  274. package/dist/core/shared/command-types.js +1 -4
  275. package/dist/core/shared/conflict-markers.js +1 -31
  276. package/dist/core/shared/constants.js +1 -405
  277. package/dist/core/shared/errors.js +1 -20
  278. package/dist/core/shared/html-entity-decode.js +1 -131
  279. package/dist/core/shared/index.js +1 -12
  280. package/dist/core/shared/item-metadata-contract.js +1 -89
  281. package/dist/core/shared/lazy-module.js +1 -16
  282. package/dist/core/shared/levenshtein.js +1 -61
  283. package/dist/core/shared/memo.js +1 -19
  284. package/dist/core/shared/numeric-parsers.js +1 -20
  285. package/dist/core/shared/option-alias-visibility.js +1 -67
  286. package/dist/core/shared/primitives.js +1 -127
  287. package/dist/core/shared/serial-queue.js +1 -79
  288. package/dist/core/shared/serialization.js +1 -210
  289. package/dist/core/shared/split-comma-list.js +1 -30
  290. package/dist/core/shared/text-normalization.js +1 -38
  291. package/dist/core/shared/time.js +1 -306
  292. package/dist/core/store/index.js +1 -12
  293. package/dist/core/store/item-format-migration.js +1 -125
  294. package/dist/core/store/item-metadata-cache.js +1 -1116
  295. package/dist/core/store/item-metadata-query-index.js +9 -394
  296. package/dist/core/store/item-metadata-read-work.js +1 -43
  297. package/dist/core/store/item-store.js +1 -693
  298. package/dist/core/store/paths.d.ts +1 -1
  299. package/dist/core/store/paths.js +1 -214
  300. package/dist/core/store/settings-read-cache.js +1 -85
  301. package/dist/core/store/settings-validator.js +1 -421
  302. package/dist/core/store/settings.js +3 -1309
  303. package/dist/core/store/tracker-preflight.js +1 -141
  304. package/dist/core/telemetry/consent.js +5 -108
  305. package/dist/core/telemetry/observability.js +1 -246
  306. package/dist/core/telemetry/runtime.js +4 -1988
  307. package/dist/core/test/background-runs.js +4 -945
  308. package/dist/core/test/item-test-run-tracking.js +1 -63
  309. package/dist/core/test/run-selectors.js +1 -120
  310. package/dist/core/validate/estimate-defaults.js +1 -89
  311. package/dist/core/validate/fix-planning.js +1 -189
  312. package/dist/core/validate/linked-artifact-reference.js +1 -36
  313. package/dist/core/validate/missing-by-type.js +1 -34
  314. package/dist/core/validate/missing-link-owners.js +1 -95
  315. package/dist/core/validate/stale-file-classification.js +1 -82
  316. package/dist/mcp/http-server.js +5 -448
  317. package/dist/mcp/legacy-adapter.js +1 -77
  318. package/dist/mcp/runtime-capabilities.js +1 -200
  319. package/dist/mcp/server.js +4 -1233
  320. package/dist/mcp/tool-definitions.js +1 -804
  321. package/dist/sdk/actionability.js +1 -13
  322. package/dist/sdk/agent/closed-domain-contracts.js +1 -161
  323. package/dist/sdk/agent/command-recovery.js +1 -59
  324. package/dist/sdk/agent/command-suggestions.js +1 -66
  325. package/dist/sdk/agent/create-option-policy.js +1 -31
  326. package/dist/sdk/agent/identity-config.js +1 -106
  327. package/dist/sdk/agent/item-addressing.js +1 -207
  328. package/dist/sdk/agent/refusal-closure-census.js +1 -151
  329. package/dist/sdk/agent/refusal-closure.js +1 -133
  330. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -193
  331. package/dist/sdk/agent/refusal-reachability.js +1 -593
  332. package/dist/sdk/agent/subcommand-recovery.js +1 -83
  333. package/dist/sdk/agent/task-transcript-contracts.js +1 -197
  334. package/dist/sdk/agent/tracker-preflight-contracts.js +1 -126
  335. package/dist/sdk/agent-capability-contracts.js +1 -428
  336. package/dist/sdk/agent-session-context.js +1 -9
  337. package/dist/sdk/annotations.js +1 -448
  338. package/dist/sdk/author-attribution.js +1 -468
  339. package/dist/sdk/authoring.js +1 -20
  340. package/dist/sdk/cli-bootstrap.js +1 -838
  341. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +1 -1
  342. package/dist/sdk/cli-contracts/agent-output-contracts.js +4 -476
  343. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -79
  344. package/dist/sdk/cli-contracts/command-aliases.d.ts +4 -0
  345. package/dist/sdk/cli-contracts/command-aliases.js +1 -107
  346. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -151
  347. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1081
  348. package/dist/sdk/cli-contracts/commander-types.js +1 -159
  349. package/dist/sdk/cli-contracts/completeness.js +1 -393
  350. package/dist/sdk/cli-contracts/enum-contracts.js +1 -222
  351. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1947
  352. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -347
  353. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -986
  354. package/dist/sdk/cli-contracts/registration-helpers.js +7 -990
  355. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +5 -0
  356. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -2090
  357. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -324
  358. package/dist/sdk/cli-contracts/string-lists.js +1 -16
  359. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -461
  360. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -2167
  361. package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -1
  362. package/dist/sdk/cli-contracts/tool-schema.js +1 -1664
  363. package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -4
  364. package/dist/sdk/cli-contracts.d.ts +1 -1
  365. package/dist/sdk/cli-contracts.js +1 -17
  366. package/dist/sdk/cli-program.js +1 -49
  367. package/dist/sdk/command-line.d.ts +2 -5
  368. package/dist/sdk/command-line.js +1 -78
  369. package/dist/sdk/comments.js +1 -133
  370. package/dist/sdk/compile-cache.js +1 -73
  371. package/dist/sdk/completion.js +157 -837
  372. package/dist/sdk/compose.js +1 -1090
  373. package/dist/sdk/config.js +1 -1204
  374. package/dist/sdk/context/recency.js +1 -33
  375. package/dist/sdk/context/semantic-session-attribution.js +1 -82
  376. package/dist/sdk/context/usage-egress.js +1 -29
  377. package/dist/sdk/context/usage-ledger.js +3 -185
  378. package/dist/sdk/context-intent-contracts.js +1 -709
  379. package/dist/sdk/context-intent-runtime.js +1 -115
  380. package/dist/sdk/context-packing.js +1 -218
  381. package/dist/sdk/context-relevance.js +1 -503
  382. package/dist/sdk/context-signal-store.js +2 -426
  383. package/dist/sdk/context-usage.js +1 -367
  384. package/dist/sdk/contracts.js +1 -23
  385. package/dist/sdk/core-governance.js +1 -14
  386. package/dist/sdk/core.js +1 -14
  387. package/dist/sdk/corpus-shape.js +1 -401
  388. package/dist/sdk/define.js +1 -220
  389. package/dist/sdk/dependencies.js +1 -718
  390. package/dist/sdk/dependency-flag-validation.js +1 -156
  391. package/dist/sdk/dependency-provenance.js +1 -135
  392. package/dist/sdk/docs.js +1 -14
  393. package/dist/sdk/duplicates.js +1 -40
  394. package/dist/sdk/environment/agent-environment.js +1 -466
  395. package/dist/sdk/environment/host-environment-errors.js +1 -8
  396. package/dist/sdk/environment/project-runtime-compatibility.js +1 -481
  397. package/dist/sdk/environment/source-context.js +1 -28
  398. package/dist/sdk/environment/tracker-preflight.js +1 -9
  399. package/dist/sdk/error-code-catalog.js +1 -153
  400. package/dist/sdk/error-runtime.js +1 -58
  401. package/dist/sdk/errors.js +1 -58
  402. package/dist/sdk/eval.js +1 -190
  403. package/dist/sdk/extension/author-manifest.js +1 -92
  404. package/dist/sdk/extension/bundled-catalog.js +1 -332
  405. package/dist/sdk/extension/concurrency.js +1 -25
  406. package/dist/sdk/extension/copy-scope.d.ts +2 -0
  407. package/dist/sdk/extension/copy-scope.js +2 -0
  408. package/dist/sdk/extension/custom-field-collisions.js +1 -30
  409. package/dist/sdk/extension/describe.js +3 -189
  410. package/dist/sdk/extension/doctor.js +1 -606
  411. package/dist/sdk/extension/install-plan.d.ts +69 -0
  412. package/dist/sdk/extension/install-plan.js +2 -0
  413. package/dist/sdk/extension/install-receipts.d.ts +7 -0
  414. package/dist/sdk/extension/install-receipts.js +2 -0
  415. package/dist/sdk/extension/install-runtime.js +3 -313
  416. package/dist/sdk/extension/install-snapshot.js +1 -66
  417. package/dist/sdk/extension/install-sources.js +5 -1057
  418. package/dist/sdk/extension/managed-state.js +2 -252
  419. package/dist/sdk/extension/migrations.js +2 -174
  420. package/dist/sdk/extension/output-ownership.js +1 -25
  421. package/dist/sdk/extension/runtime-summary.js +1 -18
  422. package/dist/sdk/extension/scaffold.js +4 -2308
  423. package/dist/sdk/extension/shared.js +1 -147
  424. package/dist/sdk/extension/source-resolution.js +1 -65
  425. package/dist/sdk/extension/update-check.js +1 -67
  426. package/dist/sdk/extension-command-context.js +1 -44
  427. package/dist/sdk/extension-contracts.js +1 -73
  428. package/dist/sdk/extension.d.ts +7 -2
  429. package/dist/sdk/extension.js +1 -2196
  430. package/dist/sdk/files.js +1 -535
  431. package/dist/sdk/flag-invocation-contracts.d.ts +0 -5
  432. package/dist/sdk/flag-invocation-contracts.js +1 -344
  433. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -2224
  434. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -2236
  435. package/dist/sdk/generated-error-code-catalog.js +1 -16
  436. package/dist/sdk/governance/assurance-action-contracts.js +1 -4
  437. package/dist/sdk/governance/assurance-action.js +1 -411
  438. package/dist/sdk/governance/assurance-limits.js +1 -10
  439. package/dist/sdk/governance/assurance-mutation-error.js +1 -81
  440. package/dist/sdk/governance/assurance-presets.js +1 -135
  441. package/dist/sdk/governance/assurance-runtime.js +1 -238
  442. package/dist/sdk/governance/assurance.js +4 -1182
  443. package/dist/sdk/governance/boundary-fixtures.js +1 -200
  444. package/dist/sdk/governance/coverage-assurance.js +1 -60
  445. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -188
  446. package/dist/sdk/governance/defect-recurrence-graph.js +1 -120
  447. package/dist/sdk/governance/defect-recurrence-signals.js +1 -24
  448. package/dist/sdk/governance/defect-recurrence.js +1 -623
  449. package/dist/sdk/governance/extension-host-version.js +1 -115
  450. package/dist/sdk/governance/gc.js +1 -368
  451. package/dist/sdk/governance/health.js +1 -2367
  452. package/dist/sdk/governance/hierarchy-validation.js +1 -108
  453. package/dist/sdk/governance/linked-file-report.js +1 -71
  454. package/dist/sdk/governance/merge-receipt-history.js +1 -206
  455. package/dist/sdk/governance/provenance-health.js +1 -282
  456. package/dist/sdk/governance/reindex.js +4 -761
  457. package/dist/sdk/governance/stale-work.js +1 -82
  458. package/dist/sdk/governance/status-role-diagnostics.js +1 -35
  459. package/dist/sdk/governance/storage-integrity.js +1 -280
  460. package/dist/sdk/governance/tracked-runtime-cache.js +1 -106
  461. package/dist/sdk/governance/upgrade.js +2 -327
  462. package/dist/sdk/governance/validate-history-drift.js +1 -81
  463. package/dist/sdk/governance/validate-item-reader.js +1 -17
  464. package/dist/sdk/governance/validate-normalization.js +1 -36
  465. package/dist/sdk/governance/validate.js +1 -2261
  466. package/dist/sdk/governance/workspace-position.js +1 -163
  467. package/dist/sdk/governance.d.ts +1 -0
  468. package/dist/sdk/governance.js +1 -31
  469. package/dist/sdk/graph/adapter.js +1 -181
  470. package/dist/sdk/graph/analytics.js +1 -474
  471. package/dist/sdk/graph/assembly.js +1 -377
  472. package/dist/sdk/graph/cache.js +1 -160
  473. package/dist/sdk/graph/centrality.js +1 -258
  474. package/dist/sdk/graph/conformance.js +1 -130
  475. package/dist/sdk/graph/deadline-scheduling.d.ts +90 -0
  476. package/dist/sdk/graph/deadline-scheduling.js +2 -0
  477. package/dist/sdk/graph/durable-cache.d.ts +1 -1
  478. package/dist/sdk/graph/durable-cache.js +1 -361
  479. package/dist/sdk/graph/governance-contracts.js +1 -34
  480. package/dist/sdk/graph/governance.d.ts +13 -1
  481. package/dist/sdk/graph/governance.js +1 -735
  482. package/dist/sdk/graph/hierarchy-integrity.js +1 -310
  483. package/dist/sdk/graph/index.d.ts +3 -2
  484. package/dist/sdk/graph/index.js +1 -26
  485. package/dist/sdk/graph/lifecycle-coverage.d.ts +32 -0
  486. package/dist/sdk/graph/lifecycle-coverage.js +2 -0
  487. package/dist/sdk/graph/mutation-advisory.js +1 -176
  488. package/dist/sdk/graph/remediation.js +1 -197
  489. package/dist/sdk/graph/run.d.ts +15 -1
  490. package/dist/sdk/graph/run.js +1 -768
  491. package/dist/sdk/graph/scheduling.js +1 -124
  492. package/dist/sdk/graph/traversal.js +1 -284
  493. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -27
  494. package/dist/sdk/graph.js +1 -15
  495. package/dist/sdk/guide-topics.js +1 -707
  496. package/dist/sdk/guide.js +1 -279
  497. package/dist/sdk/history/maintenance.d.ts +71 -0
  498. package/dist/sdk/history/maintenance.js +2 -0
  499. package/dist/sdk/history/salvage.js +2 -247
  500. package/dist/sdk/history/subject.d.ts +19 -0
  501. package/dist/sdk/history/subject.js +2 -0
  502. package/dist/sdk/history-analytics.js +1 -282
  503. package/dist/sdk/history-compact.js +1 -527
  504. package/dist/sdk/history-mcp.js +1 -68
  505. package/dist/sdk/history-provenance.js +1 -182
  506. package/dist/sdk/history-read.js +1 -96
  507. package/dist/sdk/history-redact.d.ts +1 -14
  508. package/dist/sdk/history-redact.js +1 -643
  509. package/dist/sdk/history-repair.d.ts +5 -0
  510. package/dist/sdk/history-repair.js +1 -657
  511. package/dist/sdk/improvement-ledger-validation.js +1 -62
  512. package/dist/sdk/improvement-ledger.js +2 -257
  513. package/dist/sdk/index.d.ts +4 -0
  514. package/dist/sdk/index.js +1 -183
  515. package/dist/sdk/init-agent-guidance.js +2 -496
  516. package/dist/sdk/init.js +2 -820
  517. package/dist/sdk/invocation-author.js +1 -39
  518. package/dist/sdk/item-children.js +1 -90
  519. package/dist/sdk/item-metadata-index.js +1 -15
  520. package/dist/sdk/item-schedule.js +1 -27
  521. package/dist/sdk/item-transaction.js +1 -396
  522. package/dist/sdk/learnings.js +1 -29
  523. package/dist/sdk/lifecycle/append.js +2 -53
  524. package/dist/sdk/lifecycle/claim.d.ts +2 -0
  525. package/dist/sdk/lifecycle/claim.js +1 -242
  526. package/dist/sdk/lifecycle/close-many.js +1 -438
  527. package/dist/sdk/lifecycle/close.js +1 -468
  528. package/dist/sdk/lifecycle/copy.js +1 -212
  529. package/dist/sdk/lifecycle/create.js +1 -1949
  530. package/dist/sdk/lifecycle/delete.js +1 -45
  531. package/dist/sdk/lifecycle/event-validation-messages.js +1 -91
  532. package/dist/sdk/lifecycle/focus.js +1 -91
  533. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -24
  534. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -149
  535. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -40
  536. package/dist/sdk/lifecycle/mcp-actions.d.ts +2 -0
  537. package/dist/sdk/lifecycle/mcp-actions.js +1 -51
  538. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -46
  539. package/dist/sdk/lifecycle/mutation-command-options.js +1 -9
  540. package/dist/sdk/lifecycle/plan.js +1 -1606
  541. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -147
  542. package/dist/sdk/lifecycle/reopen.js +1 -68
  543. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +1 -143
  544. package/dist/sdk/lifecycle/restore.d.ts +1 -0
  545. package/dist/sdk/lifecycle/restore.js +1 -330
  546. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -295
  547. package/dist/sdk/lifecycle/update-many.js +1 -861
  548. package/dist/sdk/lifecycle/update.js +1 -2136
  549. package/dist/sdk/lifecycle-completion.js +1 -92
  550. package/dist/sdk/lifecycle-policy.js +1 -120
  551. package/dist/sdk/linked-artifacts.js +1 -530
  552. package/dist/sdk/mcp/apps.js +4 -133
  553. package/dist/sdk/mcp/authorization.js +1 -404
  554. package/dist/sdk/mcp/discovery.js +1 -494
  555. package/dist/sdk/mcp/interactions.js +1 -336
  556. package/dist/sdk/mcp/protocol.d.ts +7 -0
  557. package/dist/sdk/mcp/protocol.js +1 -184
  558. package/dist/sdk/mcp/skills.js +1 -389
  559. package/dist/sdk/mcp/subscriptions.js +1 -211
  560. package/dist/sdk/mcp/tasks.js +2 -430
  561. package/dist/sdk/mcp/transport.js +1 -260
  562. package/dist/sdk/merge/abandoned-receipts.js +1 -46
  563. package/dist/sdk/merge/driver.js +1 -212
  564. package/dist/sdk/merge/index.js +1 -16
  565. package/dist/sdk/merge/install.js +3 -561
  566. package/dist/sdk/merge/receipt-file-boundary.js +1 -46
  567. package/dist/sdk/merge/receipt-operation.js +1 -96
  568. package/dist/sdk/merge/receipt-schema.js +1 -397
  569. package/dist/sdk/merge/receipts.js +4 -525
  570. package/dist/sdk/merge/reconcile.js +1 -352
  571. package/dist/sdk/merge/three-way.js +3 -775
  572. package/dist/sdk/merge.js +1 -10
  573. package/dist/sdk/mutation-events.js +1 -292
  574. package/dist/sdk/mutation-guard.js +1 -216
  575. package/dist/sdk/notes.js +1 -139
  576. package/dist/sdk/output-contracts.js +1 -172
  577. package/dist/sdk/output-projection.js +1 -430
  578. package/dist/sdk/output-token-accounting.js +1 -140
  579. package/dist/sdk/output.js +1 -64
  580. package/dist/sdk/ownership-source.js +1 -21
  581. package/dist/sdk/package-import-adapters.js +1 -442
  582. package/dist/sdk/package-migrations.js +1 -20
  583. package/dist/sdk/package-runtime-options.js +1 -80
  584. package/dist/sdk/pagination.js +1 -162
  585. package/dist/sdk/profile.js +1 -454
  586. package/dist/sdk/provenance.js +1 -258
  587. package/dist/sdk/public-surface.json +1 -1
  588. package/dist/sdk/query/activity.js +1 -401
  589. package/dist/sdk/query/aggregate.d.ts +16 -0
  590. package/dist/sdk/query/aggregate.js +1 -390
  591. package/dist/sdk/query/calendar.js +1 -964
  592. package/dist/sdk/query/complete-list.js +1 -215
  593. package/dist/sdk/query/context.js +1 -1702
  594. package/dist/sdk/query/duplicate-candidates.js +1 -70
  595. package/dist/sdk/query/get.js +1 -450
  596. package/dist/sdk/query/history.js +1 -186
  597. package/dist/sdk/query/item-filter-options.js +1 -9
  598. package/dist/sdk/query/light-metadata.js +1 -18
  599. package/dist/sdk/query/list-filter-shared.js +1 -81
  600. package/dist/sdk/query/list.js +1 -1304
  601. package/dist/sdk/query/multi-value-filters.js +1 -78
  602. package/dist/sdk/query/next.js +1 -513
  603. package/dist/sdk/query/parsers.js +1 -44
  604. package/dist/sdk/query/projection-contracts.js +1 -184
  605. package/dist/sdk/query/search-contracts.js +1 -230
  606. package/dist/sdk/query/search-pagination.js +1 -35
  607. package/dist/sdk/query/search-rendering.js +1 -105
  608. package/dist/sdk/query/search.js +2 -1987
  609. package/dist/sdk/query.js +1 -35
  610. package/dist/sdk/read-output/continuation.js +1 -194
  611. package/dist/sdk/read-output-budget.js +1 -135
  612. package/dist/sdk/read-output-contracts.js +1 -1225
  613. package/dist/sdk/read-output-rows.js +1 -186
  614. package/dist/sdk/read-output-session.js +1 -208
  615. package/dist/sdk/relationship-analytics.js +1 -410
  616. package/dist/sdk/relationship-context.js +1 -284
  617. package/dist/sdk/relationship-history.js +4 -519
  618. package/dist/sdk/relationship-kinds/contract.js +1 -22
  619. package/dist/sdk/relationship-migration.js +1 -77
  620. package/dist/sdk/relationships.js +1 -579
  621. package/dist/sdk/reproducibility/process.js +1 -87
  622. package/dist/sdk/runtime-action-aliases.js +1 -59
  623. package/dist/sdk/runtime-extended-actions.js +1 -177
  624. package/dist/sdk/runtime-input.js +1 -614
  625. package/dist/sdk/runtime-primitives.js +1 -84
  626. package/dist/sdk/runtime-public-contracts.js +1 -4
  627. package/dist/sdk/runtime-stats-options.js +1 -38
  628. package/dist/sdk/runtime.js +1 -1928
  629. package/dist/sdk/scheduling-shortcuts.js +1 -63
  630. package/dist/sdk/schema-migration.js +3 -856
  631. package/dist/sdk/schema.js +1 -1376
  632. package/dist/sdk/search-refresh-worker.js +1 -18
  633. package/dist/sdk/similarity-scoring.js +1 -53
  634. package/dist/sdk/similarity.js +1 -326
  635. package/dist/sdk/start-task-status.js +1 -14
  636. package/dist/sdk/stats.js +1 -270
  637. package/dist/sdk/structured-mutations.js +1 -580
  638. package/dist/sdk/telemetry-flush.js +1 -13
  639. package/dist/sdk/telemetry.js +1 -405
  640. package/dist/sdk/templates.js +2 -292
  641. package/dist/sdk/test/batch.js +2 -509
  642. package/dist/sdk/test/entry.js +1 -70
  643. package/dist/sdk/test/execution.js +6 -2211
  644. package/dist/sdk/test/linked-command-detection.js +1 -546
  645. package/dist/sdk/test/measurements.js +1 -91
  646. package/dist/sdk/test/parsers.js +1 -545
  647. package/dist/sdk/test/runs.js +1 -193
  648. package/dist/sdk/test/trust.js +2 -206
  649. package/dist/sdk/testing.js +4 -1391
  650. package/dist/sdk/traceability/runtime-files-lookup.js +1 -32
  651. package/dist/sdk/traceability/source-traceability.js +1 -292
  652. package/dist/sdk/tracker-root-discovery.js +1 -9
  653. package/dist/sdk/workspace-contracts-cache.js +1 -28
  654. package/dist/sdk/workspace-contracts.js +1 -33
  655. package/dist/sdk/workspace-memory.js +2 -318
  656. package/dist/sdk/workspace-recipe.js +1 -71
  657. package/dist/sdk/workspace-snapshot.js +4 -613
  658. package/dist/sdk/workspace-transaction-gc.js +1 -149
  659. package/dist/sdk/workspace-transaction.js +2 -363
  660. package/dist/sdk/workspace.js +3 -127
  661. package/dist/types/index.js +1 -9
  662. package/dist/types.js +1 -245
  663. package/docs/AGENT_GUIDE.md +1 -1
  664. package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +167 -0
  665. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +9 -3
  666. package/docs/EXTENSIONS.md +1 -0
  667. package/docs/HISTORY_MAINTENANCE.md +125 -0
  668. package/docs/MCP_2026_07_28_CONFORMANCE.md +20 -10
  669. package/docs/PACKAGE_EVIDENCE.md +92 -0
  670. package/docs/PLANNING_MEASUREMENTS.md +183 -0
  671. package/docs/README.md +3 -0
  672. package/docs/RELEASING.md +1 -0
  673. package/docs/SCRIPTING.md +21 -0
  674. package/docs/TESTING.md +23 -0
  675. package/docs/generated/FLAG_LEXICON_BUDGETS.md +5 -5
  676. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +2 -2
  677. package/marketplace.json +2 -2
  678. package/package.json +1 -1
  679. package/packages/pm-beads/package.json +1 -1
  680. package/packages/pm-calendar/package.json +1 -1
  681. package/packages/pm-command-kit/package.json +1 -1
  682. package/packages/pm-digital-twin/package.json +1 -1
  683. package/packages/pm-governance-audit/package.json +1 -1
  684. package/packages/pm-guide-shell/package.json +1 -1
  685. package/packages/pm-kanban/package.json +1 -1
  686. package/packages/pm-lifecycle-hooks/package.json +1 -1
  687. package/packages/pm-linked-test-adapters/package.json +1 -1
  688. package/packages/pm-search-advanced/package.json +1 -1
  689. package/packages/pm-templates/package.json +1 -1
  690. package/packages/pm-todos/package.json +1 -1
  691. package/packages/pm-vcs/package.json +1 -1
  692. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  693. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  694. package/scripts/finalize-build.mjs +45 -3
  695. package/dist/cli-bundle/chunks/chunk-AZDFJGH6.js +0 -9
  696. package/dist/cli-bundle/chunks/chunk-BAX2BYUW.js +0 -2111
  697. package/dist/cli-bundle/chunks/chunk-CKOL5U7J.js +0 -77
  698. package/dist/cli-bundle/chunks/chunk-OF76PSDQ.js +0 -5
  699. package/dist/cli-bundle/chunks/chunk-QUWFABDM.js +0 -232
  700. package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +0 -2
  701. package/dist/cli-bundle/chunks/chunk-RWWBOWJ5.js +0 -2
  702. package/dist/cli-bundle/chunks/chunk-WGAOYSYH.js +0 -40
  703. package/dist/cli-bundle/chunks/chunk-WI2AYPA7.js +0 -2
  704. package/dist/cli-bundle/chunks/register-list-query-5JL52D33.js +0 -11
  705. package/dist/cli-bundle/chunks/register-mutation-ZPG7KMVP.js +0 -20
  706. package/dist/cli-bundle/chunks/register-setup-H4SVAVX7.js +0 -2
  707. package/dist/cli-bundle/focused-chunks/chunk-AL5ON6K6.js +0 -2
  708. package/dist/cli-bundle/focused-chunks/chunk-CHC2IDXA.js +0 -6
  709. package/dist/cli-bundle/focused-chunks/chunk-CK6QFAPZ.js +0 -20
  710. package/dist/cli-bundle/focused-chunks/chunk-EZR3GHFE.js +0 -2
  711. package/dist/cli-bundle/focused-chunks/chunk-H2WJWK7L.js +0 -56
  712. package/dist/cli-bundle/focused-chunks/chunk-NTPY5GSO.js +0 -3
  713. package/dist/cli-bundle/focused-chunks/chunk-P5O7MP5Y.js +0 -2
  714. package/dist/cli-bundle/focused-chunks/chunk-PDMW2E36.js +0 -177
  715. package/dist/cli-bundle/focused-chunks/chunk-QTVCLMSZ.js +0 -6
  716. package/dist/cli-bundle/focused-chunks/chunk-QTZRBUYA.js +0 -8
  717. package/dist/cli-bundle/focused-chunks/chunk-SGQST3PQ.js +0 -12
  718. package/dist/cli-bundle/focused-chunks/chunk-UKHASMMP.js +0 -10
  719. package/dist/cli-bundle/focused-chunks/chunk-ZPEKQHOC.js +0 -2
@@ -1,2309 +1,5 @@
1
- /**
2
- * @module sdk/extension/scaffold
3
- *
4
- * Implements extension package-management support for Scaffold.
5
- */
6
-
7
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5321d574-4de4-5f94-99db-0c49639673fc")}catch(e){}}();
8
- import fs from "node:fs/promises";
9
- import path from "node:path";
10
- import { pathExists } from "../../core/fs/fs-utils.js";
11
- import { EXIT_CODE } from "../../core/shared/constants.js";
12
- import { PmCliError } from "../../core/shared/errors.js";
13
- import { EXECUTABLE_COMMAND_ALIASES, PM_CORE_COMMAND_NAMES, } from "../cli-contracts.js";
14
- import { normalizeManagedDirectoryName } from "./shared.js";
15
- // Safe compatibility floor emitted into scaffolded manifests. The current
16
- // starters are loaded as TypeScript and use the SDK define*/testing helpers; the
17
- // first released host that supports that full generated contract is v2026.6.24.
18
- // manifest_version tracks the manifest schema generation (currently 1).
19
- const SCAFFOLD_MANIFEST_VERSION = 1;
20
- /** Public contract for scaffold pm min version, shared by SDK and presentation-layer consumers. */
21
- export const SCAFFOLD_PM_MIN_VERSION = "2026.6.24";
22
- const SCAFFOLD_NODE_ENGINE = ">=22.18.0";
23
- const SCAFFOLD_DECLARED_PERMISSIONS = {
24
- fs_read: false,
25
- fs_write: false,
26
- network: false,
27
- env_read: false,
28
- env_write: false,
29
- process_spawn: false,
30
- };
31
- const RESERVED_SCAFFOLD_COMMAND_ROOTS = new Set([
32
- ...PM_CORE_COMMAND_NAMES.map((commandName) => commandName.split("-")[0].toLowerCase()),
33
- ...Object.keys(EXECUTABLE_COMMAND_ALIASES).map((alias) => alias.toLowerCase()),
34
- // "scaffold" is a Commander command that currently lives outside both
35
- // PM_CORE_COMMAND_NAMES and EXECUTABLE_COMMAND_ALIASES.
36
- "scaffold",
37
- ]);
38
- // TypeScript dev-dependency floor for scaffolded packages, matching the CLI's own
39
- // toolchain so generated packages compile against the same compiler generation.
40
- const SCAFFOLD_TYPESCRIPT_VERSION = "^6.0.0";
41
- // `@types/node` floor for scaffolded packages: the colocated `index.test.ts`
42
- // imports `node:test`/`node:assert`, which need Node's ambient type definitions
43
- // to type-check. Pinned to the engines floor (Node >=22.18), matching the CLI
44
- // itself — the version where Node strips TypeScript types on load by default.
45
- const SCAFFOLD_TYPES_NODE_VERSION = "^22.0.0";
46
- const SAMPLE_HARNESS_CLEANUP_LINES = [
47
- "type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;",
48
- "",
49
- "async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {",
50
- " if (!deactivated) {",
51
- " try {",
52
- " await ext.deactivate();",
53
- " } catch {",
54
- " // Preserve the original assertion error; cleanup is best effort.",
55
- " }",
56
- " }",
57
- "}",
58
- "",
59
- ];
60
- const SAMPLE_HARNESS_FINALLY_LINES = [
61
- " } finally {",
62
- " await deactivateIfNeeded(ext, deactivated);",
63
- " }",
64
- ];
65
- function indentGeneratedLines(lines, prefix) {
66
- return lines.map((line) => (line === "" ? line : `${prefix}${line}`));
67
- }
68
- function buildSchemaCapabilityAssertionLines(options) {
69
- const migrationHint = options.includeMigrationReplacementHint === true
70
- ? [" // as your migration grows."]
71
- : [];
72
- return [
73
- " // assertItemType/Field/Migration throw unless the registration is present, so",
74
- " // reaching each next line already proves the wiring; assert on the returned",
75
- " // definitions to demonstrate inspecting registered metadata.",
76
- ` const itemType = ext.assertItemType({ name: ${JSON.stringify(options.itemTypeName)}, extensionName: ${JSON.stringify(options.extensionName)} });`,
77
- ` assert.equal(itemType.itemType.folder, ${JSON.stringify(options.itemTypeFolder)});`,
78
- ` const itemField = ext.assertItemField({ name: ${JSON.stringify(options.fieldName)}, extensionName: ${JSON.stringify(options.extensionName)} });`,
79
- ' assert.equal(itemField.field.type, "string");',
80
- ` ext.assertMigration({ name: ${JSON.stringify(options.migrationId)}, extensionName: ${JSON.stringify(options.extensionName)}, mandatory: false });`,
81
- "",
82
- " // runMigration invokes the migration through pm's real runner with a synthetic",
83
- " // context and returns its result.",
84
- ...migrationHint,
85
- ` const migrated = await ext.runMigration({ migration: ${JSON.stringify(options.migrationId)} });`,
86
- ` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(options.migrationId)} });`,
87
- ];
88
- }
89
- function buildProfileCapabilityAssertionLines(extensionName) {
90
- return [
91
- " // assertProfile throws unless the profile is registered, so reaching the next",
92
- " // line already proves the wiring; assert on the returned definition to inspect",
93
- " // the bundled archetype dimensions.",
94
- ` const { profile } = ext.assertProfile({ name: ${JSON.stringify(extensionName)}, extensionName: ${JSON.stringify(extensionName)} });`,
95
- ` assert.equal(profile.title, ${JSON.stringify(`${extensionName} archetype`)});`,
96
- " assert.equal(profile.types.length, 1);",
97
- " assert.equal(profile.workflows.length, 1);",
98
- ];
99
- }
100
- // Strict NodeNext tsconfig emitted into every scaffold (ADR pm-2c28 / pm-m1uz:
101
- // extensions are authored AND loaded as TypeScript). It is a type-check-only
102
- // config (`noEmit`): there is no compile step — pm loads the `./index.ts`
103
- // manifest entry directly via Node's native type stripping (Node >=22.18), so
104
- // no `.js` is emitted or committed. `allowImportingTsExtensions` lets the
105
- // colocated `index.test.ts` import the sibling `./index.ts` entry with its real
106
- // extension, exactly as Node resolves it at load time. NodeNext resolution keeps
107
- // the module graph identical to the runtime loader.
108
- const SCAFFOLD_TSCONFIG = {
109
- compilerOptions: {
110
- target: "ES2022",
111
- module: "NodeNext",
112
- moduleResolution: "NodeNext",
113
- strict: true,
114
- esModuleInterop: true,
115
- skipLibCheck: true,
116
- noEmit: true,
117
- allowImportingTsExtensions: true,
118
- resolveJsonModule: true,
119
- // `node:test`/`node:assert` in the colocated test (and Node globals) resolve
120
- // from `@types/node`; name it explicitly so it is loaded regardless of how the
121
- // package manager lays out `node_modules/@types`.
122
- types: ["node"],
123
- },
124
- // Recursive so a package that grows into subdirectory `*.ts` modules still
125
- // type-checks; tsc excludes `node_modules` by default.
126
- include: ["**/*.ts"],
127
- };
128
- /** Capability shapes the package/extension scaffolder can target via the `--capability` selector — one per SDK extension capability, so every registration surface has a runnable starter. `commands` emits the default command-only starter; `hooks` additionally wires an `after_command` lifecycle reactor; `search` wires an in-memory provider/adapter pair; `importers` wires importer and exporter command primitives so authors can customize project context movement; `schema` registers a custom item type, item field, and migration so authors can model their own project domain; `profile` registers a complete project-profile archetype (item types, statuses, fields, a workflow, config, a template, and package recommendations) via `api.registerProfile` so `pm profile apply` can tailor a tracker in one shot; `renderers` overrides how a command's output is serialized for a format; `parser` rewrites a command's parsed options before its handler runs; `preflight` adjusts pm's pre-run migration/format gate decision; and `services` overrides a built-in pm service (e.g. output formatting) — without starting from a blank extension. */
129
- export const SCAFFOLD_CAPABILITIES = [
130
- "commands",
131
- "hooks",
132
- "search",
133
- "importers",
134
- "schema",
135
- "profile",
136
- "renderers",
137
- "parser",
138
- "preflight",
139
- "services",
140
- ];
141
- const SCAFFOLD_MANIFEST_CAPABILITIES = {
142
- commands: ["commands"],
143
- hooks: ["commands", "hooks"],
144
- search: ["commands", "search"],
145
- importers: ["commands", "schema", "importers"],
146
- schema: ["commands", "schema"],
147
- // A profile registration IS a schema+config bundle, so the loader gate requires
148
- // the `schema` capability (no separate `profile` capability) — same grant as the
149
- // schema starter, mirroring the bundled pm-kanban exemplar.
150
- profile: ["commands", "schema"],
151
- renderers: ["commands", "renderers"],
152
- // The parser starter declares `--shout`/`--upper` command flags so the
153
- // override is runnable through `pm <command> --shout`; flag metadata is
154
- // schema-governed, so the manifest also declares `schema`.
155
- parser: ["commands", "parser", "schema"],
156
- preflight: ["commands", "preflight"],
157
- services: ["commands", "services"],
158
- };
159
- const SAMPLE_TEST_CAPABILITIES_LITERAL = {
160
- commands: '["commands"]',
161
- hooks: '["commands", "hooks"]',
162
- search: '["commands", "search"]',
163
- importers: '["commands", "schema", "importers"]',
164
- schema: '["commands", "schema"]',
165
- profile: '["commands", "schema"]',
166
- renderers: '["commands", "renderers"]',
167
- parser: '["commands", "parser", "schema"]',
168
- preflight: '["commands", "preflight"]',
169
- services: '["commands", "services"]',
170
- };
171
- const ENTRYPOINT_BULLETS = {
172
- commands: "- `index.ts`: the TypeScript manifest entry — starter command registration plus a `deactivate` teardown stub.",
173
- hooks: "- `index.ts`: the TypeScript manifest entry — starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",
174
- search: "- `index.ts`: the TypeScript manifest entry — starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",
175
- importers: "- `index.ts`: the TypeScript manifest entry — starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",
176
- schema: "- `index.ts`: the TypeScript manifest entry — starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",
177
- profile: "- `index.ts`: the TypeScript manifest entry — 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.",
178
- renderers: "- `index.ts`: the TypeScript manifest entry — starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",
179
- parser: "- `index.ts`: the TypeScript manifest entry — starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",
180
- preflight: "- `index.ts`: the TypeScript manifest entry — starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",
181
- services: "- `index.ts`: the TypeScript manifest entry — starter command registration, an `output_format` service override, and a `deactivate` teardown stub.",
182
- };
183
- const SAMPLE_TEST_BULLETS = {
184
- commands: "- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",
185
- hooks: "- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",
186
- search: "- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",
187
- importers: "- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",
188
- 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.",
189
- 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.",
190
- 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.",
191
- 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.",
192
- 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.",
193
- 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.",
194
- };
195
- const TSCONFIG_BULLET = "- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.";
196
- const PACKAGE_CAPABILITY_README_SECTIONS = {
197
- commands: [],
198
- hooks: [
199
- "",
200
- "## Lifecycle Hook",
201
- "`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.",
202
- "pm fires it once a command finishes, passing the command outcome and the",
203
- "items it mutated (`context.affected`). React there to keep external context",
204
- "in sync - sync records, emit telemetry, or refresh derived state. The",
205
- "`hooks` capability in `manifest.json` is what grants the hook registration;",
206
- "remove it (and the hook) if your package only needs commands.",
207
- ],
208
- search: [
209
- "",
210
- "## Search Provider",
211
- "`index.ts` registers a deterministic in-memory search provider and",
212
- "vector-store adapter through `api.registerSearchProvider` and",
213
- "`api.registerVectorStoreAdapter`. Replace the sample scoring,",
214
- "embedding, and storage behavior with your project-specific retrieval",
215
- "logic. The `search` capability in `manifest.json` grants both",
216
- "registrations.",
217
- ],
218
- importers: [
219
- "",
220
- "## Importer and Exporter",
221
- "`index.ts` registers paired project-context import/export commands through",
222
- "`api.registerImporter` and `api.registerExporter`. Replace the starter",
223
- "payloads with your domain adapter: GitHub issues, CSV rows, documents,",
224
- "tickets, or another project-management source of truth. The `importers`",
225
- "capability grants both registrations, and `schema` grants the example",
226
- "command flag metadata.",
227
- ],
228
- schema: [
229
- "",
230
- "## Custom Schema",
231
- "`index.ts` models a project domain by registering a custom item type, a",
232
- "custom item field, and a schema migration through `api.registerItemTypes`,",
233
- "`api.registerItemFields`, and `api.registerMigration`. This is how a package",
234
- "turns pm into a domain-specific tracker — `project management = context",
235
- "management`. Replace the sample type/field/migration with your own domain",
236
- "model; the `schema` capability in `manifest.json` grants all three",
237
- "registrations. Once installed, the custom type is usable everywhere, e.g.",
238
- '`pm create <type> "<title>"` and `pm list --type <type>`.',
239
- ],
240
- profile: [
241
- "",
242
- "## Project Profile",
243
- "`index.ts` registers a complete project-profile archetype through",
244
- "`api.registerProfile`. A profile is the broadest customization primitive pm",
245
- "has — one declarative bundle of item types, custom statuses, fields, a per-type",
246
- "workflow, config knobs, create templates, and package recommendations. Once the",
247
- "package is installed the profile resolves by name through `pm profile list`,",
248
- "`pm profile show <name>`, and `pm profile apply <name>`, which stages every",
249
- "dimension idempotently — exactly like a core archetype (agile/ops/research),",
250
- "with no consumer code required. Replace the sample archetype with your own",
251
- "domain; the `schema` capability in `manifest.json` grants the registration (a",
252
- "profile is a schema+config bundle, so it needs no separate capability).",
253
- ],
254
- renderers: [
255
- "",
256
- "## Output Renderer",
257
- "`index.ts` registers a `toon` output renderer override through",
258
- "`api.registerRenderer`. Renderer overrides run for every command's output in",
259
- "that format, so this starter scopes itself to THIS package's own command and",
260
- "returns `null` (pass-through to pm's default renderer) for everything else.",
261
- "Return a string to take over rendering. Replace the sample serialization with",
262
- "your own; the `renderers` capability in `manifest.json` grants the",
263
- "registration.",
264
- ],
265
- parser: [
266
- "",
267
- "## Parser Override",
268
- "`index.ts` registers a parser override for the starter command through",
269
- "`api.registerParser`. pm runs it on the command's parsed options BEFORE the",
270
- "handler, merging the delta you return. This starter rewrites a deprecated",
271
- "`--shout` alias to the canonical `--upper` flag; replace it with your",
272
- "command's real normalization. The `parser` capability in `manifest.json`",
273
- "grants the registration.",
274
- ],
275
- preflight: [
276
- "",
277
- "## Preflight Override",
278
- "`index.ts` registers a preflight override through `api.registerPreflight`. pm",
279
- "calls it only for its declared command ownership to compute the migration/format",
280
- "gate decision. Overlapping or legacy global ownership is diagnosed. Return only",
281
- "the decision keys you want to",
282
- "change; this starter echoes the current decision unchanged (a safe no-op) so",
283
- "installing the package does not alter gate behavior. The `preflight`",
284
- "capability in `manifest.json` grants the registration.",
285
- ],
286
- services: [
287
- "",
288
- "## Service Override",
289
- "`index.ts` overrides the built-in `output_format` service through",
290
- "`api.registerService`. The service renders a command's structured result;",
291
- "returning the payload unchanged passes through to pm's default formatting.",
292
- "This starter scopes itself to THIS package's own command and passes every",
293
- "other command through, so it never disrupts unrelated output. The `services`",
294
- "capability in `manifest.json` grants the registration.",
295
- ],
296
- };
297
- // README activation explainer for command-bearing starters (commands/hooks/
298
- // search/importers): they declare `activation.commands` so pm loads them lazily.
299
- const LAZY_ACTIVATION_README_SECTION = {
300
- package: [
301
- "",
302
- "## Lazy Activation",
303
- "`manifest.json` declares `activation.commands`: the exact command paths this",
304
- "package's `activate` registers. pm imports and activates the package lazily —",
305
- "only when an invoked command path matches one of these entries — so unrelated",
306
- "commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in",
307
- "sync with the registrations in `index.ts`: add an entry when you register a new",
308
- "command, importer, or exporter, and remove one you drop. An omitted or stale",
309
- "entry means the matching command will not dispatch from the CLI. Globally-scoped",
310
- "surfaces (hooks, parser/preflight/renderer overrides, and search providers for",
311
- "built-in search commands) still activate regardless of this list.",
312
- ],
313
- extension: [
314
- "",
315
- "## Lazy Activation",
316
- "`manifest.json` declares `activation.commands`: the exact command paths this",
317
- "extension's `activate` registers. pm imports and activates the extension lazily —",
318
- "only when an invoked command path matches one of these entries — so unrelated",
319
- "commands never pay to load it. Keep this list in sync with the registrations in",
320
- "`index.ts`: an omitted or stale entry means the matching command will not dispatch",
321
- "from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,",
322
- "and search providers for built-in search commands) still activate regardless.",
323
- ],
324
- };
325
- // README activation explainer for the `schema` starter: it contributes a GLOBAL
326
- // custom item type/field, so it intentionally omits `activation.commands` and
327
- // relies on pm's conservative activation tier (see buildScaffoldActivationCommands).
328
- const SCHEMA_ACTIVATION_README_SECTION = {
329
- package: [
330
- "",
331
- "## Activation",
332
- "This package contributes a GLOBAL custom item type and field, so `manifest.json`",
333
- "intentionally declares no `activation.commands`. pm activates the package",
334
- "conservatively — for every command — so the custom type is present wherever it is",
335
- "used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.",
336
- "Declaring narrow `activation.commands` here would gate activation to only those",
337
- "commands and silently leave the custom type unregistered for `pm create`. If you",
338
- "drop the schema registrations and keep only command/hook/search/importer surfaces,",
339
- "add `activation.commands` back so pm can load the package lazily.",
340
- ],
341
- extension: [
342
- "",
343
- "## Activation",
344
- "This extension contributes a GLOBAL custom item type and field, so `manifest.json`",
345
- "intentionally declares no `activation.commands`. pm activates the extension",
346
- "conservatively — for every command — so the custom type is present wherever it is",
347
- "used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.",
348
- "Declaring narrow `activation.commands` here would gate activation to only those",
349
- "commands and silently leave the custom type unregistered for `pm create`.",
350
- ],
351
- };
352
- // README activation explainer for the `profile` starter: the contributed profile
353
- // is resolved by the built-in `pm profile list/show/apply` commands (which the
354
- // package does not own), so it intentionally omits `activation.commands` and relies
355
- // on pm's conservative activation tier (granted by the `schema` capability).
356
- const PROFILE_ACTIVATION_README_SECTION = {
357
- package: [
358
- "",
359
- "## Activation",
360
- "This package contributes a project profile resolved by the built-in",
361
- "`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`",
362
- "commands — commands the package does not own — so `manifest.json` intentionally",
363
- "declares no `activation.commands`. pm activates the package conservatively (for",
364
- "every command, granted by the `schema` capability) so the profile is present",
365
- "whenever `pm profile` runs. Declaring narrow `activation.commands` here would",
366
- "gate activation to only the listed commands and silently leave the profile",
367
- "unregistered for `pm profile`.",
368
- ],
369
- extension: [
370
- "",
371
- "## Activation",
372
- "This extension contributes a project profile resolved by the built-in",
373
- "`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`",
374
- "commands, so `manifest.json` intentionally declares no `activation.commands`. pm",
375
- "activates the extension conservatively (for every command, granted by the",
376
- "`schema` capability) so the profile is present whenever `pm profile` runs.",
377
- "Declaring narrow `activation.commands` here would silently leave the profile",
378
- "unregistered for `pm profile`.",
379
- ],
380
- };
381
- /**
382
- * Build the README "Included Files" bullet describing `manifest.json` for the
383
- * chosen capability and vocabulary. The `schema` and `profile` starters omit
384
- * `activation.commands` (see {@link buildScaffoldActivationCommands}), so their
385
- * bullet explains the global-contribution tradeoff instead of referencing a field
386
- * they deliberately lack.
387
- */
388
- function buildScaffoldManifestBullet(capability, vocabulary) {
389
- if (capability === "schema") {
390
- return `- \`manifest.json\`: ${vocabulary} metadata and capabilities (no \`activation.commands\` — the custom item type activates for every command).`;
391
- }
392
- if (capability === "profile") {
393
- return `- \`manifest.json\`: ${vocabulary} metadata and capabilities (no \`activation.commands\` — the contributed profile resolves through \`pm profile\` for every command).`;
394
- }
395
- return `- \`manifest.json\`: ${vocabulary} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${vocabulary}).`;
396
- }
397
- /** Select the README activation section for the chosen capability and vocabulary: the `schema` and `profile` starters explain conservative activation (they omit `activation.commands`); every other capability documents lazy activation. */
398
- function buildScaffoldActivationReadmeSection(capability, vocabulary) {
399
- if (capability === "schema") {
400
- return SCHEMA_ACTIVATION_README_SECTION[vocabulary];
401
- }
402
- if (capability === "profile") {
403
- return PROFILE_ACTIVATION_README_SECTION[vocabulary];
404
- }
405
- return LAZY_ACTIVATION_README_SECTION[vocabulary];
406
- }
407
- /** Builds the starter command path from the normalized package/extension name. Names that start with a built-in pm command or executable alias are prefixed with `starter` so the generated command dispatches to the package instead of being consumed by core command parsing. */
408
- export function buildScaffoldCommandName(extensionName) {
409
- const commandWords = extensionName
410
- .replace(/-/g, " ")
411
- .trim()
412
- .split(/\s+/)
413
- .filter((word) => word.length > 0);
414
- if (commandWords.length === 0) {
415
- return "starter ping";
416
- }
417
- const firstWordLower = commandWords[0].toLowerCase();
418
- let leadingStarterWords = 0;
419
- while (commandWords[leadingStarterWords]?.toLowerCase() === "starter") {
420
- leadingStarterWords += 1;
421
- }
422
- const nextStarterWord = commandWords[leadingStarterWords]?.toLowerCase();
423
- const starterRootCollision = leadingStarterWords > 0 &&
424
- (leadingStarterWords === commandWords.length ||
425
- (nextStarterWord !== undefined &&
426
- RESERVED_SCAFFOLD_COMMAND_ROOTS.has(nextStarterWord)));
427
- const reservedRoot = RESERVED_SCAFFOLD_COMMAND_ROOTS.has(firstWordLower) || starterRootCollision;
428
- const resolvedWords = reservedRoot
429
- ? ["starter", ...commandWords]
430
- : commandWords;
431
- return `${resolvedWords.join(" ")} ping`;
432
- }
433
- /**
434
- * Build the project-profile archetype object literal the `profile` starter
435
- * registers — a complete {@link ProjectProfileDefinition} derived from the package
436
- * name: one custom item type, a custom status, a custom field, a per-type workflow,
437
- * offline search config, a create template, and an advisory package recommendation.
438
- *
439
- * Returned as the lines BETWEEN the object braces at a two-space base indent. Both
440
- * authoring styles read from this single source so they never drift: the imperative
441
- * {@link buildActivateBodyLines} wraps them in `api.registerProfile({ ... })`
442
- * (re-indenting by the `activate` body offset) and the declarative
443
- * {@link buildDeclarativeBlueprintSurface} wraps them in
444
- * `defineProjectProfile({ ... })`.
445
- */
446
- function buildProfileArchetypeFieldLines(extensionName) {
447
- const typeName = extensionName;
448
- const typeFolder = `${extensionName}s`;
449
- // De-hyphenate for a short alias; omit a redundant self-alias for single-word names.
450
- const typeAlias = extensionName.replace(/-/g, "");
451
- const typeAliases = typeAlias === typeName ? [] : [typeAlias];
452
- const fieldKey = `${extensionName.replace(/-/g, "_")}_owner`;
453
- const statusId = "reviewing";
454
- return [
455
- ` name: ${JSON.stringify(extensionName)},`,
456
- ` title: ${JSON.stringify(`${extensionName} archetype`)},`,
457
- ' summary: "Starter project profile. Replace these dimensions with your own archetype.",',
458
- " // Item types the profile upserts into the project schema when applied.",
459
- " types: [",
460
- " {",
461
- ` name: ${JSON.stringify(typeName)},`,
462
- ` folder: ${JSON.stringify(typeFolder)},`,
463
- ` aliases: ${JSON.stringify(typeAliases)},`,
464
- ` description: ${JSON.stringify(`A ${extensionName} work item that flows to done.`)},`,
465
- " },",
466
- " ],",
467
- " // Custom statuses upserted into the project status set.",
468
- " statuses: [",
469
- " {",
470
- ` id: ${JSON.stringify(statusId)},`,
471
- ' roles: ["active"],',
472
- ' aliases: ["in-review"],',
473
- ' description: "Work is implementation-complete and awaiting review.",',
474
- " },",
475
- " ],",
476
- " // Custom item-metadata fields the archetype tracks.",
477
- " fields: [",
478
- " {",
479
- ` key: ${JSON.stringify(fieldKey)},`,
480
- ' type: "string",',
481
- ' commands: ["create", "update", "list"],',
482
- ' description: "Stakeholder accountable for the item.",',
483
- " },",
484
- " ],",
485
- " // Per-type workflow transition allow-list staged into settings.",
486
- " workflows: [",
487
- " {",
488
- ` type: ${JSON.stringify(typeName)},`,
489
- " allowed_transitions: [",
490
- ' ["open", "in_progress"],',
491
- ` ["in_progress", ${JSON.stringify(statusId)}],`,
492
- ` [${JSON.stringify(statusId)}, "in_progress"],`,
493
- ` [${JSON.stringify(statusId)}, "closed"],`,
494
- ' ["in_progress", "blocked"],',
495
- ' ["blocked", "in_progress"],',
496
- " ],",
497
- " },",
498
- " ],",
499
- " // Nested-settings knobs staged when the profile is applied.",
500
- " config: [",
501
- ' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',
502
- ' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },',
503
- " ],",
504
- " // Create templates staged into <pmRoot>/templates.",
505
- " templates: [",
506
- " {",
507
- ` name: ${JSON.stringify(extensionName)},`,
508
- " options: {",
509
- ` type: ${JSON.stringify(typeName)},`,
510
- ' priority: "2",',
511
- ` tags: ${JSON.stringify(extensionName)},`,
512
- ' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',
513
- ' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",',
514
- " },",
515
- " },",
516
- " ],",
517
- " // Advisory package recommendations (never auto-installed).",
518
- " packages: [",
519
- ' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },',
520
- " ],",
521
- ];
522
- }
523
- /** Build the `activate` body lines for the starter entrypoint. The base body always registers the starter command; capability-specific variants append the matching SDK surface so generated packages demonstrate one runnable customization primitive end to end. */
524
- function buildActivateBodyLines(extensionName, commandName, capability) {
525
- const searchProviderName = `${extensionName}-search`;
526
- const vectorAdapterName = `${extensionName}-vector`;
527
- const adapterName = `${extensionName.replace(/-/g, " ")} items`;
528
- const commandLines = [
529
- " api.registerCommand({",
530
- ` name: ${JSON.stringify(commandName)},`,
531
- ' description: "Starter scaffold command. Replace with your own behavior.",',
532
- " run: async (context) => ({",
533
- " ok: true,",
534
- ` source: ${JSON.stringify(extensionName)},`,
535
- " command: context.command,",
536
- ' message: "Starter extension scaffold is active.",',
537
- " }),",
538
- " });",
539
- ];
540
- if (capability === "commands") {
541
- return commandLines;
542
- }
543
- if (capability === "search") {
544
- return [
545
- ...commandLines,
546
- "",
547
- " // Search providers let packages customize how pm ranks and retrieves",
548
- " // project context. This starter is deterministic and dependency-free:",
549
- " // replace the scoring with your domain retrieval, embedding, or rerank",
550
- " // logic as the package grows.",
551
- " api.registerSearchProvider({",
552
- ` name: ${JSON.stringify(searchProviderName)},`,
553
- " query: async (context) => {",
554
- " const needle = context.query.toLowerCase();",
555
- " const hits = context.documents",
556
- " .filter((document) => {",
557
- ' const title = String(document.metadata.title ?? "").toLowerCase();',
558
- " return title.includes(needle);",
559
- " })",
560
- " .map((document) => ({",
561
- " id: document.metadata.id,",
562
- " score: 1,",
563
- ' matched_fields: ["title"],',
564
- " }));",
565
- " return { hits };",
566
- " },",
567
- " embed: async (context) => [context.input.length],",
568
- " });",
569
- "",
570
- " // Vector-store adapters let packages own semantic index storage. This",
571
- " // starter returns a stable in-memory hit so generated tests can exercise",
572
- " // the adapter without external services.",
573
- " api.registerVectorStoreAdapter({",
574
- ` name: ${JSON.stringify(vectorAdapterName)},`,
575
- ' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],',
576
- " upsert: async (context) => ({ upserted: context.points.length }),",
577
- " delete: async (context) => ({ deleted: context.ids.length }),",
578
- " });",
579
- ];
580
- }
581
- if (capability === "schema") {
582
- const itemTypeName = extensionName;
583
- const itemTypeFolder = `${extensionName}s`;
584
- // De-hyphenate for a short alias (e.g. "my-tracker" -> "mytracker"). For a
585
- // single-word name the de-hyphenated form equals the type name, so omit the
586
- // alias rather than register a redundant self-alias in the starter.
587
- const itemTypeAlias = extensionName.replace(/-/g, "");
588
- const itemTypeAliases = itemTypeAlias === itemTypeName ? [] : [itemTypeAlias];
589
- const fieldName = `${extensionName.replace(/-/g, "_")}_note`;
590
- const migrationId = `${extensionName}-0001-init`;
591
- return [
592
- ...commandLines,
593
- "",
594
- " // Schema registrations let a package model its own project domain — the",
595
- ' // heart of "project management = context management". Item types and fields',
596
- " // are GLOBAL contributions: built-in commands like `pm create <type>` and",
597
- " // `pm list --type <type>` must see them, so this package declares no",
598
- " // `activation.commands` and pm activates it conservatively for every command.",
599
- " // The `schema` capability in manifest.json grants all three registrations.",
600
- " api.registerItemFields([",
601
- " {",
602
- ` name: ${JSON.stringify(fieldName)},`,
603
- ' type: "string",',
604
- " optional: true,",
605
- " },",
606
- " ]);",
607
- "",
608
- " api.registerItemTypes([",
609
- " {",
610
- ` name: ${JSON.stringify(itemTypeName)},`,
611
- " // Replace with your domain's canonical plural folder name.",
612
- ` folder: ${JSON.stringify(itemTypeFolder)},`,
613
- ` aliases: ${JSON.stringify(itemTypeAliases)},`,
614
- " // Add field names here to force them at `pm create` time.",
615
- " required_create_fields: [],",
616
- " },",
617
- " ]);",
618
- "",
619
- " // Migrations let a package evolve stored items as its schema changes. pm",
620
- " // runs each migration ONCE through the preflight gate (not once per item),",
621
- " // passing a context that identifies the migration itself: `context.id` is",
622
- " // the migration id (not an item id), alongside `context.pm_root` — iterate",
623
- " // the corpus yourself from there. This starter is a deterministic no-op so",
624
- " // package tests can invoke it without touching the corpus; replace the body",
625
- " // with your real rewrite.",
626
- " api.registerMigration({",
627
- ` id: ${JSON.stringify(migrationId)},`,
628
- ` description: ${JSON.stringify(`Initialize ${extensionName} schema state.`)},`,
629
- " mandatory: false,",
630
- " run: async (context) => ({ migrated: true, id: context.id }),",
631
- " });",
632
- ];
633
- }
634
- if (capability === "profile") {
635
- return [
636
- ...commandLines,
637
- "",
638
- " // A project profile is the broadest customization primitive pm has: one",
639
- " // declarative bundle of item types, custom statuses, fields, a per-type",
640
- " // workflow, config knobs, create templates, and package recommendations. Once",
641
- " // this package is installed the profile resolves by name through `pm profile",
642
- " // list`, `pm profile show`, and `pm profile apply`, which stages every dimension",
643
- " // idempotently like a core archetype. A profile registration is a schema+config",
644
- " // bundle, so the `schema` capability in manifest.json grants it.",
645
- " api.registerProfile({",
646
- // The archetype field lines are all non-empty, so re-indent each by the
647
- // `activate` body offset (object braces sit at two spaces, fields at four).
648
- ...buildProfileArchetypeFieldLines(extensionName).map((line) => ` ${line}`),
649
- " });",
650
- ];
651
- }
652
- if (capability === "importers") {
653
- return [
654
- ...commandLines,
655
- "",
656
- " // Importers/exporters are the bridge between pm's context graph and",
657
- " // another project-management system. Keep the starter deterministic so",
658
- " // package tests can run without touching the network or filesystem; replace",
659
- " // these payloads with your adapter's real mapping as the package grows.",
660
- " api.registerImporter(",
661
- ` ${JSON.stringify(adapterName)},`,
662
- " async (context) => ({",
663
- " imported: 1,",
664
- ' source: context.options.source ?? "starter",',
665
- " args: context.args,",
666
- " }),",
667
- " {",
668
- ` action: ${JSON.stringify(`${adapterName} import`)},`,
669
- ' description: "Import starter records into pm context.",',
670
- " flags: [",
671
- " {",
672
- ' long: "--source",',
673
- ' value_name: "name",',
674
- ' value_type: "string",',
675
- ' description: "Source name or path to import from.",',
676
- " },",
677
- " ],",
678
- " },",
679
- " );",
680
- "",
681
- " api.registerExporter(",
682
- ` ${JSON.stringify(adapterName)},`,
683
- " async (context) => ({",
684
- " exported: true,",
685
- ' destination: context.options.destination ?? "stdout",',
686
- " args: context.args,",
687
- " }),",
688
- " {",
689
- ` action: ${JSON.stringify(`${adapterName} export`)},`,
690
- ' description: "Export pm context into starter records.",',
691
- " flags: [",
692
- " {",
693
- ' long: "--destination",',
694
- ' value_name: "name",',
695
- ' value_type: "string",',
696
- ' description: "Destination name or path to export to.",',
697
- " },",
698
- " ],",
699
- " },",
700
- " );",
701
- ];
702
- }
703
- if (capability === "renderers") {
704
- return [
705
- ...commandLines,
706
- "",
707
- " // Renderer overrides customize how pm serializes a command's structured",
708
- ' // result for an output format ("toon" or "json"). Host-enforced ownership',
709
- " // prevents unrelated commands from reaching this callback.",
710
- " // The `renderers` capability in manifest.json grants the registration.",
711
- ' api.registerRenderer("toon", (context) => {',
712
- ` return ${JSON.stringify(`${extensionName}: `)} + JSON.stringify(context.result);`,
713
- ` }, { commands: [${JSON.stringify(commandName)}] });`,
714
- ];
715
- }
716
- if (capability === "parser") {
717
- return [
718
- // The parser starter declares its own flags so the override is runnable end
719
- // to end through `pm <command> --shout`: the command defines the deprecated
720
- // `--shout` alias and canonical `--upper` flag, the parser rewrites one to
721
- // the other, and the handler surfaces the normalized value. Flag metadata
722
- // needs the `schema` capability (declared in manifest.json).
723
- " api.registerCommand({",
724
- ` name: ${JSON.stringify(commandName)},`,
725
- ' description: "Starter scaffold command. Replace with your own behavior.",',
726
- " flags: [",
727
- " {",
728
- ' long: "--shout",',
729
- ' value_type: "boolean",',
730
- ' description: "Deprecated alias for --upper; the parser override rewrites it.",',
731
- " },",
732
- " {",
733
- ' long: "--upper",',
734
- ' value_type: "boolean",',
735
- ' description: "Echo the canonical flag the parser override produces.",',
736
- " },",
737
- " ],",
738
- " run: async (context) => ({",
739
- " ok: true,",
740
- ` source: ${JSON.stringify(extensionName)},`,
741
- " command: context.command,",
742
- " // Surfaces the normalized option so `--shout`/`--upper` is observable.",
743
- " upper: context.options.upper === true,",
744
- ' message: "Starter extension scaffold is active.",',
745
- " }),",
746
- " });",
747
- "",
748
- " // Parser overrides preprocess a command's parsed options BEFORE its handler",
749
- " // runs, returning a delta — only the keys you set are merged over the parsed",
750
- " // input. This override is scoped to THIS package's own command. Here it",
751
- " // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`",
752
- " // flag; replace it with your command's real normalization. The `parser`",
753
- " // capability in manifest.json grants the registration.",
754
- ` api.registerParser(${JSON.stringify(commandName)}, (context) => {`,
755
- " const options = { ...context.options };",
756
- " if (options.shout === true) {",
757
- " options.upper = true;",
758
- " }",
759
- " delete options.shout;",
760
- " return { options };",
761
- " });",
762
- ];
763
- }
764
- if (capability === "preflight") {
765
- return [
766
- ...commandLines,
767
- "",
768
- " // Preflight overrides adjust pm's pre-run gate decision (extension",
769
- " // migrations + item-format checks) for the commands it owns. Disjoint",
770
- " // packages compose; overlapping or legacy global ownership is diagnosed.",
771
- " // Return a delta of the keys you want to change",
772
- " // (enforce_item_format_gate, run_preflight_item_format_sync,",
773
- " // run_extension_migrations, enforce_mandatory_migration_gate); returning",
774
- " // context.decision unchanged is a safe no-op so installing the package does",
775
- " // not alter gate behavior — replace it with your policy, e.g.",
776
- " // `{ run_extension_migrations: false }`. The `preflight` capability in",
777
- " // manifest.json grants the registration.",
778
- " api.registerPreflight({",
779
- ` commands: [${JSON.stringify(commandName)}],`,
780
- " run: (context) => context.decision,",
781
- " });",
782
- ];
783
- }
784
- if (capability === "services") {
785
- return [
786
- ...commandLines,
787
- "",
788
- " // Service overrides replace a built-in pm service. The `output_format`",
789
- " // service renders a command's structured result; returning the payload",
790
- " // unchanged passes through to pm's default formatting. This override scopes",
791
- " // itself to THIS package's own command and passes every other command",
792
- " // through, so it never disrupts unrelated output. The `services` capability",
793
- " // in manifest.json grants the registration.",
794
- ' api.registerService("output_format", (context) => {',
795
- ` if (context.command !== ${JSON.stringify(commandName)}) {`,
796
- " return { handled: false };",
797
- " }",
798
- ` return { rendered_by: ${JSON.stringify(extensionName)}, payload: context.payload };`,
799
- " });",
800
- ];
801
- }
802
- return [
803
- ...commandLines,
804
- "",
805
- " // after_command hooks fire once pm finishes a command, receiving the items",
806
- " // it mutated. This is the natural place to react to every change - sync to",
807
- " // an external system, emit telemetry, or refresh derived context",
808
- ' // ("project management = context management"). This starter is a documented',
809
- " // no-op on the success path; replace the body with your own reaction.",
810
- " api.hooks.afterCommand((context) => {",
811
- " if (!context.ok) {",
812
- " return;",
813
- " }",
814
- " // `context.affected` lists the items pm mutated (id, status,",
815
- " // changed_fields). React here, e.g.:",
816
- " // for (const item of context.affected ?? []) { /* ...item.id... */ }",
817
- " });",
818
- ];
819
- }
820
- /** Build the colocated `node:test` sample suite (`index.test.ts`) for the chosen capability. Authored in TypeScript and run through the generated package's `npm test` script (typecheck first, then `node --test`, which strips types on Node >=22.18), it imports the `./index.ts` manifest entry directly under NodeNext resolution. Every variant covers activation, command invocation, and teardown via `createExtensionTestHarness`; capability variants add tests that use the harness-bound `assert*`/`run*` helpers and deactivate in `finally`. */
821
- function buildSampleTestSource(extensionName, commandName, capability) {
822
- const hooksEnabled = capability === "hooks";
823
- const searchEnabled = capability === "search";
824
- const importersEnabled = capability === "importers";
825
- const schemaEnabled = capability === "schema";
826
- const profileEnabled = capability === "profile";
827
- const renderersEnabled = capability === "renderers";
828
- const parserEnabled = capability === "parser";
829
- const preflightEnabled = capability === "preflight";
830
- const servicesEnabled = capability === "services";
831
- const capabilitiesLiteral = SAMPLE_TEST_CAPABILITIES_LITERAL[capability];
832
- const itemTypeName = extensionName;
833
- const itemTypeFolder = `${extensionName}s`;
834
- const fieldName = `${extensionName.replace(/-/g, "_")}_note`;
835
- const migrationId = `${extensionName}-0001-init`;
836
- const importNames = [
837
- " assertExtensionDeactivated,",
838
- " createExtensionTestHarness,",
839
- ];
840
- const hookTestLines = hooksEnabled
841
- ? [
842
- `test(${JSON.stringify(`${extensionName} reacts to commands via its after_command hook`)}, async () => {`,
843
- " const ext = await createExtensionTestHarness(extension, {",
844
- ` name: ${JSON.stringify(extensionName)},`,
845
- ` capabilities: ${capabilitiesLiteral},`,
846
- " });",
847
- " let deactivated = false;",
848
- " try {",
849
- " // assertHook throws unless an after_command hook is registered, so",
850
- " // reaching the next line already proves the hook is wired.",
851
- " ext.assertHook({",
852
- ' kind: "after_command",',
853
- ` extensionName: ${JSON.stringify(extensionName)},`,
854
- " });",
855
- " // runHook fires the hook through pm's real runner with a synthetic",
856
- " // context and returns the warnings it produced; a clean hook returns none.",
857
- " // Replace the context/assertions as your hook grows.",
858
- " const warnings = await ext.runHook({",
859
- ' kind: "after_command",',
860
- " context: {",
861
- ` command: ${JSON.stringify(commandName)},`,
862
- " args: [],",
863
- ' pm_root: "",',
864
- " ok: true,",
865
- " affected: [],",
866
- " },",
867
- " });",
868
- " assert.deepEqual(warnings, []);",
869
- " const teardown = await ext.deactivate();",
870
- " assertExtensionDeactivated(teardown);",
871
- " deactivated = true;",
872
- ...SAMPLE_HARNESS_FINALLY_LINES,
873
- "});",
874
- "",
875
- ]
876
- : [];
877
- const searchTestLines = searchEnabled
878
- ? buildDeclarativeCapabilityTestBlock(extensionName, commandName, "search", capabilitiesLiteral)
879
- : [];
880
- const importerTestLines = importersEnabled
881
- ? buildDeclarativeCapabilityTestBlock(extensionName, commandName, "importers", capabilitiesLiteral)
882
- : [];
883
- const schemaTestLines = schemaEnabled
884
- ? [
885
- `test(${JSON.stringify(`${extensionName} registers and runs its custom schema`)}, async () => {`,
886
- " const ext = await createExtensionTestHarness(extension, {",
887
- ` name: ${JSON.stringify(extensionName)},`,
888
- ` capabilities: ${capabilitiesLiteral},`,
889
- " });",
890
- " let deactivated = false;",
891
- " try {",
892
- ...indentGeneratedLines(buildSchemaCapabilityAssertionLines({
893
- extensionName,
894
- itemTypeName,
895
- itemTypeFolder,
896
- fieldName,
897
- migrationId,
898
- includeMigrationReplacementHint: true,
899
- }), " "),
900
- " const teardown = await ext.deactivate();",
901
- " assertExtensionDeactivated(teardown);",
902
- " deactivated = true;",
903
- ...SAMPLE_HARNESS_FINALLY_LINES,
904
- "});",
905
- "",
906
- ]
907
- : [];
908
- const profileTestLines = profileEnabled
909
- ? [
910
- `test(${JSON.stringify(`${extensionName} registers its project profile`)}, async () => {`,
911
- " const ext = await createExtensionTestHarness(extension, {",
912
- ` name: ${JSON.stringify(extensionName)},`,
913
- ` capabilities: ${capabilitiesLiteral},`,
914
- " });",
915
- " let deactivated = false;",
916
- " try {",
917
- ...indentGeneratedLines(buildProfileCapabilityAssertionLines(extensionName), " "),
918
- " const teardown = await ext.deactivate();",
919
- " assertExtensionDeactivated(teardown);",
920
- " deactivated = true;",
921
- ...SAMPLE_HARNESS_FINALLY_LINES,
922
- "});",
923
- "",
924
- ]
925
- : [];
926
- const rendererTestLines = renderersEnabled
927
- ? [
928
- `test(${JSON.stringify(`${extensionName} registers and invokes its renderer override`)}, async () => {`,
929
- " const ext = await createExtensionTestHarness(extension, {",
930
- ` name: ${JSON.stringify(extensionName)},`,
931
- ` capabilities: ${capabilitiesLiteral},`,
932
- " });",
933
- " let deactivated = false;",
934
- " try {",
935
- " // assertRendererOverride throws unless a renderer is registered for the",
936
- " // format, so reaching the next line already proves the wiring.",
937
- ` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(extensionName)} });`,
938
- ' assert.equal(override.format, "toon");',
939
- "",
940
- " // runRendererOverride renders through pm's real runner. The override",
941
- " // customizes only THIS package's command output and returns a string the",
942
- " // host uses verbatim. Replace the assertions as it grows.",
943
- " const rendered = await ext.runRendererOverride({",
944
- ' format: "toon",',
945
- ` command: ${JSON.stringify(commandName)},`,
946
- " result: { ok: true },",
947
- " });",
948
- " assert.equal(rendered.overridden, true);",
949
- ` assert.equal(rendered.rendered, ${JSON.stringify(`${extensionName}: `)} + JSON.stringify({ ok: true }));`,
950
- "",
951
- " // Output for any other command passes through to pm's default renderer.",
952
- " const passthrough = await ext.runRendererOverride({",
953
- ' format: "toon",',
954
- ' command: "list",',
955
- " result: { ok: true },",
956
- " });",
957
- " assert.equal(passthrough.overridden, false);",
958
- " const teardown = await ext.deactivate();",
959
- " assertExtensionDeactivated(teardown);",
960
- " deactivated = true;",
961
- ...SAMPLE_HARNESS_FINALLY_LINES,
962
- "});",
963
- "",
964
- ]
965
- : [];
966
- const parserTestLines = parserEnabled
967
- ? [
968
- `test(${JSON.stringify(`${extensionName} rewrites command options via its parser override`)}, async () => {`,
969
- " const ext = await createExtensionTestHarness(extension, {",
970
- ` name: ${JSON.stringify(extensionName)},`,
971
- ` capabilities: ${capabilitiesLiteral},`,
972
- " });",
973
- " let deactivated = false;",
974
- " try {",
975
- " // assertParserOverride throws unless a parser is registered for the",
976
- " // command, so reaching the next line already proves the wiring.",
977
- ` ext.assertParserOverride({ name: ${JSON.stringify(commandName)}, extensionName: ${JSON.stringify(extensionName)} });`,
978
- "",
979
- " // runParserOverride runs the override through pm's real parser runner and",
980
- " // returns the rewritten context. The starter rewrites the deprecated",
981
- " // `shout` alias to the canonical `upper` flag.",
982
- " const result = await ext.runParserOverride({",
983
- ` command: ${JSON.stringify(commandName)},`,
984
- " args: [],",
985
- " options: { shout: true },",
986
- " global: {},",
987
- ' pm_root: "",',
988
- " });",
989
- " assert.equal(result.overridden, true);",
990
- " assert.deepEqual(result.context.options, { upper: true });",
991
- "",
992
- " // End to end: feed the rewritten options into the command handler to",
993
- " // prove `pm <command> --shout` surfaces the normalized `upper` flag in",
994
- " // the result.",
995
- ` const invocation = await ext.runCommand({ command: ${JSON.stringify(commandName)}, options: result.context.options });`,
996
- " assert.equal(invocation.handled, true);",
997
- " assert.deepEqual(invocation.result, {",
998
- " ok: true,",
999
- ` source: ${JSON.stringify(extensionName)},`,
1000
- ` command: ${JSON.stringify(commandName)},`,
1001
- " upper: true,",
1002
- ' message: "Starter extension scaffold is active.",',
1003
- " });",
1004
- " const teardown = await ext.deactivate();",
1005
- " assertExtensionDeactivated(teardown);",
1006
- " deactivated = true;",
1007
- ...SAMPLE_HARNESS_FINALLY_LINES,
1008
- "});",
1009
- "",
1010
- ]
1011
- : [];
1012
- const preflightTestLines = preflightEnabled
1013
- ? [
1014
- `test(${JSON.stringify(`${extensionName} returns a preflight gate decision via its override`)}, async () => {`,
1015
- " const ext = await createExtensionTestHarness(extension, {",
1016
- ` name: ${JSON.stringify(extensionName)},`,
1017
- ` capabilities: ${capabilitiesLiteral},`,
1018
- " });",
1019
- " let deactivated = false;",
1020
- " try {",
1021
- " // assertPreflightOverride throws unless a preflight override is",
1022
- " // registered, so reaching the next line already proves the wiring.",
1023
- ` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(extensionName)} });`,
1024
- "",
1025
- " // runPreflightOverride runs the override through pm's real runner with a",
1026
- " // synthetic gate decision. The starter echoes the decision unchanged;",
1027
- " // replace the values/assertions with your real policy.",
1028
- " const decision = {",
1029
- " enforce_item_format_gate: true,",
1030
- " run_preflight_item_format_sync: false,",
1031
- " run_extension_migrations: true,",
1032
- " enforce_mandatory_migration_gate: false,",
1033
- " };",
1034
- " const result = await ext.runPreflightOverride({",
1035
- ` command: ${JSON.stringify(commandName)},`,
1036
- " args: [],",
1037
- " options: {},",
1038
- " global: {},",
1039
- ' pm_root: "",',
1040
- " decision,",
1041
- " });",
1042
- " assert.equal(result.overridden, true);",
1043
- " assert.deepEqual(result.decision, decision);",
1044
- " const teardown = await ext.deactivate();",
1045
- " assertExtensionDeactivated(teardown);",
1046
- " deactivated = true;",
1047
- ...SAMPLE_HARNESS_FINALLY_LINES,
1048
- "});",
1049
- "",
1050
- ]
1051
- : [];
1052
- const serviceTestLines = servicesEnabled
1053
- ? [
1054
- `test(${JSON.stringify(`${extensionName} customizes command output via its service override`)}, async () => {`,
1055
- " const ext = await createExtensionTestHarness(extension, {",
1056
- ` name: ${JSON.stringify(extensionName)},`,
1057
- ` capabilities: ${capabilitiesLiteral},`,
1058
- " });",
1059
- " let deactivated = false;",
1060
- " try {",
1061
- " // assertServiceOverride throws unless a service override is registered",
1062
- " // for the service, so reaching the next line proves the wiring.",
1063
- ` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(extensionName)} });`,
1064
- "",
1065
- " // runServiceOverride runs the override through pm's real service runner.",
1066
- " // The override customizes only THIS package's command output (handled),",
1067
- " // passing every other command through (not handled).",
1068
- " const handled = await ext.runServiceOverride({",
1069
- ' service: "output_format",',
1070
- ` command: ${JSON.stringify(commandName)},`,
1071
- " payload: { ok: true },",
1072
- " });",
1073
- " assert.equal(handled.handled, true);",
1074
- ` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(extensionName)}, payload: { ok: true } });`,
1075
- "",
1076
- " // Output for any other command passes through to pm's default formatter.",
1077
- " const passthrough = await ext.runServiceOverride({",
1078
- ' service: "output_format",',
1079
- ' command: "list",',
1080
- " payload: { ok: true },",
1081
- " });",
1082
- " assert.equal(passthrough.handled, false);",
1083
- " const teardown = await ext.deactivate();",
1084
- " assertExtensionDeactivated(teardown);",
1085
- " deactivated = true;",
1086
- ...SAMPLE_HARNESS_FINALLY_LINES,
1087
- "});",
1088
- "",
1089
- ]
1090
- : [];
1091
- return [
1092
- 'import assert from "node:assert/strict";',
1093
- 'import { test } from "node:test";',
1094
- "import {",
1095
- ...importNames,
1096
- '} from "@unbrained/pm-cli/sdk/testing";',
1097
- // The search sample's synthetic query/vector contexts reference these SDK types
1098
- // for their typed-stub fixtures; other capabilities need no extra type imports.
1099
- ...(searchEnabled
1100
- ? [
1101
- 'import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";',
1102
- ]
1103
- : []),
1104
- 'import extension from "./index.ts";',
1105
- "",
1106
- ...SAMPLE_HARNESS_CLEANUP_LINES,
1107
- `test(${JSON.stringify(`${extensionName} registers its starter command`)}, async () => {`,
1108
- " // `capabilities` mirrors manifest.json so the in-memory activation grants",
1109
- " // the capabilities the entrypoint relies on.",
1110
- " const ext = await createExtensionTestHarness(extension, {",
1111
- ` name: ${JSON.stringify(extensionName)},`,
1112
- ` capabilities: ${capabilitiesLiteral},`,
1113
- " });",
1114
- " let deactivated = false;",
1115
- " try {",
1116
- " // assertCommandContract is bound to the right activation registry and throws",
1117
- " // if the command is not registered, so reaching here already proves the",
1118
- " // wiring; assert on the returned definition to inspect metadata.",
1119
- " const registered = ext.assertCommandContract({",
1120
- ` name: ${JSON.stringify(commandName)},`,
1121
- ` extensionName: ${JSON.stringify(extensionName)},`,
1122
- " });",
1123
- ' assert.equal(typeof registered.command.description, "string");',
1124
- "",
1125
- " // runCommand invokes the handler through pm's real dispatch engine, so this",
1126
- " // asserts behavior - not just that the command is wired. Replace these",
1127
- " // assertions as you flesh out your command.",
1128
- " const invocation = await ext.runCommand({",
1129
- ` command: ${JSON.stringify(commandName)},`,
1130
- " });",
1131
- " assert.equal(invocation.handled, true);",
1132
- " // The handler result is typed `unknown`, so deep-equality on the whole",
1133
- " // structured payload keeps the assertion type-safe without a cast.",
1134
- " assert.deepEqual(invocation.result, {",
1135
- " ok: true,",
1136
- ` source: ${JSON.stringify(extensionName)},`,
1137
- ` command: ${JSON.stringify(commandName)},`,
1138
- // The parser starter's command surfaces the normalized `upper` flag, which
1139
- // defaults to false when the command is invoked without `--shout`/`--upper`.
1140
- ...(parserEnabled ? [" upper: false,"] : []),
1141
- ' message: "Starter extension scaffold is active.",',
1142
- " });",
1143
- " const teardown = await ext.deactivate();",
1144
- " assertExtensionDeactivated(teardown);",
1145
- " deactivated = true;",
1146
- ...SAMPLE_HARNESS_FINALLY_LINES,
1147
- "});",
1148
- "",
1149
- ...hookTestLines,
1150
- ...searchTestLines,
1151
- ...importerTestLines,
1152
- ...schemaTestLines,
1153
- ...profileTestLines,
1154
- ...rendererTestLines,
1155
- ...parserTestLines,
1156
- ...preflightTestLines,
1157
- ...serviceTestLines,
1158
- `test(${JSON.stringify(`${extensionName} tears down cleanly via deactivate`)}, async () => {`,
1159
- " // createExtensionTestHarness binds teardown to the same name/layer used for",
1160
- " // activation, so this proves your `deactivate` hook runs without throwing.",
1161
- " const ext = await createExtensionTestHarness(extension, {",
1162
- ` name: ${JSON.stringify(extensionName)},`,
1163
- ` capabilities: ${capabilitiesLiteral},`,
1164
- " });",
1165
- " const teardown = await ext.deactivate();",
1166
- " // assertExtensionDeactivated throws unless exactly one extension tore down",
1167
- " // with no failures, so reaching the next line already proves teardown ran.",
1168
- " assertExtensionDeactivated(teardown);",
1169
- " assert.equal(teardown.deactivated, 1);",
1170
- "});",
1171
- "",
1172
- ].join("\n");
1173
- }
1174
- /**
1175
- * Build the manifest `activation.commands` list for the chosen capability: the
1176
- * exact command paths the starter `activate` registers.
1177
- *
1178
- * pm uses this list for lazy activation — it imports and activates the package
1179
- * only when an invoked command path matches one of these entries — so it must
1180
- * stay in sync with the registrations in {@link buildActivateBodyLines}. Every
1181
- * first-party bundled package declares the same field; emitting it keeps
1182
- * generated packages on that convention so they get precise, lazy, correct
1183
- * activation instead of falling back to capability heuristics (which cannot
1184
- * enumerate the contributed commands). The `importers` variant additionally
1185
- * registers paired import/export command handlers under the adapter name.
1186
- *
1187
- * The `schema` and `profile` variants are the deliberate exceptions: each returns
1188
- * an empty list so the manifest omits `activation.commands`. Custom item types and
1189
- * fields are GLOBAL schema contributions that built-in commands (`pm create
1190
- * <type>`, `pm list --type <type>`, `pm validate`) must see, and a contributed
1191
- * project profile is resolved by the built-in `pm profile list/show/apply` commands
1192
- * — commands the package does not own and cannot enumerate. Declaring narrow
1193
- * `activation.commands` there would gate activation to only the listed commands and
1194
- * silently leave the custom type or profile unregistered for those built-ins;
1195
- * omitting it lets pm's conservative activation tier (which covers `schema`) load
1196
- * the package for every command.
1197
- */
1198
- function buildScaffoldActivationCommands(extensionName, commandName, capability) {
1199
- if (capability === "schema" || capability === "profile") {
1200
- return [];
1201
- }
1202
- if (capability === "importers") {
1203
- const adapterName = `${extensionName.replace(/-/g, " ")} items`;
1204
- return [commandName, `${adapterName} import`, `${adapterName} export`];
1205
- }
1206
- return [commandName];
1207
- }
1208
- // One-line surface phrase per capability, listing the registration surfaces the
1209
- // declarative blueprint populates beyond the always-present starter command. Used
1210
- // to keep the generated README's entrypoint bullet accurate per capability.
1211
- const DECLARATIVE_ENTRYPOINT_SURFACE_PHRASE = {
1212
- commands: "starter command",
1213
- hooks: "starter command and after_command hook",
1214
- search: "starter command, search provider, and vector-store adapter",
1215
- importers: "starter command, importer, and exporter",
1216
- schema: "starter command, custom item type, item field, and migration",
1217
- profile: "starter command and project profile",
1218
- renderers: "starter command and toon renderer override",
1219
- parser: "starter command and parser override",
1220
- preflight: "starter command and preflight override",
1221
- services: "starter command and output_format service override",
1222
- };
1223
- // The `ExtensionBlueprint` fields each capability populates, rendered as inline
1224
- // code in the README's Declarative Authoring section so authors can see which
1225
- // blueprint surface maps to the capability they scaffolded.
1226
- const DECLARATIVE_CAPABILITY_BLUEPRINT_FIELDS = {
1227
- commands: "`commands`",
1228
- hooks: "`commands` and `hooks.afterCommand`",
1229
- search: "`commands`, `searchProviders`, and `vectorStoreAdapters`",
1230
- importers: "`commands`, `importers`, and `exporters`",
1231
- schema: "`commands`, `itemTypes`, `itemFields`, and `migrations`",
1232
- profile: "`commands` and `profiles`",
1233
- renderers: "`commands` and `renderers`",
1234
- parser: "`commands` and `parsers`",
1235
- preflight: "`commands` and `preflights`",
1236
- services: "`commands` and `services`",
1237
- };
1238
- /**
1239
- * Build the `defineCommand` starter-command definition for the declarative
1240
- * entrypoint. Mirrors the imperative {@link buildActivateBodyLines} command body
1241
- * (same name/description/run result), and for the `parser` capability declares the
1242
- * `--shout`/`--upper` flags and surfaces the normalized `upper` option so the
1243
- * override is runnable end to end through `pm <command> --shout`.
1244
- */
1245
- function buildDeclarativePingCommandLines(extensionName, commandName, capability) {
1246
- const parserEnabled = capability === "parser";
1247
- return [
1248
- "// The starter command, authored with the `defineCommand` builder so its literal",
1249
- "// name is preserved and the handler `context` is inferred. Exporting it lets you",
1250
- "// unit-test the definition in isolation, apart from the blueprint.",
1251
- "export const pingCommand = defineCommand({",
1252
- ` name: ${JSON.stringify(commandName)},`,
1253
- ' description: "Starter scaffold command. Replace with your own behavior.",',
1254
- ...(parserEnabled
1255
- ? [
1256
- " flags: [",
1257
- " {",
1258
- ' long: "--shout",',
1259
- ' value_type: "boolean",',
1260
- ' description: "Deprecated alias for --upper; the parser override rewrites it.",',
1261
- " },",
1262
- " {",
1263
- ' long: "--upper",',
1264
- ' value_type: "boolean",',
1265
- ' description: "Echo the canonical flag the parser override produces.",',
1266
- " },",
1267
- " ],",
1268
- ]
1269
- : []),
1270
- " run: async (context) => ({",
1271
- " ok: true,",
1272
- ` source: ${JSON.stringify(extensionName)},`,
1273
- " command: context.command,",
1274
- ...(parserEnabled ? [" upper: context.options.upper === true,"] : []),
1275
- ' message: "Starter extension scaffold is active.",',
1276
- " }),",
1277
- "});",
1278
- ];
1279
- }
1280
- /**
1281
- * Build the {@link DeclarativeBlueprintSurface} for a capability: the starter
1282
- * command plus the capability's `define*`-authored registration definitions and
1283
- * the `ExtensionBlueprint` fields that collect them.
1284
- *
1285
- * Blueprint fields are emitted in {@link composeExtension}'s registration order so
1286
- * the generated `activate` wires them deterministically. Each surface mirrors the
1287
- * imperative {@link buildActivateBodyLines} registration (same names, same handler
1288
- * behavior) so a package scaffolded in either style installs and dispatches
1289
- * identically — the manifest, derived capabilities, and registered surfaces match.
1290
- */
1291
- function buildDeclarativeBlueprintSurface(extensionName, commandName, capability) {
1292
- const builderImports = [];
1293
- const definitions = [
1294
- ...buildDeclarativePingCommandLines(extensionName, commandName, capability),
1295
- ];
1296
- const blueprintFields = [" commands: [pingCommand],"];
1297
- const searchProviderName = `${extensionName}-search`;
1298
- const vectorAdapterName = `${extensionName}-vector`;
1299
- const adapterName = `${extensionName.replace(/-/g, " ")} items`;
1300
- const itemTypeName = extensionName;
1301
- const itemTypeFolder = `${extensionName}s`;
1302
- // De-hyphenate for a short alias; omit a redundant self-alias for single-word names.
1303
- const itemTypeAlias = extensionName.replace(/-/g, "");
1304
- const itemTypeAliases = itemTypeAlias === itemTypeName ? [] : [itemTypeAlias];
1305
- const fieldName = `${extensionName.replace(/-/g, "_")}_note`;
1306
- const migrationId = `${extensionName}-0001-init`;
1307
- switch (capability) {
1308
- case "commands":
1309
- break;
1310
- case "hooks":
1311
- builderImports.push("defineAfterCommandHook");
1312
- definitions.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... */ }", "});");
1313
- blueprintFields.push(" hooks: { afterCommand: [afterCommandHook] },");
1314
- break;
1315
- case "search":
1316
- builderImports.push("defineSearchProvider", "defineVectorStoreAdapter");
1317
- definitions.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(searchProviderName)},`, " 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(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 }),", "});");
1318
- blueprintFields.push(" searchProviders: [searchProvider],", " vectorStoreAdapters: [vectorStoreAdapter],");
1319
- break;
1320
- case "importers":
1321
- builderImports.push("defineExporter", "defineImporter");
1322
- definitions.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,", "}));");
1323
- blueprintFields.push(" importers: [", " {", ` name: ${JSON.stringify(adapterName)},`, " importer,", " options: {", ` action: ${JSON.stringify(`${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.",', " },", " ],", " },", " },", " ],", " exporters: [", " {", ` name: ${JSON.stringify(adapterName)},`, " exporter,", " options: {", ` action: ${JSON.stringify(`${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.",', " },", " ],", " },", " },", " ],");
1324
- break;
1325
- case "schema":
1326
- builderImports.push("defineItemField", "defineItemType", "defineMigration");
1327
- definitions.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(fieldName)},`, ' type: "string",', " optional: true,", "});", "", "export const itemType = defineItemType({", ` name: ${JSON.stringify(itemTypeName)},`, " // Replace with your domain's canonical plural folder name.", ` folder: ${JSON.stringify(itemTypeFolder)},`, ` aliases: ${JSON.stringify(itemTypeAliases)},`, " // 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(migrationId)},`, ` description: ${JSON.stringify(`Initialize ${extensionName} schema state.`)},`, " mandatory: false,", " run: async (context) => ({ migrated: true, id: context.id }),", "});");
1328
- blueprintFields.push(" itemTypes: [itemType],", " itemFields: [noteField],", " migrations: [initMigration],");
1329
- break;
1330
- case "profile":
1331
- builderImports.push("defineProjectProfile");
1332
- definitions.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({", ...buildProfileArchetypeFieldLines(extensionName), "});");
1333
- blueprintFields.push(" profiles: [starterProfile],");
1334
- break;
1335
- case "renderers":
1336
- builderImports.push("defineRendererOverride");
1337
- definitions.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(commandName)}],`, " run: (context) => {", ` return ${JSON.stringify(`${extensionName}: `)} + JSON.stringify(context.result);`, " },", "});");
1338
- blueprintFields.push(" renderers: { toon: toonRenderer },");
1339
- break;
1340
- case "parser":
1341
- builderImports.push("defineParserOverride");
1342
- definitions.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 };", "});");
1343
- blueprintFields.push(` parsers: { ${JSON.stringify(commandName)}: pingParser },`);
1344
- break;
1345
- case "preflight":
1346
- builderImports.push("definePreflightOverride");
1347
- definitions.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(commandName)}],`, " run: (context) => context.decision,", "});");
1348
- blueprintFields.push(" preflights: [preflightOverride],");
1349
- break;
1350
- case "services":
1351
- builderImports.push("defineServiceOverride");
1352
- definitions.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(commandName)}) {`, " return { handled: false };", " }", ` return { rendered_by: ${JSON.stringify(extensionName)}, payload: context.payload };`, "});");
1353
- blueprintFields.push(" services: { output_format: outputService },");
1354
- break;
1355
- }
1356
- return { builderImports, definitions, blueprintFields };
1357
- }
1358
- /**
1359
- * Build the declarative (`composeExtension`) variant of the starter `index.ts` for
1360
- * the chosen capability.
1361
- *
1362
- * Where {@link buildActivateBodyLines} emits an imperative `activate` that calls
1363
- * `api.register*` directly, this emits the SDK's flagship declarative loop: the
1364
- * capability's surfaces are authored with the `define*` builders (via the shared
1365
- * {@link buildDeclarativeBlueprintSurface}), collected into an `ExtensionBlueprint`
1366
- * by `defineExtensionBlueprint`, and turned into the runtime module by
1367
- * `composeExtension` (which generates the `activate` that registers every blueprint
1368
- * surface in order). Every definition, the blueprint, and the module are exported
1369
- * so the colocated test can preflight the blueprint and exercise the module — see
1370
- * {@link buildDeclarativeSampleTestSource}.
1371
- *
1372
- * It is package-mode by construction: `composeExtension` is a runtime SDK *value*
1373
- * import, so it belongs in package-mode authoring where the SDK is a linked
1374
- * dependency, not in the import-free extension-only starters.
1375
- * {@link scaffoldExtensionProject} enforces that constraint before this is reached.
1376
- */
1377
- function buildDeclarativeEntrypoint(extensionName, commandName, capability) {
1378
- const surface = buildDeclarativeBlueprintSurface(extensionName, commandName, capability);
1379
- // `composeExtension`/`defineCommand`/`defineExtensionBlueprint` are always needed;
1380
- // sort the full set so the import line is stable and idiomatic per capability.
1381
- const builderImports = [
1382
- "composeExtension",
1383
- "defineCommand",
1384
- "defineExtensionBlueprint",
1385
- ...surface.builderImports,
1386
- ].sort((left, right) => left.localeCompare(right));
1387
- return [
1388
- `import { ${builderImports.join(", ")} } from "@unbrained/pm-cli/sdk";`,
1389
- "",
1390
- ...surface.definitions,
1391
- "",
1392
- "// Declarative authoring: describe WHAT the package registers as a blueprint and",
1393
- "// let `composeExtension` generate the `activate` that wires every surface in order,",
1394
- "// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`",
1395
- "// contract-checks the blueprint where it is authored. Keep `manifest.json`'s",
1396
- "// `capabilities` equal to the set this blueprint derives.",
1397
- "export const blueprint = defineExtensionBlueprint({",
1398
- ...surface.blueprintFields,
1399
- " // `deactivate` is the teardown counterpart to the generated `activate`: pm runs",
1400
- " // it on host shutdown/reload to release anything the package opened (timers,",
1401
- " // connections, caches). This starter holds none, so it stays a no-op.",
1402
- " deactivate: () => {},",
1403
- "});",
1404
- "",
1405
- "// `composeExtension(blueprint)` is the package's default export — the runtime",
1406
- "// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`",
1407
- "// in index.test.ts before publishing.",
1408
- "export default composeExtension(blueprint);",
1409
- "",
1410
- ].join("\n");
1411
- }
1412
- /**
1413
- * Build the capability-specific `node:test` block for the declarative starter:
1414
- * a dedicated test that activates the composed module through
1415
- * {@link ExtensionTestHarness} and asserts + invokes the capability's surface
1416
- * (hook, search provider/adapter, importer/exporter, schema, renderer, parser,
1417
- * preflight, or service override). Returns `[]` for the `commands` capability,
1418
- * whose only surface — the starter command — is already covered by the base test.
1419
- *
1420
- * Each block mirrors the imperative {@link buildSampleTestSource} capability test
1421
- * but reaches it through the harness's bound `assert*`/`run*` helpers instead of
1422
- * the standalone helpers, so the declarative starter never threads
1423
- * `activation.registrations` / `activation.parsers` / ... by hand.
1424
- */
1425
- function buildDeclarativeCapabilityTestBlock(extensionName, commandName, capability, capabilitiesLiteral) {
1426
- if (capability === "commands") {
1427
- return [];
1428
- }
1429
- const searchProviderName = `${extensionName}-search`;
1430
- const vectorAdapterName = `${extensionName}-vector`;
1431
- const adapterName = `${extensionName.replace(/-/g, " ")} items`;
1432
- const itemTypeName = extensionName;
1433
- const itemTypeFolder = `${extensionName}s`;
1434
- const fieldName = `${extensionName.replace(/-/g, "_")}_note`;
1435
- const migrationId = `${extensionName}-0001-init`;
1436
- const harness = [
1437
- " const ext = await createExtensionTestHarness(extension, {",
1438
- ` name: ${JSON.stringify(extensionName)},`,
1439
- ` capabilities: ${capabilitiesLiteral},`,
1440
- " });",
1441
- ];
1442
- const withHarnessCleanup = (body) => [
1443
- ...harness,
1444
- " let deactivated = false;",
1445
- " try {",
1446
- ...body.map((line) => (line === "" ? line : ` ${line}`)),
1447
- " const teardown = await ext.deactivate();",
1448
- " assertExtensionDeactivated(teardown);",
1449
- " deactivated = true;",
1450
- ...SAMPLE_HARNESS_FINALLY_LINES,
1451
- ];
1452
- switch (capability) {
1453
- case "hooks":
1454
- return [
1455
- `test(${JSON.stringify(`${extensionName} reacts to commands via its after_command hook`)}, async () => {`,
1456
- ...withHarnessCleanup([
1457
- " // assertHook throws unless an after_command hook is registered, so reaching the",
1458
- " // next line already proves the hook is wired.",
1459
- ` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(extensionName)} });`,
1460
- " // runHook fires the hook through pm's real runner with a synthetic context and",
1461
- " // returns the warnings it produced; a clean hook returns none.",
1462
- " const warnings = await ext.runHook({",
1463
- ' kind: "after_command",',
1464
- " context: {",
1465
- ` command: ${JSON.stringify(commandName)},`,
1466
- " args: [],",
1467
- ' pm_root: "",',
1468
- " ok: true,",
1469
- " affected: [],",
1470
- " },",
1471
- " });",
1472
- " assert.deepEqual(warnings, []);",
1473
- ]),
1474
- "});",
1475
- "",
1476
- ];
1477
- case "search":
1478
- return [
1479
- `test(${JSON.stringify(`${extensionName} registers and invokes search primitives`)}, async () => {`,
1480
- ...withHarnessCleanup([
1481
- ` ext.assertSearchProvider({ name: ${JSON.stringify(searchProviderName)}, extensionName: ${JSON.stringify(extensionName)} });`,
1482
- ` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(vectorAdapterName)}, extensionName: ${JSON.stringify(extensionName)} });`,
1483
- "",
1484
- " // The starter provider reads only document title/id, so `settings` is a minimal",
1485
- " // typed stub and `documents` carry just the fields it inspects.",
1486
- " const settings = {",
1487
- " testing: {",
1488
- " record_results_to_items: false,",
1489
- " allow_untrusted_linked_tests: false,",
1490
- " },",
1491
- " } as PmSettings;",
1492
- " const query = await ext.runSearchProvider({",
1493
- ` provider: ${JSON.stringify(searchProviderName)},`,
1494
- ' operation: "query",',
1495
- " context: {",
1496
- ' query: "sync",',
1497
- ' mode: "semantic",',
1498
- ' tokens: ["sync"],',
1499
- " options: {},",
1500
- " settings,",
1501
- " documents: [",
1502
- ' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',
1503
- ' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },',
1504
- " ] as ItemDocument[],",
1505
- " },",
1506
- " });",
1507
- ' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',
1508
- "",
1509
- " const embedding = await ext.runSearchProvider({",
1510
- ` provider: ${JSON.stringify(searchProviderName)},`,
1511
- ' operation: "embed",',
1512
- ' context: { input: "abc", settings, model: "starter-model" },',
1513
- " });",
1514
- " assert.deepEqual(embedding, [3]);",
1515
- "",
1516
- " const vectorHits = await ext.runVectorStoreAdapter({",
1517
- ` adapter: ${JSON.stringify(vectorAdapterName)},`,
1518
- ' operation: "query",',
1519
- " context: { vector: [0.1, 0.2], limit: 2, settings },",
1520
- " });",
1521
- ' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);',
1522
- ]),
1523
- "});",
1524
- "",
1525
- ];
1526
- case "importers":
1527
- return [
1528
- `test(${JSON.stringify(`${extensionName} registers and invokes import/export primitives`)}, async () => {`,
1529
- ...withHarnessCleanup([
1530
- ` ext.assertImporter({ name: ${JSON.stringify(adapterName)}, extensionName: ${JSON.stringify(extensionName)} });`,
1531
- ` ext.assertExporter({ name: ${JSON.stringify(adapterName)}, extensionName: ${JSON.stringify(extensionName)} });`,
1532
- "",
1533
- " const imported = await ext.runImporter({",
1534
- ` importer: ${JSON.stringify(adapterName)},`,
1535
- ' options: { source: "tickets" },',
1536
- ' args: ["batch-1"],',
1537
- " });",
1538
- " assert.equal(imported.handled, true);",
1539
- ' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',
1540
- "",
1541
- " const exported = await ext.runExporter({",
1542
- ` exporter: ${JSON.stringify(adapterName)},`,
1543
- ' options: { destination: "archive" },',
1544
- ' args: ["done"],',
1545
- " });",
1546
- " assert.equal(exported.handled, true);",
1547
- ' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });',
1548
- ]),
1549
- "});",
1550
- "",
1551
- ];
1552
- case "schema":
1553
- return [
1554
- `test(${JSON.stringify(`${extensionName} registers and runs its custom schema`)}, async () => {`,
1555
- ...withHarnessCleanup(buildSchemaCapabilityAssertionLines({
1556
- extensionName,
1557
- itemTypeName,
1558
- itemTypeFolder,
1559
- fieldName,
1560
- migrationId,
1561
- })),
1562
- "});",
1563
- "",
1564
- ];
1565
- case "profile":
1566
- return [
1567
- `test(${JSON.stringify(`${extensionName} registers its project profile`)}, async () => {`,
1568
- ...withHarnessCleanup(buildProfileCapabilityAssertionLines(extensionName)),
1569
- "});",
1570
- "",
1571
- ];
1572
- case "renderers":
1573
- return [
1574
- `test(${JSON.stringify(`${extensionName} registers and invokes its renderer override`)}, async () => {`,
1575
- ...withHarnessCleanup([
1576
- " // assertRendererOverride throws unless a renderer is registered for the format,",
1577
- " // so reaching the next line already proves the wiring.",
1578
- ` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(extensionName)} });`,
1579
- ' assert.equal(override.format, "toon");',
1580
- "",
1581
- " // runRendererOverride renders through pm's real runner. The override customizes",
1582
- " // only THIS package's command output and returns a string the host uses verbatim.",
1583
- " const rendered = await ext.runRendererOverride({",
1584
- ' format: "toon",',
1585
- ` command: ${JSON.stringify(commandName)},`,
1586
- " result: { ok: true },",
1587
- " });",
1588
- " assert.equal(rendered.overridden, true);",
1589
- " assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",
1590
- "",
1591
- " // Output for any other command passes through to pm's default renderer.",
1592
- " const passthrough = await ext.runRendererOverride({",
1593
- ' format: "toon",',
1594
- ' command: "list",',
1595
- " result: { ok: true },",
1596
- " });",
1597
- " assert.equal(passthrough.overridden, false);",
1598
- ]),
1599
- "});",
1600
- "",
1601
- ];
1602
- case "parser":
1603
- return [
1604
- `test(${JSON.stringify(`${extensionName} rewrites command options via its parser override`)}, async () => {`,
1605
- ...withHarnessCleanup([
1606
- " // assertParserOverride throws unless a parser is registered for the command, so",
1607
- " // reaching the next line already proves the wiring.",
1608
- ` ext.assertParserOverride({ name: ${JSON.stringify(commandName)}, extensionName: ${JSON.stringify(extensionName)} });`,
1609
- "",
1610
- " // runParserOverride runs the override through pm's real parser runner and returns",
1611
- " // the rewritten context. The starter rewrites the deprecated `shout` alias to the",
1612
- " // canonical `upper` flag.",
1613
- " const result = await ext.runParserOverride({",
1614
- ` command: ${JSON.stringify(commandName)},`,
1615
- " args: [],",
1616
- " options: { shout: true },",
1617
- " global: {},",
1618
- ' pm_root: "",',
1619
- " });",
1620
- " assert.equal(result.overridden, true);",
1621
- " assert.deepEqual(result.context.options, { upper: true });",
1622
- "",
1623
- " // End to end: feed the rewritten options into the command handler to prove",
1624
- " // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",
1625
- ` const invocation = await ext.runCommand({ command: ${JSON.stringify(commandName)}, options: result.context.options });`,
1626
- " assert.equal(invocation.handled, true);",
1627
- " assert.deepEqual(invocation.result, {",
1628
- " ok: true,",
1629
- ` source: ${JSON.stringify(extensionName)},`,
1630
- ` command: ${JSON.stringify(commandName)},`,
1631
- " upper: true,",
1632
- ' message: "Starter extension scaffold is active.",',
1633
- " });",
1634
- ]),
1635
- "});",
1636
- "",
1637
- ];
1638
- case "preflight":
1639
- return [
1640
- `test(${JSON.stringify(`${extensionName} returns a preflight gate decision via its override`)}, async () => {`,
1641
- ...withHarnessCleanup([
1642
- " // assertPreflightOverride throws unless a preflight override is registered, so",
1643
- " // reaching the next line already proves the wiring.",
1644
- ` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(extensionName)} });`,
1645
- "",
1646
- " // runPreflightOverride runs the override through pm's real runner with a synthetic",
1647
- " // gate decision. The starter echoes the decision unchanged; replace the",
1648
- " // values/assertions with your real policy.",
1649
- " const decision = {",
1650
- " enforce_item_format_gate: true,",
1651
- " run_preflight_item_format_sync: false,",
1652
- " run_extension_migrations: true,",
1653
- " enforce_mandatory_migration_gate: false,",
1654
- " };",
1655
- " const result = await ext.runPreflightOverride({",
1656
- ` command: ${JSON.stringify(commandName)},`,
1657
- " args: [],",
1658
- " options: {},",
1659
- " global: {},",
1660
- ' pm_root: "",',
1661
- " decision,",
1662
- " });",
1663
- " assert.equal(result.overridden, true);",
1664
- " assert.deepEqual(result.decision, decision);",
1665
- ]),
1666
- "});",
1667
- "",
1668
- ];
1669
- case "services":
1670
- return [
1671
- `test(${JSON.stringify(`${extensionName} customizes command output via its service override`)}, async () => {`,
1672
- ...withHarnessCleanup([
1673
- " // assertServiceOverride throws unless a service override is registered for the",
1674
- " // service, so reaching the next line proves the wiring.",
1675
- ` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(extensionName)} });`,
1676
- "",
1677
- " // runServiceOverride runs the override through pm's real service runner. The",
1678
- " // override customizes only THIS package's command output (handled), passing every",
1679
- " // other command through (not handled).",
1680
- " const handled = await ext.runServiceOverride({",
1681
- ' service: "output_format",',
1682
- ` command: ${JSON.stringify(commandName)},`,
1683
- " payload: { ok: true },",
1684
- " });",
1685
- " assert.equal(handled.handled, true);",
1686
- ` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(extensionName)}, payload: { ok: true } });`,
1687
- "",
1688
- " // Output for any other command passes through to pm's default formatter.",
1689
- " const passthrough = await ext.runServiceOverride({",
1690
- ' service: "output_format",',
1691
- ' command: "list",',
1692
- " payload: { ok: true },",
1693
- " });",
1694
- " assert.equal(passthrough.handled, false);",
1695
- ]),
1696
- "});",
1697
- "",
1698
- ];
1699
- }
1700
- }
1701
- /**
1702
- * Build the declarative variant of the colocated `node:test` suite
1703
- * (`index.test.ts`) for the chosen capability's `composeExtension` starter.
1704
- *
1705
- * Like {@link buildSampleTestSource}, this uses the harness-bound runtime
1706
- * helpers; it also exercises the author-time capstone the declarative loop
1707
- * unlocks:
1708
- * `assertExtensionPreflight(blueprint, { identity, target })` (lint + manifest
1709
- * synthesis + version-compat in one call) over the exported `blueprint`, and the
1710
- * ergonomic runtime `createExtensionTestHarness(module)` whose `assert*`/`run*`/
1711
- * `deactivate` methods are pre-bound to the right activation sub-registry. The base
1712
- * suite covers preflight, the starter command, and teardown; for non-`commands`
1713
- * capabilities {@link buildDeclarativeCapabilityTestBlock} adds a dedicated test for
1714
- * the capability's surface. The `identity`/`target` versions are pinned to the
1715
- * scaffolded `pm_min_version` so the synthesized manifest is trivially compatible
1716
- * and the suite stays deterministic; an author edits them as the package matures.
1717
- */
1718
- function buildDeclarativeSampleTestSource(extensionName, commandName, capability) {
1719
- const parserEnabled = capability === "parser";
1720
- // The preflight report's capability set is DERIVED from the blueprint and SORTED,
1721
- // so assert against the sorted manifest capabilities (a set match in canonical
1722
- // order); the harness `capabilities` grant uses the same literal.
1723
- const capabilitiesLiteral = JSON.stringify([...SCAFFOLD_MANIFEST_CAPABILITIES[capability]].sort());
1724
- return [
1725
- 'import assert from "node:assert/strict";',
1726
- 'import { test } from "node:test";',
1727
- 'import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',
1728
- // The search sample's synthetic query/vector contexts reference these SDK types
1729
- // for their typed-stub fixtures; other capabilities need no extra type imports.
1730
- ...(capability === "search"
1731
- ? [
1732
- 'import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";',
1733
- ]
1734
- : []),
1735
- 'import extension, { blueprint } from "./index.ts";',
1736
- 'import manifest from "./manifest.json" with { type: "json" };',
1737
- "",
1738
- ...SAMPLE_HARNESS_CLEANUP_LINES,
1739
- `test(${JSON.stringify(`${extensionName} passes author-time preflight`)}, () => {`,
1740
- " // assertExtensionPreflight is the author-time capstone: it lints the blueprint,",
1741
- " // synthesizes the least-privilege manifest from `identity`, and checks the version",
1742
- " // bounds against `target` in one call, throwing on any blocking finding. It returns",
1743
- " // the full report so you can inspect the derived data.",
1744
- " const report = assertExtensionPreflight(blueprint, {",
1745
- " identity: {",
1746
- ` name: ${JSON.stringify(extensionName)},`,
1747
- ' version: "0.1.0",',
1748
- ' entry: "./index.ts",',
1749
- " priority: 0,",
1750
- ` pm_min_version: ${JSON.stringify(SCAFFOLD_PM_MIN_VERSION)},`,
1751
- " },",
1752
- ` target: { pmVersion: ${JSON.stringify(SCAFFOLD_PM_MIN_VERSION)} },`,
1753
- " });",
1754
- " // Fail the starter suite whenever the checked-in manifest drifts from the",
1755
- " // capabilities derived from the blueprint.",
1756
- " assertExtensionManifestMatchesBlueprint(manifest, blueprint);",
1757
- " // The capability set is DERIVED from the blueprint, never hand-synced. Keep",
1758
- " // manifest.json's `capabilities` equal to this list (set match, sorted).",
1759
- ` assert.deepEqual(report.capabilities, ${capabilitiesLiteral});`,
1760
- ` assert.deepEqual(report.manifest?.capabilities, ${capabilitiesLiteral});`,
1761
- "});",
1762
- "",
1763
- `test(${JSON.stringify(`${extensionName} registers and runs its starter command`)}, async () => {`,
1764
- " // createExtensionTestHarness activates the composed module once and binds the",
1765
- " // assert*/run*/deactivate helpers to the right activation sub-registry, so you",
1766
- " // never thread activation.registrations vs activation.commands by hand.",
1767
- " // `capabilities` mirrors manifest.json so the in-memory activation grants what the",
1768
- " // blueprint needs.",
1769
- " const ext = await createExtensionTestHarness(extension, {",
1770
- ` name: ${JSON.stringify(extensionName)},`,
1771
- ` capabilities: ${capabilitiesLiteral},`,
1772
- " });",
1773
- " let deactivated = false;",
1774
- " try {",
1775
- " // assertCommandContract throws unless the command is registered, so reaching",
1776
- " // the next line already proves the wiring; assert on the returned definition",
1777
- " // to demonstrate inspecting registered metadata.",
1778
- ` const registered = ext.assertCommandContract({ name: ${JSON.stringify(commandName)} });`,
1779
- ' assert.equal(typeof registered.command.description, "string");',
1780
- "",
1781
- " // runCommand invokes the handler through pm's real dispatch engine, so this",
1782
- " // asserts behavior - not just that the command is wired. Replace these",
1783
- " // assertions as you flesh out your command.",
1784
- ` const invocation = await ext.runCommand({ command: ${JSON.stringify(commandName)} });`,
1785
- " assert.equal(invocation.handled, true);",
1786
- " assert.deepEqual(invocation.result, {",
1787
- " ok: true,",
1788
- ` source: ${JSON.stringify(extensionName)},`,
1789
- ` command: ${JSON.stringify(commandName)},`,
1790
- // The parser starter's command surfaces the normalized `upper` flag, false when
1791
- // the command is invoked without `--shout`/`--upper`.
1792
- ...(parserEnabled ? [" upper: false,"] : []),
1793
- ' message: "Starter extension scaffold is active.",',
1794
- " });",
1795
- " // deactivate runs pm's real teardown engine over the module; exactly one",
1796
- " // extension tears down with no failures.",
1797
- " const teardown = await ext.deactivate();",
1798
- " assertExtensionDeactivated(teardown);",
1799
- " deactivated = true;",
1800
- ...SAMPLE_HARNESS_FINALLY_LINES,
1801
- "});",
1802
- "",
1803
- ...buildDeclarativeCapabilityTestBlock(extensionName, commandName, capability, capabilitiesLiteral),
1804
- ].join("\n");
1805
- }
1806
- /**
1807
- * Build the README for the declarative (`composeExtension`) package starter for
1808
- * the chosen capability.
1809
- *
1810
- * It documents the same metadata/validation sections as the imperative package
1811
- * README but frames the entrypoint around the declarative loop and the author-time
1812
- * preflight test, so the generated docs match the generated `index.ts`/
1813
- * `index.test.ts`. The included-files bullets, the Declarative Authoring blueprint
1814
- * fields, and the activation section are capability-aware: the `schema` starter
1815
- * contributes a global item type (so it omits `activation.commands`), while every
1816
- * other capability declares the command paths that lazily activate the package.
1817
- */
1818
- function buildDeclarativePackageReadme(packageName, commandName, capability) {
1819
- // The schema/profile starters omit `activation.commands` (their surface is a
1820
- // global contribution), so describe the manifest accurately and use the
1821
- // conservative-activation section.
1822
- const manifestBullet = buildScaffoldManifestBullet(capability, "package");
1823
- const activationSection = buildScaffoldActivationReadmeSection(capability, "package");
1824
- return [
1825
- `# ${packageName}`,
1826
- "",
1827
- "Generated by `pm package init --declarative`.",
1828
- "",
1829
- "## Included Files",
1830
- "- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",
1831
- manifestBullet,
1832
- `- \`index.ts\`: the TypeScript manifest entry — a \`defineExtensionBlueprint\` blueprint (${DECLARATIVE_ENTRYPOINT_SURFACE_PHRASE[capability]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,
1833
- "- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",
1834
- TSCONFIG_BULLET,
1835
- "- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.",
1836
- "",
1837
- "## Quick Start",
1838
- "This package is authored AND loaded as TypeScript: the manifest `entry` is",
1839
- "`./index.ts` and pm imports it directly via Node's native type stripping",
1840
- "(Node >=22.18), so there is no build step — install and run:",
1841
- "```bash",
1842
- "npm install",
1843
- "pm install --project <package-path>",
1844
- `pm ${commandName}`,
1845
- "pm package doctor --project --detail summary",
1846
- "```",
1847
- "",
1848
- "## Declarative Authoring",
1849
- "`index.ts` uses the SDK's declarative authoring loop instead of an imperative",
1850
- "`activate` body. You describe WHAT the package registers as an",
1851
- "`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires",
1852
- "every surface in order:",
1853
- "- The `define*` builders author each surface with literal-type preservation and",
1854
- " contextual handler inference (`defineCommand`, `defineSearchProvider`,",
1855
- " `defineItemType`, `defineParserOverride`, ...).",
1856
- `- \`defineExtensionBlueprint({ ... })\` collects the definitions into the blueprint;`,
1857
- ` this starter populates ${DECLARATIVE_CAPABILITY_BLUEPRINT_FIELDS[capability]}. Add more`,
1858
- " fields as the package grows.",
1859
- "- `composeExtension(blueprint)` is the default export — the runtime module pm",
1860
- " loads. Its generated `activate` requires exactly the capabilities the blueprint",
1861
- " derives, so `manifest.json`'s `capabilities` never drift.",
1862
- "",
1863
- "## Validate the Package",
1864
- "`npm install` pulls the peer SDK and TypeScript. `npm test` is the default",
1865
- "validation gate: it type-checks the package, then runs the colocated sample:",
1866
- "```bash",
1867
- "npm install",
1868
- "npm test",
1869
- "```",
1870
- "`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`",
1871
- "(the author-time lint + manifest synthesis + version-compatibility check over the",
1872
- "exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose",
1873
- "`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).",
1874
- "`npm run typecheck` is available when you only want the SDK contract check.",
1875
- "`npm run test:runtime` runs just `node --test`, which strips types on load and",
1876
- "executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`",
1877
- "helpers - no compile step and no extra test runner required.",
1878
- ...activationSection,
1879
- "",
1880
- "## Compatibility Bounds",
1881
- "`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",
1882
- `- \`manifest_version\` (integer): manifest schema generation. Leave at \`${SCAFFOLD_MANIFEST_VERSION}\` unless you adopt a newer manifest schema.`,
1883
- `- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${SCAFFOLD_PM_MIN_VERSION}\`. The loader blocks the package on older CLIs.`,
1884
- "- `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.",
1885
- "",
1886
- "## Policy Metadata",
1887
- '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`.',
1888
- "",
1889
- "## Notes",
1890
- "- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload — there is no `.js` to regenerate.",
1891
- "- 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).",
1892
- "- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",
1893
- "",
1894
- ].join("\n");
1895
- }
1896
- /**
1897
- * Project the {@link ScaffoldSnippetNames} for `extensionName`, omitting a
1898
- * redundant self-alias when the de-hyphenated form already equals the type name.
1899
- */
1900
- function buildScaffoldSnippetNames(extensionName) {
1901
- const itemTypeName = extensionName;
1902
- const itemTypeAlias = extensionName.replace(/-/g, "");
1903
- return {
1904
- searchProviderName: `${extensionName}-search`,
1905
- vectorAdapterName: `${extensionName}-vector`,
1906
- adapterName: `${extensionName.replace(/-/g, " ")} items`,
1907
- itemTypeName,
1908
- itemTypeFolder: `${extensionName}s`,
1909
- itemTypeAliases: itemTypeAlias === itemTypeName ? [] : [itemTypeAlias],
1910
- fieldName: `${extensionName.replace(/-/g, "_")}_note`,
1911
- migrationId: `${extensionName}-0001-init`,
1912
- };
1913
- }
1914
- /** Build the comma-separated `define*` builder import list for the README snippet, including only the builders the chosen capability demonstrates. */
1915
- function buildDefineBuilderImports(capability) {
1916
- return [
1917
- "defineCommand",
1918
- ...(capability === "hooks" ? ["defineAfterCommandHook"] : []),
1919
- ...(capability === "search"
1920
- ? ["defineSearchProvider", "defineVectorStoreAdapter"]
1921
- : []),
1922
- ...(capability === "importers" ? ["defineImporter", "defineExporter"] : []),
1923
- ...(capability === "schema"
1924
- ? ["defineItemType", "defineItemField", "defineMigration"]
1925
- : []),
1926
- ...(capability === "profile" ? ["defineProjectProfile"] : []),
1927
- ...(capability === "renderers" ? ["defineRendererOverride"] : []),
1928
- ...(capability === "parser" ? ["defineParserOverride"] : []),
1929
- ...(capability === "preflight" ? ["definePreflightOverride"] : []),
1930
- ...(capability === "services" ? ["defineServiceOverride"] : []),
1931
- ].join(", ");
1932
- }
1933
- /** Build the exported `define*` declarations for the README snippet: the base `pingCommand` (with parser flags for the parser capability) plus the one capability-specific export the chosen capability demonstrates. */
1934
- function buildDefineBuilderExports(extensionName, commandName, capability, names) {
1935
- const lines = [
1936
- "export const pingCommand = defineCommand({",
1937
- ` name: ${JSON.stringify(commandName)},`,
1938
- ' description: "Starter scaffold command. Replace with your own behavior.",',
1939
- // The parser starter's command declares the flags its override normalizes so
1940
- // the demo is runnable through `pm <command> --shout`, and surfaces the
1941
- // canonical `upper` flag in the result.
1942
- ...(capability === "parser"
1943
- ? [
1944
- " flags: [",
1945
- ' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',
1946
- ' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },',
1947
- " ],",
1948
- " run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),",
1949
- ]
1950
- : [" run: (context) => ({ ok: true, command: context.command }),"]),
1951
- "});",
1952
- ];
1953
- if (capability === "hooks") {
1954
- lines.push("", "export const afterCommandHook = defineAfterCommandHook((context) => {", " if (!context.ok) return;", " // React to context.affected here as your package grows.", "});");
1955
- }
1956
- if (capability === "search") {
1957
- lines.push("", "export const searchProvider = defineSearchProvider({", ` name: ${JSON.stringify(names.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(names.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 }),", "});");
1958
- }
1959
- if (capability === "importers") {
1960
- lines.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,", "}));");
1961
- }
1962
- if (capability === "schema") {
1963
- lines.push("", `export const noteField = defineItemField({ name: ${JSON.stringify(names.fieldName)}, type: "string", optional: true });`, "", "export const itemType = defineItemType({", ` name: ${JSON.stringify(names.itemTypeName)},`, ` folder: ${JSON.stringify(names.itemTypeFolder)},`, ` aliases: ${JSON.stringify(names.itemTypeAliases)},`, " required_create_fields: [],", "});", "", "export const initMigration = defineMigration({", ` id: ${JSON.stringify(names.migrationId)},`, ` description: ${JSON.stringify(`Initialize ${extensionName} schema state.`)},`, " mandatory: false,", " run: async (context) => ({ migrated: true, id: context.id }),", "});");
1964
- }
1965
- if (capability === "profile") {
1966
- // Abbreviated illustration; the generated index.ts populates every archetype
1967
- // dimension (types, statuses, fields, workflow, config, template, packages).
1968
- lines.push("", "export const starterProfile = defineProjectProfile({", ` name: ${JSON.stringify(extensionName)},`, ` title: ${JSON.stringify(`${extensionName} archetype`)},`, ' summary: "Starter project profile. Replace these dimensions with your own archetype.",', " types: [", ` { name: ${JSON.stringify(names.itemTypeName)}, folder: ${JSON.stringify(names.itemTypeFolder)} },`, " ],", " // ...plus statuses, fields, workflows, config, templates, and packages.", "});");
1969
- }
1970
- if (capability === "renderers") {
1971
- lines.push("", "export const toonRenderer = defineRendererOverride({", ` commands: [${JSON.stringify(commandName)}],`, " run: (context) => JSON.stringify(context.result),", "});");
1972
- }
1973
- if (capability === "parser") {
1974
- lines.push("", "export const pingParser = defineParserOverride((context) => {", " const options = { ...context.options };", " if (options.shout === true) options.upper = true;", " delete options.shout;", " return { options };", "});");
1975
- }
1976
- if (capability === "preflight") {
1977
- lines.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(commandName)}],`, " run: (context) => context.decision,", "});");
1978
- }
1979
- if (capability === "services") {
1980
- lines.push("", "export const outputService = defineServiceOverride((context) => {", ` if (context.command !== ${JSON.stringify(commandName)}) return { handled: false };`, ` return { rendered_by: ${JSON.stringify(extensionName)}, payload: context.payload };`, "});");
1981
- }
1982
- return lines;
1983
- }
1984
- /**
1985
- * Build the `activate` body registrations for the README snippet: one
1986
- * `api.register*`/`api.hooks.*` call wiring the capability-specific exports
1987
- * produced by {@link buildDefineBuilderExports}.
1988
- */
1989
- function buildDefineBuilderActivate(commandName, capability, names) {
1990
- const lines = [];
1991
- if (capability === "renderers") {
1992
- lines.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);');
1993
- }
1994
- if (capability === "parser") {
1995
- lines.push(` api.registerParser(${JSON.stringify(commandName)}, pingParser);`);
1996
- }
1997
- if (capability === "preflight") {
1998
- lines.push(" api.registerPreflight(preflightOverride);");
1999
- }
2000
- if (capability === "services") {
2001
- lines.push(' api.registerService("output_format", outputService);');
2002
- }
2003
- if (capability === "hooks") {
2004
- lines.push(" api.hooks.afterCommand(afterCommandHook);");
2005
- }
2006
- if (capability === "search") {
2007
- lines.push(" api.registerSearchProvider(searchProvider);", " api.registerVectorStoreAdapter(vectorStoreAdapter);");
2008
- }
2009
- if (capability === "schema") {
2010
- lines.push(" api.registerItemFields([noteField]);", " api.registerItemTypes([itemType]);", " api.registerMigration(initMigration);");
2011
- }
2012
- if (capability === "profile") {
2013
- lines.push(" api.registerProfile(starterProfile);");
2014
- }
2015
- if (capability === "importers") {
2016
- lines.push(` api.registerImporter(${JSON.stringify(names.adapterName)}, importer, {`, ` action: ${JSON.stringify(`${names.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(names.adapterName)}, exporter, {`, ` action: ${JSON.stringify(`${names.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.",', " },", " ],", " });");
2017
- }
2018
- return lines;
2019
- }
2020
- /** Implements build starter extension scaffold files for the public runtime surface of this module. */
2021
- export function buildStarterExtensionScaffoldFiles(extensionName, commandName, _vocabulary, capability = "commands", declarative = false) {
2022
- const packageName = `pm-${extensionName}`;
2023
- const capabilities = SCAFFOLD_MANIFEST_CAPABILITIES[capability];
2024
- const activationCommands = buildScaffoldActivationCommands(extensionName, commandName, capability);
2025
- const manifest = `${JSON.stringify({
2026
- name: extensionName,
2027
- version: "0.1.0",
2028
- entry: "./index.ts",
2029
- manifest_version: SCAFFOLD_MANIFEST_VERSION,
2030
- pm_min_version: SCAFFOLD_PM_MIN_VERSION,
2031
- trusted: true,
2032
- sandbox_profile: "strict",
2033
- permissions: { ...SCAFFOLD_DECLARED_PERMISSIONS },
2034
- capabilities,
2035
- // Declares the exact command paths `activate` registers so pm activates
2036
- // this package lazily — only when an invoked command matches — mirroring
2037
- // every first-party bundled package. Keep it in sync with the entrypoint.
2038
- // The schema and profile starters omit this field (empty list) so their
2039
- // global contribution — a custom item type/field, or a project profile
2040
- // resolved by `pm profile` — stays available to built-in commands (see
2041
- // buildScaffoldActivationCommands).
2042
- ...(activationCommands.length > 0
2043
- ? { activation: { commands: activationCommands } }
2044
- : {}),
2045
- }, null, 2)}\n`;
2046
- // The entrypoint is authored AND loaded as TypeScript (ADR pm-2c28 / pm-m1uz):
2047
- // the manifest `entry` points at `./index.ts` and pm imports it directly via
2048
- // Node's native type stripping (Node >=22.18) — there is no compile step and no
2049
- // `.js` artifact. The typed `ExtensionApi` parameter is checked against the SDK
2050
- // contract at author time (`npm run typecheck`).
2051
- const entrypoint = [
2052
- 'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',
2053
- "",
2054
- "export function activate(api: ExtensionApi): void {",
2055
- ...buildActivateBodyLines(extensionName, commandName, capability),
2056
- "}",
2057
- "",
2058
- "// `deactivate` is the teardown counterpart to `activate`: pm runs it on host",
2059
- "// shutdown/reload (e.g. the MCP server between requests) to release anything",
2060
- "// `activate` opened - timers, connections, caches. This starter holds no such",
2061
- "// resources, so it stays a documented no-op; add cleanup here as you grow.",
2062
- "export function deactivate(): void {}",
2063
- "",
2064
- "export default {",
2065
- " activate,",
2066
- " deactivate,",
2067
- "};",
2068
- "",
2069
- ].join("\n");
2070
- const tsconfig = `${JSON.stringify(SCAFFOLD_TSCONFIG, null, 2)}\n`;
2071
- // README bullet describing what index.ts wires, kept in sync with the chosen
2072
- // capability so the generated docs match the generated code.
2073
- const entrypointBullet = ENTRYPOINT_BULLETS[capability];
2074
- // The schema/profile starters omit `activation.commands` (their surface is a
2075
- // global contribution), so describe the manifest accurately instead of
2076
- // referencing a field they deliberately lack.
2077
- const manifestBullet = buildScaffoldManifestBullet(capability, "package");
2078
- const packageJson = `${JSON.stringify({
2079
- name: packageName,
2080
- version: "0.1.0",
2081
- private: true,
2082
- type: "module",
2083
- keywords: ["pm-package"],
2084
- engines: {
2085
- node: SCAFFOLD_NODE_ENGINE,
2086
- },
2087
- // There is no build step: pm loads the `./index.ts` manifest entry
2088
- // directly via Node's native type stripping (Node >=22.18). `typecheck`
2089
- // validates the source against the SDK contracts (`tsc --noEmit`), and
2090
- // `test` is the self-validating author gate: typecheck first, then run
2091
- // the colocated sample with Node's built-in runner (which strips types
2092
- // on load) against the peer SDK testing helpers — no third-party test
2093
- // runner or compile output required. `test:runtime` remains available
2094
- // for tight loops after a separate `npm run typecheck`.
2095
- scripts: {
2096
- typecheck: "tsc --noEmit",
2097
- "test:runtime": "node --test",
2098
- test: "npm run typecheck && npm run test:runtime",
2099
- },
2100
- peerDependencies: {
2101
- "@unbrained/pm-cli": `>=${SCAFFOLD_PM_MIN_VERSION}`,
2102
- },
2103
- devDependencies: {
2104
- "@types/node": SCAFFOLD_TYPES_NODE_VERSION,
2105
- typescript: SCAFFOLD_TYPESCRIPT_VERSION,
2106
- },
2107
- pm: {
2108
- aliases: [extensionName],
2109
- extensions: ["."],
2110
- docs: ["README.md"],
2111
- examples: ["README.md"],
2112
- catalog: {
2113
- display_name: extensionName,
2114
- category: "workflow",
2115
- summary: "Starter pm package scaffold.",
2116
- tags: ["starter"],
2117
- },
2118
- },
2119
- }, null, 2)}\n`;
2120
- // node:test sample: demonstrates validating the package with the SDK testing
2121
- // helpers without adding a third-party test runner. The suite covers the
2122
- // capability the scaffold targets (command invocation, and for the hooks
2123
- // capability, the after_command lifecycle hook).
2124
- const sampleTest = buildSampleTestSource(extensionName, commandName, capability);
2125
- const sampleTestBullet = SAMPLE_TEST_BULLETS[capability];
2126
- // The package commits only TypeScript source — pm loads the `.ts` entry
2127
- // directly, so there is no compiled output to ignore. Keep dependencies and
2128
- // the tsc incremental cache out of version control.
2129
- const gitignore = ["node_modules/", "*.log", "*.tsbuildinfo", ""].join("\n");
2130
- const names = buildScaffoldSnippetNames(extensionName);
2131
- const defineBuilderImports = buildDefineBuilderImports(capability);
2132
- const defineBuilderSnippet = [
2133
- "```ts",
2134
- `import { ${defineBuilderImports} } from "@unbrained/pm-cli/sdk";`,
2135
- 'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',
2136
- "",
2137
- ...buildDefineBuilderExports(extensionName, commandName, capability, names),
2138
- "",
2139
- "export function activate(api: ExtensionApi): void {",
2140
- " api.registerCommand(pingCommand);",
2141
- ...buildDefineBuilderActivate(commandName, capability, names),
2142
- "}",
2143
- "",
2144
- "export function deactivate(): void {}",
2145
- "",
2146
- "export default { activate, deactivate };",
2147
- "```",
2148
- ];
2149
- const packageReadme = [
2150
- `# ${packageName}`,
2151
- "",
2152
- "Generated by `pm package init` or `pm extension init`.",
2153
- "",
2154
- "## Included Files",
2155
- "- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",
2156
- manifestBullet,
2157
- entrypointBullet,
2158
- sampleTestBullet,
2159
- TSCONFIG_BULLET,
2160
- "- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.",
2161
- "",
2162
- "## Quick Start",
2163
- "This package is authored AND loaded as TypeScript: the manifest `entry` is",
2164
- "`./index.ts` and pm imports it directly via Node's native type stripping",
2165
- "(Node >=22.18), so there is no build step — install and run:",
2166
- "```bash",
2167
- "npm install",
2168
- "pm install --project <package-path>",
2169
- `pm ${commandName}`,
2170
- "pm package doctor --project --detail summary",
2171
- "```",
2172
- "",
2173
- "## Validate the Package",
2174
- "`npm install` pulls the peer SDK and TypeScript. `npm test` is the default",
2175
- "validation gate: it type-checks the package, then runs the colocated sample:",
2176
- "```bash",
2177
- "npm install",
2178
- "npm test",
2179
- "```",
2180
- "`npm run typecheck` is available when you only want the SDK contract check.",
2181
- "`npm run test:runtime` runs just `node --test`, which strips types on load and",
2182
- "executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`",
2183
- "helpers - no compile step and no extra test runner required.",
2184
- "",
2185
- "## Authoring With define* Builders",
2186
- "`index.ts` is authored fully in TypeScript so every registration is checked",
2187
- "against the SDK contracts at author time. Use the public SDK authoring",
2188
- "builders for exported definitions you want literal-type preservation,",
2189
- "contextual handler inference, and direct unit tests for:",
2190
- ...defineBuilderSnippet,
2191
- "The builders return their argument unchanged; runtime validation still lives",
2192
- "in `api.register*`, and behavior validation lives in `sdk/testing`.",
2193
- ...PACKAGE_CAPABILITY_README_SECTIONS[capability],
2194
- ...buildScaffoldActivationReadmeSection(capability, "package"),
2195
- "",
2196
- "## Compatibility Bounds",
2197
- `- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${SCAFFOLD_PM_MIN_VERSION}\`. 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.`,
2198
- "`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",
2199
- `- \`manifest_version\` (integer): manifest schema generation. Leave at \`${SCAFFOLD_MANIFEST_VERSION}\` unless you adopt a newer manifest schema.`,
2200
- `- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${SCAFFOLD_PM_MIN_VERSION}\`. The loader blocks the package on older CLIs.`,
2201
- "- `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.",
2202
- "",
2203
- "## Policy Metadata",
2204
- '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`.',
2205
- "",
2206
- "## Notes",
2207
- "- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload — there is no `.js` to regenerate.",
2208
- "- 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).",
2209
- "- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.",
2210
- "- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",
2211
- "",
2212
- ].join("\n");
2213
- // The declarative starter swaps the imperative entrypoint/test/README for the
2214
- // `composeExtension` blueprint form (package-mode, any capability, enforced by
2215
- // scaffoldExtensionProject). package.json, manifest.json, tsconfig.json, and
2216
- // .gitignore are identical to the imperative starter for the same capability.
2217
- return {
2218
- "package.json": packageJson,
2219
- "manifest.json": manifest,
2220
- "index.ts": declarative
2221
- ? buildDeclarativeEntrypoint(extensionName, commandName, capability)
2222
- : entrypoint,
2223
- "index.test.ts": declarative
2224
- ? buildDeclarativeSampleTestSource(extensionName, commandName, capability)
2225
- : sampleTest,
2226
- "tsconfig.json": tsconfig,
2227
- ".gitignore": gitignore,
2228
- "README.md": declarative
2229
- ? buildDeclarativePackageReadme(packageName, commandName, capability)
2230
- : packageReadme,
2231
- };
2232
- }
2233
- /** Implements scaffold extension project for the public runtime surface of this module. */
2234
- export async function scaffoldExtensionProject(target, vocabulary = "extension", capability = "commands", declarative = false) {
2235
- const normalizedCapability = capability.trim().toLowerCase();
2236
- if (!SCAFFOLD_CAPABILITIES.includes(normalizedCapability)) {
2237
- throw new PmCliError(`Unknown scaffold capability "${capability}". Supported capabilities: ${SCAFFOLD_CAPABILITIES.join(", ")}.`, EXIT_CODE.USAGE);
2238
- }
2239
- const resolvedCapability = normalizedCapability;
2240
- // The declarative (`composeExtension` blueprint) starter is package-mode only.
2241
- // `composeExtension` is a runtime SDK *value* import, so it belongs in
2242
- // package-mode authoring where the SDK is a linked dependency — not in the
2243
- // import-free extension-only starters that must load without it. Every capability
2244
- // emits its blueprint form (see buildDeclarativeBlueprintSurface).
2245
- if (declarative && vocabulary !== "package") {
2246
- throw new PmCliError("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.", EXIT_CODE.USAGE);
2247
- }
2248
- const style = declarative
2249
- ? "declarative"
2250
- : "imperative";
2251
- const normalizedTarget = target.trim();
2252
- const targetPath = path.resolve(process.cwd(), normalizedTarget);
2253
- const extensionName = normalizeManagedDirectoryName(path.basename(targetPath)).replace(/^(?:pm-)+/u, "");
2254
- // Hyphenated names become space-separated command words; reserved roots get a
2255
- // `starter` prefix so core commands and aliases cannot intercept dispatch.
2256
- const commandName = buildScaffoldCommandName(extensionName);
2257
- const scaffoldFiles = buildStarterExtensionScaffoldFiles(extensionName, commandName, vocabulary, resolvedCapability, declarative);
2258
- let createdDirectory = false;
2259
- if (await pathExists(targetPath)) {
2260
- const existingTargetStats = await fs.stat(targetPath);
2261
- if (!existingTargetStats.isDirectory()) {
2262
- throw new PmCliError(`Scaffold target "${targetPath}" exists and is not a directory.`, EXIT_CODE.CONFLICT);
2263
- }
2264
- }
2265
- else {
2266
- await fs.mkdir(targetPath, { recursive: true });
2267
- createdDirectory = true;
2268
- }
2269
- for (const [relativePath, content] of Object.entries(scaffoldFiles)) {
2270
- const absolutePath = path.join(targetPath, relativePath);
2271
- if (!(await pathExists(absolutePath))) {
2272
- continue;
2273
- }
2274
- const existingContent = await fs.readFile(absolutePath, "utf8");
2275
- if (existingContent !== content) {
2276
- throw new PmCliError(`Scaffold file "${relativePath}" already exists with different content in "${targetPath}". Choose a new target path or remove conflicting files.`, EXIT_CODE.CONFLICT);
2277
- }
2278
- }
2279
- const files = [];
2280
- for (const [relativePath, content] of Object.entries(scaffoldFiles)) {
2281
- const absolutePath = path.join(targetPath, relativePath);
2282
- if (await pathExists(absolutePath)) {
2283
- files.push({
2284
- path: relativePath,
2285
- status: "unchanged",
2286
- });
2287
- continue;
2288
- }
2289
- await fs.mkdir(path.dirname(absolutePath), { recursive: true });
2290
- await fs.writeFile(absolutePath, content, "utf8");
2291
- files.push({
2292
- path: relativePath,
2293
- status: "created",
2294
- });
2295
- }
2296
- return {
2297
- extension_name: extensionName,
2298
- package_name: `pm-${extensionName}`,
2299
- command_name: commandName,
2300
- invocation_command: `pm ${commandName}`,
2301
- capability: resolvedCapability,
2302
- style,
2303
- target_path: targetPath,
2304
- created_directory: createdDirectory,
2305
- files,
2306
- };
2307
- }
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="60ab864f-43c5-512c-b33f-456de96f8090")}catch(e2){}})();import fs from"node:fs/promises";import path from"node:path";import{pathExists}from"../../core/fs/fs-utils.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{EXECUTABLE_COMMAND_ALIASES,PM_CORE_COMMAND_NAMES}from"../cli-contracts.js";import{normalizeManagedDirectoryName}from"./shared.js";const SCAFFOLD_MANIFEST_VERSION=1;const SCAFFOLD_PM_MIN_VERSION="2026.6.24";const SCAFFOLD_NODE_ENGINE=">=22.18.0";const SCAFFOLD_DECLARED_PERMISSIONS={fs_read:false,fs_write:false,network:false,env_read:false,env_write:false,process_spawn:false};const RESERVED_SCAFFOLD_COMMAND_ROOTS=new Set([...PM_CORE_COMMAND_NAMES.map(commandName=>commandName.split("-")[0].toLowerCase()),...Object.keys(EXECUTABLE_COMMAND_ALIASES).map(alias=>alias.toLowerCase()),"scaffold"]);const SCAFFOLD_TYPESCRIPT_VERSION="^6.0.0";const SCAFFOLD_TYPES_NODE_VERSION="^22.0.0";const SAMPLE_HARNESS_CLEANUP_LINES=["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."," }"," }","}",""];const SAMPLE_HARNESS_FINALLY_LINES=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function indentGeneratedLines(lines,prefix){return lines.map(line=>line===""?line:`${prefix}${line}`)}function buildSchemaCapabilityAssertionLines(options){const migrationHint=options.includeMigrationReplacementHint===true?[" // 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(options.itemTypeName)}, extensionName: ${JSON.stringify(options.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(options.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(options.fieldName)}, extensionName: ${JSON.stringify(options.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(options.migrationId)}, extensionName: ${JSON.stringify(options.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...migrationHint,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(options.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(options.migrationId)} });`]}function buildProfileCapabilityAssertionLines(extensionName){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(extensionName)}, extensionName: ${JSON.stringify(extensionName)} });`,` assert.equal(profile.title, ${JSON.stringify(`${extensionName} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}const SCAFFOLD_TSCONFIG={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:true,esModuleInterop:true,skipLibCheck:true,noEmit:true,allowImportingTsExtensions:true,resolveJsonModule:true,types:["node"]},include:["**/*.ts"]};const SCAFFOLD_CAPABILITIES=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"];const SCAFFOLD_MANIFEST_CAPABILITIES={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"]};const SAMPLE_TEST_CAPABILITIES_LITERAL={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"]'};const ENTRYPOINT_BULLETS={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."};const SAMPLE_TEST_BULLETS={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."};const TSCONFIG_BULLET="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.";const PACKAGE_CAPABILITY_README_SECTIONS={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."]};const LAZY_ACTIVATION_README_SECTION={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."]};const SCHEMA_ACTIVATION_README_SECTION={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`."]};const PROFILE_ACTIVATION_README_SECTION={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 buildScaffoldManifestBullet(capability,vocabulary){if(capability==="schema"){return`- \`manifest.json\`: ${vocabulary} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`}if(capability==="profile"){return`- \`manifest.json\`: ${vocabulary} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`}return`- \`manifest.json\`: ${vocabulary} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${vocabulary}).`}function buildScaffoldActivationReadmeSection(capability,vocabulary){if(capability==="schema"){return SCHEMA_ACTIVATION_README_SECTION[vocabulary]}if(capability==="profile"){return PROFILE_ACTIVATION_README_SECTION[vocabulary]}return LAZY_ACTIVATION_README_SECTION[vocabulary]}function buildScaffoldCommandName(extensionName){const commandWords=extensionName.replace(/-/g," ").trim().split(/\s+/).filter(word=>word.length>0);if(commandWords.length===0){return"starter ping"}const firstWordLower=commandWords[0].toLowerCase();let leadingStarterWords=0;while(commandWords[leadingStarterWords]?.toLowerCase()==="starter"){leadingStarterWords+=1}const nextStarterWord=commandWords[leadingStarterWords]?.toLowerCase();const starterRootCollision=leadingStarterWords>0&&(leadingStarterWords===commandWords.length||nextStarterWord!==void 0&&RESERVED_SCAFFOLD_COMMAND_ROOTS.has(nextStarterWord));const reservedRoot=RESERVED_SCAFFOLD_COMMAND_ROOTS.has(firstWordLower)||starterRootCollision;const resolvedWords=reservedRoot?["starter",...commandWords]:commandWords;return`${resolvedWords.join(" ")} ping`}function buildProfileArchetypeFieldLines(extensionName){const typeName=extensionName;const typeFolder=`${extensionName}s`;const typeAlias=extensionName.replace(/-/g,"");const typeAliases=typeAlias===typeName?[]:[typeAlias];const fieldKey=`${extensionName.replace(/-/g,"_")}_owner`;const statusId="reviewing";return[` name: ${JSON.stringify(extensionName)},`,` title: ${JSON.stringify(`${extensionName} 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(typeName)},`,` folder: ${JSON.stringify(typeFolder)},`,` aliases: ${JSON.stringify(typeAliases)},`,` description: ${JSON.stringify(`A ${extensionName} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(statusId)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(fieldKey)},`,' 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(typeName)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(statusId)}],`,` [${JSON.stringify(statusId)}, "in_progress"],`,` [${JSON.stringify(statusId)}, "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(extensionName)},`," options: {",` type: ${JSON.stringify(typeName)},`,' priority: "2",',` tags: ${JSON.stringify(extensionName)},`,' 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 buildActivateBodyLines(extensionName,commandName,capability){const searchProviderName=`${extensionName}-search`;const vectorAdapterName=`${extensionName}-vector`;const adapterName=`${extensionName.replace(/-/g," ")} items`;const commandLines=[" api.registerCommand({",` name: ${JSON.stringify(commandName)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(extensionName)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(capability==="commands"){return commandLines}if(capability==="search"){return[...commandLines,""," // 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(searchProviderName)},`," 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(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 }),"," });"]}if(capability==="schema"){const itemTypeName=extensionName;const itemTypeFolder=`${extensionName}s`;const itemTypeAlias=extensionName.replace(/-/g,"");const itemTypeAliases=itemTypeAlias===itemTypeName?[]:[itemTypeAlias];const fieldName=`${extensionName.replace(/-/g,"_")}_note`;const migrationId=`${extensionName}-0001-init`;return[...commandLines,""," // 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(fieldName)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(itemTypeName)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(itemTypeFolder)},`,` aliases: ${JSON.stringify(itemTypeAliases)},`," // 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(migrationId)},`,` description: ${JSON.stringify(`Initialize ${extensionName} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}if(capability==="profile"){return[...commandLines,""," // 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({",...buildProfileArchetypeFieldLines(extensionName).map(line=>` ${line}`)," });"]}if(capability==="importers"){return[...commandLines,""," // 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(adapterName)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${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(adapterName)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${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.",'," },"," ],"," },"," );"]}if(capability==="renderers"){return[...commandLines,""," // 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(`${extensionName}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(commandName)}] });`]}if(capability==="parser"){return[" api.registerCommand({",` name: ${JSON.stringify(commandName)},`,' 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(extensionName)},`," 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(commandName)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]}if(capability==="preflight"){return[...commandLines,""," // 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(commandName)}],`," run: (context) => context.decision,"," });"]}if(capability==="services"){return[...commandLines,""," // 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(commandName)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(extensionName)}, payload: context.payload };`," });"]}return[...commandLines,""," // 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 buildSampleTestSource(extensionName,commandName,capability){const hooksEnabled=capability==="hooks";const searchEnabled=capability==="search";const importersEnabled=capability==="importers";const schemaEnabled=capability==="schema";const profileEnabled=capability==="profile";const renderersEnabled=capability==="renderers";const parserEnabled=capability==="parser";const preflightEnabled=capability==="preflight";const servicesEnabled=capability==="services";const capabilitiesLiteral=SAMPLE_TEST_CAPABILITIES_LITERAL[capability];const itemTypeName=extensionName;const itemTypeFolder=`${extensionName}s`;const fieldName=`${extensionName.replace(/-/g,"_")}_note`;const migrationId=`${extensionName}-0001-init`;const importNames=[" assertExtensionDeactivated,"," createExtensionTestHarness,"];const hookTestLines=hooksEnabled?[`test(${JSON.stringify(`${extensionName} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(extensionName)},`,` capabilities: ${capabilitiesLiteral},`," });"," 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(extensionName)},`," });"," // 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(commandName)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...SAMPLE_HARNESS_FINALLY_LINES,"});",""]:[];const searchTestLines=searchEnabled?buildDeclarativeCapabilityTestBlock(extensionName,commandName,"search",capabilitiesLiteral):[];const importerTestLines=importersEnabled?buildDeclarativeCapabilityTestBlock(extensionName,commandName,"importers",capabilitiesLiteral):[];const schemaTestLines=schemaEnabled?[`test(${JSON.stringify(`${extensionName} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(extensionName)},`,` capabilities: ${capabilitiesLiteral},`," });"," let deactivated = false;"," try {",...indentGeneratedLines(buildSchemaCapabilityAssertionLines({extensionName,itemTypeName,itemTypeFolder,fieldName,migrationId,includeMigrationReplacementHint:true})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...SAMPLE_HARNESS_FINALLY_LINES,"});",""]:[];const profileTestLines=profileEnabled?[`test(${JSON.stringify(`${extensionName} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(extensionName)},`,` capabilities: ${capabilitiesLiteral},`," });"," let deactivated = false;"," try {",...indentGeneratedLines(buildProfileCapabilityAssertionLines(extensionName)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...SAMPLE_HARNESS_FINALLY_LINES,"});",""]:[];const rendererTestLines=renderersEnabled?[`test(${JSON.stringify(`${extensionName} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(extensionName)},`,` capabilities: ${capabilitiesLiteral},`," });"," 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(extensionName)} });`,' 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(commandName)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${extensionName}: `)} + 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;",...SAMPLE_HARNESS_FINALLY_LINES,"});",""]:[];const parserTestLines=parserEnabled?[`test(${JSON.stringify(`${extensionName} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(extensionName)},`,` capabilities: ${capabilitiesLiteral},`," });"," 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(commandName)}, extensionName: ${JSON.stringify(extensionName)} });`,""," // 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(commandName)},`," 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(commandName)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(extensionName)},`,` command: ${JSON.stringify(commandName)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...SAMPLE_HARNESS_FINALLY_LINES,"});",""]:[];const preflightTestLines=preflightEnabled?[`test(${JSON.stringify(`${extensionName} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(extensionName)},`,` capabilities: ${capabilitiesLiteral},`," });"," 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(extensionName)} });`,""," // 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(commandName)},`," 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;",...SAMPLE_HARNESS_FINALLY_LINES,"});",""]:[];const serviceTestLines=servicesEnabled?[`test(${JSON.stringify(`${extensionName} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(extensionName)},`,` capabilities: ${capabilitiesLiteral},`," });"," 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(extensionName)} });`,""," // 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(commandName)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(extensionName)}, 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;",...SAMPLE_HARNESS_FINALLY_LINES,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...importNames,'} from "@unbrained/pm-cli/sdk/testing";',...searchEnabled?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...SAMPLE_HARNESS_CLEANUP_LINES,`test(${JSON.stringify(`${extensionName} 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(extensionName)},`,` capabilities: ${capabilitiesLiteral},`," });"," 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(commandName)},`,` extensionName: ${JSON.stringify(extensionName)},`," });",' 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(commandName)},`," });"," 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(extensionName)},`,` command: ${JSON.stringify(commandName)},`,...parserEnabled?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...SAMPLE_HARNESS_FINALLY_LINES,"});","",...hookTestLines,...searchTestLines,...importerTestLines,...schemaTestLines,...profileTestLines,...rendererTestLines,...parserTestLines,...preflightTestLines,...serviceTestLines,`test(${JSON.stringify(`${extensionName} 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(extensionName)},`,` capabilities: ${capabilitiesLiteral},`," });"," 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("\n")}function buildScaffoldActivationCommands(extensionName,commandName,capability){if(capability==="schema"||capability==="profile"){return[]}if(capability==="importers"){const adapterName=`${extensionName.replace(/-/g," ")} items`;return[commandName,`${adapterName} import`,`${adapterName} export`]}return[commandName]}const DECLARATIVE_ENTRYPOINT_SURFACE_PHRASE={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"};const DECLARATIVE_CAPABILITY_BLUEPRINT_FIELDS={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 buildDeclarativePingCommandLines(extensionName,commandName,capability){const parserEnabled=capability==="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(commandName)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...parserEnabled?[" 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(extensionName)},`," command: context.command,",...parserEnabled?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function buildDeclarativeBlueprintSurface(extensionName,commandName,capability){const builderImports=[];const definitions=[...buildDeclarativePingCommandLines(extensionName,commandName,capability)];const blueprintFields=[" commands: [pingCommand],"];const searchProviderName=`${extensionName}-search`;const vectorAdapterName=`${extensionName}-vector`;const adapterName=`${extensionName.replace(/-/g," ")} items`;const itemTypeName=extensionName;const itemTypeFolder=`${extensionName}s`;const itemTypeAlias=extensionName.replace(/-/g,"");const itemTypeAliases=itemTypeAlias===itemTypeName?[]:[itemTypeAlias];const fieldName=`${extensionName.replace(/-/g,"_")}_note`;const migrationId=`${extensionName}-0001-init`;switch(capability){case"commands":break;case"hooks":builderImports.push("defineAfterCommandHook");definitions.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... */ }","});");blueprintFields.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":builderImports.push("defineSearchProvider","defineVectorStoreAdapter");definitions.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(searchProviderName)},`," 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(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 }),","});");blueprintFields.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":builderImports.push("defineExporter","defineImporter");definitions.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,","}));");blueprintFields.push(" importers: ["," {",` name: ${JSON.stringify(adapterName)},`," importer,"," options: {",` action: ${JSON.stringify(`${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.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(adapterName)},`," exporter,"," options: {",` action: ${JSON.stringify(`${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.",'," },"," ],"," },"," },"," ],");break;case"schema":builderImports.push("defineItemField","defineItemType","defineMigration");definitions.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(fieldName)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(itemTypeName)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(itemTypeFolder)},`,` aliases: ${JSON.stringify(itemTypeAliases)},`," // 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(migrationId)},`,` description: ${JSON.stringify(`Initialize ${extensionName} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});");blueprintFields.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":builderImports.push("defineProjectProfile");definitions.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({",...buildProfileArchetypeFieldLines(extensionName),"});");blueprintFields.push(" profiles: [starterProfile],");break;case"renderers":builderImports.push("defineRendererOverride");definitions.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(commandName)}],`," run: (context) => {",` return ${JSON.stringify(`${extensionName}: `)} + JSON.stringify(context.result);`," },","});");blueprintFields.push(" renderers: { toon: toonRenderer },");break;case"parser":builderImports.push("defineParserOverride");definitions.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 };","});");blueprintFields.push(` parsers: { ${JSON.stringify(commandName)}: pingParser },`);break;case"preflight":builderImports.push("definePreflightOverride");definitions.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(commandName)}],`," run: (context) => context.decision,","});");blueprintFields.push(" preflights: [preflightOverride],");break;case"services":builderImports.push("defineServiceOverride");definitions.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(commandName)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(extensionName)}, payload: context.payload };`,"});");blueprintFields.push(" services: { output_format: outputService },");break}return{builderImports,definitions,blueprintFields}}function buildDeclarativeEntrypoint(extensionName,commandName,capability){const surface=buildDeclarativeBlueprintSurface(extensionName,commandName,capability);const builderImports=["composeExtension","defineCommand","defineExtensionBlueprint",...surface.builderImports].sort((left,right)=>left.localeCompare(right));return[`import { ${builderImports.join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...surface.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({",...surface.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("\n")}function buildDeclarativeCapabilityTestBlock(extensionName,commandName,capability,capabilitiesLiteral){if(capability==="commands"){return[]}const searchProviderName=`${extensionName}-search`;const vectorAdapterName=`${extensionName}-vector`;const adapterName=`${extensionName.replace(/-/g," ")} items`;const itemTypeName=extensionName;const itemTypeFolder=`${extensionName}s`;const fieldName=`${extensionName.replace(/-/g,"_")}_note`;const migrationId=`${extensionName}-0001-init`;const harness=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(extensionName)},`,` capabilities: ${capabilitiesLiteral},`," });"];const withHarnessCleanup=body=>[...harness," let deactivated = false;"," try {",...body.map(line=>line===""?line:` ${line}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...SAMPLE_HARNESS_FINALLY_LINES];switch(capability){case"hooks":return[`test(${JSON.stringify(`${extensionName} reacts to commands via its after_command hook`)}, async () => {`,...withHarnessCleanup([" // 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(extensionName)} });`," // 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(commandName)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${extensionName} registers and invokes search primitives`)}, async () => {`,...withHarnessCleanup([` ext.assertSearchProvider({ name: ${JSON.stringify(searchProviderName)}, extensionName: ${JSON.stringify(extensionName)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(vectorAdapterName)}, extensionName: ${JSON.stringify(extensionName)} });`,""," // 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(searchProviderName)},`,' 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(searchProviderName)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(vectorAdapterName)},`,' 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(`${extensionName} registers and invokes import/export primitives`)}, async () => {`,...withHarnessCleanup([` ext.assertImporter({ name: ${JSON.stringify(adapterName)}, extensionName: ${JSON.stringify(extensionName)} });`,` ext.assertExporter({ name: ${JSON.stringify(adapterName)}, extensionName: ${JSON.stringify(extensionName)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(adapterName)},`,' 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(adapterName)},`,' 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(`${extensionName} registers and runs its custom schema`)}, async () => {`,...withHarnessCleanup(buildSchemaCapabilityAssertionLines({extensionName,itemTypeName,itemTypeFolder,fieldName,migrationId})),"});",""];case"profile":return[`test(${JSON.stringify(`${extensionName} registers its project profile`)}, async () => {`,...withHarnessCleanup(buildProfileCapabilityAssertionLines(extensionName)),"});",""];case"renderers":return[`test(${JSON.stringify(`${extensionName} registers and invokes its renderer override`)}, async () => {`,...withHarnessCleanup([" // 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(extensionName)} });`,' 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(commandName)},`," 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(`${extensionName} rewrites command options via its parser override`)}, async () => {`,...withHarnessCleanup([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(commandName)}, extensionName: ${JSON.stringify(extensionName)} });`,""," // 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(commandName)},`," 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(commandName)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(extensionName)},`,` command: ${JSON.stringify(commandName)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${extensionName} returns a preflight gate decision via its override`)}, async () => {`,...withHarnessCleanup([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(extensionName)} });`,""," // 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(commandName)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${extensionName} customizes command output via its service override`)}, async () => {`,...withHarnessCleanup([" // 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(extensionName)} });`,""," // 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(commandName)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(extensionName)}, 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 buildDeclarativeSampleTestSource(extensionName,commandName,capability){const parserEnabled=capability==="parser";const capabilitiesLiteral=JSON.stringify([...SCAFFOLD_MANIFEST_CAPABILITIES[capability]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...capability==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...SAMPLE_HARNESS_CLEANUP_LINES,`test(${JSON.stringify(`${extensionName} 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(extensionName)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(SCAFFOLD_PM_MIN_VERSION)},`," },",` target: { pmVersion: ${JSON.stringify(SCAFFOLD_PM_MIN_VERSION)} },`," });"," // 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, ${capabilitiesLiteral});`,` assert.deepEqual(report.manifest?.capabilities, ${capabilitiesLiteral});`,"});","",`test(${JSON.stringify(`${extensionName} 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(extensionName)},`,` capabilities: ${capabilitiesLiteral},`," });"," 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(commandName)} });`,' 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(commandName)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(extensionName)},`,` command: ${JSON.stringify(commandName)},`,...parserEnabled?[" 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;",...SAMPLE_HARNESS_FINALLY_LINES,"});","",...buildDeclarativeCapabilityTestBlock(extensionName,commandName,capability,capabilitiesLiteral)].join("\n")}function buildDeclarativePackageReadme(packageName,commandName,capability){const manifestBullet=buildScaffoldManifestBullet(capability,"package");const activationSection=buildScaffoldActivationReadmeSection(capability,"package");return[`# ${packageName}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",manifestBullet,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${DECLARATIVE_ENTRYPOINT_SURFACE_PHRASE[capability]}) 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`.",TSCONFIG_BULLET,"- `.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 ${commandName}`,"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 ${DECLARATIVE_CAPABILITY_BLUEPRINT_FIELDS[capability]}. 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.",...activationSection,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${SCAFFOLD_MANIFEST_VERSION}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${SCAFFOLD_PM_MIN_VERSION}\`. 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("\n")}function buildScaffoldSnippetNames(extensionName){const itemTypeName=extensionName;const itemTypeAlias=extensionName.replace(/-/g,"");return{searchProviderName:`${extensionName}-search`,vectorAdapterName:`${extensionName}-vector`,adapterName:`${extensionName.replace(/-/g," ")} items`,itemTypeName,itemTypeFolder:`${extensionName}s`,itemTypeAliases:itemTypeAlias===itemTypeName?[]:[itemTypeAlias],fieldName:`${extensionName.replace(/-/g,"_")}_note`,migrationId:`${extensionName}-0001-init`}}function buildDefineBuilderImports(capability){return["defineCommand",...capability==="hooks"?["defineAfterCommandHook"]:[],...capability==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...capability==="importers"?["defineImporter","defineExporter"]:[],...capability==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...capability==="profile"?["defineProjectProfile"]:[],...capability==="renderers"?["defineRendererOverride"]:[],...capability==="parser"?["defineParserOverride"]:[],...capability==="preflight"?["definePreflightOverride"]:[],...capability==="services"?["defineServiceOverride"]:[]].join(", ")}function buildDefineBuilderExports(extensionName,commandName,capability,names){const lines=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(commandName)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...capability==="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 }),"],"});"];if(capability==="hooks"){lines.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});")}if(capability==="search"){lines.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(names.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(names.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 }),","});")}if(capability==="importers"){lines.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,","}));")}if(capability==="schema"){lines.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(names.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(names.itemTypeName)},`,` folder: ${JSON.stringify(names.itemTypeFolder)},`,` aliases: ${JSON.stringify(names.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(names.migrationId)},`,` description: ${JSON.stringify(`Initialize ${extensionName} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});")}if(capability==="profile"){lines.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(extensionName)},`,` title: ${JSON.stringify(`${extensionName} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(names.itemTypeName)}, folder: ${JSON.stringify(names.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});")}if(capability==="renderers"){lines.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(commandName)}],`," run: (context) => JSON.stringify(context.result),","});")}if(capability==="parser"){lines.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});")}if(capability==="preflight"){lines.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(commandName)}],`," run: (context) => context.decision,","});")}if(capability==="services"){lines.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(commandName)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(extensionName)}, payload: context.payload };`,"});")}return lines}function buildDefineBuilderActivate(commandName,capability,names){const lines=[];if(capability==="renderers"){lines.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);')}if(capability==="parser"){lines.push(` api.registerParser(${JSON.stringify(commandName)}, pingParser);`)}if(capability==="preflight"){lines.push(" api.registerPreflight(preflightOverride);")}if(capability==="services"){lines.push(' api.registerService("output_format", outputService);')}if(capability==="hooks"){lines.push(" api.hooks.afterCommand(afterCommandHook);")}if(capability==="search"){lines.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);")}if(capability==="schema"){lines.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);")}if(capability==="profile"){lines.push(" api.registerProfile(starterProfile);")}if(capability==="importers"){lines.push(` api.registerImporter(${JSON.stringify(names.adapterName)}, importer, {`,` action: ${JSON.stringify(`${names.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(names.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${names.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.",'," },"," ],"," });")}return lines}function buildStarterExtensionScaffoldFiles(extensionName,commandName,_vocabulary,capability="commands",declarative=false){const packageName=`pm-${extensionName}`;const capabilities=SCAFFOLD_MANIFEST_CAPABILITIES[capability];const activationCommands=buildScaffoldActivationCommands(extensionName,commandName,capability);const manifest=`${JSON.stringify({name:extensionName,version:"0.1.0",entry:"./index.ts",manifest_version:SCAFFOLD_MANIFEST_VERSION,pm_min_version:SCAFFOLD_PM_MIN_VERSION,trusted:true,sandbox_profile:"strict",permissions:{...SCAFFOLD_DECLARED_PERMISSIONS},capabilities,...activationCommands.length>0?{activation:{commands:activationCommands}}:{}},null,2)}
2
+ `;const entrypoint=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...buildActivateBodyLines(extensionName,commandName,capability),"}","","// `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("\n");const tsconfig=`${JSON.stringify(SCAFFOLD_TSCONFIG,null,2)}
3
+ `;const entrypointBullet=ENTRYPOINT_BULLETS[capability];const manifestBullet=buildScaffoldManifestBullet(capability,"package");const packageJson=`${JSON.stringify({name:packageName,version:"0.1.0",private:true,type:"module",keywords:["pm-package"],engines:{node:SCAFFOLD_NODE_ENGINE},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${SCAFFOLD_PM_MIN_VERSION}`},devDependencies:{"@types/node":SCAFFOLD_TYPES_NODE_VERSION,typescript:SCAFFOLD_TYPESCRIPT_VERSION},pm:{aliases:[extensionName],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:extensionName,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
4
+ `;const sampleTest=buildSampleTestSource(extensionName,commandName,capability);const sampleTestBullet=SAMPLE_TEST_BULLETS[capability];const gitignore=["node_modules/","*.log","*.tsbuildinfo",""].join("\n");const names=buildScaffoldSnippetNames(extensionName);const defineBuilderImports=buildDefineBuilderImports(capability);const defineBuilderSnippet=["```ts",`import { ${defineBuilderImports} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...buildDefineBuilderExports(extensionName,commandName,capability,names),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...buildDefineBuilderActivate(commandName,capability,names),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"];const packageReadme=[`# ${packageName}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",manifestBullet,entrypointBullet,sampleTestBullet,TSCONFIG_BULLET,"- `.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 ${commandName}`,"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:",...defineBuilderSnippet,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...PACKAGE_CAPABILITY_README_SECTIONS[capability],...buildScaffoldActivationReadmeSection(capability,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${SCAFFOLD_PM_MIN_VERSION}\`. 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 \`${SCAFFOLD_MANIFEST_VERSION}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${SCAFFOLD_PM_MIN_VERSION}\`. 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("\n");return{"package.json":packageJson,"manifest.json":manifest,"index.ts":declarative?buildDeclarativeEntrypoint(extensionName,commandName,capability):entrypoint,"index.test.ts":declarative?buildDeclarativeSampleTestSource(extensionName,commandName,capability):sampleTest,"tsconfig.json":tsconfig,".gitignore":gitignore,"README.md":declarative?buildDeclarativePackageReadme(packageName,commandName,capability):packageReadme}}async function scaffoldExtensionProject(target,vocabulary="extension",capability="commands",declarative=false){const normalizedCapability=capability.trim().toLowerCase();if(!SCAFFOLD_CAPABILITIES.includes(normalizedCapability)){throw new PmCliError(`Unknown scaffold capability "${capability}". Supported capabilities: ${SCAFFOLD_CAPABILITIES.join(", ")}.`,EXIT_CODE.USAGE)}const resolvedCapability=normalizedCapability;if(declarative&&vocabulary!=="package"){throw new PmCliError("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",EXIT_CODE.USAGE)}const style=declarative?"declarative":"imperative";const normalizedTarget=target.trim();const targetPath=path.resolve(process.cwd(),normalizedTarget);const extensionName=normalizeManagedDirectoryName(path.basename(targetPath)).replace(/^(?:pm-)+/u,"");const commandName=buildScaffoldCommandName(extensionName);const scaffoldFiles=buildStarterExtensionScaffoldFiles(extensionName,commandName,vocabulary,resolvedCapability,declarative);let createdDirectory=false;if(await pathExists(targetPath)){const existingTargetStats=await fs.stat(targetPath);if(!existingTargetStats.isDirectory()){throw new PmCliError(`Scaffold target "${targetPath}" exists and is not a directory.`,EXIT_CODE.CONFLICT)}}else{await fs.mkdir(targetPath,{recursive:true});createdDirectory=true}for(const[relativePath,content]of Object.entries(scaffoldFiles)){const absolutePath=path.join(targetPath,relativePath);if(!await pathExists(absolutePath)){continue}const existingContent=await fs.readFile(absolutePath,"utf8");if(existingContent!==content){throw new PmCliError(`Scaffold file "${relativePath}" already exists with different content in "${targetPath}". Choose a new target path or remove conflicting files.`,EXIT_CODE.CONFLICT)}}const files=[];for(const[relativePath,content]of Object.entries(scaffoldFiles)){const absolutePath=path.join(targetPath,relativePath);if(await pathExists(absolutePath)){files.push({path:relativePath,status:"unchanged"});continue}await fs.mkdir(path.dirname(absolutePath),{recursive:true});await fs.writeFile(absolutePath,content,"utf8");files.push({path:relativePath,status:"created"})}return{extension_name:extensionName,package_name:`pm-${extensionName}`,command_name:commandName,invocation_command:`pm ${commandName}`,capability:resolvedCapability,style,target_path:targetPath,created_directory:createdDirectory,files}}export{SCAFFOLD_CAPABILITIES,SCAFFOLD_PM_MIN_VERSION,buildScaffoldCommandName,buildStarterExtensionScaffoldFiles,scaffoldExtensionProject};
2308
5
  //# sourceMappingURL=scaffold.js.map
2309
- //# debugId=5321d574-4de4-5f94-99db-0c49639673fc