@unbrained/pm-cli 2026.11.7 → 2026.11.9

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 (259) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +84 -48
  3. package/dist/cli/extension-command-help.js +4 -3
  4. package/dist/cli/help-json-payload.js +1 -1
  5. package/dist/cli/main.js +1 -1
  6. package/dist/cli/register-annotations.js +1 -1
  7. package/dist/cli/register-list-query.js +5 -5
  8. package/dist/cli/runtime/annotation-option-retry.js +2 -0
  9. package/dist/cli/runtime/invocation-options.js +1 -1
  10. package/dist/cli/runtime/projection-retry.js +1 -1
  11. package/dist/cli/runtime/read-output-mutation-retry.js +2 -0
  12. package/dist/cli-bundle/bundle-manifest.json +1 -1
  13. package/dist/cli-bundle/chunks/chunk-3BMIAI4P.js +8 -0
  14. package/dist/cli-bundle/chunks/chunk-5VRJPPUC.js +2 -0
  15. package/dist/cli-bundle/chunks/{chunk-WXVMPLBY.js → chunk-6V4PGJBZ.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-F3B2ULHB.js → chunk-ASJZMYKM.js} +33 -33
  17. package/dist/cli-bundle/chunks/chunk-BLUCQ4T4.js +2 -0
  18. package/dist/cli-bundle/chunks/chunk-ELNWRSGZ.js +9 -0
  19. package/dist/cli-bundle/chunks/{chunk-RFI4O6NU.js → chunk-EZRLW4R6.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-OJZG7Y6S.js → chunk-G6Q4VQSI.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-GCPP37N6.js +116 -0
  22. package/dist/cli-bundle/chunks/{chunk-OIBSKKCO.js → chunk-GDQ2T2OR.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-KPAVZILX.js → chunk-GZVOOHTO.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-3DI6CEF3.js → chunk-IGT252ES.js} +2 -2
  25. package/dist/cli-bundle/chunks/chunk-JK7O7MFO.js +31 -0
  26. package/dist/cli-bundle/chunks/{chunk-MQOZNGPS.js → chunk-JYQXIC6C.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-XSEDESNW.js → chunk-LVDFPGD7.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-QG6FLDM4.js → chunk-MSJ7IHMJ.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-BQ5O3CBF.js → chunk-O2M3TNFY.js} +69 -65
  30. package/dist/cli-bundle/chunks/chunk-UFIM5ZC5.js +6 -0
  31. package/dist/cli-bundle/chunks/chunk-VATZTJE3.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-WS2N4TQW.js → chunk-XKY4LUXN.js} +2 -2
  33. package/dist/cli-bundle/chunks/{chunk-VM6OGNQC.js → chunk-YK5GAWOT.js} +2 -2
  34. package/dist/cli-bundle/chunks/{chunk-TGQPCNAD.js → chunk-YV5ALMG2.js} +2 -2
  35. package/dist/cli-bundle/chunks/{chunk-ETHAZC3F.js → chunk-Z3QEEOAM.js} +2 -2
  36. package/dist/cli-bundle/chunks/item-revision-Y5CE3EIN.js +2 -0
  37. package/dist/cli-bundle/chunks/item-transaction-XBIN4KYM.js +2 -0
  38. package/dist/cli-bundle/chunks/{mutation-admission-LUXUKISJ.js → mutation-admission-TAQN2AKK.js} +2 -2
  39. package/dist/cli-bundle/chunks/register-list-query-XMQYFUFI.js +11 -0
  40. package/dist/cli-bundle/chunks/register-mutation-OBVCFLDK.js +20 -0
  41. package/dist/cli-bundle/chunks/{register-operations-AHDWE2G3.js → register-operations-CGNFZ6DR.js} +2 -2
  42. package/dist/cli-bundle/chunks/{register-setup-7BGG3CI3.js → register-setup-LFB5ERXH.js} +2 -2
  43. package/dist/cli-bundle/chunks/{stage-S5BYWLGY.js → stage-NQHF6JPC.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-2SQUWQP3.js +26 -0
  45. package/dist/cli-bundle/focused-chunks/chunk-4FWMXQN3.js +12 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-AH5IST3V.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/{chunk-4EXRRSDS.js → chunk-ALLOWZSH.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-IYJRFJHT.js → chunk-C3DO4ZGZ.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-CUGJ2DY2.js +24 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-HLQOGAWG.js +26 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-HNFY3XLC.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-IB6TCE7N.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-LW4TN5ZM.js → chunk-IS5FLEZW.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-J7PWHKZK.js +91 -0
  55. package/dist/cli-bundle/focused-chunks/chunk-JU62TKJP.js +82 -0
  56. package/dist/cli-bundle/focused-chunks/chunk-LDMBNTOG.js +2 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-LWMPQRJT.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-MYBKRV5R.js +2 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-NUFO3OR6.js +44 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-NZQYHPUN.js +3 -0
  61. package/dist/cli-bundle/focused-chunks/{chunk-JRJOFMI7.js → chunk-Q45LDP7P.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/chunk-QWUWNFQO.js +2 -0
  63. package/dist/cli-bundle/focused-chunks/chunk-RNZUORGI.js +2 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-G2VIY6XA.js → chunk-UIKLNSW3.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-BIDF4KO7.js → chunk-XLSTFUXM.js} +8 -8
  66. package/dist/cli-bundle/focused-chunks/item-revision-M6FOLME2.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/item-transaction-H6VA5JGB.js +2 -0
  68. package/dist/cli-bundle/focused-chunks/mutation-admission-PRTQWQK6.js +2 -0
  69. package/dist/cli-bundle/focused-chunks/stage-7T77PSJD.js +2 -0
  70. package/dist/cli-bundle/main.js +32 -31
  71. package/dist/cli-bundle/sdk-authoring.js +1 -1
  72. package/dist/cli-bundle/sdk-contracts.js +4 -4
  73. package/dist/cli-bundle/sdk-core.js +1 -1
  74. package/dist/cli-bundle/sdk-governance.js +1 -1
  75. package/dist/cli-bundle/sdk-graph.js +1 -1
  76. package/dist/cli-bundle/sdk-merge.js +57 -57
  77. package/dist/cli-bundle/sdk-query.js +1 -1
  78. package/dist/cli-bundle/sdk-runtime.js +1 -1
  79. package/dist/cli-bundle/sdk-testing.js +1 -1
  80. package/dist/cli-bundle/sdk.js +12 -12
  81. package/dist/core/extensions/flag-definition-validation.js +1 -1
  82. package/dist/core/extensions/reserved-host-flags.js +1 -1
  83. package/dist/core/history/history-stream-policy.d.ts +12 -3
  84. package/dist/core/history/history-stream-policy.js +1 -1
  85. package/dist/core/history/projection.d.ts +7 -2
  86. package/dist/core/history/projection.js +1 -1
  87. package/dist/core/item/item-format.d.ts +13 -1
  88. package/dist/core/item/item-format.js +2 -2
  89. package/dist/core/lock/lock.d.ts +1 -1
  90. package/dist/core/lock/lock.js +1 -1
  91. package/dist/core/output/output.d.ts +17 -1
  92. package/dist/core/output/output.js +7 -7
  93. package/dist/core/search/corpus.js +1 -1
  94. package/dist/core/search/providers.d.ts +3 -2
  95. package/dist/core/search/providers.js +1 -1
  96. package/dist/core/search/vector-stores.d.ts +3 -2
  97. package/dist/core/search/vector-stores.js +1 -1
  98. package/dist/core/sentry/instrument.d.ts +2 -1
  99. package/dist/core/sentry/instrument.js +1 -1
  100. package/dist/mcp/tool-definitions.js +1 -1
  101. package/dist/sdk/annotations.d.ts +44 -1
  102. package/dist/sdk/annotations.js +1 -1
  103. package/dist/sdk/authoring.d.ts +6 -0
  104. package/dist/sdk/authoring.js +1 -1
  105. package/dist/sdk/cli-contracts/flag-contracts.d.ts +15 -0
  106. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  107. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  108. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +6 -0
  109. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  110. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  111. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  112. package/dist/sdk/command-line.d.ts +2 -1
  113. package/dist/sdk/command-line.js +1 -1
  114. package/dist/sdk/comments.d.ts +4 -2
  115. package/dist/sdk/comments.js +1 -1
  116. package/dist/sdk/completion/bash.js +1 -1
  117. package/dist/sdk/completion/fish.js +2 -1
  118. package/dist/sdk/completion/zsh.js +4 -1
  119. package/dist/sdk/context-intent-contracts.d.ts +5 -1
  120. package/dist/sdk/context-intent-contracts.js +1 -1
  121. package/dist/sdk/contracts.d.ts +3 -0
  122. package/dist/sdk/contracts.js +1 -1
  123. package/dist/sdk/core.d.ts +14 -0
  124. package/dist/sdk/core.js +1 -1
  125. package/dist/sdk/corpus-shape.d.ts +2 -2
  126. package/dist/sdk/corpus-shape.js +1 -1
  127. package/dist/sdk/define.d.ts +14 -8
  128. package/dist/sdk/define.js +1 -1
  129. package/dist/sdk/extension/command-options.d.ts +123 -0
  130. package/dist/sdk/extension/command-options.js +2 -0
  131. package/dist/sdk/extension-contracts.d.ts +1 -2
  132. package/dist/sdk/extension-contracts.js +1 -1
  133. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  134. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  135. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  136. package/dist/sdk/governance.d.ts +8 -0
  137. package/dist/sdk/governance.js +1 -1
  138. package/dist/sdk/graph.d.ts +5 -0
  139. package/dist/sdk/graph.js +1 -1
  140. package/dist/sdk/index.d.ts +61 -1
  141. package/dist/sdk/index.js +1 -1
  142. package/dist/sdk/learnings.d.ts +4 -2
  143. package/dist/sdk/learnings.js +1 -1
  144. package/dist/sdk/lifecycle/item-revision.d.ts +6 -0
  145. package/dist/sdk/lifecycle/item-revision.js +1 -1
  146. package/dist/sdk/lifecycle/restore.d.ts +1 -1
  147. package/dist/sdk/merge.d.ts +3 -0
  148. package/dist/sdk/merge.js +1 -1
  149. package/dist/sdk/notes.d.ts +4 -2
  150. package/dist/sdk/notes.js +1 -1
  151. package/dist/sdk/public-surface.json +1 -1
  152. package/dist/sdk/query/get-facet-roots.js +2 -0
  153. package/dist/sdk/query/get.js +1 -1
  154. package/dist/sdk/query/list.d.ts +5 -1
  155. package/dist/sdk/query/list.js +1 -1
  156. package/dist/sdk/query/search/semantic.d.ts +11 -3
  157. package/dist/sdk/query/search/semantic.js +1 -1
  158. package/dist/sdk/query/search-rendering.d.ts +9 -3
  159. package/dist/sdk/query/search-rendering.js +1 -1
  160. package/dist/sdk/query.d.ts +11 -0
  161. package/dist/sdk/query.js +1 -1
  162. package/dist/sdk/read-output/continuation.d.ts +8 -0
  163. package/dist/sdk/read-output/continuation.js +1 -1
  164. package/dist/sdk/read-output/options.d.ts +1 -1
  165. package/dist/sdk/read-output/options.js +1 -1
  166. package/dist/sdk/read-output/positional-rows.js +2 -0
  167. package/dist/sdk/read-output/surfaces.js +1 -1
  168. package/dist/sdk/read-output/tail-retention.d.ts +34 -0
  169. package/dist/sdk/read-output/tail-retention.js +2 -0
  170. package/dist/sdk/read-output-budget.d.ts +14 -2
  171. package/dist/sdk/read-output-budget.js +1 -1
  172. package/dist/sdk/read-output-contracts.d.ts +24 -4
  173. package/dist/sdk/read-output-contracts.js +1 -1
  174. package/dist/sdk/read-output-rows.d.ts +7 -3
  175. package/dist/sdk/read-output-rows.js +1 -1
  176. package/dist/sdk/runtime/actions.js +1 -1
  177. package/dist/sdk/runtime-input.js +1 -1
  178. package/dist/sdk/runtime.d.ts +26 -3
  179. package/dist/sdk/runtime.js +1 -1
  180. package/dist/sdk/test/execution.d.ts +29 -2
  181. package/dist/sdk/test/execution.js +1 -1
  182. package/dist/sdk/testing.d.ts +14 -1
  183. package/dist/sdk/testing.js +1 -1
  184. package/dist/sdk/traceability/source-traceability.d.ts +4 -1
  185. package/dist/sdk/traceability/source-traceability.js +1 -1
  186. package/dist/sdk/workspace-recipe.d.ts +2 -2
  187. package/dist/sdk/workspace-recipe.js +1 -1
  188. package/docs/AGENT_OUTPUT_ENCODINGS.md +16 -0
  189. package/docs/ARCHITECTURE.md +2 -1
  190. package/docs/COMMANDS.md +4 -1
  191. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +1 -1
  192. package/docs/EXTENSIONS.md +1 -1
  193. package/docs/MCP_OPTION_CONFORMANCE.md +13 -0
  194. package/docs/README.md +2 -2
  195. package/docs/READ_OUTPUT_CONTRACTS.md +99 -0
  196. package/docs/RELEASING.md +27 -5
  197. package/docs/SDK.md +100 -2
  198. package/docs/SDK_CONTEXT_INTEGRITY.md +2 -0
  199. package/docs/agent-task-token-baseline.json +1 -1
  200. package/docs/generated/FLAG_LEXICON_BUDGETS.md +6 -6
  201. package/marketplace.json +1 -1
  202. package/package.json +3 -1
  203. package/packages/pm-beads/package.json +1 -1
  204. package/packages/pm-calendar/package.json +1 -1
  205. package/packages/pm-command-kit/package.json +1 -1
  206. package/packages/pm-digital-twin/package.json +1 -1
  207. package/packages/pm-governance-audit/package.json +1 -1
  208. package/packages/pm-guide-shell/package.json +1 -1
  209. package/packages/pm-kanban/package.json +1 -1
  210. package/packages/pm-lifecycle-hooks/package.json +1 -1
  211. package/packages/pm-linked-test-adapters/package.json +1 -1
  212. package/packages/pm-search-advanced/package.json +1 -1
  213. package/packages/pm-templates/package.json +1 -1
  214. package/packages/pm-todos/package.json +1 -1
  215. package/packages/pm-vcs/package.json +1 -1
  216. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  217. package/plugins/pm-claude/package.json +1 -1
  218. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  219. package/plugins/pm-codex/package.json +1 -1
  220. package/plugins/pm-codex/plugin.json +1 -1
  221. package/runtime-dependencies.json +1 -1
  222. package/dist/cli/extension-command-options.js +0 -2
  223. package/dist/cli-bundle/chunks/chunk-4PPWVIIT.js +0 -2
  224. package/dist/cli-bundle/chunks/chunk-5KHLV7JU.js +0 -116
  225. package/dist/cli-bundle/chunks/chunk-COKKWMSC.js +0 -8
  226. package/dist/cli-bundle/chunks/chunk-D53G3NOE.js +0 -6
  227. package/dist/cli-bundle/chunks/chunk-JZWFZH2K.js +0 -2
  228. package/dist/cli-bundle/chunks/chunk-O6TIOKCM.js +0 -9
  229. package/dist/cli-bundle/chunks/chunk-WYIDX67P.js +0 -31
  230. package/dist/cli-bundle/chunks/item-revision-SPEKTFBB.js +0 -2
  231. package/dist/cli-bundle/chunks/item-transaction-BT55TQXE.js +0 -2
  232. package/dist/cli-bundle/chunks/register-list-query-DU4W7VJU.js +0 -11
  233. package/dist/cli-bundle/chunks/register-mutation-IC2C53QK.js +0 -20
  234. package/dist/cli-bundle/focused-chunks/chunk-4LDOL6U7.js +0 -26
  235. package/dist/cli-bundle/focused-chunks/chunk-4PW5XWVI.js +0 -2
  236. package/dist/cli-bundle/focused-chunks/chunk-A46YSPRF.js +0 -2
  237. package/dist/cli-bundle/focused-chunks/chunk-AI2PYNFI.js +0 -2
  238. package/dist/cli-bundle/focused-chunks/chunk-AJ2I377F.js +0 -44
  239. package/dist/cli-bundle/focused-chunks/chunk-CWFNQQZE.js +0 -3
  240. package/dist/cli-bundle/focused-chunks/chunk-D3U7FOZR.js +0 -2
  241. package/dist/cli-bundle/focused-chunks/chunk-GFF6BITP.js +0 -2
  242. package/dist/cli-bundle/focused-chunks/chunk-IIBWXNW3.js +0 -3
  243. package/dist/cli-bundle/focused-chunks/chunk-J5N42SKC.js +0 -3
  244. package/dist/cli-bundle/focused-chunks/chunk-KL33JMPC.js +0 -2
  245. package/dist/cli-bundle/focused-chunks/chunk-LH4C7BLB.js +0 -2
  246. package/dist/cli-bundle/focused-chunks/chunk-LTQEYE2L.js +0 -81
  247. package/dist/cli-bundle/focused-chunks/chunk-LTTMERPN.js +0 -12
  248. package/dist/cli-bundle/focused-chunks/chunk-MESFDQ3H.js +0 -26
  249. package/dist/cli-bundle/focused-chunks/chunk-MWTBAI3V.js +0 -2
  250. package/dist/cli-bundle/focused-chunks/chunk-TWULNB3N.js +0 -2
  251. package/dist/cli-bundle/focused-chunks/chunk-XAC6NP7U.js +0 -2
  252. package/dist/cli-bundle/focused-chunks/chunk-XG3TBYQK.js +0 -23
  253. package/dist/cli-bundle/focused-chunks/chunk-XMZAFKVP.js +0 -91
  254. package/dist/cli-bundle/focused-chunks/item-revision-ELI6NGMY.js +0 -2
  255. package/dist/cli-bundle/focused-chunks/item-transaction-GUGAUY77.js +0 -2
  256. package/dist/cli-bundle/focused-chunks/mutation-admission-54FI37AA.js +0 -2
  257. package/dist/cli-bundle/focused-chunks/stage-OHDJ43T2.js +0 -2
  258. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +0 -274
  259. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +0 -472
@@ -297,7 +297,8 @@ flags?:string[];
297
297
  /** Public hook lifecycle kinds an extension can register through `api.hooks.*`. */
298
298
  export type RegisteredHookKind = "before_command" | "before_mutation" | "after_command" | "on_read" | "on_write" | "on_index";
299
299
  declare const HOOK_KIND_TO_REGISTRY_FIELD:Record<RegisteredHookKind,keyof ExtensionHookRegistry>;
300
- type RegisteredHookEntry<TKind extends RegisteredHookKind> = NonNullable<ExtensionHookRegistry[(typeof HOOK_KIND_TO_REGISTRY_FIELD)[TKind]]>[number];
300
+ /** One registered hook of the given lifecycle kind, as stored in the extension hook registry. */
301
+ export type RegisteredHookEntry<TKind extends RegisteredHookKind> = NonNullable<ExtensionHookRegistry[(typeof HOOK_KIND_TO_REGISTRY_FIELD)[TKind]]>[number];
301
302
  /** Documents the registered hook expectation payload exchanged by command, SDK, and package integrations. */
302
303
  export interface RegisteredHookExpectation {
303
304
  /** Value that configures or reports kind for this contract. */
@@ -471,6 +472,13 @@ export declare function deactivateExtensionForTest(module:unknown,options?:Deact
471
472
  * the `"<name> import"` / `"<name> export"` command paths, this same helper
472
473
  * exercises importer and exporter handlers too.
473
474
  *
475
+ * When `commands` comes from {@link activateExtensionForTest}, `options` pass
476
+ * through the same definition-driven normalizer as CLI dispatch and
477
+ * `PmClient.run` (pm-gh1665): a declared CLI spelling such as `status-filter`
478
+ * folds into the handler key `statusFilter`, declared defaults and value
479
+ * coercion apply, two spellings with different values are refused with
480
+ * `extension_option_spelling_conflict`, and undeclared keys pass through.
481
+ *
474
482
  * Throws a descriptive error (listing the available handler command paths) when
475
483
  * no handler is registered for `command`, since that is a wiring/typo bug in the
476
484
  * test rather than a behavior under test. When a handler is found, the result is
@@ -1048,3 +1056,8 @@ deactivateTimeoutMs?:number;
1048
1056
  * {@link activateExtensionForTest} directly and inspect `activation.failed`.
1049
1057
  */
1050
1058
  export declare function createExtensionTestHarness(module:unknown,options?:ActivateExtensionForTestOptions):Promise<ExtensionTestHarness>;
1059
+ export type { CommandHandlerResult,CommandOverrideContext,CommandOverrideResult,ExtensionActivationResult,ExtensionCommandRegistry,ExtensionDeactivationResult,ExtensionHookRegistry,ExtensionManifest,ExtensionParserRegistry,ExtensionPreflightRegistry,ExtensionRegistrationRegistry,ExtensionRendererRegistry,ExtensionServiceRegistry,ParserOverrideContext,ParserOverrideResult,PreflightOverrideContext,PreflightOverrideResult,RegisteredExtensionCommandOverride,RegisteredExtensionExporter,RegisteredExtensionFlagDefinitions,RegisteredExtensionImporter,RegisteredExtensionParserOverride,RegisteredExtensionPreflightOverride,RegisteredExtensionRendererOverride,RegisteredExtensionSchemaMigrationDefinition,RegisteredExtensionSearchProvider,RegisteredExtensionServiceOverride,RegisteredExtensionVectorStoreAdapter,RendererOverrideContext,RendererOverrideResult,ServiceOverrideContext,ServiceOverrideResult } from "../core/extensions/extension-types.js";
1060
+ export type { PmPackageManifest } from "../core/packages/manifest.js";
1061
+ export type { ProjectProfileLintReport } from "../core/profile/profile-lint.js";
1062
+ export type { ProjectProfileDefinition } from "../core/profile/profile-presets.js";
1063
+ export type { ExtensionManifestCompatibilityManifest,ExtensionManifestCompatibilityResult,ExtensionManifestCompatibilityTarget,ExtensionPreflightReport,PreflightExtensionOptions } from "./compose.js";
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0b5eab16-4305-5dfd-902c-fefc7ee0de2b")}catch{}})();import{activateExtensions,deactivateExtensions,runAfterCommandHooks,runBeforeCommandHooks,runBeforeMutationHooks,runCommandHandler,runCommandOverride,runOnIndexHooks,runOnReadHooks,runOnWriteHooks,runParserOverride,runPreflightOverride,runRendererOverride,runServiceOverride}from"../core/extensions/loader.js";import{createDefaultExtensionGovernancePolicy}from"../core/extensions/extension-types.js";import{getMigrationRuntimeDefinition,resolveRegisteredSearchProvider,resolveRegisteredVectorStoreAdapter}from"../core/extensions/runtime-registrations.js";import{collectUsedExtensionCapabilities}from"../core/extensions/capability-usage.js";import{normalizeKnownExtensionCapability}from"../core/extensions/extension-capability-aliases.js";import{checkExtensionManifestCompatibility,describeExtensionBlueprint,lintExtensionBlueprint,preflightExtension}from"./compose.js";import{describeExtensionActivation}from"../core/extensions/activation-summary.js";import{lintProjectProfile}from"../core/profile/profile-lint.js";import{renderExtensionSurfaceMarkdown}from"../core/extensions/activation-summary-markdown.js";import{asPropertyRecord,resolveActivatablePropertyRecord}from"../core/shared/primitives.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{PmClient}from"./runtime.js";import{decode,encode}from"@toon-format/toon";function registeredExpectationName(expectation,legacyValue){return expectation.name??legacyValue??""}const HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",before_mutation:"beforeMutation",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"},RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};function normalizeSdkIdentifier(value){return value.trim().toLowerCase()}function normalizeSdkProfileMatchKey(value){return normalizeSdkIdentifier(value).replaceAll("-","_")}function extensionNameSuffix(extensionName){return extensionName?` from extension "${extensionName}"`:""}function sortedUnique(values){return[...new Set(values)].sort((left,right)=>left.localeCompare(right))}function normalizeSdkCommandName(command){if(typeof command!="string")throw new Error('A command name string is required. Pass it via the options object, e.g. runRegisteredCommandForTest(activation, { command: "my command" }) \u2014 positional command arguments are not supported.');return command.trim().toLowerCase().split(/\s+/).filter(part=>part.length>0).join(" ")}function formatAvailable(values){return values.length>0?values.join(", "):"(none)"}function assertStringSetIncludes(actual,expected,label){const actualValues=new Set(actual??[]),missing=sortedUnique(expected.filter(value=>!actualValues.has(value)));if(missing.length>0)throw new Error(`Expected package manifest ${label} to include ${missing.join(", ")}; available: ${formatAvailable(sortedUnique(actual??[]))}`)}function collectFlagLabels(flags){const labels=new Set;for(const flag of flags)typeof flag.long=="string"&&flag.long.trim().length>0&&labels.add(flag.long.trim()),typeof flag.short=="string"&&flag.short.trim().length>0&&labels.add(flag.short.trim());return labels}function readTestExtensionManifest(module){const moduleRecord=asPropertyRecord(module);if(!moduleRecord)return{};const manifest=asPropertyRecord(moduleRecord.manifest);if(manifest)return manifest;const defaultExport=asPropertyRecord(moduleRecord.default);return asPropertyRecord(defaultExport?.manifest)||(defaultExport&&typeof moduleRecord.default!="function"&&("name"in defaultExport||"capabilities"in defaultExport)?defaultExport:typeof module!="function"&&("name"in moduleRecord||"capabilities"in moduleRecord)?moduleRecord:{})}function resolveTestExtensionName(manifest,explicitName){return explicitName??(typeof manifest.name=="string"&&manifest.name.trim().length>0?manifest.name.trim():"test-extension")}function readTestExtensionCapabilities(manifest,options){return Array.isArray(options.capabilities)?[...options.capabilities]:Array.isArray(manifest.capabilities)?manifest.capabilities.filter(capability=>typeof capability=="string"):[]}function buildSingleExtensionLoadResult(module,manifest,identity){return{disabled_by_flag:!1,roots:{global:"",project:""},configured_enabled:[],configured_disabled:[],discovered:[],effective:[],warnings:[],policy:identity.policy,failed:[],loaded:[{layer:identity.layer,directory:"",manifest_path:"",name:identity.name,version:typeof manifest.version=="string"?manifest.version:"0.0.0",entry:typeof manifest.entry=="string"?manifest.entry:"./index.js",priority:typeof manifest.priority=="number"?manifest.priority:0,entry_path:"",capabilities:identity.capabilities,manifest_version:typeof manifest.manifest_version=="number"?manifest.manifest_version:void 0,pm_min_version:typeof manifest.pm_min_version=="string"?manifest.pm_min_version:void 0,pm_max_version:typeof manifest.pm_max_version=="string"?manifest.pm_max_version:void 0,engines:manifest.engines,trusted:manifest.trusted,provenance:manifest.provenance,sandbox_profile:manifest.sandbox_profile,permissions:manifest.permissions,activation:manifest.activation,module}]}}async function activateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module);return activateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,options),policy:options.policy??createDefaultExtensionGovernancePolicy()}))}async function deactivateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module);return deactivateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,{}),policy:createDefaultExtensionGovernancePolicy()}),options.activation,options.deactivateTimeoutMs===void 0?{}:{deactivate_timeout_ms:options.deactivateTimeoutMs})}async function runRegisteredCommandForTest(commands,options){const command=normalizeSdkCommandName(options.command);if(command.length===0)throw new Error("Expected command name must be a non-empty string");if(!commands.handlers.some(entry=>entry.command===command)){const available=sortedUnique(commands.handlers.map(entry=>entry.command));throw new Error(`Expected a registered command handler for "${command}" to invoke. Available command handlers: ${formatAvailable(available)}`)}if(options.sdk!==void 0&&options.sdkFactory!==void 0)throw new TypeError("runRegisteredCommandForTest accepts sdk or sdkFactory, not both");const pmRoot=options.pmRoot??"",global2={json:!0,quiet:!0,noPager:!0,...options.global},sdk=options.sdk??options.sdkFactory?.({pmRoot,global:global2})??(pmRoot.length>0?createExtensionCommandSdk(pmRoot,new PmClient({pmRoot}),void 0,command):void 0);return runCommandHandler(commands,{command,args:options.args?[...options.args]:[],options:options.options?{...options.options}:{},global:global2,pm_root:pmRoot,...sdk===void 0?{}:{sdk}})}async function runRegisteredMutationGuardForTest(hooks,options){if((hooks.beforeMutation?.length??0)===0)throw new Error("Expected a registered before_mutation hook to invoke");await runBeforeMutationHooks(hooks,options.context)}async function runRegisteredHookForTest(hooks,options){const kind=options.kind;if(kind==="before_mutation")throw new Error("Invoke before_mutation hooks with runRegisteredMutationGuardForTest so denials and failures retain fail-closed semantics.");if((hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[kind]]?.length??0)===0){const populatedKinds=sortedUnique(Object.keys(RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD).filter(candidateKind=>(hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[candidateKind]]?.length??0)>0));throw new Error(`Expected a registered "${kind}" hook to invoke. Hook kinds with registrations: ${formatAvailable(populatedKinds)}`)}switch(options.kind){case"before_command":return runBeforeCommandHooks(hooks,options.context);case"after_command":return runAfterCommandHooks(hooks,options.context);case"on_read":return runOnReadHooks(hooks,options.context);case"on_write":return runOnWriteHooks(hooks,options.context);case"on_index":return runOnIndexHooks(hooks,options.context)}}async function runRegisteredParserOverrideForTest(parsers,context){const command=normalizeSdkCommandName(context.command);if(!parsers.overrides.some(entry=>entry.command===command))throw new Error(`Expected a registered parser override for command "${command}" to invoke. Available parser override commands: ${formatAvailable(sortedUnique(parsers.overrides.map(entry=>entry.command)))}`);return runParserOverride(parsers,context)}async function runRegisteredPreflightOverrideForTest(preflight,context){if(preflight.overrides.length===0)throw new Error("Expected a registered preflight override to invoke, but none are registered.");return runPreflightOverride(preflight,context)}async function runRegisteredCommandOverrideForTest(commands,context){const command=normalizeSdkCommandName(context.command);if(!commands.overrides.some(entry=>entry.command===command))throw new Error(`Expected a registered command override for command "${command}" to invoke. Available command override commands: ${formatAvailable(sortedUnique(commands.overrides.map(entry=>entry.command)))}`);return runCommandOverride(commands,context)}async function runRegisteredRendererOverrideForTest(renderers,context){if(!renderers.overrides.some(entry=>entry.format===context.format))throw new Error(`Expected a registered renderer override for format "${context.format}" to invoke. Available renderer override formats: ${formatAvailable(sortedUnique(renderers.overrides.map(entry=>entry.format)))}`);return runRendererOverride(renderers,context)}async function runRegisteredServiceOverrideForTest(services,context){if(!services.overrides.some(entry=>entry.service===context.service))throw new Error(`Expected a registered service override for service "${context.service}" to invoke. Available service override services: ${formatAvailable(sortedUnique(services.overrides.map(entry=>entry.service)))}`);return runServiceOverride(services,context)}const SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS={query:["query"],embed:["embed"],embedBatch:["embedBatch","embed_batch"],queryExpansion:["queryExpansion","query_expansion"],rerank:["rerank"]};async function runRegisteredSearchProviderForTest(registrations,options){const registration=resolveRegisteredSearchProvider(registrations,options.provider);if(!registration){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected a registered search provider "${options.provider}" to invoke. Available search providers: ${formatAvailable(available)}`)}const runtimeDefinition=registration.runtime_definition,operationFn=SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS[options.operation].map(key=>runtimeDefinition[key]).find(value=>typeof value=="function");if(typeof operationFn!="function")throw new Error(`Registered search provider "${options.provider}" does not implement the "${options.operation}" operation.`);return await operationFn(options.context)}async function runRegisteredVectorStoreAdapterForTest(registrations,options){const registration=resolveRegisteredVectorStoreAdapter(registrations,options.adapter);if(!registration){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected a registered vector store adapter "${options.adapter}" to invoke. Available vector store adapters: ${formatAvailable(available)}`)}const operationFn=registration.runtime_definition[options.operation];if(typeof operationFn!="function")throw new Error(`Registered vector store adapter "${options.adapter}" does not implement the "${options.operation}" operation.`);return await operationFn(options.context)}async function runRegisteredMigrationForTest(registrations,options){const migration=assertRegisteredMigration(registrations,{migration:options.migration,extensionName:options.extensionName}),run=getMigrationRuntimeDefinition(migration).run;if(typeof run!="function")throw new Error(`Registered migration "${options.migration}" does not implement a run function to invoke.`);const declaredStatus=migration.definition.status,context={id:migration.definition.id,command:"migration",layer:migration.layer,extension:migration.name,pm_root:options.pmRoot??"",status:(typeof declaredStatus=="string"?declaredStatus.trim().toLowerCase():"")||"pending"};return await run(context)}async function runRegisteredImporterForTest(activation,options){const importer=assertRegisteredImporter(activation.registrations,{importer:options.importer,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${importer.importer} import`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}async function runRegisteredExporterForTest(activation,options){const exporter=assertRegisteredExporter(activation.registrations,{exporter:options.exporter,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${exporter.exporter} export`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}function assertExtensionDeactivated(result,expectation={}){const expectedDeactivated=expectation.deactivated??1;if(result.deactivated!==expectedDeactivated)throw new Error(`Expected ${expectedDeactivated} extension${expectedDeactivated===1?"":"s"} to deactivate cleanly, but ${result.deactivated} did.`);const expectedFailed=expectation.failed??0;if(result.failed.length!==expectedFailed){const detail=result.failed.map(failure=>`${failure.layer}:${failure.name} (${failure.error})`).join(", ");throw new Error(`Expected ${expectedFailed} teardown failure${expectedFailed===1?"":"s"}, but observed ${result.failed.length}${detail.length>0?`: ${detail}`:""}.`)}return result}function assertPackageManifest(manifest,expectation){if(expectation.packageName!==void 0&&manifest.package_name!==expectation.packageName)throw new Error(`Expected package manifest package_name to be "${expectation.packageName}"; received "${manifest.package_name??"(none)"}"`);if(expectation.aliases!==void 0&&assertStringSetIncludes(manifest.aliases,expectation.aliases,"aliases"),expectation.resources!==void 0)for(const[kind,expectedPaths]of Object.entries(expectation.resources))assertStringSetIncludes(manifest.resources[kind],expectedPaths,`pm.${kind}`);return manifest}function assertRegisteredCommandContract(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const commandCandidates=registrations.commands.filter(entry=>entry.command===expectedCommand),command=expectation.extensionName?commandCandidates.find(entry=>entry.name===expectation.extensionName):commandCandidates[0];if(!command){const available=registrations.commands.map(entry=>entry.command).sort((left,right)=>left.localeCompare(right)),extensionSuffix=expectation.extensionName?` from extension "${expectation.extensionName}"`:"";throw new Error(`Expected extension command "${expectedCommand}"${extensionSuffix} to be registered. Available commands: ${formatAvailable(available)}`)}if(expectation.action!==void 0&&command.action!==expectation.action)throw new Error(`Expected extension command "${expectedCommand}" action "${expectation.action}", received "${command.action}"`);if(expectation.arguments!==void 0){const actualArguments=(command.arguments??[]).map(argument=>argument.name),missingArguments=expectation.arguments.filter(argument=>!actualArguments.includes(argument));if(missingArguments.length>0)throw new Error(`Expected extension command "${expectedCommand}" arguments ${formatAvailable(expectation.arguments)}; missing ${formatAvailable(missingArguments)}; available ${formatAvailable(actualArguments)}`)}const flags=registrations.flags.filter(entry=>entry.target_command===expectedCommand&&(expectation.extensionName===void 0||entry.name===expectation.extensionName)).flatMap(entry=>entry.flags);if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(flags),missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0)throw new Error(`Expected extension command "${expectedCommand}" flags ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}return{command,flags}}function assertRegisteredFlags(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.targetCommand));if(expectedCommand.length===0)throw new Error("Expected target command name must be a non-empty string");const candidates=registrations.flags.filter(entry=>entry.target_command===expectedCommand);let registration;if(expectation.extensionName)registration=candidates.find(entry=>entry.name===expectation.extensionName);else if(candidates.length===1)registration=candidates[0];else if(candidates.length>1){const availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}" matched multiple extensions: ${formatAvailable(availableExtensions)}. Specify extensionName to choose one registration.`)}if(!registration){const available=sortedUnique(registrations.flags.map(entry=>entry.target_command)),availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available flag target commands: ${formatAvailable(available)}; matching extensions: ${formatAvailable(availableExtensions)}`)}if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(registration.flags),missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0)throw new Error(`Expected flags for target command "${expectedCommand}" to include ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}return registration}function assertRegisteredHook(hooks,expectation){const field=HOOK_KIND_TO_REGISTRY_FIELD[expectation.kind],candidates=hooks[field]??[],hook=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!hook){const available=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected a "${expectation.kind}" hook${extensionNameSuffix(expectation.extensionName)} to be registered. Available "${expectation.kind}" hooks: ${formatAvailable(available)}`)}return hook}function assertRegisteredSearchProvider(registrations,expectation){const expectedProvider=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.provider));if(expectedProvider.length===0)throw new Error("Expected search provider name must be a non-empty string");const candidates=registrations.search_providers.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedProvider),provider=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!provider){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected search provider "${expectedProvider}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available search providers: ${formatAvailable(available)}`)}return provider}function assertRegisteredVectorStoreAdapter(registrations,expectation){const expectedAdapter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.adapter));if(expectedAdapter.length===0)throw new Error("Expected vector store adapter name must be a non-empty string");const candidates=registrations.vector_store_adapters.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedAdapter),adapter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!adapter){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected vector store adapter "${expectedAdapter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available vector store adapters: ${formatAvailable(available)}`)}return adapter}function assertRegisteredImporter(registrations,expectation){const expectedImporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.importer));if(expectedImporter.length===0)throw new Error("Expected importer name must be a non-empty string");const candidates=registrations.importers.filter(entry=>normalizeSdkIdentifier(entry.importer)===expectedImporter),importer=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!importer){const available=sortedUnique(registrations.importers.map(entry=>entry.importer));throw new Error(`Expected importer "${expectedImporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available importers: ${formatAvailable(available)}`)}return importer}function assertRegisteredExporter(registrations,expectation){const expectedExporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.exporter));if(expectedExporter.length===0)throw new Error("Expected exporter name must be a non-empty string");const candidates=registrations.exporters.filter(entry=>normalizeSdkIdentifier(entry.exporter)===expectedExporter),exporter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!exporter){const available=sortedUnique(registrations.exporters.map(entry=>entry.exporter));throw new Error(`Expected exporter "${expectedExporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available exporters: ${formatAvailable(available)}`)}return exporter}function assertRegisteredItemField(registrations,expectation){const expectedField=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.field));if(expectedField.length===0)throw new Error("Expected item field name must be a non-empty string");const match=registrations.item_fields.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,field:registration.fields.find(field=>normalizeSdkIdentifier(field.name)===expectedField)})).filter(entry=>entry.field!==void 0).find(entry=>expectation.type===void 0||entry.field.type===expectation.type);if(!match){const available=sortedUnique(registrations.item_fields.flatMap(entry=>entry.fields.map(field=>`${field.name}:${field.type}`)));throw new Error(`Expected item field "${expectedField}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item fields: ${formatAvailable(available)}`)}return match}function assertRegisteredItemType(registrations,expectation){const expectedType=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.itemType));if(expectedType.length===0)throw new Error("Expected item type name must be a non-empty string");const match=registrations.item_types.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,itemType:registration.types.find(itemType=>normalizeSdkIdentifier(itemType.name)===expectedType)})).filter(entry=>entry.itemType!==void 0).find(entry=>expectation.folder===void 0||entry.itemType.folder===expectation.folder);if(!match){const available=sortedUnique(registrations.item_types.flatMap(entry=>entry.types.map(itemType=>`${itemType.name}:${itemType.folder}`)));throw new Error(`Expected item type "${expectedType}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item types: ${formatAvailable(available)}`)}return match}function assertRegisteredProfile(registrations,expectation){const expectedProfile=normalizeSdkProfileMatchKey(registeredExpectationName(expectation,expectation.profile));if(expectedProfile.length===0)throw new Error("Expected profile name must be a non-empty string");const match=registrations.profiles.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).find(entry=>normalizeSdkProfileMatchKey(entry.profile.name)===expectedProfile);if(!match){const available=sortedUnique(registrations.profiles.map(entry=>entry.profile.name));throw new Error(`Expected profile "${expectedProfile}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available profiles: ${formatAvailable(available)}`)}return{registration:match,profile:match.profile}}function assertRegisteredCommandOverride(commands,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const candidates=commands.overrides.filter(entry=>entry.command===expectedCommand),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(commands.overrides.map(entry=>entry.command));throw new Error(`Expected command override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available command overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredParserOverride(parsers,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const candidates=parsers.overrides.filter(entry=>entry.command===expectedCommand),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(parsers.overrides.map(entry=>entry.command));throw new Error(`Expected parser override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available parser overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredPreflightOverride(preflight,expectation={}){const override=expectation.extensionName?preflight.overrides.find(entry=>entry.name===expectation.extensionName):preflight.overrides[0];if(!override){const available=sortedUnique(preflight.overrides.map(entry=>entry.name));throw new Error(`Expected a preflight override${extensionNameSuffix(expectation.extensionName)} to be registered. Available preflight overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredRendererOverride(renderers,expectation){const expectedFormat=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.format));if(expectedFormat.length===0)throw new Error("Expected renderer format must be a non-empty string");const candidates=renderers.overrides.filter(entry=>entry.format===expectedFormat),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(renderers.overrides.map(entry=>entry.format));throw new Error(`Expected renderer override "${expectedFormat}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available renderer overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredServiceOverride(services,expectation){const expectedService=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.service));if(expectedService.length===0)throw new Error("Expected service name must be a non-empty string");const candidates=services.overrides.filter(entry=>normalizeSdkIdentifier(entry.service)===expectedService),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(services.overrides.map(entry=>entry.service));throw new Error(`Expected service override "${expectedService}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available service overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredMigration(registrations,expectation){const expectedMigration=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.migration));if(expectedMigration.length===0)throw new Error("Expected migration id must be a non-empty string");const candidates=registrations.migrations.filter(entry=>(expectation.extensionName===void 0||entry.name===expectation.extensionName)&&typeof entry.definition.id=="string"&&normalizeSdkIdentifier(entry.definition.id)===expectedMigration),match=candidates.find(entry=>expectation.mandatory===void 0||(entry.definition.mandatory??!1)===expectation.mandatory);if(match)return match;const idMatch=candidates[0];if(idMatch!==void 0)throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to have mandatory=${expectation.mandatory}, but it is mandatory=${idMatch.definition.mandatory??!1}.`);const available=sortedUnique(registrations.migrations.map(entry=>`${typeof entry.definition.id=="string"&&entry.definition.id.trim().length>0?entry.definition.id.trim():"(unnamed)"}:${entry.definition.mandatory===!0}`));throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available migrations: ${formatAvailable(available)}`)}function assertExtensionCapabilityUsage(activation,expectation){const toKnownCapabilitySet=(capabilities,field)=>{const known=new Set;for(const capability of capabilities){const normalized=normalizeKnownExtensionCapability(capability);if(normalized===null)throw new Error(`Expected ${field} capability "${capability}" to be a known extension capability. Use canonical capability names (see manifest.capabilities).`);known.add(normalized)}return known},declared=[...toKnownCapabilitySet(expectation.declared,"declared")].sort((left,right)=>left.localeCompare(right)),allowUnused=toKnownCapabilitySet(expectation.allowUnused??[],"allowUnused"),used=collectUsedExtensionCapabilities(activation,{extensionName:expectation.extensionName}),usedSet=new Set(used),unused=declared.filter(capability=>!usedSet.has(capability)&&!allowUnused.has(capability));if(unused.length>0){const scopeSuffix=extensionNameSuffix(expectation.extensionName);throw new Error(`Expected every declared capability${scopeSuffix} to be exercised, but [${unused.join(", ")}] ${unused.length===1?"is":"are"} declared yet never registered against. Remove ${unused.length===1?"it":"them"} from manifest.capabilities for least privilege, or pass allowUnused for capabilities registered only behind a runtime flag.`)}return{declared,used,unused}}function assertExtensionBlueprint(blueprint,options={}){const result=lintExtensionBlueprint(blueprint,options);if(!result.ok){const errors=result.findings.filter(finding=>finding.severity==="error");throw new Error(`Extension blueprint failed preflight with ${errors.length} ${errors.length===1?"error":"errors"}:
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="65a4dbbe-c9a7-5092-a325-3ba73c0fc026")}catch{}})();import{activateExtensions,deactivateExtensions,runAfterCommandHooks,runBeforeCommandHooks,runBeforeMutationHooks,runCommandHandler,runCommandOverride,runOnIndexHooks,runOnReadHooks,runOnWriteHooks,runParserOverride,runPreflightOverride,runRendererOverride,runServiceOverride}from"../core/extensions/loader.js";import{createDefaultExtensionGovernancePolicy}from"../core/extensions/extension-types.js";import{getMigrationRuntimeDefinition,resolveRegisteredSearchProvider,resolveRegisteredVectorStoreAdapter}from"../core/extensions/runtime-registrations.js";import{collectUsedExtensionCapabilities}from"../core/extensions/capability-usage.js";import{normalizeKnownExtensionCapability}from"../core/extensions/extension-capability-aliases.js";import{checkExtensionManifestCompatibility,describeExtensionBlueprint,lintExtensionBlueprint,preflightExtension}from"./compose.js";import{describeExtensionActivation}from"../core/extensions/activation-summary.js";import{lintProjectProfile}from"../core/profile/profile-lint.js";import{renderExtensionSurfaceMarkdown}from"../core/extensions/activation-summary-markdown.js";import{asPropertyRecord,resolveActivatablePropertyRecord}from"../core/shared/primitives.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{collectExtensionFlagDefinitionsForCommand,normalizeDirectExtensionCommandOptions}from"./extension/command-options.js";import{PmClient}from"./runtime.js";import{decode,encode}from"@toon-format/toon";const ACTIVATED_COMMAND_FLAG_REGISTRATIONS=Symbol.for("pm.sdk.testing.activatedFlagRegistrations");function readActivatedFlagRegistrations(commands){return commands[ACTIVATED_COMMAND_FLAG_REGISTRATIONS]}function registeredExpectationName(expectation,legacyValue){return expectation.name??legacyValue??""}const HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",before_mutation:"beforeMutation",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"},RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};function normalizeSdkIdentifier(value){return value.trim().toLowerCase()}function normalizeSdkProfileMatchKey(value){return normalizeSdkIdentifier(value).replaceAll("-","_")}function extensionNameSuffix(extensionName){return extensionName?` from extension "${extensionName}"`:""}function sortedUnique(values){return[...new Set(values)].sort((left,right)=>left.localeCompare(right))}function normalizeSdkCommandName(command){if(typeof command!="string")throw new Error('A command name string is required. Pass it via the options object, e.g. runRegisteredCommandForTest(activation, { command: "my command" }) \u2014 positional command arguments are not supported.');return command.trim().toLowerCase().split(/\s+/).filter(part=>part.length>0).join(" ")}function formatAvailable(values){return values.length>0?values.join(", "):"(none)"}function assertStringSetIncludes(actual,expected,label){const actualValues=new Set(actual??[]),missing=sortedUnique(expected.filter(value=>!actualValues.has(value)));if(missing.length>0)throw new Error(`Expected package manifest ${label} to include ${missing.join(", ")}; available: ${formatAvailable(sortedUnique(actual??[]))}`)}function collectFlagLabels(flags){const labels=new Set;for(const flag of flags)typeof flag.long=="string"&&flag.long.trim().length>0&&labels.add(flag.long.trim()),typeof flag.short=="string"&&flag.short.trim().length>0&&labels.add(flag.short.trim());return labels}function readTestExtensionManifest(module){const moduleRecord=asPropertyRecord(module);if(!moduleRecord)return{};const manifest=asPropertyRecord(moduleRecord.manifest);if(manifest)return manifest;const defaultExport=asPropertyRecord(moduleRecord.default);return asPropertyRecord(defaultExport?.manifest)||(defaultExport&&typeof moduleRecord.default!="function"&&("name"in defaultExport||"capabilities"in defaultExport)?defaultExport:typeof module!="function"&&("name"in moduleRecord||"capabilities"in moduleRecord)?moduleRecord:{})}function resolveTestExtensionName(manifest,explicitName){return explicitName??(typeof manifest.name=="string"&&manifest.name.trim().length>0?manifest.name.trim():"test-extension")}function readTestExtensionCapabilities(manifest,options){return Array.isArray(options.capabilities)?[...options.capabilities]:Array.isArray(manifest.capabilities)?manifest.capabilities.filter(capability=>typeof capability=="string"):[]}function buildSingleExtensionLoadResult(module,manifest,identity){return{disabled_by_flag:!1,roots:{global:"",project:""},configured_enabled:[],configured_disabled:[],discovered:[],effective:[],warnings:[],policy:identity.policy,failed:[],loaded:[{layer:identity.layer,directory:"",manifest_path:"",name:identity.name,version:typeof manifest.version=="string"?manifest.version:"0.0.0",entry:typeof manifest.entry=="string"?manifest.entry:"./index.js",priority:typeof manifest.priority=="number"?manifest.priority:0,entry_path:"",capabilities:identity.capabilities,manifest_version:typeof manifest.manifest_version=="number"?manifest.manifest_version:void 0,pm_min_version:typeof manifest.pm_min_version=="string"?manifest.pm_min_version:void 0,pm_max_version:typeof manifest.pm_max_version=="string"?manifest.pm_max_version:void 0,engines:manifest.engines,trusted:manifest.trusted,provenance:manifest.provenance,sandbox_profile:manifest.sandbox_profile,permissions:manifest.permissions,activation:manifest.activation,module}]}}async function activateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module),activation=await activateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,options),policy:options.policy??createDefaultExtensionGovernancePolicy()}));return Object.defineProperty(activation.commands,ACTIVATED_COMMAND_FLAG_REGISTRATIONS,{value:activation.registrations,enumerable:!1}),activation}async function deactivateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module);return deactivateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,{}),policy:createDefaultExtensionGovernancePolicy()}),options.activation,options.deactivateTimeoutMs===void 0?{}:{deactivate_timeout_ms:options.deactivateTimeoutMs})}async function runRegisteredCommandForTest(commands,options){const command=normalizeSdkCommandName(options.command);if(command.length===0)throw new Error("Expected command name must be a non-empty string");if(!commands.handlers.some(entry=>entry.command===command)){const available=sortedUnique(commands.handlers.map(entry=>entry.command));throw new Error(`Expected a registered command handler for "${command}" to invoke. Available command handlers: ${formatAvailable(available)}`)}if(options.sdk!==void 0&&options.sdkFactory!==void 0)throw new TypeError("runRegisteredCommandForTest accepts sdk or sdkFactory, not both");const pmRoot=options.pmRoot??"",global2={json:!0,quiet:!0,noPager:!0,...options.global},sdk=options.sdk??options.sdkFactory?.({pmRoot,global:global2})??(pmRoot.length>0?createExtensionCommandSdk(pmRoot,new PmClient({pmRoot}),void 0,command):void 0),registrations=readActivatedFlagRegistrations(commands),handlerOptions=options.options?{...options.options}:{};return runCommandHandler(commands,{command,args:options.args?[...options.args]:[],options:registrations===void 0?handlerOptions:normalizeDirectExtensionCommandOptions(handlerOptions,collectExtensionFlagDefinitionsForCommand(registrations,command),command),global:global2,pm_root:pmRoot,...sdk===void 0?{}:{sdk}})}async function runRegisteredMutationGuardForTest(hooks,options){if((hooks.beforeMutation?.length??0)===0)throw new Error("Expected a registered before_mutation hook to invoke");await runBeforeMutationHooks(hooks,options.context)}async function runRegisteredHookForTest(hooks,options){const kind=options.kind;if(kind==="before_mutation")throw new Error("Invoke before_mutation hooks with runRegisteredMutationGuardForTest so denials and failures retain fail-closed semantics.");if((hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[kind]]?.length??0)===0){const populatedKinds=sortedUnique(Object.keys(RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD).filter(candidateKind=>(hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[candidateKind]]?.length??0)>0));throw new Error(`Expected a registered "${kind}" hook to invoke. Hook kinds with registrations: ${formatAvailable(populatedKinds)}`)}switch(options.kind){case"before_command":return runBeforeCommandHooks(hooks,options.context);case"after_command":return runAfterCommandHooks(hooks,options.context);case"on_read":return runOnReadHooks(hooks,options.context);case"on_write":return runOnWriteHooks(hooks,options.context);case"on_index":return runOnIndexHooks(hooks,options.context)}}async function runRegisteredParserOverrideForTest(parsers,context){const command=normalizeSdkCommandName(context.command);if(!parsers.overrides.some(entry=>entry.command===command))throw new Error(`Expected a registered parser override for command "${command}" to invoke. Available parser override commands: ${formatAvailable(sortedUnique(parsers.overrides.map(entry=>entry.command)))}`);return runParserOverride(parsers,context)}async function runRegisteredPreflightOverrideForTest(preflight,context){if(preflight.overrides.length===0)throw new Error("Expected a registered preflight override to invoke, but none are registered.");return runPreflightOverride(preflight,context)}async function runRegisteredCommandOverrideForTest(commands,context){const command=normalizeSdkCommandName(context.command);if(!commands.overrides.some(entry=>entry.command===command))throw new Error(`Expected a registered command override for command "${command}" to invoke. Available command override commands: ${formatAvailable(sortedUnique(commands.overrides.map(entry=>entry.command)))}`);return runCommandOverride(commands,context)}async function runRegisteredRendererOverrideForTest(renderers,context){if(!renderers.overrides.some(entry=>entry.format===context.format))throw new Error(`Expected a registered renderer override for format "${context.format}" to invoke. Available renderer override formats: ${formatAvailable(sortedUnique(renderers.overrides.map(entry=>entry.format)))}`);return runRendererOverride(renderers,context)}async function runRegisteredServiceOverrideForTest(services,context){if(!services.overrides.some(entry=>entry.service===context.service))throw new Error(`Expected a registered service override for service "${context.service}" to invoke. Available service override services: ${formatAvailable(sortedUnique(services.overrides.map(entry=>entry.service)))}`);return runServiceOverride(services,context)}const SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS={query:["query"],embed:["embed"],embedBatch:["embedBatch","embed_batch"],queryExpansion:["queryExpansion","query_expansion"],rerank:["rerank"]};async function runRegisteredSearchProviderForTest(registrations,options){const registration=resolveRegisteredSearchProvider(registrations,options.provider);if(!registration){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected a registered search provider "${options.provider}" to invoke. Available search providers: ${formatAvailable(available)}`)}const runtimeDefinition=registration.runtime_definition,operationFn=SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS[options.operation].map(key=>runtimeDefinition[key]).find(value=>typeof value=="function");if(typeof operationFn!="function")throw new Error(`Registered search provider "${options.provider}" does not implement the "${options.operation}" operation.`);return await operationFn(options.context)}async function runRegisteredVectorStoreAdapterForTest(registrations,options){const registration=resolveRegisteredVectorStoreAdapter(registrations,options.adapter);if(!registration){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected a registered vector store adapter "${options.adapter}" to invoke. Available vector store adapters: ${formatAvailable(available)}`)}const operationFn=registration.runtime_definition[options.operation];if(typeof operationFn!="function")throw new Error(`Registered vector store adapter "${options.adapter}" does not implement the "${options.operation}" operation.`);return await operationFn(options.context)}async function runRegisteredMigrationForTest(registrations,options){const migration=assertRegisteredMigration(registrations,{migration:options.migration,extensionName:options.extensionName}),run=getMigrationRuntimeDefinition(migration).run;if(typeof run!="function")throw new Error(`Registered migration "${options.migration}" does not implement a run function to invoke.`);const declaredStatus=migration.definition.status,context={id:migration.definition.id,command:"migration",layer:migration.layer,extension:migration.name,pm_root:options.pmRoot??"",status:(typeof declaredStatus=="string"?declaredStatus.trim().toLowerCase():"")||"pending"};return await run(context)}async function runRegisteredImporterForTest(activation,options){const importer=assertRegisteredImporter(activation.registrations,{importer:options.importer,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${importer.importer} import`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}async function runRegisteredExporterForTest(activation,options){const exporter=assertRegisteredExporter(activation.registrations,{exporter:options.exporter,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${exporter.exporter} export`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}function assertExtensionDeactivated(result,expectation={}){const expectedDeactivated=expectation.deactivated??1;if(result.deactivated!==expectedDeactivated)throw new Error(`Expected ${expectedDeactivated} extension${expectedDeactivated===1?"":"s"} to deactivate cleanly, but ${result.deactivated} did.`);const expectedFailed=expectation.failed??0;if(result.failed.length!==expectedFailed){const detail=result.failed.map(failure=>`${failure.layer}:${failure.name} (${failure.error})`).join(", ");throw new Error(`Expected ${expectedFailed} teardown failure${expectedFailed===1?"":"s"}, but observed ${result.failed.length}${detail.length>0?`: ${detail}`:""}.`)}return result}function assertPackageManifest(manifest,expectation){if(expectation.packageName!==void 0&&manifest.package_name!==expectation.packageName)throw new Error(`Expected package manifest package_name to be "${expectation.packageName}"; received "${manifest.package_name??"(none)"}"`);if(expectation.aliases!==void 0&&assertStringSetIncludes(manifest.aliases,expectation.aliases,"aliases"),expectation.resources!==void 0)for(const[kind,expectedPaths]of Object.entries(expectation.resources))assertStringSetIncludes(manifest.resources[kind],expectedPaths,`pm.${kind}`);return manifest}function assertRegisteredCommandContract(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const commandCandidates=registrations.commands.filter(entry=>entry.command===expectedCommand),command=expectation.extensionName?commandCandidates.find(entry=>entry.name===expectation.extensionName):commandCandidates[0];if(!command){const available=registrations.commands.map(entry=>entry.command).sort((left,right)=>left.localeCompare(right)),extensionSuffix=expectation.extensionName?` from extension "${expectation.extensionName}"`:"";throw new Error(`Expected extension command "${expectedCommand}"${extensionSuffix} to be registered. Available commands: ${formatAvailable(available)}`)}if(expectation.action!==void 0&&command.action!==expectation.action)throw new Error(`Expected extension command "${expectedCommand}" action "${expectation.action}", received "${command.action}"`);if(expectation.arguments!==void 0){const actualArguments=(command.arguments??[]).map(argument=>argument.name),missingArguments=expectation.arguments.filter(argument=>!actualArguments.includes(argument));if(missingArguments.length>0)throw new Error(`Expected extension command "${expectedCommand}" arguments ${formatAvailable(expectation.arguments)}; missing ${formatAvailable(missingArguments)}; available ${formatAvailable(actualArguments)}`)}const flags=registrations.flags.filter(entry=>entry.target_command===expectedCommand&&(expectation.extensionName===void 0||entry.name===expectation.extensionName)).flatMap(entry=>entry.flags);if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(flags),missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0)throw new Error(`Expected extension command "${expectedCommand}" flags ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}return{command,flags}}function assertRegisteredFlags(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.targetCommand));if(expectedCommand.length===0)throw new Error("Expected target command name must be a non-empty string");const candidates=registrations.flags.filter(entry=>entry.target_command===expectedCommand);let registration;if(expectation.extensionName)registration=candidates.find(entry=>entry.name===expectation.extensionName);else if(candidates.length===1)registration=candidates[0];else if(candidates.length>1){const availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}" matched multiple extensions: ${formatAvailable(availableExtensions)}. Specify extensionName to choose one registration.`)}if(!registration){const available=sortedUnique(registrations.flags.map(entry=>entry.target_command)),availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available flag target commands: ${formatAvailable(available)}; matching extensions: ${formatAvailable(availableExtensions)}`)}if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(registration.flags),missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0)throw new Error(`Expected flags for target command "${expectedCommand}" to include ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}return registration}function assertRegisteredHook(hooks,expectation){const field=HOOK_KIND_TO_REGISTRY_FIELD[expectation.kind],candidates=hooks[field]??[],hook=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!hook){const available=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected a "${expectation.kind}" hook${extensionNameSuffix(expectation.extensionName)} to be registered. Available "${expectation.kind}" hooks: ${formatAvailable(available)}`)}return hook}function assertRegisteredSearchProvider(registrations,expectation){const expectedProvider=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.provider));if(expectedProvider.length===0)throw new Error("Expected search provider name must be a non-empty string");const candidates=registrations.search_providers.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedProvider),provider=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!provider){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected search provider "${expectedProvider}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available search providers: ${formatAvailable(available)}`)}return provider}function assertRegisteredVectorStoreAdapter(registrations,expectation){const expectedAdapter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.adapter));if(expectedAdapter.length===0)throw new Error("Expected vector store adapter name must be a non-empty string");const candidates=registrations.vector_store_adapters.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedAdapter),adapter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!adapter){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected vector store adapter "${expectedAdapter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available vector store adapters: ${formatAvailable(available)}`)}return adapter}function assertRegisteredImporter(registrations,expectation){const expectedImporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.importer));if(expectedImporter.length===0)throw new Error("Expected importer name must be a non-empty string");const candidates=registrations.importers.filter(entry=>normalizeSdkIdentifier(entry.importer)===expectedImporter),importer=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!importer){const available=sortedUnique(registrations.importers.map(entry=>entry.importer));throw new Error(`Expected importer "${expectedImporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available importers: ${formatAvailable(available)}`)}return importer}function assertRegisteredExporter(registrations,expectation){const expectedExporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.exporter));if(expectedExporter.length===0)throw new Error("Expected exporter name must be a non-empty string");const candidates=registrations.exporters.filter(entry=>normalizeSdkIdentifier(entry.exporter)===expectedExporter),exporter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!exporter){const available=sortedUnique(registrations.exporters.map(entry=>entry.exporter));throw new Error(`Expected exporter "${expectedExporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available exporters: ${formatAvailable(available)}`)}return exporter}function assertRegisteredItemField(registrations,expectation){const expectedField=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.field));if(expectedField.length===0)throw new Error("Expected item field name must be a non-empty string");const match=registrations.item_fields.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,field:registration.fields.find(field=>normalizeSdkIdentifier(field.name)===expectedField)})).filter(entry=>entry.field!==void 0).find(entry=>expectation.type===void 0||entry.field.type===expectation.type);if(!match){const available=sortedUnique(registrations.item_fields.flatMap(entry=>entry.fields.map(field=>`${field.name}:${field.type}`)));throw new Error(`Expected item field "${expectedField}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item fields: ${formatAvailable(available)}`)}return match}function assertRegisteredItemType(registrations,expectation){const expectedType=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.itemType));if(expectedType.length===0)throw new Error("Expected item type name must be a non-empty string");const match=registrations.item_types.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,itemType:registration.types.find(itemType=>normalizeSdkIdentifier(itemType.name)===expectedType)})).filter(entry=>entry.itemType!==void 0).find(entry=>expectation.folder===void 0||entry.itemType.folder===expectation.folder);if(!match){const available=sortedUnique(registrations.item_types.flatMap(entry=>entry.types.map(itemType=>`${itemType.name}:${itemType.folder}`)));throw new Error(`Expected item type "${expectedType}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item types: ${formatAvailable(available)}`)}return match}function assertRegisteredProfile(registrations,expectation){const expectedProfile=normalizeSdkProfileMatchKey(registeredExpectationName(expectation,expectation.profile));if(expectedProfile.length===0)throw new Error("Expected profile name must be a non-empty string");const match=registrations.profiles.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).find(entry=>normalizeSdkProfileMatchKey(entry.profile.name)===expectedProfile);if(!match){const available=sortedUnique(registrations.profiles.map(entry=>entry.profile.name));throw new Error(`Expected profile "${expectedProfile}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available profiles: ${formatAvailable(available)}`)}return{registration:match,profile:match.profile}}function assertRegisteredCommandOverride(commands,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const candidates=commands.overrides.filter(entry=>entry.command===expectedCommand),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(commands.overrides.map(entry=>entry.command));throw new Error(`Expected command override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available command overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredParserOverride(parsers,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const candidates=parsers.overrides.filter(entry=>entry.command===expectedCommand),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(parsers.overrides.map(entry=>entry.command));throw new Error(`Expected parser override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available parser overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredPreflightOverride(preflight,expectation={}){const override=expectation.extensionName?preflight.overrides.find(entry=>entry.name===expectation.extensionName):preflight.overrides[0];if(!override){const available=sortedUnique(preflight.overrides.map(entry=>entry.name));throw new Error(`Expected a preflight override${extensionNameSuffix(expectation.extensionName)} to be registered. Available preflight overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredRendererOverride(renderers,expectation){const expectedFormat=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.format));if(expectedFormat.length===0)throw new Error("Expected renderer format must be a non-empty string");const candidates=renderers.overrides.filter(entry=>entry.format===expectedFormat),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(renderers.overrides.map(entry=>entry.format));throw new Error(`Expected renderer override "${expectedFormat}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available renderer overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredServiceOverride(services,expectation){const expectedService=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.service));if(expectedService.length===0)throw new Error("Expected service name must be a non-empty string");const candidates=services.overrides.filter(entry=>normalizeSdkIdentifier(entry.service)===expectedService),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(services.overrides.map(entry=>entry.service));throw new Error(`Expected service override "${expectedService}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available service overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredMigration(registrations,expectation){const expectedMigration=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.migration));if(expectedMigration.length===0)throw new Error("Expected migration id must be a non-empty string");const candidates=registrations.migrations.filter(entry=>(expectation.extensionName===void 0||entry.name===expectation.extensionName)&&typeof entry.definition.id=="string"&&normalizeSdkIdentifier(entry.definition.id)===expectedMigration),match=candidates.find(entry=>expectation.mandatory===void 0||(entry.definition.mandatory??!1)===expectation.mandatory);if(match)return match;const idMatch=candidates[0];if(idMatch!==void 0)throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to have mandatory=${expectation.mandatory}, but it is mandatory=${idMatch.definition.mandatory??!1}.`);const available=sortedUnique(registrations.migrations.map(entry=>`${typeof entry.definition.id=="string"&&entry.definition.id.trim().length>0?entry.definition.id.trim():"(unnamed)"}:${entry.definition.mandatory===!0}`));throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available migrations: ${formatAvailable(available)}`)}function assertExtensionCapabilityUsage(activation,expectation){const toKnownCapabilitySet=(capabilities,field)=>{const known=new Set;for(const capability of capabilities){const normalized=normalizeKnownExtensionCapability(capability);if(normalized===null)throw new Error(`Expected ${field} capability "${capability}" to be a known extension capability. Use canonical capability names (see manifest.capabilities).`);known.add(normalized)}return known},declared=[...toKnownCapabilitySet(expectation.declared,"declared")].sort((left,right)=>left.localeCompare(right)),allowUnused=toKnownCapabilitySet(expectation.allowUnused??[],"allowUnused"),used=collectUsedExtensionCapabilities(activation,{extensionName:expectation.extensionName}),usedSet=new Set(used),unused=declared.filter(capability=>!usedSet.has(capability)&&!allowUnused.has(capability));if(unused.length>0){const scopeSuffix=extensionNameSuffix(expectation.extensionName);throw new Error(`Expected every declared capability${scopeSuffix} to be exercised, but [${unused.join(", ")}] ${unused.length===1?"is":"are"} declared yet never registered against. Remove ${unused.length===1?"it":"them"} from manifest.capabilities for least privilege, or pass allowUnused for capabilities registered only behind a runtime flag.`)}return{declared,used,unused}}function assertExtensionBlueprint(blueprint,options={}){const result=lintExtensionBlueprint(blueprint,options);if(!result.ok){const errors=result.findings.filter(finding=>finding.severity==="error");throw new Error(`Extension blueprint failed preflight with ${errors.length} ${errors.length===1?"error":"errors"}:
2
2
  `+errors.map(finding=>` - [${finding.code}] ${finding.message}`).join(`
3
3
  `))}return result}function assertProjectProfile(profile,options={}){const report=lintProjectProfile(profile),blocking=report.findings.filter(finding=>finding.severity==="error"||options.strict===!0&&finding.severity==="warning");if(blocking.length>0)throw new Error(`Project profile "${report.profile}" failed lint with ${blocking.length} ${blocking.length===1?"issue":"issues"}:
4
4
  `+blocking.map(finding=>` - ${finding.severity} [${finding.code}] ${finding.message}`).join(`
@@ -65,8 +65,11 @@ unmapped_commit_count:number;
65
65
  /** Maximum relationship depth searched for a governing decision. */
66
66
  decision_depth:number;
67
67
  }
68
- interface TraceabilityCandidate {
68
+ /** An item that may explain a source file, with the linked files that tie it to the source. */
69
+ export interface TraceabilityCandidate {
70
+ /** Candidate item metadata. */
69
71
  item:ItemMetadata;
72
+ /** Linked files of the item that match the source under explanation. */
70
73
  files:LinkedFile[];
71
74
  }
72
75
  interface GitAttribution {
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3bb613e2-51f9-5947-8d92-d6207bb62cdc")}catch{}})();import{execFile}from"node:child_process";import path from"node:path";import{assembleWorkspaceRelationshipGraph}from"../graph/assembly.js";function runGit(workspaceRoot,args){return new Promise((resolve,reject)=>{execFile("git",[...args],{cwd:workspaceRoot,encoding:"utf8",maxBuffer:4*1024*1024},(error,stdout)=>{error?reject(error):resolve(stdout)})})}function validateLineRange(range){if(range&&(!Number.isSafeInteger(range.start)||!Number.isSafeInteger(range.end)||range.start<1||range.end<range.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function parseSourceLineRange(value){const match=/^(\d+):(\d+)$/u.exec(value.trim()),range=match?{start:Number(match[1]),end:Number(match[2])}:void 0;if(validateLineRange(range),!range)throw new RangeError("Source line range must use start:end.");return range}function parseBlameCommits(output){const lines=new Map;for(const row of output.split(`
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="15749905-177d-5ae0-b475-668733f41e8a")}catch{}})();import{execFile}from"node:child_process";import path from"node:path";import{assembleWorkspaceRelationshipGraph}from"../graph/assembly.js";function runGit(workspaceRoot,args){return new Promise((resolve,reject)=>{execFile("git",[...args],{cwd:workspaceRoot,encoding:"utf8",maxBuffer:4*1024*1024},(error,stdout)=>{error?reject(error):resolve(stdout)})})}function validateLineRange(range){if(range&&(!Number.isSafeInteger(range.start)||!Number.isSafeInteger(range.end)||range.start<1||range.end<range.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function parseSourceLineRange(value){const match=/^(\d+):(\d+)$/u.exec(value.trim()),range=match?{start:Number(match[1]),end:Number(match[2])}:void 0;if(validateLineRange(range),!range)throw new RangeError("Source line range must use start:end.");return range}function parseBlameCommits(output){const lines=new Map;for(const row of output.split(`
2
2
  `)){const commit=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(row)?.[1];commit&&lines.set(commit,(lines.get(commit)??0)+1)}return lines}function parseCommitItemReferences(output){const fields=output.split("\0"),references=new Map;for(let index=0;index+1<fields.length;index+=2){const commit=fields[index]?.trim();if(!commit)continue;const ids=[...new Set(fields[index+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((left,right)=>left.localeCompare(right));references.set(commit,ids)}return references}async function readGitAttribution(params){const relativePath=path.relative(params.workspaceRoot,path.resolve(params.workspaceRoot,params.sourcePath)),blame=await runGit(params.workspaceRoot,["blame","--line-porcelain","-L",`${params.lineRange.start},${params.lineRange.end}`,"--",relativePath]),log=await runGit(params.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",relativePath]);return{commitLines:parseBlameCommits(blame),commitItems:parseCommitItemReferences(log),available:!0}}function expandDecisionPath(params){const tail=params.current.nodes.at(-1),nextDepth=params.current.kinds.length+1;let foundDepth;for(const edge of params.graph.incidentEdges(tail)){const outgoing=edge.source===tail,next=outgoing?edge.target:edge.source;if((params.visitedDepth.get(next)??Number.POSITIVE_INFINITY)<nextDepth)continue;params.visitedDepth.set(next,nextDepth);const definition=params.graph.registry().require(edge.kind),nextPath={nodes:[...params.current.nodes,next],kinds:[...params.current.kinds,outgoing?edge.kind:definition.inverse??edge.kind]};params.details.get(next)?.type?.toLowerCase()==="decision"?(foundDepth=nextDepth,params.found.push(nextPath)):params.queue.push(nextPath)}return foundDepth}function collectDecisionPaths(params){const queue=[{nodes:[params.itemId],kinds:[]}],visitedDepth=new Map([[params.itemId,0]]),found=[];let foundDepth;for(;queue.length>0;){const current=queue.shift(),depth=current.kinds.length;foundDepth!==void 0&&depth>=foundDepth||depth>=params.maxDepth||(foundDepth=expandDecisionPath({current,graph:params.graph,details:params.details,visitedDepth,queue,found})??foundDepth)}return found.sort((left,right)=>left.nodes.join("\0").localeCompare(right.nodes.join("\0"))),found}function shortestDecisionPath(itemId,corpus,maxDepth){const assembly=assembleWorkspaceRelationshipGraph(corpus);if(!assembly.graph.hasNode(itemId))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};const found=collectDecisionPaths({itemId,maxDepth,graph:assembly.graph,details:new Map(assembly.details.map(detail=>[detail.id,detail]))}),selected=found[0];if(!selected)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};const decisionIds=[...new Set(found.map(entry=>entry.nodes.at(-1)))];return{status:decisionIds.length===1?"found":"ambiguous",nodes:selected.nodes,kinds:selected.kinds,alternative_decision_ids:decisionIds.slice(1)}}async function resolveGitAttribution(params){if(!params.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await readGitAttribution({workspaceRoot:params.workspaceRoot,sourcePath:params.paths[0],lineRange:params.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function sourceAmbiguities(params){const ambiguities=[];return params.hasLineRange&&!params.attributionAvailable&&ambiguities.push("git_attribution_unavailable"),params.hasLineRange&&params.contributionLines===0&&ambiguities.push("line_attribution_unmapped"),params.decisionStatus==="ambiguous"&&ambiguities.push("multiple_governing_decisions"),params.decisionStatus==="not_found"&&ambiguities.push("governing_decision_not_found"),ambiguities}function mappedBlamedCommits(attribution){return[...attribution.commitLines.keys()].filter(commit=>(attribution.commitItems.get(commit)?.length??0)>0)}async function explainSourceTraceability(params){validateLineRange(params.lineRange);const decisionDepth=params.decisionDepth??8;if(!Number.isSafeInteger(decisionDepth)||decisionDepth<1||decisionDepth>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");const attribution=await resolveGitAttribution(params),mappedCommits=mappedBlamedCommits(attribution),explanations=new Map;for(const candidate of params.candidates){const attributedCommits=[...attribution.commitLines.entries()].filter(([commit])=>attribution.commitItems.get(commit)?.includes(candidate.item.id)),contributionLines=attributedCommits.reduce((total,[,lines])=>total+lines,0),decisionPath=shortestDecisionPath(candidate.item.id,params.corpus,decisionDepth),ambiguities=sourceAmbiguities({hasLineRange:params.lineRange!==void 0,attributionAvailable:attribution.available,contributionLines,decisionStatus:decisionPath.status});explanations.set(candidate.item.id,{score:contributionLines*100+candidate.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(candidate.item.updated_at))/(720*60*60*1e3))),contribution_lines:contributionLines,evidence:[...candidate.files.map(file=>({kind:"linked_file",reference:file.path})),...attributedCommits.map(([commit,lines])=>({kind:"git_commit",reference:commit.slice(0,12),contribution_lines:lines}))],rationale:{value:candidate.item.value?.trim()||null,why_now:candidate.item.why_now?.trim()||null,outcome:candidate.item.outcome?.trim()||null,objective:candidate.item.objective?.trim()||null},decision_path:decisionPath,ambiguities})}return{explanations,receipt:{line_range:params.lineRange??null,blamed_commit_count:attribution.commitLines.size,mapped_commit_count:mappedCommits.length,unmapped_commit_count:attribution.commitLines.size-mappedCommits.length,decision_depth:decisionDepth}}}const _testOnlySourceTraceability={mappedBlamedCommits,parseBlameCommits,parseCommitItemReferences,shortestDecisionPath};export{_testOnlySourceTraceability,explainSourceTraceability,parseSourceLineRange};
3
3
  //# sourceMappingURL=source-traceability.js.map
@@ -25,11 +25,11 @@ schema:typeof PM_WORKSPACE_RECIPE_SCHEMA;
25
25
  /** Ordered operations executed inside the deterministic context. */
26
26
  operations:readonly WorkspaceRecipeOperation[];
27
27
  }
28
- type ExactWorkspaceRecipe<TRecipe extends WorkspaceRecipe> = TRecipe & Record<Exclude<keyof TRecipe,keyof WorkspaceRecipe>,never>;
28
+ /** A workspace recipe literal with no keys beyond WorkspaceRecipe, so misspelled fields fail at compile time. */
29
+ export type ExactWorkspaceRecipe<TRecipe extends WorkspaceRecipe> = TRecipe & Record<Exclude<keyof TRecipe,keyof WorkspaceRecipe>,never>;
29
30
  /** Validate and freeze a caller-authored reproducible workspace recipe. */
30
31
  export declare function defineWorkspaceRecipe<const TRecipe extends WorkspaceRecipe>(recipe:ExactWorkspaceRecipe<TRecipe>):Readonly<TRecipe>;
31
32
  /** Run arbitrary SDK work under the recipe's deterministic clock and entropy. */
32
33
  export declare function runWithWorkspaceRecipe<T>(recipe:WorkspaceRecipe,operation:() => Promise<T>):Promise<T>;
33
34
  /** Replay every declared recipe operation with a caller-provided dispatcher. */
34
35
  export declare function executeWorkspaceRecipe<T>(recipe:WorkspaceRecipe,execute:(operation:WorkspaceRecipeOperation,index:number) => Promise<T>):Promise<T[]>;
35
- export {};
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2b24276b-948b-50bd-bfd9-f429cd74be70")}catch{}})();import{runWithReproducibleExecution,validateReproducibleExecutionSettings}from"../core/reproducibility/context.js";const PM_WORKSPACE_RECIPE_SCHEMA="https://schema.unbrained.dev/pm/workspace-recipe/v1";function cloneAndFreezeRecipeJson(value,location){if(value===null||typeof value=="boolean"||typeof value=="string")return value;if(typeof value=="number"){if(!Number.isFinite(value))throw new Error(`Workspace recipe JSON number must be finite at ${location}`);return value}if(Array.isArray(value))return Object.freeze(value.map((entry,index)=>cloneAndFreezeRecipeJson(entry,`${location}[${index}]`)));if(typeof value!="object"||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)throw new Error(`Workspace recipe input must contain JSON values at ${location}`);return Object.freeze(Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,cloneAndFreezeRecipeJson(entry,`${location}.${key}`)])))}function defineWorkspaceRecipe(recipe){if(recipe.schema!==PM_WORKSPACE_RECIPE_SCHEMA)throw new Error(`Unsupported workspace recipe schema: ${recipe.schema}`);const normalized=validateReproducibleExecutionSettings(recipe);if(recipe.operations.some(operation=>operation.action.trim().length===0||operation.input===null||Array.isArray(operation.input)))throw new Error("Workspace recipe operations require an action and object input");return Object.freeze({...normalized,operations:Object.freeze(recipe.operations.map((operation,index)=>Object.freeze({action:operation.action,input:cloneAndFreezeRecipeJson(operation.input,`operations[${index}].input`)})))})}async function runWithWorkspaceRecipe(recipe,operation){const defined=defineWorkspaceRecipe(recipe);return runWithReproducibleExecution(defined,operation)}async function executeWorkspaceRecipe(recipe,execute){return runWithWorkspaceRecipe(recipe,async()=>{const results=[];for(const[index,operation]of recipe.operations.entries())results.push(await execute(operation,index));return results})}export{PM_WORKSPACE_RECIPE_SCHEMA,defineWorkspaceRecipe,executeWorkspaceRecipe,runWithWorkspaceRecipe};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="619dbd55-b854-5e69-b5a5-c0bcada81629")}catch{}})();import{runWithReproducibleExecution,validateReproducibleExecutionSettings}from"../core/reproducibility/context.js";const PM_WORKSPACE_RECIPE_SCHEMA="https://schema.unbrained.dev/pm/workspace-recipe/v1";function cloneAndFreezeRecipeJson(value,location){if(value===null||typeof value=="boolean"||typeof value=="string")return value;if(typeof value=="number"){if(!Number.isFinite(value))throw new Error(`Workspace recipe JSON number must be finite at ${location}`);return value}if(Array.isArray(value))return Object.freeze(value.map((entry,index)=>cloneAndFreezeRecipeJson(entry,`${location}[${index}]`)));if(typeof value!="object"||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)throw new Error(`Workspace recipe input must contain JSON values at ${location}`);return Object.freeze(Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,cloneAndFreezeRecipeJson(entry,`${location}.${key}`)])))}function defineWorkspaceRecipe(recipe){if(recipe.schema!==PM_WORKSPACE_RECIPE_SCHEMA)throw new Error(`Unsupported workspace recipe schema: ${recipe.schema}`);const normalized=validateReproducibleExecutionSettings(recipe);if(recipe.operations.some(operation=>operation.action.trim().length===0||operation.input===null||Array.isArray(operation.input)))throw new Error("Workspace recipe operations require an action and object input");return Object.freeze({...normalized,operations:Object.freeze(recipe.operations.map((operation,index)=>Object.freeze({action:operation.action,input:cloneAndFreezeRecipeJson(operation.input,`operations[${index}].input`)})))})}async function runWithWorkspaceRecipe(recipe,operation){const defined=defineWorkspaceRecipe(recipe);return runWithReproducibleExecution(defined,operation)}async function executeWorkspaceRecipe(recipe,execute){return runWithWorkspaceRecipe(recipe,async()=>{const results=[];for(const[index,operation]of recipe.operations.entries())results.push(await execute(operation,index));return results})}export{PM_WORKSPACE_RECIPE_SCHEMA,defineWorkspaceRecipe,executeWorkspaceRecipe,runWithWorkspaceRecipe};
2
2
  //# sourceMappingURL=workspace-recipe.js.map
@@ -40,6 +40,22 @@ Explicit codec calls construct a dense grid proportional to row count times
40
40
  distinct-column count; package authors must budget that allocation for sparse
41
41
  inputs. This public codec does not impose a row cap or silently change encoding.
42
42
 
43
+ Two read shapes keep values the sparse policy would otherwise drop
44
+ ([pm-e3hfv8](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-e3hfv8.toon),
45
+ [pm-fkhdy8](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-fkhdy8.toon);
46
+ tracker records excluded from npm):
47
+
48
+ - Rows addressed by absolute position. `PM_READ_OUTPUT_POSITIONAL_ROW_PATHS`
49
+ declares the `comments`, `notes` and `learnings` listings, whose rows
50
+ `--edit <index>` and `--delete <index>` address. Their TOON listing renders
51
+ every stored row, a malformed `null` entry included, so the rendered length
52
+ matches `count` and a row's position matches its address. A listing with no
53
+ such row renders exactly as before.
54
+ - An explicit `get --fields` selection renders every empty collection inside
55
+ the selected item fields and derived facets (`linked`, `schedule`,
56
+ `claim_state`, `children`, `blockers`) at any depth, as JSON delivers it,
57
+ for example `linked.tests: []`. Nulls inside those values stay dropped.
58
+
43
59
  The TOON presentation of an item prints `collection_counts.notes` and
44
60
  `collection_counts.tests` once, suppressing `notes_count` or `tests_count` only
45
61
  when the alias equals its canonical count. Zero counts and differing values stay
@@ -56,7 +56,6 @@ src/
56
56
  extension/
57
57
  help-content.ts
58
58
  error-guidance.ts
59
- extension-command-options.ts
60
59
  core/
61
60
  extensions/
62
61
  loader.ts
@@ -101,6 +100,8 @@ src/
101
100
  semantic.ts
102
101
  response.ts
103
102
  types.ts
103
+ extension/
104
+ command-options.ts
104
105
  mcp/
105
106
  discovery.ts
106
107
  types/
package/docs/COMMANDS.md CHANGED
@@ -1093,11 +1093,14 @@ printf '%s\n' '## Verification summary' '- Linux pass' '- macOS pass' | pm comme
1093
1093
  pm comments <id> --file docs/release-evidence.md
1094
1094
  pm comments <id> --edit 2 "Corrected: the regression was in the parser, not the renderer."
1095
1095
  pm comments <id> --delete 3
1096
+ pm comments <id> --edit 263 --expect-at 2026-11-06T06:02:01.768Z "Corrected the newest comment."
1096
1097
  pm notes <id> --add "Keep renderer changes isolated to TOON output." --if-absent
1097
1098
  pm learnings <id> --add "Use runtime contracts instead of duplicating flag lists." --if-absent
1098
1099
  ```
1099
1100
 
1100
- Use comments for progress and evidence, notes for implementation context, and learnings for durable future guidance. All three accept `--text` as a hidden compatibility alias for canonical `--add`; comments also retain `--body`/`--comment`, and notes retain `--note`. Choose exactly one input source (`[text]`, an add alias, `--stdin`, or `--file`) per invocation. Conflicting alias values fail before mutation. For retrying agents, `--if-absent` makes any annotation append idempotent by the resolved author plus exact normalized stored text: the first call returns `changed: true` and `mutation_receipt.changed_count: 1`; an exact retry returns `changed: false`, the existing entry position, and `changed_count: 0` without writing item or history state. Different authors remain distinct, and omitting `--if-absent` deliberately preserves duplicate-appending compatibility. The flag is append-only and is rejected for list, edit, and delete operations. To clean up obsolete orchestration notes, `--edit <index>` rewrites the comment at a 1-based index and `--delete <index>` removes it; both record history and honor ownership rules.
1101
+ Use comments for progress and evidence, notes for implementation context, and learnings for durable future guidance. All three accept `--text` as a hidden compatibility alias for canonical `--add`; comments also retain `--body`/`--comment`, and notes retain `--note`. Choose exactly one input source (`[text]`, an add alias, `--stdin`, or `--file`) per invocation. Conflicting alias values fail before mutation. An add alias that took an option as its value (`pm comments <id> --add --file note.md`) refuses with `annotation_flag_like_value` before any source conflict is reported: the refusal names the option's own form (`--file <path>` or `--stdin` works without `--add`) and, when dropping `--add` leaves exactly one source, `recovery.suggested_retry_args` holds your command without it. Use `--add text=--file` for literal dash-leading text. For retrying agents, `--if-absent` makes any annotation append idempotent by the resolved author plus exact normalized stored text: the first call returns `changed: true` and `mutation_receipt.changed_count: 1`; an exact retry returns `changed: false`, the existing entry position, and `changed_count: 0` without writing item or history state. Different authors remain distinct, and omitting `--if-absent` deliberately preserves duplicate-appending compatibility. The flag is append-only and is rejected for list, edit, and delete operations. To clean up obsolete orchestration notes, `--edit <index>` rewrites the comment at a 1-based index and `--delete <index>` removes it; both record history and honor ownership rules.
1102
+
1103
+ Reading annotations (tracked by [pm-8s53lj](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8s53lj.toon) and [pm-hka7ep](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-hka7ep.toon); tracker records excluded from npm): rows stay in stored order, oldest first. Every row leads with `index`, its absolute 1-based position in the stored collection, so the index a row reports is the one `--edit` and `--delete` accept on any page, limit or `pm notes` event filter. When a bare `pm comments`, `pm notes` or `pm learnings` read must be bounded by its output budget, it keeps the newest entries, the same tail `--limit <n>` and `--output-limit <n>` select, so `.comments[-1]` is always the newest comment. The page then carries `count` (rows delivered) beside `total_count` (entries stored), and `next_cursor` continues backwards: `--output-cursor <cursor>` returns the next older page until no older rows remain. A page's `count` is not an entry address. To check that an index still holds an entry with the timestamp you read, pass that row's `created_at` as `--expect-at <ts>` with `--edit` or `--delete` (MCP and SDK: `expectAt`). An entry at that index with a different `created_at` is refused with exit 4 and `annotation_entry_mismatch` before anything is written. On that refusal, `details.matching_indexes` lists every index whose entry has the expected `created_at`. The flag is refused without `--edit` or `--delete` (`annotation_expectation_without_target`). Without `--expect-at`, `--edit <index>` and `--delete <index>` behave as before and address the absolute index unguarded. `created_at` is a timestamp, not a unique identity: entries imported or written in the same millisecond can share one, and when such entries shift, the guard accepts any entry with that timestamp at the index without a refusal. A stable per-entry identity is owned by [pm-gh1381](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-gh1381.toon) (tracker record excluded from npm).
1101
1104
 
1102
1105
  ## Linked Artifacts
1103
1106
 
@@ -139,7 +139,7 @@ catalog rows across 17 canonical groups. Two of those rows are author-manifest
139
139
  schema findings reached through a real `pm health --full --strict-exit --json`
140
140
  process: an unknown top-level key and omitted canonical pm version bounds. The
141
141
  remaining rows stay explicit `uncovered` obligations in
142
- [the generated census](generated/REFUSAL_CLOSURE_CENSUS.md); the ratchet does not
142
+ [the generated census](https://github.com/unbraind/pm-cli/blob/main/docs/generated/REFUSAL_CLOSURE_CENSUS.md) (current `main`, repository-only gate evidence excluded from npm; for an installed release, open the same path at its `v<version>` tag); the ratchet does not
143
143
  turn partial catalog closure into an approval claim.
144
144
 
145
145
  Run the focused proof with:
@@ -305,7 +305,7 @@ Use the public SDK barrel. Do not deep-import from `src/core` or `dist/core`.
305
305
 
306
306
  - `api.extension` is a read-only identity (`name`, `layer`, `version`, `capabilities`, `pm_min_version?`, `pm_max_version?`, `source_package?`) for self-identifying logs and version gating without re-reading the manifest.
307
307
  - `api.registerCommand(definition)` adds package-owned commands; `read_output` opts readers into the [SDK output contract](SDK.md#minimal-command-extension).
308
- - `api.registerFlags(command, flags)` adds runtime command flags. A flag may declare `value_type` (canonical; the legacy `type` alias is honored only when `value_type` is absent), `list: true` to accumulate repeated/comma-joined values like core `--tags`, a `default` applied when the flag is omitted, and `value_validation: "strict"` to refuse malformed `number`/`boolean` tokens before the handler runs (the default `"coerce"` forwards the raw token). See [Flag Contracts](SDK.md#flag-contracts).
308
+ - `api.registerFlags(command, flags)` adds runtime command flags. A flag may declare `value_type` (canonical; the legacy `type` alias is honored only when `value_type` is absent), `list: true` to accumulate repeated/comma-joined values like core `--tags`, a `default` applied when the flag is omitted, and `value_validation: "strict"` to refuse malformed `number`/`boolean` tokens before the handler runs (the default `"coerce"` forwards the raw token). The handler reads each flag from `context.options` under its camel-case handler key (`--status-filter` → `statusFilter`), published as `sdk_option` by `pm contracts --command <command> --flags-only --json`; CLI, `PmClient.run`, MCP, and `runRegisteredCommandForTest` all deliver that key with the same defaults and coercion, and host flags such as `--json`, `--author`, and `--pm-path` arrive in `context.global` and are listed as `inherited_flags`. On the CLI, a command that declares flags refuses any other option with `unknown_option` before the handler runs (a command that declares none still receives undeclared options for now, see pm-4of199 in the SDK guide), and two spellings of one flag with different values (`--status-filter open -s closed`) are refused with `extension_option_spelling_conflict`, so declare every option a handler reads. See [Handler keys and ownership](SDK.md#handler-keys-and-ownership).
309
309
  - `api.registerItemFields(fields)` adds custom metadata fields. Agents can set declared fields with repeatable `pm create --field name=value` and `pm update <id> --field name=value`; undeclared names are rejected. Extension declarations are matched first; a name that no active extension declares but the project schema does (for example `gate_evidence`) is refused with `project_schema_field_requires_declared_flag`, which names a CLI flag and an SDK option that each set only that field (each is omitted when every spelling is shared with another declared field or with an option of the command itself) and, on the CLI, an executable `suggested_retry_args` that rewrites only that assignment. The guidance follows the invoking scope (a bulk `update-many` row is routed under `update_many`, not `update`), and when the same invocation already sets that field through a declared flag, alias or option, no route or retry is offered, because the retry would carry two values for one field ([pm-wftvem](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-wftvem.toon); tracker record excluded from npm); reserved core keys keep `core_item_field_requires_dedicated_flag`. `SchemaFieldDefinition.type` is the same closed union used by `pm schema add-field`: `string | number | boolean | string_array | array | object`. Unsupported values fail at compile time for TypeScript authors and at activation for JavaScript packages, with a did-you-mean hint on typos. `string_array` is the repeatable string collection; `array` and `object` require JSON containers. Active fields support `get`, `list` and `search` projections with `--fields name` or `--fields item.name`, preserving declared value types through `PmClient` and CLI reads. Disabled packages do not contribute selectors. Tracked by [pm-gh1571](../.agents/pm/issues/pm-gh1571.toon).
310
310
  - Custom fields whose camel-case option name is already owned by a canonical MCP input remain usable through `options.<name>`, but authoring surfaces report the collision instead of allowing silent top-level shadowing. `pm schema add-field`, `pm profile lint`, and `pm package doctor` name the field, canonical `mcp_tool_input` owner, and nested recovery path. SDK authors can preflight the same rule with `resolvePmToolCustomFieldCollision`.
311
311
  - `api.registerItemTypes(types)` adds custom item types.
@@ -27,6 +27,19 @@ Array values that become CLI CSV inputs, such as `tags`, must contain only
27
27
  strings and are checked before conversion. Validation follows nested precedence:
28
28
  an explicit valid nested value replaces a flat value before either is normalized.
29
29
 
30
+ The read tools (`context`, `get`, `list`, `next`, `search`) and the annotation,
31
+ linked-artifact and linked-test tools (`comments`, `notes`, `learnings`,
32
+ `files`, `docs`, `test`) hoist every optional parameter their strict action contract declares, derived
33
+ from `PM_TOOL_ACTION_PARAMETER_CONTRACTS` rather than a hand list
34
+ ([pm-wsqxwb](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-wsqxwb.toon);
35
+ tracker record excluded from npm). A flat `add` therefore writes instead of
36
+ falling through to a listing read. The annotation `text` operand (flat or
37
+ nested) is bound to `add` the way the CLI binds positional text. Equal values
38
+ are accepted, and different `text` and `add` values are refused with
39
+ `annotation_text_source_conflict` before anything is written. A nested snake_case
40
+ spelling of a declared annotation parameter (`expect_at`, `if_absent`) is renamed
41
+ to the camelCase key the SDK reads, so it cannot silently drop a guard.
42
+
30
43
  For example, `{ "id": "pm-one", "options": {}, "priority": 4 }` changes priority;
31
44
  with `"options": { "priority": 2 }`, priority becomes `2`. Create also honors its
32
45
  advertised explicit `id`, `deadline`, and other metadata. Regressions check the
package/docs/README.md CHANGED
@@ -64,13 +64,13 @@ pm guide release --json
64
64
  - [Context Relevance and Packing](CONTEXT_RELEVANCE.md) - shared CLI/SDK signals, derived-store provenance, ranking explanations, and token budgets.
65
65
  - [Next-work Selection Budgets](NEXT_SELECTION_BUDGETS.md) - bounded executable recommendations, omission receipts, and graded 10k/100k context verification.
66
66
  - [Context Algorithm Portfolio](CONTEXT_ALGORITHM_PORTFOLIO.md) - stable proposal slugs, historical aliases, individual owners, cognitive compositions, and experiment gates.
67
- - [Ecosystem Planning Review](ECOSYSTEM_PLANNING_REVIEW.md) - dated all-status census, canonical horizons, operational evidence, and active-readiness gates.
67
+ - [Ecosystem Planning Review](https://github.com/unbraind/pm-cli/blob/main/docs/ECOSYSTEM_PLANNING_REVIEW.md) - dated all-status census, canonical horizons, operational evidence, and active-readiness gates (repository-only planning evidence on upstream `main`, excluded from npm; in a fork or another checkout, open `docs/ECOSYSTEM_PLANNING_REVIEW.md` there).
68
68
  - [Output Projection and Omission Contracts](OUTPUT_PROJECTION_CONTRACTS.md) - explicit withheld-field receipts, mode-paired row keys, and completion resolver outcomes.
69
69
  - [Output Token Accounting](OUTPUT_TOKEN_ACCOUNTING.md) - opt-in CLI/MCP byte attribution, bounded receipt overhead, and release-level tokens-per-task baselines.
70
70
  - [SDK Context Platform](SDK_CONTEXT.md) - task-oriented entry point for authoritative reads, ranking, package workflows, diagnostics, recovery, and verification.
71
71
  - [Self-Describing Context Contracts](SELF_DESCRIBING_CONTEXT_CONTRACTS.md) - intent-scoped reads, semantic flag invocation metadata, visibility parity, and generated error vocabulary.
72
72
  - [Generated Agent Capability Routing](generated/AGENT_CAPABILITY_ROUTING.md) - contract-derived command families shared by help, guide, skills, completion, MCP, and extensions.
73
- - [Generated Refusal Closure Census](generated/REFUSAL_CLOSURE_CENSUS.md) - complete error-catalog join to executable refusal evidence and explicit uncovered obligations.
73
+ - [Generated Refusal Closure Census](https://github.com/unbraind/pm-cli/blob/main/docs/generated/REFUSAL_CLOSURE_CENSUS.md) - complete error-catalog join to executable refusal evidence and explicit uncovered obligations (repository-only gate evidence on upstream `main`, excluded from npm; in a fork or another checkout, open `docs/generated/REFUSAL_CLOSURE_CENSUS.md` there).
74
74
  - [Universal Read Output Contracts](READ_OUTPUT_CONTRACTS.md) - cross-command include, amount, cost, and encoding controls for CLI, SDK, MCP, and packages.
75
75
  - [Diagnostic Output Contracts](DIAGNOSTIC_OUTPUT_CONTRACTS.md) - action-first error budgets, deterministic degradation, SDK projection, and executable refusal assurance.
76
76
  - [History Algorithms and Detached Attestations](HISTORY_ATTESTATION.md) - named record digests, portable exact-byte proofs, and read-only verification.
@@ -360,6 +360,8 @@ from the exact active result passed to telemetry and after-command hooks.
360
360
 
361
361
  When rows are dropped to satisfy a ceiling, the result also carries `output_budget_truncation`, naming the binding budget and its source, any explicitly requested dimension the budget overrode, every compacted collection path, and executable CLI/SDK/MCP recovery options — a default ceiling can override an explicit `--output-limit unbounded`, and that override is reported rather than silent. If a producer supplied an opaque item-page cursor, compaction rebases it to the last row actually returned and reports `continuation_cursor_rebased: true`; following the cursor therefore cannot skip rows removed from the middle of a producer page. If no useful content can fit, `PmReadOutputBudgetExceeded` provides a discriminated omission result, a compact `{ outputBudget: "unbounded" }` recovery object, and `omitted_result_estimated_tokens`, the last useful-result estimate before omission; use `isReadOutputBudgetExceeded` before accessing result-specific fields. The encoding control `--output-format <toon|json>` also applies to mutation envelopes, including the mutation modes of `comments`, `notes`, `files`, and `docs`. Other universal read controls remain rejected before mutation execution. `--json` remains supported.
362
362
 
363
+ That rejection is typed ([pm-rrwh2o](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-rrwh2o.toon); tracker record excluded from npm). A `comments`, `notes`, `learnings`, `files`, `docs` or package-catalog mutation given `--output-include`, `--output-limit`, `--output-budget`, `--output-session`, `--output-cursor` or `--output-row-contract` exits 2 with `read_output_mutation_conflict` before anything is written. `details.output_controls` names the offending flags, `details.output_option_keys` names the option keys the SDK or MCP caller supplied, and `details.mutation_options` names the mutation that made the call a write. The CLI recovery's `suggested_retry_args` is the caller's own invocation without those controls and their values; tracker scope, operands and every other option stay where they were. The CLI withholds `suggested_retry_args` when it cannot rebuild the invocation safely: an option whose value arity is undeclared, a control that took a flag-like token as its value, a control right after a value-taking option, a tracker selection that cannot be bound, an enclosing SDK revision scope whose guards never reached argv, or a token that may carry URL credentials, meaning any token with both an `@` and a `:` (a package source such as `https://user:token@host/pkg.tgz`), so the recovery never repeats a secret in another field. That check is deliberately conservative: a scoped package name beside a colon also gets no retry. The refusal then still names the controls, and the caller rebuilds the retry from its own arguments. SDK and MCP callers drop the named keys. To bound or page the collection, read it with the controls in a separate call after the write. `READ_OUTPUT_MUTATION_CONFLICT_CODE` and `READ_OUTPUT_SHAPING_CONTROL_FLAGS` are exported for package authors.
364
+
363
365
  Cursor recovery carries the opaque value once in `recovery.cursor` and declares
364
366
  the accepting `cli`, `sdk`, and `mcp` binding beside it. This avoids
365
367
  serializing the same cursor once per transport while retaining an executable,
@@ -385,6 +387,39 @@ an unbounded multi-megabyte response;
385
387
  `recovery_budget_multiplier: 1` declares that each next page retains the same
386
388
  useful-result ceiling.
387
389
 
390
+ Chronological annotation collections keep their newest rows instead
391
+ ([pm-8s53lj](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8s53lj.toon);
392
+ tracker record excluded from npm). `PM_READ_OUTPUT_TAIL_RETENTION_POLICIES`
393
+ declares the `comments`, `notes` and `learnings` row paths, and
394
+ `readOutputRetainsTail(command, path)` answers for one path. Budget compaction
395
+ and `--output-limit` retain the tail of those paths, matching the producer's own
396
+ latest-N `--limit`. Their continuation cursor carries `direction: "backward"`:
397
+ `offset` counts the older rows still withheld, `remaining_rows` equals it, and
398
+ replaying the cursor delivers the newest rows before that offset. A cursor whose
399
+ direction disagrees with the path's declared retention is refused as
400
+ `read_output_cursor_stale`. A withheld tail also sets the policy's `total_key`
401
+ (`total_count`) beside `count`, and a producer `returned_count` is refreshed to
402
+ the delivered page.
403
+
404
+ The MCP `pm_comments` listing applies no producer page of its own
405
+ ([pm-sbqn4h](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-sbqn4h.toon);
406
+ tracker record excluded from npm). It used to return only the newest 20
407
+ comments, so a backward cursor stopped at that page's edge while `has_more`
408
+ stayed true. A listing now reports `total_count` and `has_more` and leaves the
409
+ bound to the output budget, exactly like `pm_notes`, `pm_learnings` and the
410
+ CLI. Following `next_cursor` alone therefore reaches the oldest comment, and
411
+ `has_more` is true only while a cursor continues. `options.limit=N` still
412
+ selects the newest N comments; there the caller chose the window, so
413
+ `has_more` can report older comments without a `next_cursor`, and the caller
414
+ raises or removes the limit to read them. The same holds for `outputLimit`:
415
+ a universal row limit truncates without a cursor, so `has_more` reports the
416
+ older comments and the caller raises or removes it. Inside such a window, a
417
+ `next_cursor` still pages through the rows the budget trimmed. Without either
418
+ limit, `outputBudget: "unbounded"` returns the complete listing in one
419
+ response. A budget too small for even one comment omits the listing
420
+ (`output_budget_exceeded`, no `next_cursor`); retry with `outputBudget:
421
+ "unbounded"`, keeping any `outputCursor` already being followed.
422
+
388
423
  Health continuation fingerprints use a versioned nonvolatile-snapshot policy
389
424
  for the `checks` row. Command-lifecycle telemetry may refresh timestamps, queue
390
425
  counters, and pending spans between pages, so the policy excludes only those
@@ -407,6 +442,10 @@ uses `unbounded` explicitly. `resolveReadOutputRecoveryBudget()` exposes the
407
442
  versioned pure calculation to package authors; there is no hard-coded smaller
408
443
  retry and no recovery cycle.
409
444
 
445
+ Comments, notes and learnings declare `budget_retention_policy: ordered_suffix`:
446
+ budget compaction keeps their newest rows and their continuation pages
447
+ backwards (see the tail retention policy above). Every other surface except
448
+ assurance declares `ordered_prefix`.
410
449
  Assurance declares `budget_retention_policy: verdict_priority`: failing block,
411
450
  warn, and observe rows precede retired and passing rows while preserving order
412
451
  within each class. `assertions_total` remains the pre-projection denominator,
@@ -429,6 +468,66 @@ from successful command results. Corrective actions precede explanation and
429
468
  survive every degradation stage, while untruncated JSON avoids a per-call
430
469
  receipt tax.
431
470
 
471
+ ### Delivered bytes, intent budgets and complete receipts
472
+
473
+ Tracked by [pm-gh1678](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1678.toon),
474
+ [pm-gh1662](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1662.toon) and
475
+ [pm-sj66lm](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-sj66lm.toon)
476
+ (repository-only tracker records excluded from npm).
477
+
478
+ The CLI measures what it writes. When a scoped `registerRenderer` replacement,
479
+ an `output_format` service override, or a markdown default renders a declared
480
+ read, every estimate, compaction step and omission decision uses that
481
+ delivered string, so `read_output.estimated_tokens` describes the bytes the
482
+ caller receives. A string that cannot fit returns the bounded native
483
+ `output_budget_exceeded` refusal with exit 2; a refusal is always rendered
484
+ natively and never passed back through an expanding renderer. Commands that
485
+ declare no read output keep their renderer untouched, and
486
+ `--output-budget unbounded` keeps unbounded custom rendering.
487
+
488
+ A renderer whose output depends on its own receipts need not converge, so the
489
+ receipt estimates stop after a bounded number of passes. That bound is never
490
+ taken as proof of fit. The CLI checks the final custom rendering against its
491
+ receipts. If any receipt reports fewer tokens than the rendering costs, or the
492
+ intent receipt claims a fit that the rendering exceeds, the read is measured
493
+ and rendered natively instead. No byte that a receipt did not measure is
494
+ delivered. A renderer's own nested SDK contract calls measure their own
495
+ representation, never the outer delivery.
496
+
497
+ Read intents (`--for <intent>`) accept one budget under both spellings: a
498
+ numeric `--output-budget` binds the intent's token budget exactly as the legacy
499
+ `--token-budget` does, including its budget-derived row limit. Both spellings
500
+ apply one rule to the bytes they deliver. The legacy spelling's receipt also
501
+ carries its migration hint, so at the exact boundary it can omit where the
502
+ canonical spelling still fits. The intent estimate covers the delivered
503
+ encoding (pretty JSON or TOON, without a `row_contract` the caller did not
504
+ request). It is settled over the complete envelope, including the
505
+ `read_output` receipt and any requested row contract. A delivery whose settled
506
+ envelope exceeds the intent budget is decided again, with the measured overhead
507
+ charged against the budget, so row compaction leaves room for the receipts. A
508
+ re-settled envelope that still exceeds the budget is omitted, so a read never
509
+ delivers more than its budget allows. `--output-include` never shapes an
510
+ omission: a refused read keeps its refusal under every include selection. A
511
+ successful include projection that drops the intent receipt still answers to
512
+ the intent budget over the bytes it delivers. A refused continuation page keeps
513
+ its receipts whole, and every receipt agrees that it omitted. The retry that a
514
+ legacy refusal names keeps the caller's `--fields` projection, because its
515
+ budget was sized against that projection. An omitted intent result is
516
+ unsuccessful everywhere: the CLI exits 2, and `context_intent`, `read_output`
517
+ and the omission branch all report `result_omitted: true` and
518
+ `within_budget: false`. The canonical spelling keeps the shared
519
+ `output_budget_exceeded` branch; the legacy spelling keeps `budget_exceeded`,
520
+ whose `restore_with` carries the universal 25% recovery margin so the retry it
521
+ names returns the result. SDK consumers detect either branch with
522
+ `isReadResultOmittedForBudget`. `--output-budget unbounded` on an intent read
523
+ never omits the result; its receipt reports `within_budget: false` when the
524
+ result exceeds the declared intent ceiling.
525
+
526
+ In TOON, an omission receipt that reports nothing omitted costs one line,
527
+ `omission_receipt: complete`, and an explicit `get --fields` selection renders
528
+ each requested empty collection as `key: []`. JSON, SDK and MCP keep the typed
529
+ receipt, and receipts that report omissions are unchanged.
530
+
432
531
  ## SDK and Package Usage
433
532
 
434
533
  Typed `PmClient` read methods accept `PmReadOutputOptions` directly:
package/docs/RELEASING.md CHANGED
@@ -610,7 +610,18 @@ never move a published tag or mint a second automatic version for the same UTC d
610
610
  post-publish npm/npx/bunx verifier so those identities cannot drift. The
611
611
  explicit stable dist-tag also preserves
612
612
  correct `latest` behavior when rerunning historical ordinal tags.
613
- - post-publish npm/npx/bunx verification through
613
+ - post-publish npm/npx/bunx verification in the separate `publication` job,
614
+ which needs the publishing job and owns a 110-minute limit, so a slow build
615
+ phase can no longer cut the registry wait short. npm's publish-time malware
616
+ scan holds a new version for about five minutes and sometimes far longer
617
+ (2026.11.8 became visible 55m22s after publish); the verifier polls for
618
+ about ninety minutes, and an exhausted wait names the version, the scan and
619
+ the publication-only re-run
620
+ ([pm-0jzl5t](../.agents/pm/issues/pm-0jzl5t.toon)). The job checks out
621
+ the exact commit the release job published (recorded after exact-tag source
622
+ selection), so the verifiers read the same `package.json` identity as the
623
+ publish guard; previous-release selection keeps the reviewed dispatch-source
624
+ selector. The verifier runs
614
625
  `scripts/release/verify-published-release.mjs`, using isolated empty npm and
615
626
  Bun caches plus an empty npm user config so maintainer credentials and cached
616
627
  metadata cannot mask a public-registry outage. The verifier dispatches a real
@@ -636,10 +647,11 @@ never move a published tag or mint a second automatic version for the same UTC d
636
647
  - GitHub Release creation
637
648
  - GitHub Release metadata verification through the same local verification script
638
649
 
639
- The Auto Release parent has a 180-minute orchestration limit: 60 minutes for
640
- preparation and gates, 30 for aggregate runner queue delays, the unchanged
641
- 60-minute publication, 15-minute acceptance and 5-minute advertisement job
642
- limits, and 10 minutes for orchestration overhead. Runner queue time consumes
650
+ The Auto Release parent has a 290-minute orchestration limit: 60 minutes for
651
+ preparation and gates, 30 for aggregate runner queue delays, the serial
652
+ 60-minute build-and-publish, 110-minute publication verification, 15-minute
653
+ acceptance and 5-minute advertisement job limits, and 10 minutes for
654
+ orchestration overhead. Runner queue time consumes
643
655
  the waiting parent's wall time even when no child job is executing. The
644
656
  reserve accommodates delays without extending a child job or changing a
645
657
  quality gate. Extreme queue delays can still exhaust the parent; recover the
@@ -722,6 +734,16 @@ Use the npm registry package for maintainer global updates. Do not use `npm inst
722
734
  use the same guarded regeneration because their tag did not exist when the
723
735
  release commit's changelog was prepared. Other registry failures stop before
724
736
  source selection or publication.
737
+ - If the `publication` job fails because npm has not yet made a version that
738
+ `Publish to npm` accepted visible, the package is held by npm's publish-time
739
+ scan, not lost. Do not dispatch a recovery or touch the tag. Once
740
+ `npm view @unbrained/pm-cli@<version> version` succeeds, run
741
+ `gh run rerun <run-id> --failed`: only the publication job and the skipped
742
+ acceptance and advertisement jobs run again, without rebuilding or
743
+ republishing. The failure message prints the exact command
744
+ ([pm-0jzl5t](../.agents/pm/issues/pm-0jzl5t.toon)). Close the bot-created
745
+ `Auto Release blocked` issue by hand after that run succeeds; the parent run
746
+ that recorded the failure stays red.
725
747
  - If an immutable published package contains a defect that cannot be repaired
726
748
  by rerunning the same tag workflow, document the incident and ship the code
727
749
  fix in the next UTC day's release.