@unbrained/pm-cli 2026.9.6 → 2026.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (719) hide show
  1. package/.agents/skills/pm-developer/SKILL.md +12 -4
  2. package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +19 -10
  3. package/.agents/skills/pm-extensions/SKILL.md +6 -0
  4. package/.agents/skills/pm-sdk/SKILL.md +11 -2
  5. package/.agents/skills/pm-user/SKILL.md +5 -0
  6. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +95 -0
  7. package/.claude-plugin/marketplace.json +2 -2
  8. package/CHANGELOG.md +218 -182
  9. package/dist/cli/after-command-context-usage.js +1 -48
  10. package/dist/cli/argv-utils.js +1 -40
  11. package/dist/cli/bootstrap-args.js +1 -9
  12. package/dist/cli/bundle-integrity.js +2 -110
  13. package/dist/cli/commander-usage.js +11 -771
  14. package/dist/cli/commands/activity.js +1 -9
  15. package/dist/cli/commands/aggregate.js +1 -5
  16. package/dist/cli/commands/append.js +1 -5
  17. package/dist/cli/commands/claim.js +1 -5
  18. package/dist/cli/commands/close-many.js +1 -5
  19. package/dist/cli/commands/close.js +1 -9
  20. package/dist/cli/commands/comments.js +1 -5
  21. package/dist/cli/commands/config.js +1 -9
  22. package/dist/cli/commands/context.js +1 -9
  23. package/dist/cli/commands/contracts.js +1 -5
  24. package/dist/cli/commands/copy.js +1 -9
  25. package/dist/cli/commands/create.js +1 -9
  26. package/dist/cli/commands/delete.js +1 -9
  27. package/dist/cli/commands/deps.js +1 -9
  28. package/dist/cli/commands/docs.js +1 -9
  29. package/dist/cli/commands/duplicates.js +1 -9
  30. package/dist/cli/commands/eval.js +1 -9
  31. package/dist/cli/commands/extension/describe.js +1 -5
  32. package/dist/cli/commands/extension/scaffold.js +1 -5
  33. package/dist/cli/commands/extension/shared.js +1 -5
  34. package/dist/cli/commands/extension.js +1 -9
  35. package/dist/cli/commands/files.js +1 -9
  36. package/dist/cli/commands/focus.js +1 -9
  37. package/dist/cli/commands/gc.js +1 -9
  38. package/dist/cli/commands/get.js +1 -9
  39. package/dist/cli/commands/graph.js +1 -10
  40. package/dist/cli/commands/health.js +1 -9
  41. package/dist/cli/commands/history-compact.js +1 -10
  42. package/dist/cli/commands/history-redact.js +1 -11
  43. package/dist/cli/commands/history-repair.js +1 -10
  44. package/dist/cli/commands/history.js +1 -5
  45. package/dist/cli/commands/index.js +1 -58
  46. package/dist/cli/commands/init-agent-guidance.js +1 -9
  47. package/dist/cli/commands/init.js +1 -9
  48. package/dist/cli/commands/learnings.js +1 -5
  49. package/dist/cli/commands/lifecycle-transitions.js +1 -5
  50. package/dist/cli/commands/list.js +1 -9
  51. package/dist/cli/commands/merge.js +1 -11
  52. package/dist/cli/commands/next.js +1 -9
  53. package/dist/cli/commands/notes.js +1 -5
  54. package/dist/cli/commands/plan.js +1 -9
  55. package/dist/cli/commands/profile.js +1 -9
  56. package/dist/cli/commands/restore.js +1 -9
  57. package/dist/cli/commands/scheduling-shortcuts.js +1 -9
  58. package/dist/cli/commands/schema.js +1 -10
  59. package/dist/cli/commands/search.js +1 -9
  60. package/dist/cli/commands/stats.js +1 -9
  61. package/dist/cli/commands/telemetry.js +1 -9
  62. package/dist/cli/commands/test-all.js +1 -9
  63. package/dist/cli/commands/test-runs.js +1 -9
  64. package/dist/cli/commands/test.js +1 -9
  65. package/dist/cli/commands/update-many.js +1 -5
  66. package/dist/cli/commands/update.js +1 -9
  67. package/dist/cli/commands/upgrade.js +1 -5
  68. package/dist/cli/commands/validate.js +1 -15
  69. package/dist/cli/context-intent-invocation.js +1 -20
  70. package/dist/cli/description-stdin.js +1 -17
  71. package/dist/cli/error-guidance.js +1 -1353
  72. package/dist/cli/extension-command-help.js +5 -636
  73. package/dist/cli/extension-command-options.js +1 -427
  74. package/dist/cli/extension-recovery.js +1 -126
  75. package/dist/cli/help-content.js +2 -1001
  76. package/dist/cli/help-json-payload.js +4 -570
  77. package/dist/cli/main.d.ts +4 -0
  78. package/dist/cli/main.js +5 -2573
  79. package/dist/cli/migration-gates.js +1 -289
  80. package/dist/cli/public.js +1 -20
  81. package/dist/cli/register-annotations.js +1 -270
  82. package/dist/cli/register-assurance.js +1 -62
  83. package/dist/cli/register-files-lookup.js +1 -56
  84. package/dist/cli/register-history-activity.d.ts +8 -0
  85. package/dist/cli/register-history-activity.js +2 -0
  86. package/dist/cli/register-history-author.js +1 -38
  87. package/dist/cli/register-history-maintenance.d.ts +9 -0
  88. package/dist/cli/register-history-maintenance.js +2 -0
  89. package/dist/cli/register-list-query.js +10 -943
  90. package/dist/cli/register-mutation-options.js +1 -9
  91. package/dist/cli/register-mutation.js +19 -1893
  92. package/dist/cli/register-operations.js +1 -920
  93. package/dist/cli/register-setup.js +1 -716
  94. package/dist/cli/register-structured-mutation.js +1 -196
  95. package/dist/cli/registration-helpers.js +1 -5
  96. package/dist/cli/runtime-compatibility-boundary.js +4 -42
  97. package/dist/cli/schema-registration-helpers.js +1 -73
  98. package/dist/cli/search-refresh.js +1 -13
  99. package/dist/cli/stats-analytics-json.js +1 -68
  100. package/dist/cli/telemetry-flush.js +1 -10
  101. package/dist/cli-bundle/bundle-manifest.json +164 -156
  102. package/dist/cli-bundle/chunks/chunk-3BZZA6A3.js +5 -0
  103. package/dist/cli-bundle/chunks/chunk-AMRDVX36.js +235 -0
  104. package/dist/cli-bundle/chunks/chunk-DAM4CBBR.js +2202 -0
  105. package/dist/cli-bundle/chunks/{chunk-WYRZZ5ZE.js → chunk-DEZPZOQ7.js} +2 -2
  106. package/dist/cli-bundle/chunks/chunk-FLDWYEND.js +77 -0
  107. package/dist/cli-bundle/chunks/{chunk-NPN5I67J.js → chunk-G5ADGQ2D.js} +3 -3
  108. package/dist/cli-bundle/chunks/chunk-JAAEYHUA.js +2 -0
  109. package/dist/cli-bundle/chunks/{chunk-JX4DH4WC.js → chunk-KR3RP4FH.js} +3 -3
  110. package/dist/cli-bundle/chunks/chunk-LEZOUXG6.js +2 -0
  111. package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +2 -0
  112. package/dist/cli-bundle/chunks/chunk-QOEKOECV.js +29 -0
  113. package/dist/cli-bundle/chunks/chunk-RHSFOMHU.js +2 -0
  114. package/dist/cli-bundle/chunks/chunk-XOD2PCB6.js +20 -0
  115. package/dist/cli-bundle/chunks/{chunk-JT6XF6GE.js → chunk-YVEQ2AMO.js} +4 -4
  116. package/dist/cli-bundle/chunks/register-list-query-KSK3R63M.js +11 -0
  117. package/dist/cli-bundle/chunks/register-mutation-IQ5C7U6O.js +20 -0
  118. package/dist/cli-bundle/chunks/{register-operations-I5W3KMGB.js → register-operations-DWVHR2NC.js} +2 -2
  119. package/dist/cli-bundle/chunks/register-setup-BQ5SVD4B.js +2 -0
  120. package/dist/cli-bundle/focused-chunks/chunk-3WRPWLA7.js +3 -0
  121. package/dist/cli-bundle/focused-chunks/chunk-7MBUII7U.js +2 -0
  122. package/dist/cli-bundle/focused-chunks/chunk-COPBO5HW.js +8 -0
  123. package/dist/cli-bundle/focused-chunks/chunk-DUN4IXYN.js +20 -0
  124. package/dist/cli-bundle/focused-chunks/{chunk-LIJIA4TY.js → chunk-EE5QSM4Z.js} +3 -3
  125. package/dist/cli-bundle/focused-chunks/chunk-HJVARYM3.js +6 -0
  126. package/dist/cli-bundle/focused-chunks/chunk-IAUOUGVR.js +177 -0
  127. package/dist/cli-bundle/focused-chunks/chunk-KOOMJ54F.js +2 -0
  128. package/dist/cli-bundle/focused-chunks/chunk-MZDXX7JY.js +56 -0
  129. package/dist/cli-bundle/focused-chunks/{chunk-M6PBRFSH.js → chunk-OPFHFGDD.js} +2 -2
  130. package/dist/cli-bundle/focused-chunks/chunk-QHNETP77.js +9 -0
  131. package/dist/cli-bundle/focused-chunks/{chunk-3BZEOXLT.js → chunk-RMWES4M6.js} +2 -2
  132. package/dist/cli-bundle/focused-chunks/chunk-RXT4P5QH.js +10 -0
  133. package/dist/cli-bundle/focused-chunks/chunk-SDOL6FM2.js +12 -0
  134. package/dist/cli-bundle/focused-chunks/chunk-SQV4AAUC.js +2 -0
  135. package/dist/cli-bundle/focused-chunks/{chunk-PEFABF7E.js → chunk-WE3IUNIW.js} +3 -3
  136. package/dist/cli-bundle/focused-chunks/chunk-YALOUBWJ.js +2 -0
  137. package/dist/cli-bundle/main.js +20 -20
  138. package/dist/cli-bundle/sdk-authoring.js +1 -1
  139. package/dist/cli-bundle/sdk-contracts.js +2 -2
  140. package/dist/cli-bundle/sdk-core.js +29 -29
  141. package/dist/cli-bundle/sdk-governance.js +1 -1
  142. package/dist/cli-bundle/sdk-graph.js +1 -1
  143. package/dist/cli-bundle/sdk-merge.js +42 -42
  144. package/dist/cli-bundle/sdk-query.js +1 -1
  145. package/dist/cli-bundle/sdk-runtime.js +1 -1
  146. package/dist/cli-bundle/sdk-testing.js +1 -1
  147. package/dist/cli-bundle/sdk.js +11 -11
  148. package/dist/cli.js +1 -104
  149. package/dist/core/checkpoint/checkpoint-gc.js +1 -169
  150. package/dist/core/checkpoint/mutation-checkpoint.js +2 -133
  151. package/dist/core/config/nested-settings.js +1 -534
  152. package/dist/core/config/positional-value.js +1 -109
  153. package/dist/core/diagnostics/remediation.js +1 -506
  154. package/dist/core/extensions/activation-summary-markdown.js +2 -145
  155. package/dist/core/extensions/activation-summary.js +1 -92
  156. package/dist/core/extensions/activation-transaction.js +1 -46
  157. package/dist/core/extensions/capability-usage.js +1 -173
  158. package/dist/core/extensions/command-hook-context.js +1 -13
  159. package/dist/core/extensions/command-metadata-contract.js +1 -22
  160. package/dist/core/extensions/command-visibility-tier.js +1 -29
  161. package/dist/core/extensions/contribution-inventory.js +1 -173
  162. package/dist/core/extensions/exporter-output-contract.js +1 -66
  163. package/dist/core/extensions/extension-candidate.js +1 -18
  164. package/dist/core/extensions/extension-capability-aliases.js +1 -158
  165. package/dist/core/extensions/extension-hook-runtime.js +1 -699
  166. package/dist/core/extensions/extension-policy.js +1 -599
  167. package/dist/core/extensions/extension-registries.js +1 -62
  168. package/dist/core/extensions/extension-runtime-helpers.js +1 -33
  169. package/dist/core/extensions/extension-types.js +1 -102
  170. package/dist/core/extensions/flag-definition-validation.js +1 -52
  171. package/dist/core/extensions/flag-value-types.js +1 -64
  172. package/dist/core/extensions/index.js +1 -526
  173. package/dist/core/extensions/item-field-types.js +1 -39
  174. package/dist/core/extensions/item-fields.js +1 -261
  175. package/dist/core/extensions/loader.js +1 -2223
  176. package/dist/core/extensions/manifest-schema.js +1 -69
  177. package/dist/core/extensions/module-graph-snapshot.js +1 -33
  178. package/dist/core/extensions/preflight-ownership.js +1 -41
  179. package/dist/core/extensions/registration-validation.js +1 -82
  180. package/dist/core/extensions/registration-values.js +1 -209
  181. package/dist/core/extensions/reserved-host-flags.js +1 -36
  182. package/dist/core/extensions/runtime-registrations.js +1 -67
  183. package/dist/core/extensions/service-ownership.js +1 -19
  184. package/dist/core/extensions/version-compat.js +1 -216
  185. package/dist/core/fs/fs-utils.js +2 -158
  186. package/dist/core/fs/host-environment-errors.js +1 -141
  187. package/dist/core/fs/index.js +1 -9
  188. package/dist/core/fs/path-utils.js +1 -17
  189. package/dist/core/governance/content-fields.js +1 -160
  190. package/dist/core/governance/issue-codes.js +1 -151
  191. package/dist/core/governance/metadata-coverage.js +1 -358
  192. package/dist/core/history/drift-cache.js +3 -72
  193. package/dist/core/history/drift-scan.js +1 -342
  194. package/dist/core/history/event-classification.js +1 -109
  195. package/dist/core/history/event-index.js +8 -784
  196. package/dist/core/history/history-compact-bulk.js +1 -104
  197. package/dist/core/history/history-diff.js +1 -158
  198. package/dist/core/history/history-rewrite.d.ts +6 -1
  199. package/dist/core/history/history-rewrite.js +1 -107
  200. package/dist/core/history/history-storage-stats.js +1 -102
  201. package/dist/core/history/history-stream-policy.js +1 -62
  202. package/dist/core/history/history.js +2 -617
  203. package/dist/core/history/identity.js +1 -30
  204. package/dist/core/history/index.js +1 -9
  205. package/dist/core/history/projection.js +1 -196
  206. package/dist/core/history/read.d.ts +9 -0
  207. package/dist/core/history/read.js +1 -57
  208. package/dist/core/history/replay.js +2 -439
  209. package/dist/core/history/version-address.js +1 -32
  210. package/dist/core/history/workspace-history.js +2 -433
  211. package/dist/core/io/body-file.js +1 -62
  212. package/dist/core/io/bulk-ids-input.js +1 -112
  213. package/dist/core/item/actionability.js +1 -327
  214. package/dist/core/item/dependency-reference.js +1 -20
  215. package/dist/core/item/id.js +1 -112
  216. package/dist/core/item/index.js +1 -12
  217. package/dist/core/item/item-format-version.js +1 -78
  218. package/dist/core/item/item-format.js +5 -1473
  219. package/dist/core/item/item-record.js +1 -23
  220. package/dist/core/item/item-type-definition.js +1 -133
  221. package/dist/core/item/parent-reference-policy.js +1 -57
  222. package/dist/core/item/parse.js +2 -603
  223. package/dist/core/item/plan-lifecycle.js +1 -19
  224. package/dist/core/item/priority.js +1 -61
  225. package/dist/core/item/sprint-release-format.js +1 -38
  226. package/dist/core/item/status-filter.js +1 -115
  227. package/dist/core/item/status.js +1 -43
  228. package/dist/core/item/toon-decode.js +1 -29
  229. package/dist/core/item/type-registry.js +1 -715
  230. package/dist/core/item/type-synonyms.js +1 -38
  231. package/dist/core/lock/index.js +1 -9
  232. package/dist/core/lock/lock-gc.js +1 -240
  233. package/dist/core/lock/lock.js +3 -590
  234. package/dist/core/output/mutation-projection.js +1 -217
  235. package/dist/core/output/output-control.js +1 -25
  236. package/dist/core/output/output.js +11 -494
  237. package/dist/core/output/query-summary.js +1 -58
  238. package/dist/core/output/tabular.js +1 -77
  239. package/dist/core/packages/manifest.js +1 -244
  240. package/dist/core/packages/root.js +1 -84
  241. package/dist/core/profile/profile-describe.js +1 -83
  242. package/dist/core/profile/profile-lint.js +1 -415
  243. package/dist/core/profile/profile-plan.js +0 -0
  244. package/dist/core/profile/profile-presets.js +1 -370
  245. package/dist/core/reproducibility/context.js +1 -82
  246. package/dist/core/schema/fields-file.js +2 -288
  247. package/dist/core/schema/item-types-file.js +2 -296
  248. package/dist/core/schema/runtime-field-filters.js +1 -49
  249. package/dist/core/schema/runtime-field-values.js +1 -313
  250. package/dist/core/schema/runtime-schema.js +2 -826
  251. package/dist/core/schema/status-defs-file.js +2 -227
  252. package/dist/core/schema/status-token.js +1 -31
  253. package/dist/core/schema/type-inference.js +1 -95
  254. package/dist/core/schema/type-presets.js +1 -87
  255. package/dist/core/schema/type-workflows.js +1 -104
  256. package/dist/core/search/background-refresh.js +2 -286
  257. package/dist/core/search/bm25.js +1 -146
  258. package/dist/core/search/cache.js +2 -534
  259. package/dist/core/search/corpus.js +1 -311
  260. package/dist/core/search/embedding-batches.js +1 -163
  261. package/dist/core/search/eval.js +1 -225
  262. package/dist/core/search/http-client.js +1 -75
  263. package/dist/core/search/providers.js +1 -242
  264. package/dist/core/search/relevance.js +1 -244
  265. package/dist/core/search/semantic-defaults.js +1 -199
  266. package/dist/core/search/staleness.js +1 -30
  267. package/dist/core/search/vector-stores.js +2 -664
  268. package/dist/core/search/vectorization-metadata.js +1 -81
  269. package/dist/core/sentry/helpers.js +1 -272
  270. package/dist/core/sentry/instrument.js +1 -387
  271. package/dist/core/session/session-state.js +1 -260
  272. package/dist/core/shared/agent-session-context.js +1 -133
  273. package/dist/core/shared/author.js +1 -1172
  274. package/dist/core/shared/command-types.js +1 -4
  275. package/dist/core/shared/conflict-markers.js +1 -31
  276. package/dist/core/shared/constants.js +1 -405
  277. package/dist/core/shared/errors.js +1 -20
  278. package/dist/core/shared/html-entity-decode.js +1 -131
  279. package/dist/core/shared/index.js +1 -12
  280. package/dist/core/shared/item-metadata-contract.js +1 -89
  281. package/dist/core/shared/lazy-module.js +1 -16
  282. package/dist/core/shared/levenshtein.js +1 -61
  283. package/dist/core/shared/memo.js +1 -19
  284. package/dist/core/shared/numeric-parsers.js +1 -20
  285. package/dist/core/shared/option-alias-visibility.js +1 -67
  286. package/dist/core/shared/primitives.js +1 -127
  287. package/dist/core/shared/serial-queue.js +1 -79
  288. package/dist/core/shared/serialization.js +1 -210
  289. package/dist/core/shared/split-comma-list.js +1 -30
  290. package/dist/core/shared/text-normalization.js +1 -38
  291. package/dist/core/shared/time.js +1 -306
  292. package/dist/core/store/index.js +1 -12
  293. package/dist/core/store/item-format-migration.js +1 -125
  294. package/dist/core/store/item-metadata-cache.js +1 -1116
  295. package/dist/core/store/item-metadata-query-index.js +9 -394
  296. package/dist/core/store/item-metadata-read-work.js +1 -43
  297. package/dist/core/store/item-store.js +1 -693
  298. package/dist/core/store/paths.d.ts +1 -1
  299. package/dist/core/store/paths.js +1 -214
  300. package/dist/core/store/settings-read-cache.js +1 -85
  301. package/dist/core/store/settings-validator.js +1 -421
  302. package/dist/core/store/settings.js +3 -1309
  303. package/dist/core/store/tracker-preflight.js +1 -141
  304. package/dist/core/telemetry/consent.js +5 -108
  305. package/dist/core/telemetry/observability.js +1 -246
  306. package/dist/core/telemetry/runtime.js +4 -1988
  307. package/dist/core/test/background-runs.js +4 -945
  308. package/dist/core/test/item-test-run-tracking.js +1 -63
  309. package/dist/core/test/run-selectors.js +1 -120
  310. package/dist/core/validate/estimate-defaults.js +1 -89
  311. package/dist/core/validate/fix-planning.js +1 -189
  312. package/dist/core/validate/linked-artifact-reference.js +1 -36
  313. package/dist/core/validate/missing-by-type.js +1 -34
  314. package/dist/core/validate/missing-link-owners.js +1 -95
  315. package/dist/core/validate/stale-file-classification.js +1 -82
  316. package/dist/mcp/http-server.js +5 -448
  317. package/dist/mcp/legacy-adapter.js +1 -77
  318. package/dist/mcp/runtime-capabilities.js +1 -200
  319. package/dist/mcp/server.js +4 -1233
  320. package/dist/mcp/tool-definitions.js +1 -804
  321. package/dist/sdk/actionability.js +1 -13
  322. package/dist/sdk/agent/closed-domain-contracts.js +1 -161
  323. package/dist/sdk/agent/command-recovery.js +1 -59
  324. package/dist/sdk/agent/command-suggestions.js +1 -66
  325. package/dist/sdk/agent/create-option-policy.js +1 -31
  326. package/dist/sdk/agent/identity-config.js +1 -106
  327. package/dist/sdk/agent/item-addressing.js +1 -207
  328. package/dist/sdk/agent/refusal-closure-census.js +1 -151
  329. package/dist/sdk/agent/refusal-closure.js +1 -133
  330. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -193
  331. package/dist/sdk/agent/refusal-reachability.js +1 -593
  332. package/dist/sdk/agent/subcommand-recovery.js +1 -83
  333. package/dist/sdk/agent/task-transcript-contracts.js +1 -197
  334. package/dist/sdk/agent/tracker-preflight-contracts.js +1 -126
  335. package/dist/sdk/agent-capability-contracts.js +1 -428
  336. package/dist/sdk/agent-session-context.js +1 -9
  337. package/dist/sdk/annotations.js +1 -448
  338. package/dist/sdk/author-attribution.js +1 -468
  339. package/dist/sdk/authoring.js +1 -20
  340. package/dist/sdk/cli-bootstrap.js +1 -838
  341. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +1 -1
  342. package/dist/sdk/cli-contracts/agent-output-contracts.js +4 -476
  343. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -79
  344. package/dist/sdk/cli-contracts/command-aliases.d.ts +4 -0
  345. package/dist/sdk/cli-contracts/command-aliases.js +1 -107
  346. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -151
  347. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1081
  348. package/dist/sdk/cli-contracts/commander-types.js +1 -159
  349. package/dist/sdk/cli-contracts/completeness.js +1 -393
  350. package/dist/sdk/cli-contracts/enum-contracts.js +1 -222
  351. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1947
  352. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -347
  353. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -986
  354. package/dist/sdk/cli-contracts/registration-helpers.js +7 -990
  355. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +5 -0
  356. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -2090
  357. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -324
  358. package/dist/sdk/cli-contracts/string-lists.js +1 -16
  359. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -461
  360. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -2167
  361. package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -1
  362. package/dist/sdk/cli-contracts/tool-schema.js +1 -1664
  363. package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -4
  364. package/dist/sdk/cli-contracts.d.ts +1 -1
  365. package/dist/sdk/cli-contracts.js +1 -17
  366. package/dist/sdk/cli-program.js +1 -49
  367. package/dist/sdk/command-line.d.ts +2 -5
  368. package/dist/sdk/command-line.js +1 -78
  369. package/dist/sdk/comments.js +1 -133
  370. package/dist/sdk/compile-cache.js +1 -73
  371. package/dist/sdk/completion.js +157 -837
  372. package/dist/sdk/compose.js +1 -1090
  373. package/dist/sdk/config.js +1 -1204
  374. package/dist/sdk/context/recency.js +1 -33
  375. package/dist/sdk/context/semantic-session-attribution.js +1 -82
  376. package/dist/sdk/context/usage-egress.js +1 -29
  377. package/dist/sdk/context/usage-ledger.js +3 -185
  378. package/dist/sdk/context-intent-contracts.js +1 -709
  379. package/dist/sdk/context-intent-runtime.js +1 -115
  380. package/dist/sdk/context-packing.js +1 -218
  381. package/dist/sdk/context-relevance.js +1 -503
  382. package/dist/sdk/context-signal-store.js +2 -426
  383. package/dist/sdk/context-usage.js +1 -367
  384. package/dist/sdk/contracts.js +1 -23
  385. package/dist/sdk/core-governance.js +1 -14
  386. package/dist/sdk/core.js +1 -14
  387. package/dist/sdk/corpus-shape.js +1 -401
  388. package/dist/sdk/define.js +1 -220
  389. package/dist/sdk/dependencies.js +1 -718
  390. package/dist/sdk/dependency-flag-validation.js +1 -156
  391. package/dist/sdk/dependency-provenance.js +1 -135
  392. package/dist/sdk/docs.js +1 -14
  393. package/dist/sdk/duplicates.js +1 -40
  394. package/dist/sdk/environment/agent-environment.js +1 -466
  395. package/dist/sdk/environment/host-environment-errors.js +1 -8
  396. package/dist/sdk/environment/project-runtime-compatibility.js +1 -481
  397. package/dist/sdk/environment/source-context.js +1 -28
  398. package/dist/sdk/environment/tracker-preflight.js +1 -9
  399. package/dist/sdk/error-code-catalog.js +1 -153
  400. package/dist/sdk/error-runtime.js +1 -58
  401. package/dist/sdk/errors.js +1 -58
  402. package/dist/sdk/eval.js +1 -190
  403. package/dist/sdk/extension/author-manifest.js +1 -92
  404. package/dist/sdk/extension/bundled-catalog.js +1 -332
  405. package/dist/sdk/extension/concurrency.js +1 -25
  406. package/dist/sdk/extension/copy-scope.d.ts +2 -0
  407. package/dist/sdk/extension/copy-scope.js +2 -0
  408. package/dist/sdk/extension/custom-field-collisions.js +1 -30
  409. package/dist/sdk/extension/describe.js +3 -189
  410. package/dist/sdk/extension/doctor.js +1 -606
  411. package/dist/sdk/extension/install-plan.d.ts +69 -0
  412. package/dist/sdk/extension/install-plan.js +2 -0
  413. package/dist/sdk/extension/install-receipts.d.ts +7 -0
  414. package/dist/sdk/extension/install-receipts.js +2 -0
  415. package/dist/sdk/extension/install-runtime.js +3 -313
  416. package/dist/sdk/extension/install-snapshot.js +1 -66
  417. package/dist/sdk/extension/install-sources.js +5 -1057
  418. package/dist/sdk/extension/managed-state.js +2 -252
  419. package/dist/sdk/extension/migrations.js +2 -174
  420. package/dist/sdk/extension/output-ownership.js +1 -25
  421. package/dist/sdk/extension/runtime-summary.js +1 -18
  422. package/dist/sdk/extension/scaffold.js +4 -2308
  423. package/dist/sdk/extension/shared.js +1 -147
  424. package/dist/sdk/extension/source-resolution.js +1 -65
  425. package/dist/sdk/extension/update-check.js +1 -67
  426. package/dist/sdk/extension-command-context.js +1 -44
  427. package/dist/sdk/extension-contracts.js +1 -73
  428. package/dist/sdk/extension.d.ts +7 -2
  429. package/dist/sdk/extension.js +1 -2196
  430. package/dist/sdk/files.js +1 -535
  431. package/dist/sdk/flag-invocation-contracts.d.ts +0 -5
  432. package/dist/sdk/flag-invocation-contracts.js +1 -344
  433. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -2224
  434. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -2236
  435. package/dist/sdk/generated-error-code-catalog.js +1 -16
  436. package/dist/sdk/governance/assurance-action-contracts.js +1 -4
  437. package/dist/sdk/governance/assurance-action.js +1 -411
  438. package/dist/sdk/governance/assurance-limits.js +1 -10
  439. package/dist/sdk/governance/assurance-mutation-error.js +1 -81
  440. package/dist/sdk/governance/assurance-presets.js +1 -135
  441. package/dist/sdk/governance/assurance-runtime.js +1 -238
  442. package/dist/sdk/governance/assurance.js +4 -1182
  443. package/dist/sdk/governance/boundary-fixtures.js +1 -200
  444. package/dist/sdk/governance/coverage-assurance.js +1 -60
  445. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -188
  446. package/dist/sdk/governance/defect-recurrence-graph.js +1 -120
  447. package/dist/sdk/governance/defect-recurrence-signals.js +1 -24
  448. package/dist/sdk/governance/defect-recurrence.js +1 -623
  449. package/dist/sdk/governance/extension-host-version.js +1 -115
  450. package/dist/sdk/governance/gc.js +1 -368
  451. package/dist/sdk/governance/health.js +1 -2367
  452. package/dist/sdk/governance/hierarchy-validation.js +1 -108
  453. package/dist/sdk/governance/linked-file-report.js +1 -71
  454. package/dist/sdk/governance/merge-receipt-history.js +1 -206
  455. package/dist/sdk/governance/provenance-health.js +1 -282
  456. package/dist/sdk/governance/reindex.js +4 -761
  457. package/dist/sdk/governance/stale-work.js +1 -82
  458. package/dist/sdk/governance/status-role-diagnostics.js +1 -35
  459. package/dist/sdk/governance/storage-integrity.js +1 -280
  460. package/dist/sdk/governance/tracked-runtime-cache.js +1 -106
  461. package/dist/sdk/governance/upgrade.js +2 -327
  462. package/dist/sdk/governance/validate-history-drift.js +1 -81
  463. package/dist/sdk/governance/validate-item-reader.js +1 -17
  464. package/dist/sdk/governance/validate-normalization.js +1 -36
  465. package/dist/sdk/governance/validate.js +1 -2261
  466. package/dist/sdk/governance/workspace-position.js +1 -163
  467. package/dist/sdk/governance.d.ts +1 -0
  468. package/dist/sdk/governance.js +1 -31
  469. package/dist/sdk/graph/adapter.js +1 -181
  470. package/dist/sdk/graph/analytics.js +1 -474
  471. package/dist/sdk/graph/assembly.js +1 -377
  472. package/dist/sdk/graph/cache.js +1 -160
  473. package/dist/sdk/graph/centrality.js +1 -258
  474. package/dist/sdk/graph/conformance.js +1 -130
  475. package/dist/sdk/graph/deadline-scheduling.d.ts +90 -0
  476. package/dist/sdk/graph/deadline-scheduling.js +2 -0
  477. package/dist/sdk/graph/durable-cache.d.ts +1 -1
  478. package/dist/sdk/graph/durable-cache.js +1 -361
  479. package/dist/sdk/graph/governance-contracts.js +1 -34
  480. package/dist/sdk/graph/governance.d.ts +13 -1
  481. package/dist/sdk/graph/governance.js +1 -735
  482. package/dist/sdk/graph/hierarchy-integrity.js +1 -310
  483. package/dist/sdk/graph/index.d.ts +3 -2
  484. package/dist/sdk/graph/index.js +1 -26
  485. package/dist/sdk/graph/lifecycle-coverage.d.ts +32 -0
  486. package/dist/sdk/graph/lifecycle-coverage.js +2 -0
  487. package/dist/sdk/graph/mutation-advisory.js +1 -176
  488. package/dist/sdk/graph/remediation.js +1 -197
  489. package/dist/sdk/graph/run.d.ts +15 -1
  490. package/dist/sdk/graph/run.js +1 -768
  491. package/dist/sdk/graph/scheduling.js +1 -124
  492. package/dist/sdk/graph/traversal.js +1 -284
  493. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -27
  494. package/dist/sdk/graph.js +1 -15
  495. package/dist/sdk/guide-topics.js +1 -707
  496. package/dist/sdk/guide.js +1 -279
  497. package/dist/sdk/history/maintenance.d.ts +71 -0
  498. package/dist/sdk/history/maintenance.js +2 -0
  499. package/dist/sdk/history/salvage.js +2 -247
  500. package/dist/sdk/history/subject.d.ts +19 -0
  501. package/dist/sdk/history/subject.js +2 -0
  502. package/dist/sdk/history-analytics.js +1 -282
  503. package/dist/sdk/history-compact.js +1 -527
  504. package/dist/sdk/history-mcp.js +1 -68
  505. package/dist/sdk/history-provenance.js +1 -182
  506. package/dist/sdk/history-read.js +1 -96
  507. package/dist/sdk/history-redact.d.ts +1 -14
  508. package/dist/sdk/history-redact.js +1 -643
  509. package/dist/sdk/history-repair.d.ts +5 -0
  510. package/dist/sdk/history-repair.js +1 -657
  511. package/dist/sdk/improvement-ledger-validation.js +1 -62
  512. package/dist/sdk/improvement-ledger.js +2 -257
  513. package/dist/sdk/index.d.ts +4 -0
  514. package/dist/sdk/index.js +1 -183
  515. package/dist/sdk/init-agent-guidance.js +2 -496
  516. package/dist/sdk/init.js +2 -820
  517. package/dist/sdk/invocation-author.js +1 -39
  518. package/dist/sdk/item-children.js +1 -90
  519. package/dist/sdk/item-metadata-index.js +1 -15
  520. package/dist/sdk/item-schedule.js +1 -27
  521. package/dist/sdk/item-transaction.js +1 -396
  522. package/dist/sdk/learnings.js +1 -29
  523. package/dist/sdk/lifecycle/append.js +2 -53
  524. package/dist/sdk/lifecycle/claim.d.ts +2 -0
  525. package/dist/sdk/lifecycle/claim.js +1 -242
  526. package/dist/sdk/lifecycle/close-many.js +1 -438
  527. package/dist/sdk/lifecycle/close.js +1 -468
  528. package/dist/sdk/lifecycle/copy.js +1 -212
  529. package/dist/sdk/lifecycle/create.js +1 -1949
  530. package/dist/sdk/lifecycle/delete.js +1 -45
  531. package/dist/sdk/lifecycle/event-validation-messages.js +1 -91
  532. package/dist/sdk/lifecycle/focus.js +1 -91
  533. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -24
  534. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -149
  535. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -40
  536. package/dist/sdk/lifecycle/mcp-actions.d.ts +2 -0
  537. package/dist/sdk/lifecycle/mcp-actions.js +1 -51
  538. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -46
  539. package/dist/sdk/lifecycle/mutation-command-options.js +1 -9
  540. package/dist/sdk/lifecycle/plan.js +1 -1606
  541. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -147
  542. package/dist/sdk/lifecycle/reopen.js +1 -68
  543. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +1 -143
  544. package/dist/sdk/lifecycle/restore.d.ts +1 -0
  545. package/dist/sdk/lifecycle/restore.js +1 -330
  546. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -295
  547. package/dist/sdk/lifecycle/update-many.js +1 -861
  548. package/dist/sdk/lifecycle/update.js +1 -2136
  549. package/dist/sdk/lifecycle-completion.js +1 -92
  550. package/dist/sdk/lifecycle-policy.js +1 -120
  551. package/dist/sdk/linked-artifacts.js +1 -530
  552. package/dist/sdk/mcp/apps.js +4 -133
  553. package/dist/sdk/mcp/authorization.js +1 -404
  554. package/dist/sdk/mcp/discovery.js +1 -494
  555. package/dist/sdk/mcp/interactions.js +1 -336
  556. package/dist/sdk/mcp/protocol.d.ts +7 -0
  557. package/dist/sdk/mcp/protocol.js +1 -184
  558. package/dist/sdk/mcp/skills.js +1 -389
  559. package/dist/sdk/mcp/subscriptions.js +1 -211
  560. package/dist/sdk/mcp/tasks.js +2 -430
  561. package/dist/sdk/mcp/transport.js +1 -260
  562. package/dist/sdk/merge/abandoned-receipts.js +1 -46
  563. package/dist/sdk/merge/driver.js +1 -212
  564. package/dist/sdk/merge/index.js +1 -16
  565. package/dist/sdk/merge/install.js +3 -561
  566. package/dist/sdk/merge/receipt-file-boundary.js +1 -46
  567. package/dist/sdk/merge/receipt-operation.js +1 -96
  568. package/dist/sdk/merge/receipt-schema.js +1 -397
  569. package/dist/sdk/merge/receipts.js +4 -525
  570. package/dist/sdk/merge/reconcile.js +1 -352
  571. package/dist/sdk/merge/three-way.js +3 -775
  572. package/dist/sdk/merge.js +1 -10
  573. package/dist/sdk/mutation-events.js +1 -292
  574. package/dist/sdk/mutation-guard.js +1 -216
  575. package/dist/sdk/notes.js +1 -139
  576. package/dist/sdk/output-contracts.js +1 -172
  577. package/dist/sdk/output-projection.js +1 -430
  578. package/dist/sdk/output-token-accounting.js +1 -140
  579. package/dist/sdk/output.js +1 -64
  580. package/dist/sdk/ownership-source.js +1 -21
  581. package/dist/sdk/package-import-adapters.js +1 -442
  582. package/dist/sdk/package-migrations.js +1 -20
  583. package/dist/sdk/package-runtime-options.js +1 -80
  584. package/dist/sdk/pagination.js +1 -162
  585. package/dist/sdk/profile.js +1 -454
  586. package/dist/sdk/provenance.js +1 -258
  587. package/dist/sdk/public-surface.json +1 -1
  588. package/dist/sdk/query/activity.js +1 -401
  589. package/dist/sdk/query/aggregate.d.ts +16 -0
  590. package/dist/sdk/query/aggregate.js +1 -390
  591. package/dist/sdk/query/calendar.js +1 -964
  592. package/dist/sdk/query/complete-list.js +1 -215
  593. package/dist/sdk/query/context.js +1 -1702
  594. package/dist/sdk/query/duplicate-candidates.js +1 -70
  595. package/dist/sdk/query/get.js +1 -450
  596. package/dist/sdk/query/history.js +1 -186
  597. package/dist/sdk/query/item-filter-options.js +1 -9
  598. package/dist/sdk/query/light-metadata.js +1 -18
  599. package/dist/sdk/query/list-filter-shared.js +1 -81
  600. package/dist/sdk/query/list.js +1 -1304
  601. package/dist/sdk/query/multi-value-filters.js +1 -78
  602. package/dist/sdk/query/next.js +1 -513
  603. package/dist/sdk/query/parsers.js +1 -44
  604. package/dist/sdk/query/projection-contracts.js +1 -184
  605. package/dist/sdk/query/search-contracts.js +1 -230
  606. package/dist/sdk/query/search-pagination.js +1 -35
  607. package/dist/sdk/query/search-rendering.js +1 -105
  608. package/dist/sdk/query/search.js +2 -1987
  609. package/dist/sdk/query.js +1 -35
  610. package/dist/sdk/read-output/continuation.js +1 -194
  611. package/dist/sdk/read-output-budget.js +1 -135
  612. package/dist/sdk/read-output-contracts.js +1 -1225
  613. package/dist/sdk/read-output-rows.js +1 -186
  614. package/dist/sdk/read-output-session.js +1 -208
  615. package/dist/sdk/relationship-analytics.js +1 -410
  616. package/dist/sdk/relationship-context.js +1 -284
  617. package/dist/sdk/relationship-history.js +4 -519
  618. package/dist/sdk/relationship-kinds/contract.js +1 -22
  619. package/dist/sdk/relationship-migration.js +1 -77
  620. package/dist/sdk/relationships.js +1 -579
  621. package/dist/sdk/reproducibility/process.js +1 -87
  622. package/dist/sdk/runtime-action-aliases.js +1 -59
  623. package/dist/sdk/runtime-extended-actions.js +1 -177
  624. package/dist/sdk/runtime-input.js +1 -614
  625. package/dist/sdk/runtime-primitives.js +1 -84
  626. package/dist/sdk/runtime-public-contracts.js +1 -4
  627. package/dist/sdk/runtime-stats-options.js +1 -38
  628. package/dist/sdk/runtime.js +1 -1928
  629. package/dist/sdk/scheduling-shortcuts.js +1 -63
  630. package/dist/sdk/schema-migration.js +3 -856
  631. package/dist/sdk/schema.js +1 -1376
  632. package/dist/sdk/search-refresh-worker.js +1 -18
  633. package/dist/sdk/similarity-scoring.js +1 -53
  634. package/dist/sdk/similarity.js +1 -326
  635. package/dist/sdk/start-task-status.js +1 -14
  636. package/dist/sdk/stats.js +1 -270
  637. package/dist/sdk/structured-mutations.js +1 -580
  638. package/dist/sdk/telemetry-flush.js +1 -13
  639. package/dist/sdk/telemetry.js +1 -405
  640. package/dist/sdk/templates.js +2 -292
  641. package/dist/sdk/test/batch.js +2 -509
  642. package/dist/sdk/test/entry.js +1 -70
  643. package/dist/sdk/test/execution.js +6 -2211
  644. package/dist/sdk/test/linked-command-detection.js +1 -546
  645. package/dist/sdk/test/measurements.js +1 -91
  646. package/dist/sdk/test/parsers.js +1 -545
  647. package/dist/sdk/test/runs.js +1 -193
  648. package/dist/sdk/test/trust.js +2 -206
  649. package/dist/sdk/testing.js +4 -1391
  650. package/dist/sdk/traceability/runtime-files-lookup.js +1 -32
  651. package/dist/sdk/traceability/source-traceability.js +1 -292
  652. package/dist/sdk/tracker-root-discovery.js +1 -9
  653. package/dist/sdk/workspace-contracts-cache.js +1 -28
  654. package/dist/sdk/workspace-contracts.js +1 -33
  655. package/dist/sdk/workspace-memory.js +2 -318
  656. package/dist/sdk/workspace-recipe.js +1 -71
  657. package/dist/sdk/workspace-snapshot.js +4 -613
  658. package/dist/sdk/workspace-transaction-gc.js +1 -149
  659. package/dist/sdk/workspace-transaction.js +2 -363
  660. package/dist/sdk/workspace.js +3 -127
  661. package/dist/types/index.js +1 -9
  662. package/dist/types.js +1 -245
  663. package/docs/AGENT_GUIDE.md +1 -1
  664. package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +167 -0
  665. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +9 -3
  666. package/docs/EXTENSIONS.md +1 -0
  667. package/docs/HISTORY_MAINTENANCE.md +125 -0
  668. package/docs/MCP_2026_07_28_CONFORMANCE.md +20 -10
  669. package/docs/PACKAGE_EVIDENCE.md +92 -0
  670. package/docs/PLANNING_MEASUREMENTS.md +183 -0
  671. package/docs/README.md +3 -0
  672. package/docs/RELEASING.md +1 -0
  673. package/docs/SCRIPTING.md +21 -0
  674. package/docs/TESTING.md +23 -0
  675. package/docs/generated/FLAG_LEXICON_BUDGETS.md +5 -5
  676. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +2 -2
  677. package/marketplace.json +2 -2
  678. package/package.json +1 -1
  679. package/packages/pm-beads/package.json +1 -1
  680. package/packages/pm-calendar/package.json +1 -1
  681. package/packages/pm-command-kit/package.json +1 -1
  682. package/packages/pm-digital-twin/package.json +1 -1
  683. package/packages/pm-governance-audit/package.json +1 -1
  684. package/packages/pm-guide-shell/package.json +1 -1
  685. package/packages/pm-kanban/package.json +1 -1
  686. package/packages/pm-lifecycle-hooks/package.json +1 -1
  687. package/packages/pm-linked-test-adapters/package.json +1 -1
  688. package/packages/pm-search-advanced/package.json +1 -1
  689. package/packages/pm-templates/package.json +1 -1
  690. package/packages/pm-todos/package.json +1 -1
  691. package/packages/pm-vcs/package.json +1 -1
  692. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  693. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  694. package/scripts/finalize-build.mjs +45 -3
  695. package/dist/cli-bundle/chunks/chunk-AZDFJGH6.js +0 -9
  696. package/dist/cli-bundle/chunks/chunk-BAX2BYUW.js +0 -2111
  697. package/dist/cli-bundle/chunks/chunk-CKOL5U7J.js +0 -77
  698. package/dist/cli-bundle/chunks/chunk-OF76PSDQ.js +0 -5
  699. package/dist/cli-bundle/chunks/chunk-QUWFABDM.js +0 -232
  700. package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +0 -2
  701. package/dist/cli-bundle/chunks/chunk-RWWBOWJ5.js +0 -2
  702. package/dist/cli-bundle/chunks/chunk-WGAOYSYH.js +0 -40
  703. package/dist/cli-bundle/chunks/chunk-WI2AYPA7.js +0 -2
  704. package/dist/cli-bundle/chunks/register-list-query-5JL52D33.js +0 -11
  705. package/dist/cli-bundle/chunks/register-mutation-ZPG7KMVP.js +0 -20
  706. package/dist/cli-bundle/chunks/register-setup-H4SVAVX7.js +0 -2
  707. package/dist/cli-bundle/focused-chunks/chunk-AL5ON6K6.js +0 -2
  708. package/dist/cli-bundle/focused-chunks/chunk-CHC2IDXA.js +0 -6
  709. package/dist/cli-bundle/focused-chunks/chunk-CK6QFAPZ.js +0 -20
  710. package/dist/cli-bundle/focused-chunks/chunk-EZR3GHFE.js +0 -2
  711. package/dist/cli-bundle/focused-chunks/chunk-H2WJWK7L.js +0 -56
  712. package/dist/cli-bundle/focused-chunks/chunk-NTPY5GSO.js +0 -3
  713. package/dist/cli-bundle/focused-chunks/chunk-P5O7MP5Y.js +0 -2
  714. package/dist/cli-bundle/focused-chunks/chunk-PDMW2E36.js +0 -177
  715. package/dist/cli-bundle/focused-chunks/chunk-QTVCLMSZ.js +0 -6
  716. package/dist/cli-bundle/focused-chunks/chunk-QTZRBUYA.js +0 -8
  717. package/dist/cli-bundle/focused-chunks/chunk-SGQST3PQ.js +0 -12
  718. package/dist/cli-bundle/focused-chunks/chunk-UKHASMMP.js +0 -10
  719. package/dist/cli-bundle/focused-chunks/chunk-ZPEKQHOC.js +0 -2
@@ -1,1226 +1,2 @@
1
- /**
2
- * @module sdk/read-output-contracts
3
- *
4
- * Declares and applies one output-bounding vocabulary to every built-in read
5
- * surface without coupling package authors to command-specific option names.
6
- */
7
-
8
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2103a4dc-3037-5768-b2c7-5964de4ac86b")}catch(e){}}();
9
- import { EXIT_CODE } from "../core/shared/constants.js";
10
- import { PmCliError } from "../core/shared/errors.js";
11
- import { compactReadOutputToBudget, estimateReadOutputTokens, resolveReadOutputRecoveryBudget, updateReadOutputReceiptEstimate, } from "./read-output-budget.js";
12
- export { resolveReadOutputRecoveryBudget } from "./read-output-budget.js";
13
- import { resolvePmCommandOutputBudget } from "./cli-contracts/agent-output-contracts.js";
14
- import { boundReadOutputRows, countReadOutputRows, mapReadOutputRows, readOutputBudgetCollections, readOutputContinuationRowCollections, readOutputRowPaths, } from "./read-output-rows.js";
15
- import { applyReadOutputContinuation, decodeReadOutputContinuationCursor, encodeReadOutputContinuationCursor, prioritizeAssuranceAssertions, readOutputCollectionFingerprint, } from "./read-output/continuation.js";
16
- export { decodeReadOutputContinuationCursor, encodeReadOutputContinuationCursor, PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES, readOutputCollectionFingerprint, } from "./read-output/continuation.js";
17
- import { applyReadOutputSessionReferences, attachReadOutputSessionReceipt, parseReadOutputSession, readOutputSessionRemainingTokens, } from "./read-output-session.js";
18
- import { decodeQueryCursorEnvelope, encodeQueryCursor } from "./pagination.js";
19
- /** Stable output dimensions shared by every read surface. */
20
- export const PM_READ_OUTPUT_DIMENSIONS = [
21
- "include",
22
- "amount",
23
- "cost",
24
- "encoding",
25
- ];
26
- /** Built-in command roots whose primary operation is a read. */
27
- export const PM_READ_OUTPUT_SURFACES = [
28
- "list",
29
- "context",
30
- "search",
31
- "get",
32
- "next",
33
- "health",
34
- "deps",
35
- "graph",
36
- "history",
37
- "activity",
38
- "validate",
39
- "events",
40
- "contracts",
41
- "comments",
42
- "notes",
43
- "files",
44
- "docs",
45
- "stats",
46
- "aggregate",
47
- "duplicates",
48
- "package-catalog",
49
- "package-manage",
50
- "comments-audit",
51
- "assurance",
52
- ];
53
- const READ_OUTPUT_PRECEDENCE = [
54
- "canonical",
55
- "legacy",
56
- "intent",
57
- "default",
58
- ];
59
- const CANONICAL_OPTIONS = {
60
- include: "--output-include",
61
- amount: "--output-limit",
62
- cost: "--output-budget",
63
- encoding: "--output-format",
64
- };
65
- const READ_OUTPUT_INVOCATION_PROVENANCE = Symbol.for("pm.readOutputInvocationProvenance");
66
- /** Canonical CLI flags that opt a read invocation into universal output shaping. */
67
- export const PM_READ_OUTPUT_OPTION_FLAGS = Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map((dimension) => CANONICAL_OPTIONS[dimension]));
68
- /** Canonical control that composes the four per-call dimensions across reads. */
69
- export const PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS = Object.freeze([
70
- "--output-session",
71
- "--output-cursor",
72
- "--output-row-contract",
73
- ]);
74
- const LEGACY_FLAGS_BY_COMMAND = {
75
- list: {
76
- include: ["--brief", "--compact", "--fields", "--full"],
77
- amount: ["--after", "--limit", "--no-truncate"],
78
- cost: ["--token-budget"],
79
- encoding: ["--format", "--stream"],
80
- },
81
- context: {
82
- include: ["--fields", "--section"],
83
- amount: ["--after", "--depth", "--limit"],
84
- cost: ["--token-budget"],
85
- encoding: ["--format"],
86
- },
87
- search: {
88
- include: ["--compact", "--fields", "--full"],
89
- amount: ["--after", "--limit"],
90
- cost: ["--token-budget"],
91
- encoding: ["--format"],
92
- },
93
- get: {
94
- include: ["--fields", "--full"],
95
- amount: ["--depth"],
96
- cost: ["--token-budget"],
97
- encoding: ["--format"],
98
- },
99
- next: {
100
- amount: ["--blocked-limit", "--limit"],
101
- cost: ["--token-budget"],
102
- encoding: ["--format"],
103
- },
104
- health: {
105
- include: ["--brief", "--check-only", "--full", "--summary"],
106
- },
107
- deps: {
108
- include: ["--collapse", "--full", "--summary"],
109
- amount: ["--edge-limit", "--max-depth", "--node-limit"],
110
- cost: ["--token-budget"],
111
- encoding: ["--format"],
112
- },
113
- graph: {
114
- include: ["--full", "--summary"],
115
- amount: ["--after", "--limit", "--max-depth", "--max-paths"],
116
- },
117
- history: {
118
- include: ["--compact", "--full"],
119
- amount: ["--limit"],
120
- encoding: ["--format"],
121
- },
122
- activity: {
123
- include: ["--compact", "--full"],
124
- amount: ["--limit", "--unbounded"],
125
- encoding: ["--stream"],
126
- },
127
- validate: { include: ["--counts", "--full"] },
128
- events: {
129
- include: ["--full"],
130
- amount: ["--limit"],
131
- encoding: ["--follow"],
132
- },
133
- contracts: { include: ["--full", "--summary"] },
134
- comments: { amount: ["--limit"] },
135
- notes: { amount: ["--limit"] },
136
- files: {
137
- amount: ["--limit", "--no-truncate", "--offset"],
138
- },
139
- docs: {},
140
- stats: {},
141
- aggregate: {},
142
- duplicates: { amount: ["--limit"] },
143
- "package-catalog": {},
144
- "package-manage": {},
145
- "comments-audit": {},
146
- assurance: {},
147
- };
148
- const VALUE_BEARING_INCLUDE_ALIASES = new Set([
149
- "--collapse",
150
- "--fields",
151
- "--section",
152
- ]);
153
- const BEHAVIOR_PRESERVING_MIGRATION_HINTS = Object.freeze({
154
- "--after": "--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.",
155
- "--check-only": "--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.",
156
- "--collapse": "--collapse retains dependency grouping semantics; --output-include does not replace it.",
157
- "--depth": "--depth retains traversal or detail-depth semantics; --output-limit does not replace it.",
158
- "--follow": "--follow retains event-tail semantics; --output-format does not enable following.",
159
- "--max-depth": "--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.",
160
- "--max-paths": "--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.",
161
- "--no-truncate": "--no-truncate is a compatibility alias; prefer --output-limit unbounded.",
162
- "--offset": "--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.",
163
- "--stream": "--stream retains command streaming semantics; --output-format selects only static result encoding.",
164
- "--unbounded": "--unbounded is a compatibility alias; prefer --output-limit unbounded.",
165
- });
166
- function flagSelector(flag) {
167
- return flag.slice(2).replaceAll("-", "_");
168
- }
169
- function migrationHint(flag, dimension) {
170
- const behaviorHint = BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];
171
- if (behaviorHint !== undefined)
172
- return behaviorHint;
173
- const suffix = dimension === "include"
174
- ? VALUE_BEARING_INCLUDE_ALIASES.has(flag)
175
- ? "<csv>"
176
- : flagSelector(flag)
177
- : dimension === "amount"
178
- ? "<n>"
179
- : dimension === "cost"
180
- ? "<tokens>"
181
- : "<toon|json>";
182
- return `${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`;
183
- }
184
- function buildSurfaceContract(command) {
185
- const legacy = LEGACY_FLAGS_BY_COMMAND[command];
186
- const dimensions = Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map((dimension) => [
187
- dimension,
188
- Object.freeze({
189
- dimension,
190
- canonical_option: CANONICAL_OPTIONS[dimension],
191
- applicable: true,
192
- inapplicable_reason: null,
193
- legacy_aliases: Object.freeze((legacy[dimension] ?? []).map((flag) => Object.freeze({
194
- flag,
195
- semantics: BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag] === undefined
196
- ? "replacement"
197
- : "behavior_preserving",
198
- migration_hint: migrationHint(flag, dimension),
199
- visibility: "hidden_alias",
200
- }))),
201
- }),
202
- ])));
203
- return Object.freeze({
204
- command,
205
- dimensions,
206
- precedence: READ_OUTPUT_PRECEDENCE,
207
- budget_retention_policy: command === "assurance" ? "verdict_priority" : "ordered_prefix",
208
- projection_modes: Object.freeze([
209
- ...readOutputIncludeModeOptions(command).keys(),
210
- ]),
211
- });
212
- }
213
- /** Universal output contract for every built-in read surface. */
214
- export const PM_READ_OUTPUT_SURFACE_CONTRACTS = Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract));
215
- const SURFACE_CONTRACT_BY_COMMAND = new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map((contract) => [
216
- contract.command,
217
- contract,
218
- ]));
219
- /** Resolve a command or list/context alias to its canonical read-output surface. */
220
- export function resolveReadOutputSurface(command, options = {}) {
221
- const normalizedCommand = command
222
- .trim()
223
- .toLowerCase()
224
- .replaceAll(/\s+/gu, " ");
225
- const packageMode = normalizedCommand === "package catalog" ||
226
- normalizedCommand === "packages catalog" ||
227
- normalizedCommand === "package-catalog" ||
228
- ((normalizedCommand === "package" ||
229
- normalizedCommand === "packages" ||
230
- normalizedCommand === "extension") &&
231
- (options.catalog === true ||
232
- options.target === "catalog" ||
233
- options.action === "catalog"));
234
- const root = packageMode
235
- ? "package-catalog"
236
- : normalizedCommand === "package manage" ||
237
- normalizedCommand === "package-manage"
238
- ? "package-manage"
239
- : normalizedCommand.split(" ")[0];
240
- const normalized = root.startsWith("list-")
241
- ? "list"
242
- : root === "ctx"
243
- ? "context"
244
- : root;
245
- return PM_READ_OUTPUT_SURFACES.includes(normalized)
246
- ? normalized
247
- : undefined;
248
- }
249
- const CANONICAL_OPTION_KEYS = [
250
- "outputInclude",
251
- "output_include",
252
- "outputLimit",
253
- "output_limit",
254
- "outputBudget",
255
- "output_budget",
256
- "outputFormat",
257
- "output_format",
258
- "outputSession",
259
- "output_session",
260
- "outputCursor",
261
- "output_cursor",
262
- "outputRowContract",
263
- "output_row_contract",
264
- ];
265
- const HYBRID_READ_MUTATION_KEYS = {
266
- comments: ["add", "body", "stdin", "file", "edit", "delete"],
267
- notes: ["add", "addJson", "stdin", "file", "edit", "delete"],
268
- files: ["add", "addGlob", "remove", "migrate", "apply", "note"],
269
- docs: ["add", "addGlob", "remove", "migrate", "note"],
270
- "package-catalog": [
271
- "activate",
272
- "adopt",
273
- "adoptAll",
274
- "deactivate",
275
- "doctor",
276
- "init",
277
- "install",
278
- "manage",
279
- "migrate",
280
- "reload",
281
- "scaffold",
282
- "uninstall",
283
- ],
284
- };
285
- function hasCanonicalReadOutputOptions(options) {
286
- return CANONICAL_OPTION_KEYS.some((key) => options[key] !== undefined);
287
- }
288
- const READ_OUTPUT_VALUE_VALIDATORS = [
289
- {
290
- keys: ["outputInclude", "output_include"],
291
- valid: (value) => stringList(value) !== undefined,
292
- message: "--output-include requires at least one comma-separated field or section.",
293
- },
294
- {
295
- keys: ["outputLimit", "output_limit"],
296
- valid: (value) => value === "unbounded" || positiveInteger(value) !== undefined,
297
- message: "--output-limit must be a positive integer or unbounded.",
298
- },
299
- {
300
- keys: ["outputBudget", "output_budget"],
301
- valid: (value) => value === "unbounded" || positiveInteger(value) !== undefined,
302
- message: "--output-budget must be a positive integer or unbounded.",
303
- },
304
- {
305
- keys: ["outputFormat", "output_format"],
306
- valid: (value) => value === "toon" || value === "json",
307
- message: "--output-format must be toon or json.",
308
- },
309
- {
310
- keys: ["outputSession", "output_session"],
311
- valid: (value) => {
312
- parseReadOutputSession(value);
313
- return true;
314
- },
315
- message: "--output-session must be a valid session-state object.",
316
- },
317
- {
318
- keys: ["outputCursor", "output_cursor"],
319
- valid: (value) => typeof value === "string" && value.trim().length > 0,
320
- message: "--output-cursor requires a non-empty continuation cursor.",
321
- },
322
- ];
323
- /** Reject malformed or mutation-scoped universal output controls before command execution. */
324
- export function validateReadOutputOptions(command, options) {
325
- if (!hasCanonicalReadOutputOptions(options))
326
- return;
327
- const normalizedCommand = resolveReadOutputSurface(command, options);
328
- if (!normalizedCommand) {
329
- throw new PmCliError(`Universal output controls apply only to read commands; ${command || "this command"} is not a read surface.`, EXIT_CODE.USAGE);
330
- }
331
- if ((HYBRID_READ_MUTATION_KEYS[normalizedCommand] ?? []).some((key) => options[key] !== undefined && options[key] !== false)) {
332
- throw new PmCliError(`Universal output controls cannot be combined with a ${normalizedCommand} mutation.`, EXIT_CODE.USAGE);
333
- }
334
- for (const validator of READ_OUTPUT_VALUE_VALIDATORS) {
335
- const value = validator.keys
336
- .map((key) => options[key])
337
- .find((entry) => entry !== undefined);
338
- if (value !== undefined && !validator.valid(value)) {
339
- throw new PmCliError(validator.message, EXIT_CODE.USAGE);
340
- }
341
- }
342
- }
343
- /**
344
- * Map every canonical `--output-include` token that names a projection mode
345
- * rather than a row field onto the command-local option that mode already owns.
346
- *
347
- * The include dimension folds two kinds of legacy alias into one canonical
348
- * spelling: value-bearing selectors (`--fields`, `--section`) that name row
349
- * fields, and mode flags (`--brief`, `--full`, `--summary`, ...) that select a
350
- * whole declared projection. Only the first kind can be honoured by projecting
351
- * an already-computed result, so mode tokens have to reach the command itself.
352
- */
353
- export function readOutputIncludeModeOptions(command) {
354
- const surface = resolveReadOutputSurface(command);
355
- if (!surface)
356
- return new Map();
357
- return new Map((LEGACY_FLAGS_BY_COMMAND[surface].include ?? [])
358
- .filter((flag) => !VALUE_BEARING_INCLUDE_ALIASES.has(flag) &&
359
- BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag] === undefined)
360
- .map((flag) => [flagSelector(flag), optionKey(flag)]));
361
- }
362
- /**
363
- * Translate canonical projection-mode tokens into the command-local options
364
- * they alias, so the spelling the migration hints recommend is behaviour
365
- * identical to the legacy flag it replaces, and return the field selectors that
366
- * remain for post-execution projection.
367
- */
368
- export function applyReadOutputIncludeModes(command, includeValue, commandOptions) {
369
- const requested = stringList(includeValue) ?? [];
370
- const modeOptions = readOutputIncludeModeOptions(command);
371
- const selectors = [];
372
- const modes = [];
373
- const optionsWithProvenance = commandOptions;
374
- const existingProvenance = optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE];
375
- const canonicalModes = new Set(existingProvenance?.canonical_include_modes ?? []);
376
- const explicitLegacyAliases = new Set(existingProvenance?.explicit_legacy_aliases ?? []);
377
- for (const token of requested) {
378
- const option = modeOptions.get(token);
379
- if (option === undefined) {
380
- selectors.push(token);
381
- continue;
382
- }
383
- const legacyFlag = `--${token.replaceAll("_", "-")}`;
384
- if (isRequestedOption(readOption(commandOptions, legacyFlag))) {
385
- explicitLegacyAliases.add(legacyFlag);
386
- }
387
- commandOptions[option] = true;
388
- modes.push(token);
389
- canonicalModes.add(token);
390
- }
391
- const forwardedGetFieldSelectors = resolveReadOutputSurface(command) === "get"
392
- ? selectors.filter((selector) => selector !== "item")
393
- : [];
394
- const forwardedGetFields = forwardedGetFieldSelectors.length > 0;
395
- if (forwardedGetFields) {
396
- commandOptions.fields = [
397
- ...new Set([
398
- ...(stringList(commandOptions.fields) ?? []),
399
- ...forwardedGetFieldSelectors,
400
- ]),
401
- ].join(",");
402
- canonicalModes.add("fields");
403
- }
404
- if (modes.length > 0 || forwardedGetFields) {
405
- optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE] = {
406
- canonical_include_modes: [...canonicalModes],
407
- explicit_legacy_aliases: [...explicitLegacyAliases],
408
- ...(existingProvenance?.cli_invocation_observed === true
409
- ? { cli_invocation_observed: true }
410
- : {}),
411
- };
412
- }
413
- return { selectors, modes };
414
- }
415
- /**
416
- * Resolve canonical include modes against one combined options bag, rewriting
417
- * the include value in place to the selectors that remain.
418
- *
419
- * Used by dispatch paths that carry command options and universal output
420
- * controls in a single record, so an action honours a mode token exactly as the
421
- * CLI does.
422
- */
423
- export function normalizeReadOutputIncludeModeOptions(command, options) {
424
- const include = options.outputInclude ?? options.output_include;
425
- if (include === undefined)
426
- return;
427
- const { selectors, modes } = applyReadOutputIncludeModes(command, include, options);
428
- if (modes.length === 0)
429
- return;
430
- const residual = selectors.length > 0 ? selectors.join(",") : undefined;
431
- options.outputInclude = residual;
432
- if (Object.hasOwn(options, "output_include")) {
433
- options.output_include = residual;
434
- }
435
- }
436
- function optionKey(flag) {
437
- return flag
438
- .slice(2)
439
- .replace(/-([a-z])/gu, (_, character) => character.toUpperCase());
440
- }
441
- function readOption(options, flag) {
442
- const key = optionKey(flag);
443
- if (Object.hasOwn(options, key))
444
- return options[key];
445
- const snakeKey = flag.slice(2).replaceAll("-", "_");
446
- if (Object.hasOwn(options, snakeKey))
447
- return options[snakeKey];
448
- if (flag === "--no-truncate" && options.truncate === false)
449
- return true;
450
- return undefined;
451
- }
452
- function isRequestedOption(value) {
453
- return value !== undefined && value !== false && value !== null;
454
- }
455
- function stringList(value) {
456
- const values = Array.isArray(value) ? value : [value];
457
- const normalized = values
458
- .flatMap((entry) => (typeof entry === "string" ? entry.split(",") : []))
459
- .map((entry) => entry.trim())
460
- .filter(Boolean);
461
- return normalized.length > 0 ? [...new Set(normalized)] : undefined;
462
- }
463
- function positiveInteger(value) {
464
- const parsed = typeof value === "number"
465
- ? value
466
- : typeof value === "string" && /^\d+$/u.test(value.trim())
467
- ? Number(value)
468
- : Number.NaN;
469
- return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
470
- }
471
- function resolveLegacyDimension(contract, options, usable, ignore) {
472
- for (const alias of contract.legacy_aliases) {
473
- if (ignore(alias.flag))
474
- continue;
475
- const value = readOption(options, alias.flag);
476
- const candidate = { value, flag: alias.flag };
477
- if (isRequestedOption(value) && usable(candidate))
478
- return candidate;
479
- }
480
- return undefined;
481
- }
482
- function resolveIncludeValue(canonical, legacy) {
483
- const canonicalList = stringList(canonical);
484
- if (canonicalList)
485
- return { source: "canonical", value: canonicalList };
486
- if (!legacy)
487
- return undefined;
488
- return {
489
- source: "legacy",
490
- value: stringList(legacy.value) ?? [flagSelector(legacy.flag)],
491
- };
492
- }
493
- function resolveAmountValue(canonical, legacy) {
494
- if (canonical === "unbounded") {
495
- return { source: "canonical", value: "unbounded" };
496
- }
497
- const canonicalLimit = positiveInteger(canonical);
498
- if (canonicalLimit !== undefined) {
499
- return { source: "canonical", value: canonicalLimit };
500
- }
501
- if (!legacy)
502
- return undefined;
503
- if (legacy.flag === "--no-truncate" || legacy.flag === "--unbounded") {
504
- return { source: "legacy", value: "unbounded" };
505
- }
506
- const legacyLimit = positiveInteger(legacy.value);
507
- return legacyLimit === undefined
508
- ? undefined
509
- : { source: "legacy", value: legacyLimit };
510
- }
511
- function resolveCostValue(canonical, legacy) {
512
- if (canonical === "unbounded") {
513
- return { source: "canonical", value: "unbounded" };
514
- }
515
- const canonicalBudget = positiveInteger(canonical);
516
- if (canonicalBudget !== undefined) {
517
- return { source: "canonical", value: canonicalBudget };
518
- }
519
- if (!legacy)
520
- return undefined;
521
- const legacyBudget = positiveInteger(legacy.value);
522
- return legacyBudget === undefined
523
- ? undefined
524
- : { source: "legacy", value: legacyBudget };
525
- }
526
- function resolveEncodingValue(canonical, legacy) {
527
- if (canonical === "json" || canonical === "toon") {
528
- return { source: "canonical", value: canonical };
529
- }
530
- if (!legacy)
531
- return undefined;
532
- if (legacy.flag === "--stream" || legacy.flag === "--follow") {
533
- return { source: "legacy", value: "stream" };
534
- }
535
- return legacy.value === "json" || legacy.value === "toon"
536
- ? { source: "legacy", value: legacy.value }
537
- : undefined;
538
- }
539
- function shouldIgnoreReadOutputLegacyAlias(provenance, dimension, flag) {
540
- if (!provenance)
541
- return false;
542
- const explicitLegacyAliases = new Set(provenance.explicit_legacy_aliases);
543
- if (provenance.cli_invocation_observed === true) {
544
- return !explicitLegacyAliases.has(flag);
545
- }
546
- const forwardedIncludeAliases = new Set(provenance.canonical_include_modes.map((mode) => `--${mode.replaceAll("_", "-")}`));
547
- return (dimension === "include" &&
548
- forwardedIncludeAliases.has(flag) &&
549
- !explicitLegacyAliases.has(flag));
550
- }
551
- function hasCompleteReadOutputIntent(command, legacyByDimension, provenance) {
552
- const root = command
553
- .trim()
554
- .toLowerCase()
555
- .replaceAll(/\s+/gu, " ")
556
- .split(" ")[0];
557
- return (root === "list-all" ||
558
- legacyByDimension.amount?.flag === "--no-truncate" ||
559
- legacyByDimension.include?.flag === "--full" ||
560
- provenance?.canonical_include_modes.includes("full") === true);
561
- }
562
- function canonicalReadOutputOptionsUsed(resolvedByDimension, provenance) {
563
- return PM_READ_OUTPUT_DIMENSIONS.flatMap((dimension) => resolvedByDimension[dimension]?.source === "canonical" ||
564
- (dimension === "include" &&
565
- (provenance?.canonical_include_modes.length ?? 0) > 0)
566
- ? [CANONICAL_OPTIONS[dimension]]
567
- : []);
568
- }
569
- /** Resolve canonical and compatibility controls into the universal dimension set. */
570
- export function resolveReadOutputDimensions(command, options) {
571
- const normalizedCommand = resolveReadOutputSurface(command, options);
572
- if (!normalizedCommand)
573
- return undefined;
574
- const contract = SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand);
575
- const invocationProvenance = options[READ_OUTPUT_INVOCATION_PROVENANCE];
576
- const legacyResolvers = {
577
- include: (candidate) => resolveIncludeValue(undefined, candidate),
578
- amount: (candidate) => resolveAmountValue(undefined, candidate),
579
- cost: (candidate) => resolveCostValue(undefined, candidate),
580
- encoding: (candidate) => resolveEncodingValue(undefined, candidate),
581
- };
582
- const legacyByDimension = Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map((dimension) => [
583
- dimension,
584
- resolveLegacyDimension(contract.dimensions[dimension], options, (candidate) => legacyResolvers[dimension](candidate) !== undefined, (flag) => shouldIgnoreReadOutputLegacyAlias(invocationProvenance, dimension, flag)),
585
- ]));
586
- const legacyAliasesUsed = PM_READ_OUTPUT_DIMENSIONS.flatMap((dimension) => {
587
- const resolved = legacyByDimension[dimension];
588
- return resolved ? [resolved.flag] : [];
589
- });
590
- const migrationHints = PM_READ_OUTPUT_DIMENSIONS.flatMap((dimension) => {
591
- const resolved = legacyByDimension[dimension];
592
- if (!resolved)
593
- return [];
594
- const alias = contract.dimensions[dimension].legacy_aliases.find((entry) => entry.flag === resolved.flag);
595
- return [alias.migration_hint];
596
- });
597
- const encoding = resolveEncodingValue(options.outputFormat ?? options.output_format, legacyByDimension.encoding);
598
- const include = resolveIncludeValue(options.outputInclude ?? options.output_include, legacyByDimension.include);
599
- const amount = resolveAmountValue(options.outputLimit ?? options.output_limit, legacyByDimension.amount);
600
- const explicitCost = resolveCostValue(options.outputBudget ?? options.output_budget, legacyByDimension.cost);
601
- const completeResultIntent = hasCompleteReadOutputIntent(command, legacyByDimension, invocationProvenance);
602
- const budget = resolvePmCommandOutputBudget(command, {
603
- generateFallback: true,
604
- });
605
- const resolvedOutputFormat = encoding?.value === "json" || options.resolvedOutputFormat === "json"
606
- ? "json"
607
- : "toon";
608
- const cost = explicitCost ??
609
- (completeResultIntent
610
- ? { source: "intent", value: "unbounded" }
611
- : {
612
- source: "default",
613
- value: budget.default_max_estimated_tokens_by_format[resolvedOutputFormat],
614
- });
615
- const resolvedByDimension = { include, amount, cost, encoding };
616
- return {
617
- command: normalizedCommand,
618
- include,
619
- amount,
620
- cost,
621
- encoding,
622
- canonical_options_used: canonicalReadOutputOptionsUsed(resolvedByDimension, invocationProvenance),
623
- legacy_aliases_used: legacyAliasesUsed,
624
- migration_hints: migrationHints,
625
- precedence: READ_OUTPUT_PRECEDENCE,
626
- };
627
- }
628
- function isRecord(value) {
629
- return value !== null && typeof value === "object" && !Array.isArray(value);
630
- }
631
- const ENVELOPE_KEYS = new Set([
632
- "applied_bound",
633
- "applied_limit",
634
- "completeness",
635
- "continuation_kind",
636
- "continuation_path",
637
- "continuation_contract",
638
- "count",
639
- "filters",
640
- "has_more",
641
- "next_cursor",
642
- "now",
643
- "omission_receipt",
644
- "projection",
645
- "budget_retention_policy",
646
- "row_contract",
647
- "sorting",
648
- "total",
649
- "truncated",
650
- ]);
651
- const GET_STABLE_DERIVED_ITEM_SELECTORS = [
652
- "collection_counts",
653
- "notes_count",
654
- "tests_count",
655
- ];
656
- function projectRecordFields(value, selectors) {
657
- const selected = new Set(selectors.map((selector) => selector.split(".")[0]));
658
- return Object.fromEntries(Object.entries(value).filter(([key]) => selected.has(key)));
659
- }
660
- function getProjectionVocabulary(result) {
661
- const item = isRecord(result.item) ? result.item : {};
662
- const itemFields = [
663
- ...new Set([
664
- ...Object.keys(item),
665
- ...GET_STABLE_DERIVED_ITEM_SELECTORS.filter((key) => Object.hasOwn(item, key)),
666
- ]),
667
- ].sort((left, right) => left.localeCompare(right));
668
- const sections = Object.keys(result)
669
- .filter((key) => key !== "item" && key !== "read_output" && !ENVELOPE_KEYS.has(key))
670
- .sort((left, right) => left.localeCompare(right));
671
- return {
672
- item,
673
- itemFields,
674
- sections,
675
- valid: [
676
- ...itemFields,
677
- "item",
678
- ...itemFields.map((field) => `item.${field}`),
679
- ...sections,
680
- ],
681
- };
682
- }
683
- function applyGetIncludeProjection(result, selectors) {
684
- const vocabulary = getProjectionVocabulary(result);
685
- const unknown = selectors.filter((selector) => !vocabulary.valid.includes(selector));
686
- if (unknown.length > 0) {
687
- throw new PmCliError(`Unknown --output-include selector(s) for get: ${unknown.join(", ")}. Valid selectors: ${vocabulary.valid.join(", ")}.`, EXIT_CODE.USAGE);
688
- }
689
- const fullItem = selectors.includes("item");
690
- const itemSelectors = selectors
691
- .flatMap((selector) => selector.startsWith("item.")
692
- ? [selector.slice("item.".length)]
693
- : vocabulary.itemFields.includes(selector)
694
- ? [selector]
695
- : [])
696
- .filter((selector, index, values) => values.indexOf(selector) === index);
697
- if (fullItem && itemSelectors.length > 0) {
698
- throw new PmCliError("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.", EXIT_CODE.USAGE);
699
- }
700
- const selectedSections = new Set(selectors.filter((selector) => vocabulary.sections.includes(selector)));
701
- const projected = Object.fromEntries(Object.entries(result).filter(([key]) => ENVELOPE_KEYS.has(key) || selectedSections.has(key)));
702
- if (fullItem) {
703
- projected.item = vocabulary.item;
704
- }
705
- else if (itemSelectors.length > 0) {
706
- projected.item = projectRecordFields(vocabulary.item, itemSelectors);
707
- }
708
- const omittedFieldGroups = [
709
- ...(fullItem
710
- ? []
711
- : itemSelectors.length > 0
712
- ? vocabulary.itemFields
713
- .filter((field) => !itemSelectors.includes(field))
714
- .map((field) => ({
715
- name: `item.${field}`,
716
- restore_with: `--output-include item.${field}`,
717
- }))
718
- : [{ name: "item", restore_with: "--output-include item" }]),
719
- ...vocabulary.sections
720
- .filter((section) => !selectedSections.has(section))
721
- .map((section) => ({
722
- name: section,
723
- restore_with: `--output-include ${section}`,
724
- })),
725
- ];
726
- const inheritedOmittedFieldGroups = isRecord(projected.omission_receipt) &&
727
- Array.isArray(projected.omission_receipt.omitted_field_groups)
728
- ? projected.omission_receipt.omitted_field_groups
729
- : [];
730
- const combinedOmittedFieldGroups = [
731
- ...inheritedOmittedFieldGroups,
732
- ...omittedFieldGroups,
733
- ];
734
- projected.omission_receipt = {
735
- has_omissions: combinedOmittedFieldGroups.length > 0,
736
- omitted_field_group_count: combinedOmittedFieldGroups.length,
737
- omitted_field_groups: combinedOmittedFieldGroups,
738
- };
739
- return projected;
740
- }
741
- /** Count row objects that still carry at least one field. */
742
- function countPopulatedRows(result) {
743
- let populated = 0;
744
- mapReadOutputRows({ ...result }, (entry) => {
745
- if (isRecord(entry) && Object.keys(entry).length > 0)
746
- populated += 1;
747
- return entry;
748
- });
749
- return populated;
750
- }
751
- /**
752
- * Refuse an include projection that strips every field from every row.
753
- *
754
- * Selectors that match no field are not a narrower answer, they are no answer:
755
- * without this the surface returns the requested row count as empty objects and
756
- * exits 0, so a mistyped or mode-shaped selector is indistinguishable from a
757
- * workspace that genuinely holds nothing.
758
- */
759
- function rejectEmptyIncludeProjection(command, original, shaped, selectors) {
760
- if (countPopulatedRows(original) === 0 || countPopulatedRows(shaped) > 0) {
761
- return;
762
- }
763
- const modes = [...readOutputIncludeModeOptions(command).keys()];
764
- const domain = modes.length > 0
765
- ? ` Declared ${command} projection modes: ${modes.join(", ")}.`
766
- : ` The ${command} surface declares no projection modes; name row fields instead.`;
767
- throw new PmCliError(`Unknown --output-include selector(s) for ${command}: ${selectors.join(", ")}. No selector matched any returned row field.${domain}`, EXIT_CODE.USAGE);
768
- }
769
- function applyIncludeProjection(command, result, selectors) {
770
- if (command === "get") {
771
- return applyGetIncludeProjection(result, selectors);
772
- }
773
- const rows = readOutputRowPaths(result);
774
- const qualifiedRowSelectors = selectors.flatMap((selector) => rows.flatMap((rowPath) => selector.startsWith(`${rowPath}.`)
775
- ? [selector.slice(rowPath.length + 1)]
776
- : []));
777
- const selectedRoot = selectors.some((selector) => Object.hasOwn(result, selector.split(".")[0]) &&
778
- !rows.some((rowPath) => selector.startsWith(`${rowPath}.`)));
779
- if (rows.length > 0 && (!selectedRoot || qualifiedRowSelectors.length > 0)) {
780
- const projected = { ...result };
781
- const rowSelectors = qualifiedRowSelectors.length > 0 ? qualifiedRowSelectors : selectors;
782
- const shaped = mapReadOutputRows(projected, (entry) => isRecord(entry) ? projectRecordFields(entry, rowSelectors) : entry);
783
- rejectEmptyIncludeProjection(command, result, shaped, rowSelectors);
784
- return shaped;
785
- }
786
- return Object.fromEntries(Object.entries(result).filter(([key]) => selectors.some((selector) => selector.split(".")[0] === key) ||
787
- ENVELOPE_KEYS.has(key)));
788
- }
789
- function applyAmountBound(result, amount) {
790
- if (amount === "unbounded")
791
- return result;
792
- const { result: bounded, truncated } = boundReadOutputRows(result, amount);
793
- if (!truncated)
794
- return bounded;
795
- bounded.has_more = true;
796
- bounded.truncated = true;
797
- if (typeof bounded.count === "number") {
798
- bounded.count = countReadOutputRows(bounded);
799
- }
800
- bounded.applied_bound = {
801
- kind: "output_limit",
802
- source: "explicit",
803
- value: amount,
804
- };
805
- return bounded;
806
- }
807
- function requestedDimensions(resolved) {
808
- return PM_READ_OUTPUT_DIMENSIONS.filter((dimension) => (resolved[dimension] !== undefined &&
809
- resolved[dimension]?.source !== "default") ||
810
- resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]));
811
- }
812
- /** Stabilize the per-call and cross-call receipts in one complete envelope. */
813
- function attachReadOutputSessionContracts(result, state, receipt) {
814
- let withSession = attachReadOutputSessionReceipt(result, state);
815
- for (let iteration = 0; iteration < 8; iteration += 1) {
816
- const previousReadEstimate = receipt.estimated_tokens;
817
- const previousSessionEstimate = withSession.read_session.spent_this_call_tokens;
818
- updateReadOutputReceiptEstimate(withSession, receipt);
819
- withSession = attachReadOutputSessionReceipt(withSession, state);
820
- const sessionEstimate = withSession.read_session.spent_this_call_tokens;
821
- if (receipt.estimated_tokens === previousReadEstimate &&
822
- sessionEstimate === previousSessionEstimate) {
823
- return withSession;
824
- }
825
- }
826
- return withSession;
827
- }
828
- /** Recompute read and optional session receipts after a final envelope projection. */
829
- export function stabilizeReadOutputReceiptEstimates(result, options) {
830
- if (!isRecord(result.read_output))
831
- return result;
832
- const receipt = result.read_output;
833
- const session = parseReadOutputSession(options.outputSession ?? options.output_session);
834
- if (session === undefined) {
835
- updateReadOutputReceiptEstimate(result, receipt);
836
- return result;
837
- }
838
- return attachReadOutputSessionContracts(result, session, receipt);
839
- }
840
- /** Declare independently resumable validate diagnostic arrays on rich results. */
841
- function attachValidateDiagnosticRowContract(command, result) {
842
- if (command !== "validate")
843
- return result;
844
- const projection = isRecord(result.projection)
845
- ? result.projection
846
- : undefined;
847
- const declaredFieldGroups = Array.isArray(projection?.declared_field_groups)
848
- ? projection.declared_field_groups
849
- : [];
850
- if (!declaredFieldGroups.some((group) => isRecord(group) && group.name === "diagnostic_rows")) {
851
- return result;
852
- }
853
- const diagnosticCollectionPaths = [
854
- ...new Set(readOutputBudgetCollections(result)
855
- .map(({ path }) => path)
856
- .filter((path) => /^checks\.\d+\.details\./u.test(path))),
857
- ];
858
- const diagnosticRowKeys = diagnosticCollectionPaths.filter((path) => !diagnosticCollectionPaths.some((candidate) => candidate !== path && path.startsWith(`${candidate}.`)));
859
- if (diagnosticRowKeys.length === 0)
860
- return result;
861
- const existingContract = isRecord(result.row_contract)
862
- ? result.row_contract
863
- : {};
864
- const existingRowKeys = Array.isArray(existingContract.row_keys)
865
- ? existingContract.row_keys.filter((entry) => typeof entry === "string")
866
- : [];
867
- const existingContinuationRowKeys = Array.isArray(existingContract.continuation_row_keys)
868
- ? existingContract.continuation_row_keys.filter((entry) => typeof entry === "string")
869
- : [];
870
- const rowKeys = existingRowKeys.length > 0 ? existingRowKeys : diagnosticRowKeys;
871
- const continuationRowKeys = [...new Set(diagnosticRowKeys)];
872
- return JSON.stringify(rowKeys) === JSON.stringify(existingRowKeys) &&
873
- JSON.stringify(continuationRowKeys) ===
874
- JSON.stringify(existingContinuationRowKeys)
875
- ? result
876
- : {
877
- ...result,
878
- row_contract: {
879
- ...existingContract,
880
- row_keys: rowKeys,
881
- continuation_row_keys: continuationRowKeys,
882
- jq_selector: typeof existingContract.jq_selector === "string"
883
- ? existingContract.jq_selector
884
- : ".checks[].details",
885
- },
886
- };
887
- }
888
- /** Apply field, amount, and repeat projections to every declared row path. */
889
- function projectReadOutputRows(result, resolved, session, cursor) {
890
- let projected = { ...result };
891
- if (resolved.include?.source === "canonical") {
892
- projected = applyIncludeProjection(resolved.command, projected, resolved.include.value);
893
- }
894
- if (resolved.command === "assurance") {
895
- projected = prioritizeAssuranceAssertions(projected);
896
- }
897
- projected = applyReadOutputContinuation(projected, resolved.command, cursor);
898
- if (resolved.amount?.source === "canonical") {
899
- projected = applyAmountBound(projected, resolved.amount.value);
900
- }
901
- return session === undefined
902
- ? projected
903
- : applyReadOutputSessionReferences(projected, session);
904
- }
905
- /** Resolve the smallest binding per-call or remaining cross-call ceiling. */
906
- function resolveBindingReadOutputBudget(resolved, session) {
907
- const budgets = [
908
- ...(resolved.cost !== undefined &&
909
- resolved.cost.value !== "unbounded" &&
910
- (resolved.cost.source === "canonical" || resolved.cost.source === "default")
911
- ? [{ source: resolved.cost.source, tokens: resolved.cost.value }]
912
- : []),
913
- ...(session === undefined
914
- ? []
915
- : [
916
- {
917
- source: "session",
918
- tokens: readOutputSessionRemainingTokens(session),
919
- },
920
- ]),
921
- ];
922
- return budgets.sort((left, right) => left.tokens - right.tokens)[0];
923
- }
924
- function canonicalReadOutputReceiptFields(resolved) {
925
- const canonicalOptions = resolved.canonical_options_used;
926
- return canonicalOptions && canonicalOptions.length > 0
927
- ? { canonical_options_used: canonicalOptions }
928
- : {};
929
- }
930
- /** Build the smallest truthful omission envelope or reject an exhausted session. */
931
- function omitReadOutputForBudget(resolved, requested, session, bindingBudget, omittedResultEstimatedTokens) {
932
- const minimalReceipt = {
933
- contract_version: 1,
934
- command: resolved.command,
935
- requested_dimensions: requested,
936
- ...(bindingBudget.source === "default"
937
- ? {
938
- budget_source: bindingBudget.source,
939
- budget_tokens: bindingBudget.tokens,
940
- }
941
- : {}),
942
- precedence: resolved.precedence,
943
- ...canonicalReadOutputReceiptFields(resolved),
944
- legacy_aliases_used: [],
945
- migration_hints: [],
946
- estimated_tokens: 0,
947
- within_budget: false,
948
- strings_compacted: false,
949
- rows_compacted: false,
950
- result_omitted: true,
951
- ...(session === undefined
952
- ? { omitted_result_estimated_tokens: omittedResultEstimatedTokens }
953
- : {}),
954
- };
955
- const omitted = {
956
- output_budget_exceeded: {
957
- omitted_result: true,
958
- reason: "requested_budget_infeasible",
959
- restore_with: "Unbounded",
960
- recovery: { outputBudget: "unbounded" },
961
- },
962
- read_output: minimalReceipt,
963
- };
964
- const boundedOmission = session === undefined
965
- ? omitted
966
- : attachReadOutputSessionContracts(omitted, session, minimalReceipt);
967
- if (session === undefined) {
968
- updateReadOutputReceiptEstimate(boundedOmission, minimalReceipt);
969
- }
970
- if (session !== undefined &&
971
- minimalReceipt.estimated_tokens > bindingBudget.tokens) {
972
- throw new PmCliError("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.", EXIT_CODE.USAGE);
973
- }
974
- return boundedOmission;
975
- }
976
- /** Decide whether shaping would add no value to an already-bounded result. */
977
- function canReturnReadOutputUnchanged(resolved, session, result) {
978
- if (session !== undefined)
979
- return false;
980
- const canonicalRequestedCount = resolved.canonical_options_used.length;
981
- if (resolved.cost?.value === "unbounded") {
982
- return (canonicalRequestedCount === (resolved.cost.source === "canonical" ? 1 : 0));
983
- }
984
- if (resolved.cost?.source === "legacy" && canonicalRequestedCount === 0) {
985
- return true;
986
- }
987
- return (canonicalRequestedCount === 0 &&
988
- (resolved.cost === undefined ||
989
- estimateReadOutputTokens(result) <= resolved.cost.value));
990
- }
991
- /**
992
- * Disclose a budget-driven row drop in the envelope that carries it.
993
- *
994
- * `has_more` and `truncated` say that rows were withheld but not why, by what,
995
- * or how to get them: the row-compaction path emits no continuation cursor, so
996
- * without this an explicitly requested unbounded read is silently downgraded and
997
- * the only working recovery is never named.
998
- */
999
- function attachReadOutputTruncationDisclosure(projected, resolved, receipt, bindingBudget, continuationCursorRebased, measuredResultTokens, collectionsBeforeBudget) {
1000
- if (!receipt.rows_compacted)
1001
- return;
1002
- const overridden = resolved.amount?.value === "unbounded" ? ["amount"] : [];
1003
- const afterByPath = new Map(readOutputContinuationRowCollections(projected).map((collection) => [
1004
- collection.path,
1005
- Array.isArray(collection.value)
1006
- ? collection.value.length
1007
- : Object.keys(collection.value).length,
1008
- ]));
1009
- const continuations = [...collectionsBeforeBudget.entries()].flatMap(([path, before]) => {
1010
- // Budget compaction preserves every declared collection and shortens its
1011
- // contents, so each pre-budget path has a post-budget cardinality.
1012
- const retainedRows = afterByPath.get(path);
1013
- if (retainedRows >= before.rows)
1014
- return [];
1015
- const offset = before.baseOffset + retainedRows;
1016
- return [
1017
- {
1018
- path,
1019
- cursor: encodeReadOutputContinuationCursor({
1020
- command: resolved.command,
1021
- path,
1022
- offset,
1023
- total_rows: before.totalRows,
1024
- fingerprint: before.fingerprint,
1025
- }),
1026
- retained_rows: retainedRows,
1027
- remaining_rows: before.totalRows - offset,
1028
- total_rows: before.totalRows,
1029
- },
1030
- ];
1031
- });
1032
- const primary = continuations[0];
1033
- const recoveryBudget = resolveReadOutputRecoveryBudget({
1034
- effective_budget_tokens: bindingBudget.tokens,
1035
- measured_result_tokens: measuredResultTokens,
1036
- });
1037
- if (primary && typeof projected.next_cursor !== "string") {
1038
- projected.next_cursor = primary.cursor;
1039
- }
1040
- projected.continuation_kind = continuationCursorRebased
1041
- ? "producer_cursor"
1042
- : primary
1043
- ? "output_cursor"
1044
- : "none";
1045
- projected.output_budget_truncation = {
1046
- reason: "output_budget_reached",
1047
- budget_source: bindingBudget.source,
1048
- budget_tokens: bindingBudget.tokens,
1049
- overridden_dimensions: overridden,
1050
- compacted_row_paths: receipt.compacted_row_paths,
1051
- continuation_cursor_rebased: continuationCursorRebased,
1052
- continuation_available: continuations.length > 0,
1053
- recovery_budget_multiplier: primary
1054
- ? 1
1055
- : recoveryBudget.recovery_budget_multiplier,
1056
- continuations,
1057
- restore_with: primary
1058
- ? "Use recovery binding."
1059
- : `Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,
1060
- recovery: primary
1061
- ? {
1062
- cursor: primary.cursor,
1063
- cli: "--output-cursor",
1064
- sdk: "outputCursor",
1065
- mcp: "outputCursor",
1066
- }
1067
- : {
1068
- cli: `--output-budget ${recoveryBudget.output_budget}`,
1069
- sdk: { outputBudget: recoveryBudget.output_budget },
1070
- mcp: { outputBudget: recoveryBudget.output_budget },
1071
- },
1072
- };
1073
- }
1074
- /** Rebase a producer cursor when budget compaction removes rows from its page. */
1075
- function rebaseBudgetCompactedCursor(projected, originalItemCount, cursorSource, cursorContinuesExistingPage) {
1076
- if (typeof cursorSource !== "string" || !Array.isArray(projected.items)) {
1077
- return false;
1078
- }
1079
- const retainedCount = projected.items.length;
1080
- if (retainedCount === 0 || retainedCount >= originalItemCount) {
1081
- return false;
1082
- }
1083
- let cursor;
1084
- try {
1085
- cursor = decodeQueryCursorEnvelope(cursorSource);
1086
- }
1087
- catch {
1088
- return false;
1089
- }
1090
- const sourceIndex = cursor.after_index;
1091
- if (sourceIndex === undefined)
1092
- return false;
1093
- const last = projected.items.at(-1);
1094
- if (Object.prototype.toString.call(last) !== "[object Object]") {
1095
- return false;
1096
- }
1097
- const lastId = Reflect.get(last, "id");
1098
- if (typeof lastId !== "string" || lastId.length === 0)
1099
- return false;
1100
- const afterIndex = cursorContinuesExistingPage
1101
- ? sourceIndex - (originalItemCount - retainedCount)
1102
- : sourceIndex + retainedCount;
1103
- if (afterIndex < 0)
1104
- return false;
1105
- projected.next_cursor = encodeQueryCursor(cursor.fingerprint, lastId, afterIndex, cursor.snapshot);
1106
- if (typeof projected.applied_limit === "number") {
1107
- projected.applied_limit = retainedCount;
1108
- }
1109
- return true;
1110
- }
1111
- function captureReadOutputContinuationState(projected, command, cursor, options) {
1112
- const collectionsBeforeBudget = new Map(readOutputContinuationRowCollections(projected).map((collection) => {
1113
- const rows = Array.isArray(collection.value)
1114
- ? collection.value.length
1115
- : Object.keys(collection.value).length;
1116
- const continued = cursor?.path === collection.path;
1117
- return [
1118
- collection.path,
1119
- {
1120
- rows,
1121
- totalRows: continued ? cursor.total_rows : rows,
1122
- baseOffset: continued ? cursor.offset : 0,
1123
- fingerprint: continued
1124
- ? cursor.fingerprint
1125
- : readOutputCollectionFingerprint(collection.path, collection.value, command),
1126
- },
1127
- ];
1128
- }));
1129
- const cursorContinuesExistingPage = typeof projected.next_cursor === "string";
1130
- return {
1131
- collectionsBeforeBudget,
1132
- originalItemCount: Array.isArray(projected.items)
1133
- ? projected.items.length
1134
- : 0,
1135
- cursorContinuesExistingPage,
1136
- cursorSource: cursorContinuesExistingPage
1137
- ? projected.next_cursor
1138
- : options.after,
1139
- };
1140
- }
1141
- function compactReadOutputProjection(projected, resolved, receipt, bindingBudget, session, continuationState, measuredResultTokens) {
1142
- const assuranceMinimumRows = resolved.command === "assurance" && Array.isArray(projected.assertions)
1143
- ? projected.assertions.filter((row) => isRecord(row) && row.verdict !== "pass").length
1144
- : 0;
1145
- let compacted = compactReadOutputToBudget(projected, receipt, bindingBudget.tokens, assuranceMinimumRows > 0
1146
- ? new Map([["assertions", assuranceMinimumRows]])
1147
- : new Map());
1148
- const continuationCursorRebased = rebaseBudgetCompactedCursor(compacted, continuationState.originalItemCount, continuationState.cursorSource, continuationState.cursorContinuesExistingPage);
1149
- attachReadOutputTruncationDisclosure(compacted, resolved, receipt, bindingBudget, continuationCursorRebased, measuredResultTokens, continuationState.collectionsBeforeBudget);
1150
- if (session !== undefined) {
1151
- compacted = attachReadOutputSessionContracts(compacted, session, receipt);
1152
- }
1153
- return compacted;
1154
- }
1155
- /** Apply universal field, row, and token bounds and attach an exact receipt. */
1156
- export function applyReadOutputDimensions(command, options, result) {
1157
- const resolved = resolveReadOutputDimensions(command, options);
1158
- if (!resolved)
1159
- return result;
1160
- const session = parseReadOutputSession(options.outputSession ?? options.output_session);
1161
- const rawCursor = options.outputCursor ?? options.output_cursor;
1162
- const cursor = typeof rawCursor === "string"
1163
- ? decodeReadOutputContinuationCursor(rawCursor)
1164
- : undefined;
1165
- const requested = requestedDimensions(resolved);
1166
- if (cursor === undefined &&
1167
- canReturnReadOutputUnchanged(resolved, session, result)) {
1168
- return result;
1169
- }
1170
- const continuationReadyResult = attachValidateDiagnosticRowContract(resolved.command, result);
1171
- const bindingBudget = resolveBindingReadOutputBudget(resolved, session);
1172
- let projected = projectReadOutputRows(continuationReadyResult, resolved, session, cursor);
1173
- const continuationState = captureReadOutputContinuationState(projected, resolved.command, cursor, options);
1174
- const receipt = {
1175
- contract_version: 1,
1176
- command: resolved.command,
1177
- requested_dimensions: requested,
1178
- ...(bindingBudget?.source === "default"
1179
- ? {
1180
- budget_source: bindingBudget.source,
1181
- budget_tokens: bindingBudget.tokens,
1182
- }
1183
- : {}),
1184
- precedence: resolved.precedence,
1185
- ...canonicalReadOutputReceiptFields(resolved),
1186
- legacy_aliases_used: resolved.legacy_aliases_used,
1187
- migration_hints: resolved.migration_hints,
1188
- estimated_tokens: 0,
1189
- within_budget: true,
1190
- strings_compacted: false,
1191
- rows_compacted: false,
1192
- result_omitted: false,
1193
- };
1194
- projected.read_output = receipt;
1195
- projected =
1196
- session === undefined
1197
- ? projected
1198
- : attachReadOutputSessionContracts(projected, session, receipt);
1199
- updateReadOutputReceiptEstimate(projected, receipt);
1200
- if (bindingBudget !== undefined &&
1201
- receipt.estimated_tokens > bindingBudget.tokens) {
1202
- const measuredResultTokens = receipt.estimated_tokens;
1203
- projected = compactReadOutputProjection(projected, resolved, receipt, bindingBudget, session, continuationState, measuredResultTokens);
1204
- }
1205
- if (bindingBudget !== undefined &&
1206
- receipt.estimated_tokens > bindingBudget.tokens) {
1207
- return omitReadOutputForBudget(resolved, requested, session, bindingBudget, receipt.estimated_tokens);
1208
- }
1209
- return projected;
1210
- }
1211
- /** Narrow a universal read result to its budget-omission branch. */
1212
- export function isReadOutputBudgetExceeded(result) {
1213
- return (isRecord(result) &&
1214
- isRecord(result.output_budget_exceeded) &&
1215
- result.output_budget_exceeded.omitted_result === true &&
1216
- result.output_budget_exceeded.reason === "requested_budget_infeasible");
1217
- }
1218
- /** Resolve only the canonical renderer override for shared CLI output code. */
1219
- export function resolveReadOutputEncoding(command, options) {
1220
- const encoding = resolveReadOutputDimensions(command, options)?.encoding;
1221
- return encoding?.value === "json" || encoding?.value === "toon"
1222
- ? encoding.value
1223
- : undefined;
1224
- }
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="93f20465-cf27-56cd-8569-ac939d140dad")}catch(e2){}})();import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactReadOutputToBudget,estimateReadOutputTokens,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as resolveReadOutputRecoveryBudget2}from"./read-output-budget.js";import{resolvePmCommandOutputBudget}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputRowPaths}from"./read-output-rows.js";import{applyReadOutputContinuation,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,prioritizeAssuranceAssertions,readOutputCollectionFingerprint}from"./read-output/continuation.js";import{decodeReadOutputContinuationCursor as decodeReadOutputContinuationCursor2,encodeReadOutputContinuationCursor as encodeReadOutputContinuationCursor2,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint as readOutputCollectionFingerprint2}from"./read-output/continuation.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";import{decodeQueryCursorEnvelope,encodeQueryCursor}from"./pagination.js";const PM_READ_OUTPUT_DIMENSIONS=["include","amount","cost","encoding"];const PM_READ_OUTPUT_SURFACES=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"];const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"];const CANONICAL_OPTIONS={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"};const READ_OUTPUT_INVOCATION_PROVENANCE=Symbol.for("pm.readOutputInvocationProvenance");const PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension]));const PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]);const LEGACY_FLAGS_BY_COMMAND={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}};const VALUE_BEARING_INCLUDE_ALIASES=new Set(["--collapse","--fields","--section"]);const BEHAVIOR_PRESERVING_MIGRATION_HINTS=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function flagSelector(flag){return flag.slice(2).replaceAll("-","_")}function migrationHint(flag,dimension){const behaviorHint=BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];if(behaviorHint!==void 0)return behaviorHint;const suffix=dimension==="include"?VALUE_BEARING_INCLUDE_ALIASES.has(flag)?"<csv>":flagSelector(flag):dimension==="amount"?"<n>":dimension==="cost"?"<tokens>":"<toon|json>";return`${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`}function buildSurfaceContract(command){const legacy=LEGACY_FLAGS_BY_COMMAND[command];const dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:true,inapplicable_reason:null,legacy_aliases:Object.freeze((legacy[dimension]??[]).map(flag=>Object.freeze({flag,semantics:BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0?"replacement":"behavior_preserving",migration_hint:migrationHint(flag,dimension),visibility:"hidden_alias"})))})])));return Object.freeze({command,dimensions,precedence:READ_OUTPUT_PRECEDENCE,budget_retention_policy:command==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...readOutputIncludeModeOptions(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract));const SURFACE_CONTRACT_BY_COMMAND=new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map(contract=>[contract.command,contract]));function resolveReadOutputSurface(command,options={}){const normalizedCommand=resolvePmHistoryOperation(command.trim().toLowerCase());const packageMode=normalizedCommand==="package catalog"||normalizedCommand==="packages catalog"||normalizedCommand==="package-catalog"||(normalizedCommand==="package"||normalizedCommand==="packages"||normalizedCommand==="extension")&&(options.catalog===true||options.target==="catalog"||options.action==="catalog");const root=packageMode?"package-catalog":normalizedCommand==="package manage"||normalizedCommand==="package-manage"?"package-manage":normalizedCommand.split(" ")[0];const normalized=root.startsWith("list-")?"list":root==="ctx"?"context":root;return PM_READ_OUTPUT_SURFACES.includes(normalized)?normalized:void 0}const CANONICAL_OPTION_KEYS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"];const HYBRID_READ_MUTATION_KEYS={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function hasCanonicalReadOutputOptions(options){return CANONICAL_OPTION_KEYS.some(key=>options[key]!==void 0)}const READ_OUTPUT_VALUE_VALIDATORS=[{keys:["outputInclude","output_include"],valid:value=>stringList(value)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputFormat","output_format"],valid:value=>value==="toon"||value==="json",message:"--output-format must be toon or json."},{keys:["outputSession","output_session"],valid:value=>{parseReadOutputSession(value);return true},message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:value=>typeof value==="string"&&value.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function validateReadOutputOptions(command,options){if(!hasCanonicalReadOutputOptions(options))return;const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand){throw new PmCliError(`Universal output controls apply only to read commands; ${command||"this command"} is not a read surface.`,EXIT_CODE.USAGE)}if((HYBRID_READ_MUTATION_KEYS[normalizedCommand]??[]).some(key=>options[key]!==void 0&&options[key]!==false)){throw new PmCliError(`Universal output controls cannot be combined with a ${normalizedCommand} mutation.`,EXIT_CODE.USAGE)}for(const validator of READ_OUTPUT_VALUE_VALIDATORS){const value=validator.keys.map(key=>options[key]).find(entry=>entry!==void 0);if(value!==void 0&&!validator.valid(value)){throw new PmCliError(validator.message,EXIT_CODE.USAGE)}}}function readOutputIncludeModeOptions(command){const surface=resolveReadOutputSurface(command);if(!surface)return new Map;return new Map((LEGACY_FLAGS_BY_COMMAND[surface].include??[]).filter(flag=>!VALUE_BEARING_INCLUDE_ALIASES.has(flag)&&BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0).map(flag=>[flagSelector(flag),optionKey(flag)]))}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[];const modeOptions=readOutputIncludeModeOptions(command);const selectors=[];const modes=[];const optionsWithProvenance=commandOptions;const existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE];const canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]);const explicitLegacyAliases=new Set(existingProvenance?.explicit_legacy_aliases??[]);for(const token of requested){const option=modeOptions.get(token);if(option===void 0){selectors.push(token);continue}const legacyFlag=`--${token.replaceAll("_","-")}`;if(isRequestedOption(readOption(commandOptions,legacyFlag))){explicitLegacyAliases.add(legacyFlag)}commandOptions[option]=true;modes.push(token);canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[];const forwardedGetFields=forwardedGetFieldSelectors.length>0;if(forwardedGetFields){commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(",");canonicalModes.add("fields")}if(modes.length>0||forwardedGetFields){optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===true?{cli_invocation_observed:true}:{}}}return{selectors,modes}}function normalizeReadOutputIncludeModeOptions(command,options){const include=options.outputInclude??options.output_include;if(include===void 0)return;const{selectors,modes}=applyReadOutputIncludeModes(command,include,options);if(modes.length===0)return;const residual=selectors.length>0?selectors.join(","):void 0;options.outputInclude=residual;if(Object.hasOwn(options,"output_include")){options.output_include=residual}}function optionKey(flag){return flag.slice(2).replace(/-([a-z])/gu,(_,character)=>character.toUpperCase())}function readOption(options,flag){const key=optionKey(flag);if(Object.hasOwn(options,key))return options[key];const snakeKey=flag.slice(2).replaceAll("-","_");if(Object.hasOwn(options,snakeKey))return options[snakeKey];if(flag==="--no-truncate"&&options.truncate===false)return true;return void 0}function isRequestedOption(value){return value!==void 0&&value!==false&&value!==null}function stringList(value){const values=Array.isArray(value)?value:[value];const normalized=values.flatMap(entry=>typeof entry==="string"?entry.split(","):[]).map(entry=>entry.trim()).filter(Boolean);return normalized.length>0?[...new Set(normalized)]:void 0}function positiveInteger(value){const parsed=typeof value==="number"?value:typeof value==="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveLegacyDimension(contract,options,usable,ignore){for(const alias of contract.legacy_aliases){if(ignore(alias.flag))continue;const value=readOption(options,alias.flag);const candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}return void 0}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(!legacy)return void 0;return{source:"legacy",value:stringList(legacy.value)??[flagSelector(legacy.flag)]}}function resolveAmountValue(canonical,legacy){if(canonical==="unbounded"){return{source:"canonical",value:"unbounded"}}const canonicalLimit=positiveInteger(canonical);if(canonicalLimit!==void 0){return{source:"canonical",value:canonicalLimit}}if(!legacy)return void 0;if(legacy.flag==="--no-truncate"||legacy.flag==="--unbounded"){return{source:"legacy",value:"unbounded"}}const legacyLimit=positiveInteger(legacy.value);return legacyLimit===void 0?void 0:{source:"legacy",value:legacyLimit}}function resolveCostValue(canonical,legacy){if(canonical==="unbounded"){return{source:"canonical",value:"unbounded"}}const canonicalBudget=positiveInteger(canonical);if(canonicalBudget!==void 0){return{source:"canonical",value:canonicalBudget}}if(!legacy)return void 0;const legacyBudget=positiveInteger(legacy.value);return legacyBudget===void 0?void 0:{source:"legacy",value:legacyBudget}}function resolveEncodingValue(canonical,legacy){if(canonical==="json"||canonical==="toon"){return{source:"canonical",value:canonical}}if(!legacy)return void 0;if(legacy.flag==="--stream"||legacy.flag==="--follow"){return{source:"legacy",value:"stream"}}return legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return false;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===true){return!explicitLegacyAliases.has(flag)}const forwardedIncludeAliases=new Set(provenance.canonical_include_modes.map(mode=>`--${mode.replaceAll("_","-")}`));return dimension==="include"&&forwardedIncludeAliases.has(flag)&&!explicitLegacyAliases.has(flag)}function hasCompleteReadOutputIntent(command,legacyByDimension,provenance){const root=command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0];return root==="list-all"||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===true}function canonicalReadOutputOptionsUsed(resolvedByDimension,provenance){return PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>resolvedByDimension[dimension]?.source==="canonical"||dimension==="include"&&(provenance?.canonical_include_modes.length??0)>0?[CANONICAL_OPTIONS[dimension]]:[])}function resolveReadOutputDimensions(command,options){const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)return void 0;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand);const invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE];const legacyResolvers={include:candidate=>resolveIncludeValue(void 0,candidate),amount:candidate=>resolveAmountValue(void 0,candidate),cost:candidate=>resolveCostValue(void 0,candidate),encoding:candidate=>resolveEncodingValue(void 0,candidate)};const legacyByDimension=Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,resolveLegacyDimension(contract.dimensions[dimension],options,candidate=>legacyResolvers[dimension](candidate)!==void 0,flag=>shouldIgnoreReadOutputLegacyAlias(invocationProvenance,dimension,flag))]));const legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]});const migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];if(!resolved)return[];const alias=contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag);return[alias.migration_hint]});const encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding);const include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include);const amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount);const explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost);const completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance);const budget=resolvePmCommandOutputBudget(command,{generateFallback:true});const resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon";const cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});const resolvedByDimension={include,amount,cost,encoding};return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed(resolvedByDimension,invocationProvenance),legacy_aliases_used:legacyAliasesUsed,migration_hints:migrationHints,precedence:READ_OUTPUT_PRECEDENCE}}function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}const ENVELOPE_KEYS=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]);const GET_STABLE_DERIVED_ITEM_SELECTORS=["collection_counts","notes_count","tests_count"];function projectRecordFields(value,selectors){const selected=new Set(selectors.map(selector=>selector.split(".")[0]));return Object.fromEntries(Object.entries(value).filter(([key])=>selected.has(key)))}function getProjectionVocabulary(result){const item=isRecord(result.item)?result.item:{};const itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right));const sections=Object.keys(result).filter(key=>key!=="item"&&key!=="read_output"&&!ENVELOPE_KEYS.has(key)).sort((left,right)=>left.localeCompare(right));return{item,itemFields,sections,valid:[...itemFields,"item",...itemFields.map(field=>`item.${field}`),...sections]}}function applyGetIncludeProjection(result,selectors){const vocabulary=getProjectionVocabulary(result);const unknown=selectors.filter(selector=>!vocabulary.valid.includes(selector));if(unknown.length>0){throw new PmCliError(`Unknown --output-include selector(s) for get: ${unknown.join(", ")}. Valid selectors: ${vocabulary.valid.join(", ")}.`,EXIT_CODE.USAGE)}const fullItem=selectors.includes("item");const itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice("item.".length)]:vocabulary.itemFields.includes(selector)?[selector]:[]).filter((selector,index,values)=>values.indexOf(selector)===index);if(fullItem&&itemSelectors.length>0){throw new PmCliError("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",EXIT_CODE.USAGE)}const selectedSections=new Set(selectors.filter(selector=>vocabulary.sections.includes(selector)));const projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));if(fullItem){projected.item=vocabulary.item}else if(itemSelectors.length>0){projected.item=projectRecordFields(vocabulary.item,itemSelectors)}const omittedFieldGroups=[...fullItem?[]:itemSelectors.length>0?vocabulary.itemFields.filter(field=>!itemSelectors.includes(field)).map(field=>({name:`item.${field}`,restore_with:`--output-include item.${field}`})):[{name:"item",restore_with:"--output-include item"}],...vocabulary.sections.filter(section=>!selectedSections.has(section)).map(section=>({name:section,restore_with:`--output-include ${section}`}))];const inheritedOmittedFieldGroups=isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[];const combinedOmittedFieldGroups=[...inheritedOmittedFieldGroups,...omittedFieldGroups];projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups};return projected}function countPopulatedRows(result){let populated=0;mapReadOutputRows({...result},entry=>{if(isRecord(entry)&&Object.keys(entry).length>0)populated+=1;return entry});return populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0){return}const modes=[...readOutputIncludeModeOptions(command).keys()];const domain=modes.length>0?` Declared ${command} projection modes: ${modes.join(", ")}.`:` The ${command} surface declares no projection modes; name row fields instead.`;throw new PmCliError(`Unknown --output-include selector(s) for ${command}: ${selectors.join(", ")}. No selector matched any returned row field.${domain}`,EXIT_CODE.USAGE)}function applyIncludeProjection(command,result,selectors){if(command==="get"){return applyGetIncludeProjection(result,selectors)}const rows=readOutputRowPaths(result);const qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[]));const selectedRoot=selectors.some(selector=>Object.hasOwn(result,selector.split(".")[0])&&!rows.some(rowPath=>selector.startsWith(`${rowPath}.`)));if(rows.length>0&&(!selectedRoot||qualifiedRowSelectors.length>0)){const projected={...result};const rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors;const shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);rejectEmptyIncludeProjection(command,result,shaped,rowSelectors);return shaped}return Object.fromEntries(Object.entries(result).filter(([key])=>selectors.some(selector=>selector.split(".")[0]===key)||ENVELOPE_KEYS.has(key)))}function applyAmountBound(result,amount){if(amount==="unbounded")return result;const{result:bounded,truncated}=boundReadOutputRows(result,amount);if(!truncated)return bounded;bounded.has_more=true;bounded.truncated=true;if(typeof bounded.count==="number"){bounded.count=countReadOutputRows(bounded)}bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount};return bounded}function requestedDimensions(resolved){return PM_READ_OUTPUT_DIMENSIONS.filter(dimension=>resolved[dimension]!==void 0&&resolved[dimension]?.source!=="default"||resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]))}function attachReadOutputSessionContracts(result,state,receipt){let withSession=attachReadOutputSessionReceipt(result,state);for(let iteration=0;iteration<8;iteration+=1){const previousReadEstimate=receipt.estimated_tokens;const previousSessionEstimate=withSession.read_session.spent_this_call_tokens;updateReadOutputReceiptEstimate(withSession,receipt);withSession=attachReadOutputSessionReceipt(withSession,state);const sessionEstimate=withSession.read_session.spent_this_call_tokens;if(receipt.estimated_tokens===previousReadEstimate&&sessionEstimate===previousSessionEstimate){return withSession}}return withSession}function stabilizeReadOutputReceiptEstimates(result,options){if(!isRecord(result.read_output))return result;const receipt=result.read_output;const session=parseReadOutputSession(options.outputSession??options.output_session);if(session===void 0){updateReadOutputReceiptEstimate(result,receipt);return result}return attachReadOutputSessionContracts(result,session,receipt)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;const declaredFieldGroups=Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[];if(!declaredFieldGroups.some(group=>isRecord(group)&&group.name==="diagnostic_rows")){return result}const diagnosticCollectionPaths=[...new Set(readOutputBudgetCollections(result).map(({path})=>path).filter(path=>/^checks\.\d+\.details\./u.test(path)))];const diagnosticRowKeys=diagnosticCollectionPaths.filter(path=>!diagnosticCollectionPaths.some(candidate=>candidate!==path&&path.startsWith(`${candidate}.`)));if(diagnosticRowKeys.length===0)return result;const existingContract=isRecord(result.row_contract)?result.row_contract:{};const existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry==="string"):[];const existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry==="string"):[];const rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys;const continuationRowKeys=[...new Set(diagnosticRowKeys)];return JSON.stringify(rowKeys)===JSON.stringify(existingRowKeys)&&JSON.stringify(continuationRowKeys)===JSON.stringify(existingContinuationRowKeys)?result:{...result,row_contract:{...existingContract,row_keys:rowKeys,continuation_row_keys:continuationRowKeys,jq_selector:typeof existingContract.jq_selector==="string"?existingContract.jq_selector:".checks[].details"}}}function projectReadOutputRows(result,resolved,session,cursor){let projected={...result};if(resolved.include?.source==="canonical"){projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)}if(resolved.command==="assurance"){projected=prioritizeAssuranceAssertions(projected)}projected=applyReadOutputContinuation(projected,resolved.command,cursor);if(resolved.amount?.source==="canonical"){projected=applyAmountBound(projected,resolved.amount.value)}return session===void 0?projected:applyReadOutputSessionReferences(projected,session)}function resolveBindingReadOutputBudget(resolved,session){const budgets=[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]];return budgets.sort((left,right)=>left.tokens-right.tokens)[0]}function canonicalReadOutputReceiptFields(resolved){const canonicalOptions=resolved.canonical_options_used;return canonicalOptions&&canonicalOptions.length>0?{canonical_options_used:canonicalOptions}:{}}function omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...bindingBudget.source==="default"?{budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens}:{},precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:false,strings_compacted:false,rows_compacted:false,result_omitted:true,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}};const omitted={output_budget_exceeded:{omitted_result:true,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt};const boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt);if(session===void 0){updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt)}if(session!==void 0&&minimalReceipt.estimated_tokens>bindingBudget.tokens){throw new PmCliError("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",EXIT_CODE.USAGE)}return boundedOmission}function canReturnReadOutputUnchanged(resolved,session,result){if(session!==void 0)return false;const canonicalRequestedCount=resolved.canonical_options_used.length;if(resolved.cost?.value==="unbounded"){return canonicalRequestedCount===(resolved.cost.source==="canonical"?1:0)}if(resolved.cost?.source==="legacy"&&canonicalRequestedCount===0){return true}return canonicalRequestedCount===0&&(resolved.cost===void 0||estimateReadOutputTokens(result)<=resolved.cost.value)}function attachReadOutputTruncationDisclosure(projected,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,collectionsBeforeBudget){if(!receipt.rows_compacted)return;const overridden=resolved.amount?.value==="unbounded"?["amount"]:[];const afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length]));const continuations=[...collectionsBeforeBudget.entries()].flatMap(([path,before])=>{const retainedRows=afterByPath.get(path);if(retainedRows>=before.rows)return[];const offset=before.baseOffset+retainedRows;return[{path,cursor:encodeReadOutputContinuationCursor({command:resolved.command,path,offset,total_rows:before.totalRows,fingerprint:before.fingerprint}),retained_rows:retainedRows,remaining_rows:before.totalRows-offset,total_rows:before.totalRows}]});const primary=continuations[0];const recoveryBudget=resolveReadOutputRecoveryBudget({effective_budget_tokens:bindingBudget.tokens,measured_result_tokens:measuredResultTokens});if(primary&&typeof projected.next_cursor!=="string"){projected.next_cursor=primary.cursor}projected.continuation_kind=continuationCursorRebased?"producer_cursor":primary?"output_cursor":"none";projected.output_budget_truncation={reason:"output_budget_reached",budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens,overridden_dimensions:overridden,compacted_row_paths:receipt.compacted_row_paths,continuation_cursor_rebased:continuationCursorRebased,continuation_available:continuations.length>0,recovery_budget_multiplier:primary?1:recoveryBudget.recovery_budget_multiplier,continuations,restore_with:primary?"Use recovery binding.":`Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,recovery:primary?{cursor:primary.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${recoveryBudget.output_budget}`,sdk:{outputBudget:recoveryBudget.output_budget},mcp:{outputBudget:recoveryBudget.output_budget}}}}function rebaseBudgetCompactedCursor(projected,originalItemCount,cursorSource,cursorContinuesExistingPage){if(typeof cursorSource!=="string"||!Array.isArray(projected.items)){return false}const retainedCount=projected.items.length;if(retainedCount===0||retainedCount>=originalItemCount){return false}let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return false}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return false;const last=projected.items.at(-1);if(Object.prototype.toString.call(last)!=="[object Object]"){return false}const lastId=Reflect.get(last,"id");if(typeof lastId!=="string"||lastId.length===0)return false;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+retainedCount;if(afterIndex<0)return false;projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot);if(typeof projected.applied_limit==="number"){projected.applied_limit=retainedCount}return true}function captureReadOutputContinuationState(projected,command,cursor,options){const collectionsBeforeBudget=new Map(readOutputContinuationRowCollections(projected).map(collection=>{const rows=Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length;const continued=cursor?.path===collection.path;return[collection.path,{rows,totalRows:continued?cursor.total_rows:rows,baseOffset:continued?cursor.offset:0,fingerprint:continued?cursor.fingerprint:readOutputCollectionFingerprint(collection.path,collection.value,command)}]}));const cursorContinuesExistingPage=typeof projected.next_cursor==="string";return{collectionsBeforeBudget,originalItemCount:Array.isArray(projected.items)?projected.items.length:0,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after}}function compactReadOutputProjection(projected,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens){const assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0;let compacted=compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,assuranceMinimumRows>0?new Map([["assertions",assuranceMinimumRows]]):new Map);const continuationCursorRebased=rebaseBudgetCompactedCursor(compacted,continuationState.originalItemCount,continuationState.cursorSource,continuationState.cursorContinuesExistingPage);attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget);if(session!==void 0){compacted=attachReadOutputSessionContracts(compacted,session,receipt)}return compacted}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const session=parseReadOutputSession(options.outputSession??options.output_session);const rawCursor=options.outputCursor??options.output_cursor;const cursor=typeof rawCursor==="string"?decodeReadOutputContinuationCursor(rawCursor):void 0;const requested=requestedDimensions(resolved);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,result)){return result}const continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);const bindingBudget=resolveBindingReadOutputBudget(resolved,session);let projected=projectReadOutputRows(continuationReadyResult,resolved,session,cursor);const continuationState=captureReadOutputContinuationState(projected,resolved.command,cursor,options);const receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...bindingBudget?.source==="default"?{budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens}:{},precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:true,strings_compacted:false,rows_compacted:false,result_omitted:false};projected.read_output=receipt;projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt);updateReadOutputReceiptEstimate(projected,receipt);if(bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const measuredResultTokens=receipt.estimated_tokens;projected=compactReadOutputProjection(projected,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens)}if(bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){return omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens)}return projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===true&&result.output_budget_exceeded.reason==="requested_budget_infeasible"}function resolveReadOutputEncoding(command,options){const encoding=resolveReadOutputDimensions(command,options)?.encoding;return encoding?.value==="json"||encoding?.value==="toon"?encoding.value:void 0}export{PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACES,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,applyReadOutputIncludeModes,decodeReadOutputContinuationCursor2 as decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor2 as encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,readOutputCollectionFingerprint2 as readOutputCollectionFingerprint,readOutputIncludeModeOptions,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputRecoveryBudget2 as resolveReadOutputRecoveryBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates,validateReadOutputOptions};
1225
2
  //# sourceMappingURL=read-output-contracts.js.map
1226
- //# debugId=2103a4dc-3037-5768-b2c7-5964de4ac86b