@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,1183 +1,5 @@
1
- /**
2
- * @module sdk/assurance
3
- *
4
- * Declares, persists, evaluates, and audits project assurance contracts. The
5
- * module deliberately owns semantics while hosts inject workspace data and
6
- * external measurement adapters, keeping CLI, MCP, CI, and embedded callers on
7
- * one deterministic SDK path.
8
- */
9
-
10
- !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]="d4c380ce-031e-5b2d-aaa8-658bb4aa3087")}catch(e){}}();
11
- import { createHash } from "node:crypto";
12
- import path from "node:path";
13
- import { EXIT_CODE } from "../../core/shared/constants.js";
14
- import { PmCliError } from "../../core/shared/errors.js";
15
- import { appendWorkspaceAuditEvent, mutateWorkspaceJsonWithHistory, readFileIfExists, readHistoryEntries, readSettings, resolveAuthor, stableStringify, WORKSPACE_HISTORY_ID, getWorkspaceHistoryPath, } from "../runtime-primitives.js";
16
- import { resolveCanonicalRelationshipKind } from "../relationships.js";
17
- import { MAX_ASSURANCE_VERDICT_LIMIT } from "./assurance-limits.js";
18
- import { AssuranceEvaluationRefusalError, AssuranceMutationRefusalError, AssuranceSourceResolutionError, } from "./assurance-mutation-error.js";
19
- /** Current serialized assurance registry format. */
20
- export const ASSURANCE_DOCUMENT_VERSION = 1;
21
- /** Supported lifecycle points that can evaluate a gate. */
22
- export const ASSURANCE_GATE_TRIGGERS = [
23
- "pre-commit",
24
- "pre-push",
25
- "pre-merge",
26
- "ci",
27
- "pre-release",
28
- "post-release",
29
- "scheduled",
30
- "on-claim",
31
- "on-close",
32
- ];
33
- /** Supported discriminants for built-in, delegated, and derived measurements. */
34
- export const ASSURANCE_MEASUREMENT_SOURCE_KINDS = [
35
- "items",
36
- "dependency_kind",
37
- "prose_edge_gap",
38
- "graph",
39
- "validate",
40
- "health",
41
- "history",
42
- "links",
43
- "provider",
44
- "derived",
45
- ];
46
- const POLARITY_KEYS = [
47
- "ceiling",
48
- "floor",
49
- "equals",
50
- "zero",
51
- "monotone_nondecreasing",
52
- "monotone_nonincreasing",
53
- "subset_of",
54
- ];
55
- const ID_PATTERN = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;
56
- const LOCK_TTL_SECONDS = 30;
57
- const LOCK_WAIT_MS = 5_000;
58
- const EVALUATION_CONCURRENCY = 4;
59
- const DEFAULT_VERDICT_LIMIT = 50;
60
- function requireStableId(value, field) {
61
- if (!ID_PATTERN.test(value)) {
62
- throw new AssuranceMutationRefusalError(`${field} must be a stable lowercase id`);
63
- }
64
- }
65
- function requireFiniteNonNegative(value, field) {
66
- if (!Number.isFinite(value) || value < 0) {
67
- throw new AssuranceMutationRefusalError(`${field} must be a finite non-negative number`);
68
- }
69
- }
70
- function boundFor(assertion) {
71
- const present = POLARITY_KEYS.filter((key) => assertion[key] !== undefined);
72
- if (present.length !== 1) {
73
- throw new AssuranceMutationRefusalError(`assertion ${assertion.id} must declare exactly one polarity`);
74
- }
75
- const polarity = present[0];
76
- const raw = assertion[polarity];
77
- return {
78
- polarity,
79
- value: polarity === "zero" ? 0 : raw,
80
- };
81
- }
82
- function valuesEqual(left, right) {
83
- return stableStringify(left) === stableStringify(right);
84
- }
85
- function compareBound(observed, bound) {
86
- if (bound.polarity === "equals")
87
- return valuesEqual(observed, bound.value);
88
- if (bound.polarity === "subset_of") {
89
- if (!Array.isArray(observed) || !Array.isArray(bound.value))
90
- return false;
91
- const allowed = bound.value;
92
- return observed.every((entry) => allowed.includes(entry));
93
- }
94
- if (typeof observed !== "number") {
95
- return false;
96
- }
97
- const numericBound = bound.value;
98
- if (bound.polarity === "ceiling" ||
99
- bound.polarity === "monotone_nonincreasing") {
100
- return observed <= numericBound;
101
- }
102
- if (bound.polarity === "floor" ||
103
- bound.polarity === "monotone_nondecreasing") {
104
- return observed >= numericBound;
105
- }
106
- return observed === 0;
107
- }
108
- function proveNegativeControl(assertion) {
109
- const bound = boundFor(assertion);
110
- const cases = assertion.negative_control.cases;
111
- return (cases.some((entry) => entry.expected === "pass") &&
112
- cases.some((entry) => entry.expected === "fail") &&
113
- cases.every((entry) => compareBound(entry.observed, bound) === (entry.expected === "pass")));
114
- }
115
- function boundUpdateIsLoosening(beforeBound, afterBound) {
116
- if (beforeBound.polarity !== afterBound.polarity)
117
- return true;
118
- if (typeof beforeBound.value === "number" &&
119
- typeof afterBound.value === "number") {
120
- return beforeBound.polarity === "ceiling" ||
121
- beforeBound.polarity === "monotone_nonincreasing"
122
- ? afterBound.value > beforeBound.value
123
- : beforeBound.polarity === "floor" ||
124
- beforeBound.polarity === "monotone_nondecreasing"
125
- ? afterBound.value < beforeBound.value
126
- : afterBound.value !== beforeBound.value;
127
- }
128
- if (beforeBound.polarity === "subset_of") {
129
- const beforeValues = beforeBound.value;
130
- const afterValues = afterBound.value;
131
- return (!Array.isArray(beforeValues) ||
132
- !Array.isArray(afterValues) ||
133
- afterValues.some((entry) => !beforeValues.includes(entry)));
134
- }
135
- return !valuesEqual(beforeBound.value, afterBound.value);
136
- }
137
- /** Return true when an assertion update weakens scope, bound, lifetime, or enforcement. */
138
- export function assuranceAssertionUpdateIsLoosening(before, after) {
139
- if (before.measurement_id !== after.measurement_id ||
140
- before.owner_item_id !== after.owner_item_id ||
141
- stableStringify(before.scope) !== stableStringify(after.scope)) {
142
- return true;
143
- }
144
- const enforcementRank = {
145
- observe: 0,
146
- warn: 1,
147
- block: 2,
148
- };
149
- const lifetimeLoosened = (before.lifetime ?? "hold") === "hold" &&
150
- (after.lifetime ?? "hold") === "retire";
151
- return (boundUpdateIsLoosening(boundFor(before), boundFor(after)) ||
152
- enforcementRank[after.enforcement] < enforcementRank[before.enforcement] ||
153
- lifetimeLoosened);
154
- }
155
- /** Validate the field predicate contract of an item-backed measurement source. */
156
- function validateItemsMeasurementSource(source) {
157
- if (source.state !== undefined &&
158
- !(source.state === "present" || source.state === "missing")) {
159
- throw new AssuranceMutationRefusalError("items source state must be present or missing");
160
- }
161
- const hasEquals = Object.hasOwn(source, "equals");
162
- const hasState = source.state !== undefined;
163
- const predicateCount = Number(hasEquals) + Number(hasState);
164
- if (source.field !== undefined && predicateCount !== 1) {
165
- throw new AssuranceMutationRefusalError("items source with field requires exactly one of equals or state");
166
- }
167
- if (source.field === undefined && predicateCount !== 0) {
168
- throw new AssuranceMutationRefusalError("items source equals/state requires field");
169
- }
170
- }
171
- /** Validate relationship-provenance predicates on a dependency-kind measurement. */
172
- function validateDependencyKindMeasurementSource(source) {
173
- if (typeof source.dependency_kind !== "string" ||
174
- source.dependency_kind.trim().length === 0) {
175
- throw new AssuranceMutationRefusalError("dependency_kind source requires dependency_kind");
176
- }
177
- const provenancePredicateCount = [
178
- source.source_kind,
179
- source.source_kind_prefix,
180
- source.source_kind_state,
181
- ].filter((value) => value !== undefined).length;
182
- if (provenancePredicateCount > 1) {
183
- throw new AssuranceMutationRefusalError("dependency_kind source accepts at most one source_kind predicate");
184
- }
185
- if ((source.source_kind !== undefined &&
186
- source.source_kind.trim().length === 0) ||
187
- (source.source_kind_prefix !== undefined &&
188
- source.source_kind_prefix.trim().length === 0)) {
189
- throw new AssuranceMutationRefusalError("dependency_kind source provenance values must not be empty");
190
- }
191
- if (source.source_kind_state !== undefined &&
192
- source.source_kind_state !== "present" &&
193
- source.source_kind_state !== "missing") {
194
- throw new AssuranceMutationRefusalError("dependency_kind source source_kind_state must be present or missing");
195
- }
196
- }
197
- /** Validate bounded, reasoned prose-parity exemptions. */
198
- function validateProseEdgeGapSource(source) {
199
- if (source.sample_limit !== undefined &&
200
- (!Number.isInteger(source.sample_limit) || source.sample_limit < 1)) {
201
- throw new AssuranceMutationRefusalError("prose_edge_gap sample_limit must be a positive integer");
202
- }
203
- for (const exemption of source.exemptions ?? []) {
204
- if (typeof exemption.holder_id !== "string" ||
205
- exemption.holder_id.trim().length === 0 ||
206
- typeof exemption.reason !== "string" ||
207
- exemption.reason.trim().length === 0) {
208
- throw new AssuranceMutationRefusalError("prose_edge_gap exemptions require holder_id and reason");
209
- }
210
- if ((exemption.target_id !== undefined &&
211
- exemption.target_id.trim().length === 0) ||
212
- (exemption.text_contains !== undefined &&
213
- exemption.text_contains.trim().length === 0)) {
214
- throw new AssuranceMutationRefusalError("prose_edge_gap exemption selectors must not be empty");
215
- }
216
- }
217
- }
218
- /** Validate and return one measurement declaration. */
219
- export function validateMeasurementDefinition(definition) {
220
- requireStableId(definition.id, "measurement.id");
221
- if (definition.max_cost !== undefined) {
222
- requireFiniteNonNegative(definition.max_cost, "measurement.max_cost");
223
- }
224
- const candidateSource = definition.source;
225
- if (Object.prototype.toString.call(candidateSource) !== "[object Object]") {
226
- throw new AssuranceMutationRefusalError(`measurement.source.kind must be one of ${ASSURANCE_MEASUREMENT_SOURCE_KINDS.join(", ")}`);
227
- }
228
- const sourceKind = Reflect.get(candidateSource, "kind");
229
- if (!ASSURANCE_MEASUREMENT_SOURCE_KINDS.includes(sourceKind)) {
230
- throw new AssuranceMutationRefusalError(`measurement.source.kind must be one of ${ASSURANCE_MEASUREMENT_SOURCE_KINDS.join(", ")}`);
231
- }
232
- const source = candidateSource;
233
- if (source.kind === "items") {
234
- validateItemsMeasurementSource(source);
235
- }
236
- if (source.kind === "dependency_kind")
237
- validateDependencyKindMeasurementSource(source);
238
- if (source.kind === "prose_edge_gap")
239
- validateProseEdgeGapSource(source);
240
- if ((source.kind === "graph" ||
241
- source.kind === "validate" ||
242
- source.kind === "health") &&
243
- (typeof source.field !== "string" || source.field.trim().length === 0)) {
244
- throw new AssuranceMutationRefusalError(`${source.kind} source requires field`);
245
- }
246
- if (source.kind === "provider") {
247
- requireStableId(source.provider, "provider source provider");
248
- requireStableId(source.key, "provider source key");
249
- }
250
- return definition;
251
- }
252
- /** Validate and return one assertion declaration. */
253
- export function validateAssertionDefinition(definition) {
254
- requireStableId(definition.id, "assertion.id");
255
- requireStableId(definition.measurement_id, "assertion.measurement_id");
256
- if (typeof definition.owner_item_id !== "string" ||
257
- definition.owner_item_id.trim().length === 0) {
258
- throw new AssuranceMutationRefusalError("assertion.owner_item_id is required");
259
- }
260
- const bound = boundFor(definition);
261
- if (typeof bound.value === "number" && !Number.isFinite(bound.value)) {
262
- throw new AssuranceMutationRefusalError(`assertion.${bound.polarity} must be a finite number`);
263
- }
264
- if (definition.lifetime === "retire" &&
265
- (typeof definition.retire_reason !== "string" ||
266
- definition.retire_reason.trim().length === 0)) {
267
- throw new AssuranceMutationRefusalError("retired assertion requires retire_reason");
268
- }
269
- if (definition.scope.kind === "filter") {
270
- requireStableId(definition.scope.measurement_id, "assertion.scope.measurement_id");
271
- }
272
- const cases = definition.negative_control?.cases;
273
- if (!Array.isArray(cases) ||
274
- !cases.some((entry) => entry.expected === "pass") ||
275
- !cases.some((entry) => entry.expected === "fail")) {
276
- throw new AssuranceMutationRefusalError("assertion negative control requires pass and fail cases");
277
- }
278
- if (!proveNegativeControl(definition)) {
279
- throw new AssuranceMutationRefusalError(`assertion ${definition.id} negative control does not prove its bound`);
280
- }
281
- return definition;
282
- }
283
- function validateGateProviderPolicy(policy) {
284
- if (!Array.isArray(policy.allowed_providers)) {
285
- throw new AssuranceMutationRefusalError("gate provider_policy.allowed_providers must be an array");
286
- }
287
- for (const provider of policy.allowed_providers) {
288
- requireStableId(provider, "gate.provider_policy.allowed_provider");
289
- }
290
- if (typeof policy.triggers !== "object" ||
291
- policy.triggers === null ||
292
- Array.isArray(policy.triggers)) {
293
- throw new AssuranceMutationRefusalError("gate provider_policy.triggers must be an object");
294
- }
295
- for (const [trigger, rule] of Object.entries(policy.triggers)) {
296
- if (!ASSURANCE_GATE_TRIGGERS.includes(trigger)) {
297
- throw new AssuranceMutationRefusalError(`gate provider policy has unknown trigger ${trigger}`);
298
- }
299
- if (typeof rule !== "object" ||
300
- rule === null ||
301
- !["low", "medium", "high"].includes(rule.max_cost_class) ||
302
- typeof rule.allow_network !== "boolean") {
303
- throw new AssuranceMutationRefusalError(`gate provider policy trigger ${trigger} is invalid`);
304
- }
305
- }
306
- }
307
- /** Validate and return one gate declaration. */
308
- export function validateGateDefinition(definition) {
309
- requireStableId(definition.id, "gate.id");
310
- if (!Array.isArray(definition.assertion_ids)) {
311
- throw new AssuranceMutationRefusalError("gate.assertion_ids is required and must be an array");
312
- }
313
- if (definition.assertion_ids.length === 0) {
314
- throw new AssuranceMutationRefusalError("gate requires at least one assertion");
315
- }
316
- for (const id of definition.assertion_ids)
317
- requireStableId(id, "gate.assertion_id");
318
- if (!Array.isArray(definition.triggers)) {
319
- throw new AssuranceMutationRefusalError(`gate.triggers is required and must be an array of ${ASSURANCE_GATE_TRIGGERS.join(", ")}`);
320
- }
321
- if (definition.triggers.length === 0) {
322
- throw new AssuranceMutationRefusalError("gate requires at least one trigger");
323
- }
324
- for (const trigger of definition.triggers) {
325
- if (!ASSURANCE_GATE_TRIGGERS.includes(trigger)) {
326
- throw new AssuranceMutationRefusalError(`gate trigger must be one of ${ASSURANCE_GATE_TRIGGERS.join(", ")}`);
327
- }
328
- }
329
- if (definition.provider_policy) {
330
- validateGateProviderPolicy(definition.provider_policy);
331
- }
332
- return definition;
333
- }
334
- /** Validate registry references, uniqueness, and declaration-local contracts. */
335
- export function validateAssuranceDocument(document) {
336
- if (document.version !== ASSURANCE_DOCUMENT_VERSION) {
337
- throw new AssuranceMutationRefusalError(`unsupported assurance document version ${String(document.version)}`);
338
- }
339
- const ids = new Set();
340
- for (const definition of document.measurements) {
341
- validateMeasurementDefinition(definition);
342
- if (ids.has(`measurement:${definition.id}`)) {
343
- throw new AssuranceMutationRefusalError(`duplicate measurement ${definition.id}`);
344
- }
345
- ids.add(`measurement:${definition.id}`);
346
- }
347
- for (const definition of document.assertions) {
348
- validateAssertionDefinition(definition);
349
- if (ids.has(`assertion:${definition.id}`)) {
350
- throw new AssuranceMutationRefusalError(`duplicate assertion ${definition.id}`);
351
- }
352
- ids.add(`assertion:${definition.id}`);
353
- }
354
- for (const definition of document.gates) {
355
- validateGateDefinition(definition);
356
- const missing = definition.assertion_ids.filter((id) => !document.assertions.some((assertionDefinition) => assertionDefinition.id === id));
357
- if (missing.length > 0) {
358
- throw new AssuranceMutationRefusalError(`gate ${definition.id} references missing assertions: ${missing.join(", ")}`);
359
- }
360
- if (ids.has(`gate:${definition.id}`)) {
361
- throw new AssuranceMutationRefusalError(`duplicate gate ${definition.id}`);
362
- }
363
- ids.add(`gate:${definition.id}`);
364
- }
365
- const measurementIds = new Set(document.measurements.map((entry) => entry.id));
366
- for (const [measurementId, consumers] of collectMeasurementReferences(document)) {
367
- if (!measurementIds.has(measurementId)) {
368
- throw new AssuranceMutationRefusalError(`${consumers.join(", ")} references missing measurement ${measurementId}`);
369
- }
370
- }
371
- return document;
372
- }
373
- function collectExpressionMeasurementReferences(expression, references) {
374
- if ("measurement" in expression) {
375
- references.push(expression.measurement);
376
- return;
377
- }
378
- if ("operator" in expression) {
379
- for (const operand of expression.operands) {
380
- collectExpressionMeasurementReferences(operand, references);
381
- }
382
- }
383
- }
384
- function collectMeasurementReferences(document) {
385
- const references = new Map();
386
- const add = (measurementId, consumer) => {
387
- const consumers = references.get(measurementId) ?? [];
388
- consumers.push(consumer);
389
- references.set(measurementId, consumers);
390
- };
391
- for (const assertionDefinition of document.assertions) {
392
- add(assertionDefinition.measurement_id, `assertion ${assertionDefinition.id}`);
393
- if (assertionDefinition.scope.kind === "filter") {
394
- add(assertionDefinition.scope.measurement_id, `assertion ${assertionDefinition.id} scope`);
395
- }
396
- }
397
- for (const measurementDefinition of document.measurements) {
398
- if (measurementDefinition.source.kind !== "derived")
399
- continue;
400
- const derivedReferences = [];
401
- collectExpressionMeasurementReferences(measurementDefinition.source.expression, derivedReferences);
402
- for (const measurementId of derivedReferences) {
403
- add(measurementId, `derived measurement ${measurementDefinition.id}`);
404
- }
405
- }
406
- return references;
407
- }
408
- function collectGateProviderIds(gate, document) {
409
- const pending = gate.assertion_ids.flatMap((assertionId) => {
410
- const assertion = document.assertions.find((entry) => entry.id === assertionId);
411
- return [
412
- assertion.measurement_id,
413
- ...(assertion.scope.kind === "filter"
414
- ? [assertion.scope.measurement_id]
415
- : []),
416
- ];
417
- });
418
- const visited = new Set();
419
- const providers = new Set();
420
- while (pending.length > 0) {
421
- const measurementId = pending.pop();
422
- if (visited.has(measurementId))
423
- continue;
424
- visited.add(measurementId);
425
- const measurement = document.measurements.find((entry) => entry.id === measurementId);
426
- if (measurement.source.kind === "provider") {
427
- providers.add(measurement.source.provider);
428
- }
429
- else if (measurement.source.kind === "derived") {
430
- collectExpressionMeasurementReferences(measurement.source.expression, pending);
431
- }
432
- }
433
- return providers;
434
- }
435
- /** Create an empty, valid assurance registry. */
436
- export function createEmptyAssuranceDocument() {
437
- return {
438
- version: ASSURANCE_DOCUMENT_VERSION,
439
- measurements: [],
440
- assertions: [],
441
- gates: [],
442
- };
443
- }
444
- function itemsSourceResult(source, context) {
445
- const matches = context.items.filter((item) => (source.statuses === undefined ||
446
- source.statuses.includes(item.status)) &&
447
- (source.types === undefined || source.types.includes(item.type)) &&
448
- (source.tags === undefined ||
449
- source.tags.every((tag) => item.tags?.includes(tag))) &&
450
- (source.field === undefined ||
451
- (() => {
452
- const value = item[source.field];
453
- if (source.state !== undefined) {
454
- const missing = value === undefined ||
455
- value === null ||
456
- value === "" ||
457
- (Array.isArray(value) && value.length === 0);
458
- return source.state === "missing" ? missing : !missing;
459
- }
460
- return valuesEqual(value, source.equals);
461
- })()));
462
- return {
463
- value: matches.length,
464
- population_size: context.items.length,
465
- cost: context.items.length,
466
- contributors: matches.map((item) => item.id),
467
- };
468
- }
469
- /** Match one normalized dependency provenance against an optional partition. */
470
- function dependencyProvenanceMatches(source, sourceKind) {
471
- if (source.source_kind !== undefined) {
472
- return (sourceKind?.toLowerCase() === source.source_kind.trim().toLowerCase());
473
- }
474
- if (source.source_kind_prefix !== undefined) {
475
- return (sourceKind
476
- ?.toLowerCase()
477
- .startsWith(source.source_kind_prefix.trim().toLowerCase()) === true);
478
- }
479
- if (source.source_kind_state === "present") {
480
- return sourceKind !== undefined && sourceKind.length > 0;
481
- }
482
- if (source.source_kind_state === "missing") {
483
- return sourceKind === undefined || sourceKind.length === 0;
484
- }
485
- return true;
486
- }
487
- function dependencyKindSourceResult(source, context) {
488
- const contributors = [];
489
- const requestedKind = resolveCanonicalRelationshipKind(source.dependency_kind) ??
490
- source.dependency_kind.trim().toLowerCase();
491
- for (const item of context.items) {
492
- for (const dependency of item.dependencies ?? []) {
493
- const dependencyKind = resolveCanonicalRelationshipKind(dependency.kind) ??
494
- dependency.kind.trim().toLowerCase();
495
- const sourceKind = dependency.source_kind?.trim();
496
- if (dependencyKind === requestedKind &&
497
- dependencyProvenanceMatches(source, sourceKind))
498
- contributors.push(`${item.id}->${dependency.id}${sourceKind ? `@${sourceKind}` : ""}`);
499
- }
500
- }
501
- return {
502
- value: contributors.length,
503
- population_size: context.items.length,
504
- cost: context.items.length,
505
- contributors,
506
- };
507
- }
508
- /** Return every text segment whose item identifiers form the prose graph. */
509
- function assuranceItemProseSegments(item) {
510
- const segments = [item.description, item.body]
511
- .filter((value) => typeof value === "string")
512
- .map((value) => value.trim())
513
- .filter(Boolean);
514
- for (const key of ["comments", "notes", "learnings"]) {
515
- const entries = item[key];
516
- if (!Array.isArray(entries))
517
- continue;
518
- for (const entry of entries) {
519
- if (typeof entry === "string")
520
- segments.push(entry);
521
- else if (typeof entry === "object" && entry !== null) {
522
- const text = Reflect.get(entry, "text");
523
- if (typeof text === "string")
524
- segments.push(text);
525
- }
526
- }
527
- }
528
- return segments;
529
- }
530
- /** Return whether a reviewed exemption applies to one prose reference. */
531
- function proseReferenceIsExempt(exemptions, holderId, targetId, segment) {
532
- return exemptions.some((exemption) => exemption.holder_id.trim().toLowerCase() === holderId.toLowerCase() &&
533
- (exemption.target_id === undefined ||
534
- exemption.target_id.trim().toLowerCase() === targetId.toLowerCase()) &&
535
- (exemption.text_contains === undefined ||
536
- segment
537
- .toLowerCase()
538
- .includes(exemption.text_contains.trim().toLowerCase())));
539
- }
540
- /** Return the direction-independent identity of a prose or structured item pair. */
541
- function prosePairKey(left, right) {
542
- return [left.toLowerCase(), right.toLowerCase()].sort().join("\u0000");
543
- }
544
- /** Collect canonical ids, typed links, and raw prose mentions in one item pass. */
545
- function collectProseEdgeCensusInputs(items) {
546
- const canonicalIds = new Map();
547
- const linkedPairs = new Set();
548
- const proseMentions = [];
549
- const mentionPattern = /\b[a-z][a-z0-9]*-[a-z0-9]+\b/giu;
550
- let mentionCount = 0;
551
- for (const item of items) {
552
- canonicalIds.set(item.id.toLowerCase(), item.id);
553
- for (const dependency of item.dependencies ?? [])
554
- linkedPairs.add(prosePairKey(item.id, dependency.id));
555
- for (const scalar of [item.parent, item.blocked_by])
556
- if (typeof scalar === "string")
557
- linkedPairs.add(prosePairKey(item.id, scalar));
558
- for (const segment of assuranceItemProseSegments(item)) {
559
- const mentionedIds = [...segment.matchAll(mentionPattern)].map((match) => match[0]);
560
- mentionCount += mentionedIds.length;
561
- proseMentions.push({
562
- holder_id: item.id,
563
- segment,
564
- mentioned_ids: mentionedIds,
565
- });
566
- }
567
- }
568
- return {
569
- canonical_ids: canonicalIds,
570
- linked_pairs: linkedPairs,
571
- prose_mentions: proseMentions,
572
- mention_count: mentionCount,
573
- };
574
- }
575
- /** Count distinct prose-named item pairs that have no typed edge in either direction. */
576
- function proseEdgeGapSourceResult(source, context) {
577
- const census = collectProseEdgeCensusInputs(context.items);
578
- const gaps = new Map();
579
- for (const proseMention of census.prose_mentions) {
580
- const mentions = proseMention.mentioned_ids
581
- .map((id) => census.canonical_ids.get(id.toLowerCase()))
582
- .filter((id) => id !== undefined && id !== proseMention.holder_id);
583
- const distinctMentions = [...new Set(mentions)];
584
- for (const targetId of distinctMentions) {
585
- const key = prosePairKey(proseMention.holder_id, targetId);
586
- if (census.linked_pairs.has(key) ||
587
- proseReferenceIsExempt(source.exemptions ?? [], proseMention.holder_id, targetId, proseMention.segment))
588
- continue;
589
- const explicit = distinctMentions.some((candidate) => candidate !== targetId);
590
- if (gaps.get(key)?.explicit === true && !explicit)
591
- continue;
592
- gaps.set(key, {
593
- contributor: `${proseMention.holder_id}->${targetId}|subject=${explicit ? "explicit" : "implicit"}`,
594
- explicit,
595
- });
596
- }
597
- }
598
- const gapRows = [...gaps.values()];
599
- const contributors = gapRows.map((entry) => entry.contributor).sort();
600
- return {
601
- value: contributors.length,
602
- population_size: census.canonical_ids.size,
603
- cost: context.items.length + census.linked_pairs.size + census.mention_count,
604
- contributors: contributors.slice(0, source.sample_limit ?? 25),
605
- partitions: {
606
- explicit_subject: gapRows.filter((entry) => entry.explicit).length,
607
- implicit_subject: gapRows.filter((entry) => !entry.explicit).length,
608
- },
609
- };
610
- }
611
- function historySourceResult(source, context) {
612
- const matches = context.history.filter((entry) => (source.op === undefined || entry.op === source.op) &&
613
- (source.author === undefined || entry.author === source.author) &&
614
- (source.harness === undefined ||
615
- entry.agent_harness === source.harness) &&
616
- (source.model === undefined || entry.agent_model === source.model));
617
- return {
618
- value: matches.length,
619
- population_size: context.history.length,
620
- cost: context.history.length,
621
- };
622
- }
623
- function linksSourceResult(source, context) {
624
- const matches = context.items.filter((item) => {
625
- const links = item[source.link];
626
- const present = Array.isArray(links) && links.length > 0;
627
- return source.state === "present" ? present : !present;
628
- });
629
- return {
630
- value: matches.length,
631
- population_size: context.items.length,
632
- cost: context.items.length,
633
- contributors: matches.map((item) => item.id),
634
- };
635
- }
636
- function sourceResult(definition, context) {
637
- const source = definition.source;
638
- if (source.kind === "items")
639
- return itemsSourceResult(source, context);
640
- if (source.kind === "dependency_kind") {
641
- return dependencyKindSourceResult(source, context);
642
- }
643
- if (source.kind === "prose_edge_gap")
644
- return proseEdgeGapSourceResult(source, context);
645
- if (source.kind === "history")
646
- return historySourceResult(source, context);
647
- if (source.kind === "links")
648
- return linksSourceResult(source, context);
649
- return null;
650
- }
651
- function sumCosts(costs, durationMs) {
652
- return costs.reduce((total, cost) => ({
653
- units: total.units + cost.units,
654
- items_scanned: total.items_scanned + cost.items_scanned,
655
- history_entries: total.history_entries + cost.history_entries,
656
- provider_calls: total.provider_calls + cost.provider_calls,
657
- duration_ms: durationMs,
658
- }), {
659
- units: 0,
660
- items_scanned: 0,
661
- history_entries: 0,
662
- provider_calls: 0,
663
- duration_ms: durationMs,
664
- });
665
- }
666
- function arithmeticValue(operator, values) {
667
- if (values.length === 0)
668
- throw new TypeError(`derived ${operator} requires operands`);
669
- if (operator === "add")
670
- return values.reduce((sum, value) => sum + value, 0);
671
- if (operator === "subtract")
672
- return values.slice(1).reduce((result, value) => result - value, values[0]);
673
- if (operator === "multiply")
674
- return values.reduce((result, value) => result * value, 1);
675
- if (operator === "divide") {
676
- if (values.slice(1).includes(0))
677
- throw new TypeError("derived divide cannot divide by zero");
678
- return values.slice(1).reduce((result, value) => result / value, values[0]);
679
- }
680
- return operator === "min" ? Math.min(...values) : Math.max(...values);
681
- }
682
- async function mapWithConcurrency(values, limit, transform) {
683
- const results = new Array(values.length);
684
- let nextIndex = 0;
685
- const workers = Array.from({ length: Math.min(limit, values.length) }, async () => {
686
- while (nextIndex < values.length) {
687
- const index = nextIndex;
688
- nextIndex += 1;
689
- results[index] = await transform(values[index], index);
690
- }
691
- });
692
- await Promise.all(workers);
693
- return results;
694
- }
695
- async function evaluateExpression(expression, context, definitions, stack, state) {
696
- if ("literal" in expression)
697
- return {
698
- value: expression.literal,
699
- costs: [],
700
- population_size: 0,
701
- contributors: [],
702
- };
703
- if ("measurement" in expression) {
704
- const definition = definitions.find((entry) => entry.id === expression.measurement);
705
- if (!definition)
706
- throw new TypeError(`derived measurement references missing ${expression.measurement}`);
707
- const result = await evaluateMeasurementCached(definition, context, definitions, stack, state);
708
- if (typeof result.value !== "number")
709
- throw new TypeError(`derived measurement ${definition.id} is not numeric`);
710
- const costs = state.charged.has(definition.id) ? [] : [result.cost];
711
- state.charged.add(definition.id);
712
- return {
713
- value: result.value,
714
- costs,
715
- population_size: result.population_size,
716
- contributors: result.contributors,
717
- };
718
- }
719
- const operands = await mapWithConcurrency(expression.operands, EVALUATION_CONCURRENCY, (operand) => evaluateExpression(operand, context, definitions, stack, state));
720
- return {
721
- value: arithmeticValue(expression.operator, operands.map((entry) => entry.value)),
722
- costs: operands.flatMap((entry) => entry.costs),
723
- population_size: Math.max(0, ...operands.map((entry) => entry.population_size)),
724
- contributors: [...new Set(operands.flatMap((entry) => entry.contributors))],
725
- };
726
- }
727
- async function evaluateMeasurementInternal(definition, context, definitions, stack, state) {
728
- validateMeasurementDefinition(definition);
729
- const startedAt = Date.now();
730
- let result;
731
- let nestedCosts = [];
732
- let providerCalls = 0;
733
- if (definition.source.kind === "derived") {
734
- const derived = await evaluateExpression(definition.source.expression, context, definitions, [...stack, definition.id], state);
735
- result = {
736
- value: derived.value,
737
- population_size: derived.population_size,
738
- cost: 0,
739
- contributors: derived.contributors,
740
- };
741
- nestedCosts = derived.costs;
742
- }
743
- else {
744
- const builtin = sourceResult(definition, context);
745
- if (builtin !== null) {
746
- result = builtin;
747
- }
748
- else {
749
- result = await context.external(definition.source);
750
- providerCalls = 1;
751
- }
752
- }
753
- const ownCost = {
754
- units: result.cost,
755
- items_scanned: definition.source.kind === "items" ||
756
- definition.source.kind === "dependency_kind" ||
757
- definition.source.kind === "prose_edge_gap" ||
758
- definition.source.kind === "links"
759
- ? context.items.length
760
- : 0,
761
- history_entries: definition.source.kind === "history" ? context.history.length : 0,
762
- provider_calls: providerCalls,
763
- duration_ms: Date.now() - startedAt,
764
- };
765
- const cost = sumCosts([...nestedCosts, ownCost], Date.now() - startedAt);
766
- if (definition.max_cost !== undefined && cost.units > definition.max_cost) {
767
- throw new AssuranceEvaluationRefusalError(`measurement ${definition.id} exceeded cost ceiling ${definition.max_cost} with ${cost.units}`);
768
- }
769
- return {
770
- id: definition.id,
771
- definition_fingerprint: `sha256:${createHash("sha256")
772
- .update(stableStringify(definition))
773
- .digest("hex")}`,
774
- value: result.value,
775
- population_size: result.population_size,
776
- cost,
777
- contributors: result.contributors ?? [],
778
- ...(result.partitions ? { partitions: result.partitions } : {}),
779
- };
780
- }
781
- function evaluateMeasurementCached(definition, context, definitions, stack, state) {
782
- if (stack.includes(definition.id)) {
783
- throw new TypeError(`derived measurement cycle: ${[...stack, definition.id].join(" -> ")}`);
784
- }
785
- const cached = state.cache.get(definition.id);
786
- if (cached)
787
- return cached;
788
- const evaluation = evaluateMeasurementInternal(definition, context, definitions, stack, state).catch((error) => {
789
- if (error instanceof AssuranceSourceResolutionError &&
790
- error.measurement_id === undefined) {
791
- const sourceContext = {
792
- measurement_id: definition.id,
793
- source_kind: error.source_kind,
794
- field: error.field,
795
- ...(error.check ? { check: error.check } : {}),
796
- };
797
- const sourceError = new AssuranceSourceResolutionError(error.message, sourceContext);
798
- sourceError.cause = error;
799
- throw sourceError;
800
- }
801
- throw error;
802
- });
803
- state.cache.set(definition.id, evaluation);
804
- return evaluation;
805
- }
806
- /** Evaluate one measurement with cycle detection and a complete cost receipt. */
807
- export async function evaluateMeasurement(definition, context, definitions = [definition]) {
808
- return evaluateMeasurementCached(definition, context, definitions, [], {
809
- cache: new Map(),
810
- charged: new Set(),
811
- });
812
- }
813
- function assertionDistance(observed, bound) {
814
- if (typeof observed !== "number" || typeof bound.value !== "number")
815
- return null;
816
- if (bound.polarity === "ceiling" ||
817
- bound.polarity === "monotone_nonincreasing")
818
- return bound.value - observed;
819
- if (bound.polarity === "floor" || bound.polarity === "monotone_nondecreasing")
820
- return observed - bound.value;
821
- return observed - bound.value;
822
- }
823
- /** Evaluate one assertion against a precomputed measurement receipt. */
824
- export function evaluateAssuranceAssertion(definition, measurement, options = {}) {
825
- validateAssertionDefinition(definition);
826
- const bound = boundFor(definition);
827
- const retired = definition.lifetime === "retire" && options.owner_terminal === true;
828
- return {
829
- assertion_id: definition.id,
830
- measurement_id: definition.measurement_id,
831
- measurement_definition_fingerprint: measurement.definition_fingerprint,
832
- scope: definition.scope,
833
- population_size: measurement.population_size,
834
- observed: measurement.value,
835
- bound,
836
- distance: assertionDistance(measurement.value, bound),
837
- verdict: retired
838
- ? "retired"
839
- : compareBound(measurement.value, bound)
840
- ? "pass"
841
- : "fail",
842
- enforcement: definition.enforcement,
843
- negative_control_proven: proveNegativeControl(definition),
844
- cost: measurement.cost,
845
- contributors: measurement.contributors,
846
- ...(measurement.partitions ? { partitions: measurement.partitions } : {}),
847
- };
848
- }
849
- function enforceGateProviderPolicy(gate, document, context, trigger) {
850
- const providerIds = collectGateProviderIds(gate, document);
851
- if (providerIds.size === 0)
852
- return;
853
- const policy = gate.provider_policy;
854
- const triggerPolicy = policy?.triggers[trigger];
855
- if (!policy || !triggerPolicy) {
856
- throw new AssuranceEvaluationRefusalError(`assurance gate ${gate.id} refuses provider execution at trigger ${trigger} without an explicit provider policy`);
857
- }
858
- const allowedProviders = new Set(policy.allowed_providers);
859
- const costRank = {
860
- low: 0,
861
- medium: 1,
862
- high: 2,
863
- };
864
- for (const providerId of providerIds) {
865
- if (!allowedProviders.has(providerId)) {
866
- throw new AssuranceEvaluationRefusalError(`assurance gate ${gate.id} refuses provider ${providerId}`);
867
- }
868
- const capability = context.provider_capabilities?.[providerId];
869
- if (!capability) {
870
- throw new AssuranceEvaluationRefusalError(`assurance provider ${providerId} has no declared capabilities`);
871
- }
872
- if (costRank[capability.cost_class] > costRank[triggerPolicy.max_cost_class]) {
873
- throw new AssuranceEvaluationRefusalError(`assurance gate ${gate.id} refuses ${capability.cost_class}-cost provider ${providerId} at trigger ${trigger}`);
874
- }
875
- if (capability.network && !triggerPolicy.allow_network) {
876
- throw new AssuranceEvaluationRefusalError(`assurance gate ${gate.id} refuses network provider ${providerId} at trigger ${trigger}`);
877
- }
878
- }
879
- }
880
- async function evaluateGateMeasurement(gateId, assertionId, definition, context, definitions) {
881
- try {
882
- return await evaluateMeasurement(definition, context, definitions);
883
- }
884
- catch (error) {
885
- if (error instanceof AssuranceSourceResolutionError) {
886
- const checkLocation = error.check ? ` check ${error.check}` : "";
887
- const measurementId = error.measurement_id ?? definition.id;
888
- const refusal = new AssuranceEvaluationRefusalError(`assurance gate ${gateId} assertion ${assertionId} measurement ${measurementId} source ${error.source_kind}${checkLocation} field ${error.field} could not resolve: ${error.message}`, {
889
- gate_id: gateId,
890
- assertion_id: assertionId,
891
- measurement_id: measurementId,
892
- source_kind: error.source_kind,
893
- field: error.field,
894
- ...(error.check ? { check: error.check } : {}),
895
- });
896
- refusal.cause = error;
897
- throw refusal;
898
- }
899
- throw error;
900
- }
901
- }
902
- /** Evaluate a named gate into one presentation-independent verdict document. */
903
- export async function evaluateAssuranceGate(gateId, document, context, options) {
904
- validateAssuranceDocument(document);
905
- const gateDefinition = document.gates.find((entry) => entry.id === gateId);
906
- if (!gateDefinition)
907
- throw new AssuranceEvaluationRefusalError(`assurance gate ${gateId} not found`);
908
- if (!gateDefinition.triggers.includes(options.trigger)) {
909
- throw new AssuranceEvaluationRefusalError(`assurance gate ${gateId} does not declare trigger ${options.trigger}`);
910
- }
911
- enforceGateProviderPolicy(gateDefinition, document, context, options.trigger);
912
- const assertions = await mapWithConcurrency(gateDefinition.assertion_ids, EVALUATION_CONCURRENCY, async (id) => {
913
- const assertionDefinition = document.assertions.find((entry) => entry.id === id);
914
- const measurementDefinition = document.measurements.find((entry) => entry.id === assertionDefinition.measurement_id);
915
- let scopedContext = context;
916
- if (assertionDefinition.scope.kind === "active") {
917
- const terminalStatuses = new Set(context.terminal_statuses ?? ["closed", "canceled"]);
918
- scopedContext = {
919
- ...context,
920
- items: context.items.filter((item) => !terminalStatuses.has(item.status)),
921
- };
922
- }
923
- else if (assertionDefinition.scope.kind === "filter") {
924
- const scopeMeasurementId = assertionDefinition.scope.measurement_id;
925
- const scopeDefinition = document.measurements.find((entry) => entry.id === scopeMeasurementId);
926
- const scope = await evaluateGateMeasurement(gateDefinition.id, assertionDefinition.id, scopeDefinition, context, document.measurements);
927
- const contributorIds = new Set(scope.contributors);
928
- scopedContext = {
929
- ...context,
930
- items: context.items.filter((item) => contributorIds.has(item.id)),
931
- };
932
- }
933
- const owner = context.items.find((item) => item.id === assertionDefinition.owner_item_id);
934
- const ownerTerminal = owner !== undefined &&
935
- new Set(context.terminal_statuses ?? ["closed", "canceled"]).has(owner.status);
936
- return evaluateAssuranceAssertion(assertionDefinition, await evaluateGateMeasurement(gateDefinition.id, assertionDefinition.id, measurementDefinition, scopedContext, document.measurements), { owner_terminal: ownerTerminal });
937
- });
938
- const blocking = assertions.some((entry) => entry.verdict === "fail" && entry.enforcement === "block");
939
- const warning = assertions.some((entry) => entry.verdict === "fail" && entry.enforcement === "warn");
940
- return {
941
- gate_id: gateDefinition.id,
942
- tree_id: context.tree_id,
943
- trigger: options.trigger,
944
- dry_run: options.dry_run === true,
945
- evaluated_at: new Date().toISOString(),
946
- verdict: blocking ? "block" : warning ? "warn" : "pass",
947
- exit_code: blocking ? 1 : 0,
948
- assertions,
949
- assertions_total: assertions.length,
950
- row_contract: {
951
- row_keys: ["assertions"],
952
- jq_selector: ".assertions[]",
953
- },
954
- cost: sumCosts(assertions.map((entry) => entry.cost), Math.max(0, ...assertions.map((entry) => entry.cost.duration_ms))),
955
- };
956
- }
957
- function assurancePath(pmRoot) {
958
- return path.join(pmRoot, "assurance.json");
959
- }
960
- async function readDocument(pmRoot) {
961
- const raw = await readFileIfExists(assurancePath(pmRoot));
962
- if (raw === null)
963
- return createEmptyAssuranceDocument();
964
- return parseAssuranceDocument(raw);
965
- }
966
- function parseAssuranceDocument(raw) {
967
- try {
968
- return validateAssuranceDocument(JSON.parse(raw));
969
- }
970
- catch (error) {
971
- throw new PmCliError("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.", EXIT_CODE.GENERIC_FAILURE, {
972
- code: "assurance_registry_invalid",
973
- reason: String(error),
974
- nextSteps: [
975
- "Restore a valid assurance.json from version control or repair its declaration references.",
976
- "Run pm assurance list measurement after the repair.",
977
- ],
978
- });
979
- }
980
- }
981
- function collectionFor(document, kind) {
982
- if (kind === "measurement")
983
- return document.measurements;
984
- if (kind === "assertion")
985
- return document.assertions;
986
- return document.gates;
987
- }
988
- function validateForKind(kind, definition) {
989
- if (kind === "measurement")
990
- validateMeasurementDefinition(definition);
991
- else if (kind === "assertion")
992
- validateAssertionDefinition(definition);
993
- else
994
- validateGateDefinition(definition);
995
- }
996
- /** Read all declarations of one kind with a stable row selector receipt. */
997
- export async function listAssuranceDeclarations(pmRoot, kind) {
998
- const items = structuredClone(collectionFor(await readDocument(pmRoot), kind));
999
- return {
1000
- items,
1001
- count: items.length,
1002
- row_contract: { row_keys: ["items"], jq_selector: ".items[]" },
1003
- };
1004
- }
1005
- /** Read one named declaration or fail loudly. */
1006
- export async function getAssuranceDeclaration(pmRoot, kind, id) {
1007
- const found = collectionFor(await readDocument(pmRoot), kind).find((entry) => entry.id === id);
1008
- if (!found)
1009
- throw new TypeError(`assurance ${kind} ${id} not found`);
1010
- return structuredClone(found);
1011
- }
1012
- /** Create or update one declaration through audited singleton persistence. */
1013
- export async function putAssuranceDeclaration(pmRoot, kind, definition, options = {}) {
1014
- validateForKind(kind, definition);
1015
- const settings = await readSettings(pmRoot);
1016
- const author = resolveAuthor(options.author, settings.author_default);
1017
- const mutation = await mutateWorkspaceJsonWithHistory({
1018
- pmRoot,
1019
- filePath: assurancePath(pmRoot),
1020
- op: `assurance:${kind}:put`,
1021
- author,
1022
- message: options.message,
1023
- lockTtlSeconds: LOCK_TTL_SECONDS,
1024
- lockWaitMs: LOCK_WAIT_MS,
1025
- mutate: (beforeRaw) => {
1026
- const document = beforeRaw === null
1027
- ? createEmptyAssuranceDocument()
1028
- : parseAssuranceDocument(beforeRaw);
1029
- const collection = collectionFor(document, kind);
1030
- const index = collection.findIndex((entry) => entry.id === definition.id);
1031
- const action = index < 0 ? "created" : "updated";
1032
- if (kind === "assertion" &&
1033
- index >= 0 &&
1034
- assuranceAssertionUpdateIsLoosening(collection[index], definition)) {
1035
- const decision = definition
1036
- .authorization_decision;
1037
- if (!decision ||
1038
- !options.authorized_decision_ids?.includes(decision)) {
1039
- throw new AssuranceMutationRefusalError(`loosening assertion ${definition.id} requires a verified authorization_decision`);
1040
- }
1041
- }
1042
- if (index < 0)
1043
- collection.push(structuredClone(definition));
1044
- else
1045
- collection[index] = structuredClone(definition);
1046
- validateAssuranceDocument(document);
1047
- return {
1048
- raw: `${JSON.stringify(document, null, 2)}\n`,
1049
- result: { changed: true, action, kind, id: definition.id },
1050
- };
1051
- },
1052
- });
1053
- return { ...mutation.result, changed: mutation.changed };
1054
- }
1055
- /** Apply a declaration bundle atomically, idempotently, and without replacing divergent ids. */
1056
- export async function putAssuranceDeclarationBundle(pmRoot, bundle, options = {}) {
1057
- const candidate = createEmptyAssuranceDocument();
1058
- candidate.measurements = structuredClone(bundle.measurements);
1059
- candidate.assertions = structuredClone(bundle.assertions);
1060
- candidate.gates = structuredClone(bundle.gates);
1061
- validateAssuranceDocument(candidate);
1062
- const settings = await readSettings(pmRoot);
1063
- const author = resolveAuthor(options.author, settings.author_default);
1064
- const mutation = await mutateWorkspaceJsonWithHistory({
1065
- pmRoot,
1066
- filePath: assurancePath(pmRoot),
1067
- op: "assurance:bundle:apply",
1068
- author,
1069
- message: options.message,
1070
- lockTtlSeconds: LOCK_TTL_SECONDS,
1071
- lockWaitMs: LOCK_WAIT_MS,
1072
- mutate: (beforeRaw) => {
1073
- const document = beforeRaw === null
1074
- ? createEmptyAssuranceDocument()
1075
- : parseAssuranceDocument(beforeRaw);
1076
- const createdIds = [];
1077
- const unchangedIds = [];
1078
- const apply = (target, additions, kind) => {
1079
- for (const definition of additions) {
1080
- const existing = target.find((entry) => entry.id === definition.id);
1081
- if (!existing) {
1082
- target.push(structuredClone(definition));
1083
- createdIds.push(`${kind}:${definition.id}`);
1084
- continue;
1085
- }
1086
- if (stableStringify(existing) !== stableStringify(definition)) {
1087
- throw new AssuranceMutationRefusalError(`assurance bundle refuses to replace divergent ${kind} ${definition.id}`);
1088
- }
1089
- unchangedIds.push(`${kind}:${definition.id}`);
1090
- }
1091
- };
1092
- apply(document.measurements, candidate.measurements, "measurement");
1093
- apply(document.assertions, candidate.assertions, "assertion");
1094
- apply(document.gates, candidate.gates, "gate");
1095
- validateAssuranceDocument(document);
1096
- return {
1097
- raw: `${JSON.stringify(document, null, 2)}\n`,
1098
- result: {
1099
- changed: createdIds.length > 0,
1100
- created_ids: createdIds,
1101
- unchanged_ids: unchangedIds,
1102
- },
1103
- };
1104
- },
1105
- });
1106
- return { ...mutation.result, changed: mutation.changed };
1107
- }
1108
- /** Remove an unreferenced declaration through audited singleton persistence. */
1109
- export async function removeAssuranceDeclaration(pmRoot, kind, id, options = {}) {
1110
- const settings = await readSettings(pmRoot);
1111
- const author = resolveAuthor(options.author, settings.author_default);
1112
- const mutation = await mutateWorkspaceJsonWithHistory({
1113
- pmRoot,
1114
- filePath: assurancePath(pmRoot),
1115
- op: `assurance:${kind}:remove`,
1116
- author,
1117
- message: options.message,
1118
- lockTtlSeconds: LOCK_TTL_SECONDS,
1119
- lockWaitMs: LOCK_WAIT_MS,
1120
- mutate: (beforeRaw) => {
1121
- const document = beforeRaw === null
1122
- ? createEmptyAssuranceDocument()
1123
- : parseAssuranceDocument(beforeRaw);
1124
- if (kind === "measurement") {
1125
- const consumers = collectMeasurementReferences(document).get(id);
1126
- if (consumers && consumers.length > 0) {
1127
- throw new AssuranceMutationRefusalError(`assurance measurement ${id} is referenced by ${consumers.join(", ")}`);
1128
- }
1129
- }
1130
- if (kind === "assertion" &&
1131
- document.gates.some((entry) => entry.assertion_ids.includes(id))) {
1132
- throw new AssuranceMutationRefusalError(`assurance assertion ${id} is referenced by gate`);
1133
- }
1134
- const collection = collectionFor(document, kind);
1135
- const index = collection.findIndex((entry) => entry.id === id);
1136
- if (index < 0) {
1137
- throw new AssuranceMutationRefusalError(`assurance ${kind} ${id} not found`);
1138
- }
1139
- collection.splice(index, 1);
1140
- validateAssuranceDocument(document);
1141
- return {
1142
- raw: `${JSON.stringify(document, null, 2)}\n`,
1143
- result: { changed: true, action: "removed", kind, id },
1144
- };
1145
- },
1146
- });
1147
- return { ...mutation.result, changed: mutation.changed };
1148
- }
1149
- /** Append one immutable gate verdict without changing registry state. */
1150
- export async function recordAssuranceVerdict(pmRoot, verdict, options = {}) {
1151
- if (verdict.dry_run)
1152
- throw new TypeError("dry-run assurance verdicts are not persisted");
1153
- const settings = await readSettings(pmRoot);
1154
- await appendWorkspaceAuditEvent({
1155
- pmRoot,
1156
- op: "assurance:gate:verdict",
1157
- author: resolveAuthor(options.author, settings.author_default),
1158
- context: { assurance_verdict: verdict },
1159
- message: options.message ??
1160
- `Assurance gate ${verdict.gate_id} returned ${verdict.verdict}`,
1161
- lockTtlSeconds: LOCK_TTL_SECONDS,
1162
- lockWaitMs: LOCK_WAIT_MS,
1163
- });
1164
- }
1165
- /** Query durable assurance verdicts from the verified workspace stream. */
1166
- export async function listAssuranceVerdicts(pmRoot, options = {}) {
1167
- const limit = options.limit ?? DEFAULT_VERDICT_LIMIT;
1168
- if (!Number.isInteger(limit) ||
1169
- limit < 1 ||
1170
- limit > MAX_ASSURANCE_VERDICT_LIMIT) {
1171
- throw new TypeError(`assurance verdict limit must be an integer from 1 through ${MAX_ASSURANCE_VERDICT_LIMIT}`);
1172
- }
1173
- const entries = await readHistoryEntries(getWorkspaceHistoryPath(pmRoot), WORKSPACE_HISTORY_ID);
1174
- return entries
1175
- .reverse()
1176
- .filter((entry) => entry.op === "assurance:gate:verdict")
1177
- .map((entry) => entry.context?.assurance_verdict)
1178
- .filter((value) => typeof value === "object" && value !== null && "gate_id" in value)
1179
- .filter((verdict) => options.gate_id === undefined || verdict.gate_id === options.gate_id)
1180
- .slice(0, limit);
1181
- }
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]="00ad9b34-4feb-5812-8755-801869cce3ad")}catch(e2){}})();import{createHash}from"node:crypto";import path from"node:path";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{appendWorkspaceAuditEvent,mutateWorkspaceJsonWithHistory,readFileIfExists,readHistoryEntries,readSettings,resolveAuthor,stableStringify,WORKSPACE_HISTORY_ID,getWorkspaceHistoryPath}from"../runtime-primitives.js";import{resolveCanonicalRelationshipKind}from"../relationships.js";import{MAX_ASSURANCE_VERDICT_LIMIT}from"./assurance-limits.js";import{AssuranceEvaluationRefusalError,AssuranceMutationRefusalError,AssuranceSourceResolutionError}from"./assurance-mutation-error.js";const ASSURANCE_DOCUMENT_VERSION=1;const ASSURANCE_GATE_TRIGGERS=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"];const ASSURANCE_MEASUREMENT_SOURCE_KINDS=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"];const POLARITY_KEYS=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"];const ID_PATTERN=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;const LOCK_TTL_SECONDS=30;const LOCK_WAIT_MS=5e3;const EVALUATION_CONCURRENCY=4;const DEFAULT_VERDICT_LIMIT=50;function requireStableId(value,field){if(!ID_PATTERN.test(value)){throw new AssuranceMutationRefusalError(`${field} must be a stable lowercase id`)}}function requireFiniteNonNegative(value,field){if(!Number.isFinite(value)||value<0){throw new AssuranceMutationRefusalError(`${field} must be a finite non-negative number`)}}function boundFor(assertion){const present=POLARITY_KEYS.filter(key=>assertion[key]!==void 0);if(present.length!==1){throw new AssuranceMutationRefusalError(`assertion ${assertion.id} must declare exactly one polarity`)}const polarity=present[0];const raw=assertion[polarity];return{polarity,value:polarity==="zero"?0:raw}}function valuesEqual(left,right){return stableStringify(left)===stableStringify(right)}function compareBound(observed,bound){if(bound.polarity==="equals")return valuesEqual(observed,bound.value);if(bound.polarity==="subset_of"){if(!Array.isArray(observed)||!Array.isArray(bound.value))return false;const allowed=bound.value;return observed.every(entry=>allowed.includes(entry))}if(typeof observed!=="number"){return false}const numericBound=bound.value;if(bound.polarity==="ceiling"||bound.polarity==="monotone_nonincreasing"){return observed<=numericBound}if(bound.polarity==="floor"||bound.polarity==="monotone_nondecreasing"){return observed>=numericBound}return observed===0}function proveNegativeControl(assertion){const bound=boundFor(assertion);const cases=assertion.negative_control.cases;return cases.some(entry=>entry.expected==="pass")&&cases.some(entry=>entry.expected==="fail")&&cases.every(entry=>compareBound(entry.observed,bound)===(entry.expected==="pass"))}function boundUpdateIsLoosening(beforeBound,afterBound){if(beforeBound.polarity!==afterBound.polarity)return true;if(typeof beforeBound.value==="number"&&typeof afterBound.value==="number"){return beforeBound.polarity==="ceiling"||beforeBound.polarity==="monotone_nonincreasing"?afterBound.value>beforeBound.value:beforeBound.polarity==="floor"||beforeBound.polarity==="monotone_nondecreasing"?afterBound.value<beforeBound.value:afterBound.value!==beforeBound.value}if(beforeBound.polarity==="subset_of"){const beforeValues=beforeBound.value;const afterValues=afterBound.value;return!Array.isArray(beforeValues)||!Array.isArray(afterValues)||afterValues.some(entry=>!beforeValues.includes(entry))}return!valuesEqual(beforeBound.value,afterBound.value)}function assuranceAssertionUpdateIsLoosening(before,after){if(before.measurement_id!==after.measurement_id||before.owner_item_id!==after.owner_item_id||stableStringify(before.scope)!==stableStringify(after.scope)){return true}const enforcementRank={observe:0,warn:1,block:2};const lifetimeLoosened=(before.lifetime??"hold")==="hold"&&(after.lifetime??"hold")==="retire";return boundUpdateIsLoosening(boundFor(before),boundFor(after))||enforcementRank[after.enforcement]<enforcementRank[before.enforcement]||lifetimeLoosened}function validateItemsMeasurementSource(source){if(source.state!==void 0&&!(source.state==="present"||source.state==="missing")){throw new AssuranceMutationRefusalError("items source state must be present or missing")}const hasEquals=Object.hasOwn(source,"equals");const hasState=source.state!==void 0;const predicateCount=Number(hasEquals)+Number(hasState);if(source.field!==void 0&&predicateCount!==1){throw new AssuranceMutationRefusalError("items source with field requires exactly one of equals or state")}if(source.field===void 0&&predicateCount!==0){throw new AssuranceMutationRefusalError("items source equals/state requires field")}}function validateDependencyKindMeasurementSource(source){if(typeof source.dependency_kind!=="string"||source.dependency_kind.trim().length===0){throw new AssuranceMutationRefusalError("dependency_kind source requires dependency_kind")}const provenancePredicateCount=[source.source_kind,source.source_kind_prefix,source.source_kind_state].filter(value=>value!==void 0).length;if(provenancePredicateCount>1){throw new AssuranceMutationRefusalError("dependency_kind source accepts at most one source_kind predicate")}if(source.source_kind!==void 0&&source.source_kind.trim().length===0||source.source_kind_prefix!==void 0&&source.source_kind_prefix.trim().length===0){throw new AssuranceMutationRefusalError("dependency_kind source provenance values must not be empty")}if(source.source_kind_state!==void 0&&source.source_kind_state!=="present"&&source.source_kind_state!=="missing"){throw new AssuranceMutationRefusalError("dependency_kind source source_kind_state must be present or missing")}}function validateProseEdgeGapSource(source){if(source.sample_limit!==void 0&&(!Number.isInteger(source.sample_limit)||source.sample_limit<1)){throw new AssuranceMutationRefusalError("prose_edge_gap sample_limit must be a positive integer")}for(const exemption of source.exemptions??[]){if(typeof exemption.holder_id!=="string"||exemption.holder_id.trim().length===0||typeof exemption.reason!=="string"||exemption.reason.trim().length===0){throw new AssuranceMutationRefusalError("prose_edge_gap exemptions require holder_id and reason")}if(exemption.target_id!==void 0&&exemption.target_id.trim().length===0||exemption.text_contains!==void 0&&exemption.text_contains.trim().length===0){throw new AssuranceMutationRefusalError("prose_edge_gap exemption selectors must not be empty")}}}function validateMeasurementDefinition(definition){requireStableId(definition.id,"measurement.id");if(definition.max_cost!==void 0){requireFiniteNonNegative(definition.max_cost,"measurement.max_cost")}const candidateSource=definition.source;if(Object.prototype.toString.call(candidateSource)!=="[object Object]"){throw new AssuranceMutationRefusalError(`measurement.source.kind must be one of ${ASSURANCE_MEASUREMENT_SOURCE_KINDS.join(", ")}`)}const sourceKind=Reflect.get(candidateSource,"kind");if(!ASSURANCE_MEASUREMENT_SOURCE_KINDS.includes(sourceKind)){throw new AssuranceMutationRefusalError(`measurement.source.kind must be one of ${ASSURANCE_MEASUREMENT_SOURCE_KINDS.join(", ")}`)}const source=candidateSource;if(source.kind==="items"){validateItemsMeasurementSource(source)}if(source.kind==="dependency_kind")validateDependencyKindMeasurementSource(source);if(source.kind==="prose_edge_gap")validateProseEdgeGapSource(source);if((source.kind==="graph"||source.kind==="validate"||source.kind==="health")&&(typeof source.field!=="string"||source.field.trim().length===0)){throw new AssuranceMutationRefusalError(`${source.kind} source requires field`)}if(source.kind==="provider"){requireStableId(source.provider,"provider source provider");requireStableId(source.key,"provider source key")}return definition}function validateAssertionDefinition(definition){requireStableId(definition.id,"assertion.id");requireStableId(definition.measurement_id,"assertion.measurement_id");if(typeof definition.owner_item_id!=="string"||definition.owner_item_id.trim().length===0){throw new AssuranceMutationRefusalError("assertion.owner_item_id is required")}const bound=boundFor(definition);if(typeof bound.value==="number"&&!Number.isFinite(bound.value)){throw new AssuranceMutationRefusalError(`assertion.${bound.polarity} must be a finite number`)}if(definition.lifetime==="retire"&&(typeof definition.retire_reason!=="string"||definition.retire_reason.trim().length===0)){throw new AssuranceMutationRefusalError("retired assertion requires retire_reason")}if(definition.scope.kind==="filter"){requireStableId(definition.scope.measurement_id,"assertion.scope.measurement_id")}const cases=definition.negative_control?.cases;if(!Array.isArray(cases)||!cases.some(entry=>entry.expected==="pass")||!cases.some(entry=>entry.expected==="fail")){throw new AssuranceMutationRefusalError("assertion negative control requires pass and fail cases")}if(!proveNegativeControl(definition)){throw new AssuranceMutationRefusalError(`assertion ${definition.id} negative control does not prove its bound`)}return definition}function validateGateProviderPolicy(policy){if(!Array.isArray(policy.allowed_providers)){throw new AssuranceMutationRefusalError("gate provider_policy.allowed_providers must be an array")}for(const provider of policy.allowed_providers){requireStableId(provider,"gate.provider_policy.allowed_provider")}if(typeof policy.triggers!=="object"||policy.triggers===null||Array.isArray(policy.triggers)){throw new AssuranceMutationRefusalError("gate provider_policy.triggers must be an object")}for(const[trigger,rule]of Object.entries(policy.triggers)){if(!ASSURANCE_GATE_TRIGGERS.includes(trigger)){throw new AssuranceMutationRefusalError(`gate provider policy has unknown trigger ${trigger}`)}if(typeof rule!=="object"||rule===null||!["low","medium","high"].includes(rule.max_cost_class)||typeof rule.allow_network!=="boolean"){throw new AssuranceMutationRefusalError(`gate provider policy trigger ${trigger} is invalid`)}}}function validateGateDefinition(definition){requireStableId(definition.id,"gate.id");if(!Array.isArray(definition.assertion_ids)){throw new AssuranceMutationRefusalError("gate.assertion_ids is required and must be an array")}if(definition.assertion_ids.length===0){throw new AssuranceMutationRefusalError("gate requires at least one assertion")}for(const id of definition.assertion_ids)requireStableId(id,"gate.assertion_id");if(!Array.isArray(definition.triggers)){throw new AssuranceMutationRefusalError(`gate.triggers is required and must be an array of ${ASSURANCE_GATE_TRIGGERS.join(", ")}`)}if(definition.triggers.length===0){throw new AssuranceMutationRefusalError("gate requires at least one trigger")}for(const trigger of definition.triggers){if(!ASSURANCE_GATE_TRIGGERS.includes(trigger)){throw new AssuranceMutationRefusalError(`gate trigger must be one of ${ASSURANCE_GATE_TRIGGERS.join(", ")}`)}}if(definition.provider_policy){validateGateProviderPolicy(definition.provider_policy)}return definition}function validateAssuranceDocument(document){if(document.version!==ASSURANCE_DOCUMENT_VERSION){throw new AssuranceMutationRefusalError(`unsupported assurance document version ${String(document.version)}`)}const ids=new Set;for(const definition of document.measurements){validateMeasurementDefinition(definition);if(ids.has(`measurement:${definition.id}`)){throw new AssuranceMutationRefusalError(`duplicate measurement ${definition.id}`)}ids.add(`measurement:${definition.id}`)}for(const definition of document.assertions){validateAssertionDefinition(definition);if(ids.has(`assertion:${definition.id}`)){throw new AssuranceMutationRefusalError(`duplicate assertion ${definition.id}`)}ids.add(`assertion:${definition.id}`)}for(const definition of document.gates){validateGateDefinition(definition);const missing=definition.assertion_ids.filter(id=>!document.assertions.some(assertionDefinition=>assertionDefinition.id===id));if(missing.length>0){throw new AssuranceMutationRefusalError(`gate ${definition.id} references missing assertions: ${missing.join(", ")}`)}if(ids.has(`gate:${definition.id}`)){throw new AssuranceMutationRefusalError(`duplicate gate ${definition.id}`)}ids.add(`gate:${definition.id}`)}const measurementIds=new Set(document.measurements.map(entry=>entry.id));for(const[measurementId,consumers]of collectMeasurementReferences(document)){if(!measurementIds.has(measurementId)){throw new AssuranceMutationRefusalError(`${consumers.join(", ")} references missing measurement ${measurementId}`)}}return document}function collectExpressionMeasurementReferences(expression,references){if("measurement"in expression){references.push(expression.measurement);return}if("operator"in expression){for(const operand of expression.operands){collectExpressionMeasurementReferences(operand,references)}}}function collectMeasurementReferences(document){const references=new Map;const add=(measurementId,consumer)=>{const consumers=references.get(measurementId)??[];consumers.push(consumer);references.set(measurementId,consumers)};for(const assertionDefinition of document.assertions){add(assertionDefinition.measurement_id,`assertion ${assertionDefinition.id}`);if(assertionDefinition.scope.kind==="filter"){add(assertionDefinition.scope.measurement_id,`assertion ${assertionDefinition.id} scope`)}}for(const measurementDefinition of document.measurements){if(measurementDefinition.source.kind!=="derived")continue;const derivedReferences=[];collectExpressionMeasurementReferences(measurementDefinition.source.expression,derivedReferences);for(const measurementId of derivedReferences){add(measurementId,`derived measurement ${measurementDefinition.id}`)}}return references}function collectGateProviderIds(gate,document){const pending=gate.assertion_ids.flatMap(assertionId=>{const assertion=document.assertions.find(entry=>entry.id===assertionId);return[assertion.measurement_id,...assertion.scope.kind==="filter"?[assertion.scope.measurement_id]:[]]});const visited=new Set;const providers=new Set;while(pending.length>0){const measurementId=pending.pop();if(visited.has(measurementId))continue;visited.add(measurementId);const measurement=document.measurements.find(entry=>entry.id===measurementId);if(measurement.source.kind==="provider"){providers.add(measurement.source.provider)}else if(measurement.source.kind==="derived"){collectExpressionMeasurementReferences(measurement.source.expression,pending)}}return providers}function createEmptyAssuranceDocument(){return{version:ASSURANCE_DOCUMENT_VERSION,measurements:[],assertions:[],gates:[]}}function itemsSourceResult(source,context){const matches=context.items.filter(item=>(source.statuses===void 0||source.statuses.includes(item.status))&&(source.types===void 0||source.types.includes(item.type))&&(source.tags===void 0||source.tags.every(tag=>item.tags?.includes(tag)))&&(source.field===void 0||(()=>{const value=item[source.field];if(source.state!==void 0){const missing=value===void 0||value===null||value===""||Array.isArray(value)&&value.length===0;return source.state==="missing"?missing:!missing}return valuesEqual(value,source.equals)})()));return{value:matches.length,population_size:context.items.length,cost:context.items.length,contributors:matches.map(item=>item.id)}}function dependencyProvenanceMatches(source,sourceKind){if(source.source_kind!==void 0){return sourceKind?.toLowerCase()===source.source_kind.trim().toLowerCase()}if(source.source_kind_prefix!==void 0){return sourceKind?.toLowerCase().startsWith(source.source_kind_prefix.trim().toLowerCase())===true}if(source.source_kind_state==="present"){return sourceKind!==void 0&&sourceKind.length>0}if(source.source_kind_state==="missing"){return sourceKind===void 0||sourceKind.length===0}return true}function dependencyKindSourceResult(source,context){const contributors=[];const requestedKind=resolveCanonicalRelationshipKind(source.dependency_kind)??source.dependency_kind.trim().toLowerCase();for(const item of context.items){for(const dependency of item.dependencies??[]){const dependencyKind=resolveCanonicalRelationshipKind(dependency.kind)??dependency.kind.trim().toLowerCase();const sourceKind=dependency.source_kind?.trim();if(dependencyKind===requestedKind&&dependencyProvenanceMatches(source,sourceKind))contributors.push(`${item.id}->${dependency.id}${sourceKind?`@${sourceKind}`:""}`)}}return{value:contributors.length,population_size:context.items.length,cost:context.items.length,contributors}}function assuranceItemProseSegments(item){const segments=[item.description,item.body].filter(value=>typeof value==="string").map(value=>value.trim()).filter(Boolean);for(const key of["comments","notes","learnings"]){const entries=item[key];if(!Array.isArray(entries))continue;for(const entry of entries){if(typeof entry==="string")segments.push(entry);else if(typeof entry==="object"&&entry!==null){const text=Reflect.get(entry,"text");if(typeof text==="string")segments.push(text)}}}return segments}function proseReferenceIsExempt(exemptions,holderId,targetId,segment){return exemptions.some(exemption=>exemption.holder_id.trim().toLowerCase()===holderId.toLowerCase()&&(exemption.target_id===void 0||exemption.target_id.trim().toLowerCase()===targetId.toLowerCase())&&(exemption.text_contains===void 0||segment.toLowerCase().includes(exemption.text_contains.trim().toLowerCase())))}function prosePairKey(left,right){return[left.toLowerCase(),right.toLowerCase()].sort().join("\0")}function collectProseEdgeCensusInputs(items){const canonicalIds=new Map;const linkedPairs=new Set;const proseMentions=[];const mentionPattern=/\b[a-z][a-z0-9]*-[a-z0-9]+\b/giu;let mentionCount=0;for(const item of items){canonicalIds.set(item.id.toLowerCase(),item.id);for(const dependency of item.dependencies??[])linkedPairs.add(prosePairKey(item.id,dependency.id));for(const scalar of[item.parent,item.blocked_by])if(typeof scalar==="string")linkedPairs.add(prosePairKey(item.id,scalar));for(const segment of assuranceItemProseSegments(item)){const mentionedIds=[...segment.matchAll(mentionPattern)].map(match=>match[0]);mentionCount+=mentionedIds.length;proseMentions.push({holder_id:item.id,segment,mentioned_ids:mentionedIds})}}return{canonical_ids:canonicalIds,linked_pairs:linkedPairs,prose_mentions:proseMentions,mention_count:mentionCount}}function proseEdgeGapSourceResult(source,context){const census=collectProseEdgeCensusInputs(context.items);const gaps=new Map;for(const proseMention of census.prose_mentions){const mentions=proseMention.mentioned_ids.map(id=>census.canonical_ids.get(id.toLowerCase())).filter(id=>id!==void 0&&id!==proseMention.holder_id);const distinctMentions=[...new Set(mentions)];for(const targetId of distinctMentions){const key=prosePairKey(proseMention.holder_id,targetId);if(census.linked_pairs.has(key)||proseReferenceIsExempt(source.exemptions??[],proseMention.holder_id,targetId,proseMention.segment))continue;const explicit=distinctMentions.some(candidate=>candidate!==targetId);if(gaps.get(key)?.explicit===true&&!explicit)continue;gaps.set(key,{contributor:`${proseMention.holder_id}->${targetId}|subject=${explicit?"explicit":"implicit"}`,explicit})}}const gapRows=[...gaps.values()];const contributors=gapRows.map(entry=>entry.contributor).sort();return{value:contributors.length,population_size:census.canonical_ids.size,cost:context.items.length+census.linked_pairs.size+census.mention_count,contributors:contributors.slice(0,source.sample_limit??25),partitions:{explicit_subject:gapRows.filter(entry=>entry.explicit).length,implicit_subject:gapRows.filter(entry=>!entry.explicit).length}}}function historySourceResult(source,context){const matches=context.history.filter(entry=>(source.op===void 0||entry.op===source.op)&&(source.author===void 0||entry.author===source.author)&&(source.harness===void 0||entry.agent_harness===source.harness)&&(source.model===void 0||entry.agent_model===source.model));return{value:matches.length,population_size:context.history.length,cost:context.history.length}}function linksSourceResult(source,context){const matches=context.items.filter(item=>{const links=item[source.link];const present=Array.isArray(links)&&links.length>0;return source.state==="present"?present:!present});return{value:matches.length,population_size:context.items.length,cost:context.items.length,contributors:matches.map(item=>item.id)}}function sourceResult(definition,context){const source=definition.source;if(source.kind==="items")return itemsSourceResult(source,context);if(source.kind==="dependency_kind"){return dependencyKindSourceResult(source,context)}if(source.kind==="prose_edge_gap")return proseEdgeGapSourceResult(source,context);if(source.kind==="history")return historySourceResult(source,context);if(source.kind==="links")return linksSourceResult(source,context);return null}function sumCosts(costs,durationMs){return costs.reduce((total,cost)=>({units:total.units+cost.units,items_scanned:total.items_scanned+cost.items_scanned,history_entries:total.history_entries+cost.history_entries,provider_calls:total.provider_calls+cost.provider_calls,duration_ms:durationMs}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:durationMs})}function arithmeticValue(operator,values){if(values.length===0)throw new TypeError(`derived ${operator} requires operands`);if(operator==="add")return values.reduce((sum,value)=>sum+value,0);if(operator==="subtract")return values.slice(1).reduce((result,value)=>result-value,values[0]);if(operator==="multiply")return values.reduce((result,value)=>result*value,1);if(operator==="divide"){if(values.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return values.slice(1).reduce((result,value)=>result/value,values[0])}return operator==="min"?Math.min(...values):Math.max(...values)}async function mapWithConcurrency(values,limit,transform){const results=new Array(values.length);let nextIndex=0;const workers=Array.from({length:Math.min(limit,values.length)},async()=>{while(nextIndex<values.length){const index=nextIndex;nextIndex+=1;results[index]=await transform(values[index],index)}});await Promise.all(workers);return results}async function evaluateExpression(expression,context,definitions,stack,state){if("literal"in expression)return{value:expression.literal,costs:[],population_size:0,contributors:[]};if("measurement"in expression){const definition=definitions.find(entry=>entry.id===expression.measurement);if(!definition)throw new TypeError(`derived measurement references missing ${expression.measurement}`);const result=await evaluateMeasurementCached(definition,context,definitions,stack,state);if(typeof result.value!=="number")throw new TypeError(`derived measurement ${definition.id} is not numeric`);const costs=state.charged.has(definition.id)?[]:[result.cost];state.charged.add(definition.id);return{value:result.value,costs,population_size:result.population_size,contributors:result.contributors}}const operands=await mapWithConcurrency(expression.operands,EVALUATION_CONCURRENCY,operand=>evaluateExpression(operand,context,definitions,stack,state));return{value:arithmeticValue(expression.operator,operands.map(entry=>entry.value)),costs:operands.flatMap(entry=>entry.costs),population_size:Math.max(0,...operands.map(entry=>entry.population_size)),contributors:[...new Set(operands.flatMap(entry=>entry.contributors))]}}async function evaluateMeasurementInternal(definition,context,definitions,stack,state){validateMeasurementDefinition(definition);const startedAt=Date.now();let result;let nestedCosts=[];let providerCalls=0;if(definition.source.kind==="derived"){const derived=await evaluateExpression(definition.source.expression,context,definitions,[...stack,definition.id],state);result={value:derived.value,population_size:derived.population_size,cost:0,contributors:derived.contributors};nestedCosts=derived.costs}else{const builtin=sourceResult(definition,context);if(builtin!==null){result=builtin}else{result=await context.external(definition.source);providerCalls=1}}const ownCost={units:result.cost,items_scanned:definition.source.kind==="items"||definition.source.kind==="dependency_kind"||definition.source.kind==="prose_edge_gap"||definition.source.kind==="links"?context.items.length:0,history_entries:definition.source.kind==="history"?context.history.length:0,provider_calls:providerCalls,duration_ms:Date.now()-startedAt};const cost=sumCosts([...nestedCosts,ownCost],Date.now()-startedAt);if(definition.max_cost!==void 0&&cost.units>definition.max_cost){throw new AssuranceEvaluationRefusalError(`measurement ${definition.id} exceeded cost ceiling ${definition.max_cost} with ${cost.units}`)}return{id:definition.id,definition_fingerprint:`sha256:${createHash("sha256").update(stableStringify(definition)).digest("hex")}`,value:result.value,population_size:result.population_size,cost,contributors:result.contributors??[],...result.partitions?{partitions:result.partitions}:{}}}function evaluateMeasurementCached(definition,context,definitions,stack,state){if(stack.includes(definition.id)){throw new TypeError(`derived measurement cycle: ${[...stack,definition.id].join(" -> ")}`)}const cached=state.cache.get(definition.id);if(cached)return cached;const evaluation=evaluateMeasurementInternal(definition,context,definitions,stack,state).catch(error=>{if(error instanceof AssuranceSourceResolutionError&&error.measurement_id===void 0){const sourceContext={measurement_id:definition.id,source_kind:error.source_kind,field:error.field,...error.check?{check:error.check}:{}};const sourceError=new AssuranceSourceResolutionError(error.message,sourceContext);sourceError.cause=error;throw sourceError}throw error});state.cache.set(definition.id,evaluation);return evaluation}async function evaluateMeasurement(definition,context,definitions=[definition]){return evaluateMeasurementCached(definition,context,definitions,[],{cache:new Map,charged:new Set})}function assertionDistance(observed,bound){if(typeof observed!=="number"||typeof bound.value!=="number")return null;if(bound.polarity==="ceiling"||bound.polarity==="monotone_nonincreasing")return bound.value-observed;if(bound.polarity==="floor"||bound.polarity==="monotone_nondecreasing")return observed-bound.value;return observed-bound.value}function evaluateAssuranceAssertion(definition,measurement,options={}){validateAssertionDefinition(definition);const bound=boundFor(definition);const retired=definition.lifetime==="retire"&&options.owner_terminal===true;return{assertion_id:definition.id,measurement_id:definition.measurement_id,measurement_definition_fingerprint:measurement.definition_fingerprint,scope:definition.scope,population_size:measurement.population_size,observed:measurement.value,bound,distance:assertionDistance(measurement.value,bound),verdict:retired?"retired":compareBound(measurement.value,bound)?"pass":"fail",enforcement:definition.enforcement,negative_control_proven:proveNegativeControl(definition),cost:measurement.cost,contributors:measurement.contributors,...measurement.partitions?{partitions:measurement.partitions}:{}}}function enforceGateProviderPolicy(gate,document,context,trigger){const providerIds=collectGateProviderIds(gate,document);if(providerIds.size===0)return;const policy=gate.provider_policy;const triggerPolicy=policy?.triggers[trigger];if(!policy||!triggerPolicy){throw new AssuranceEvaluationRefusalError(`assurance gate ${gate.id} refuses provider execution at trigger ${trigger} without an explicit provider policy`)}const allowedProviders=new Set(policy.allowed_providers);const costRank={low:0,medium:1,high:2};for(const providerId of providerIds){if(!allowedProviders.has(providerId)){throw new AssuranceEvaluationRefusalError(`assurance gate ${gate.id} refuses provider ${providerId}`)}const capability=context.provider_capabilities?.[providerId];if(!capability){throw new AssuranceEvaluationRefusalError(`assurance provider ${providerId} has no declared capabilities`)}if(costRank[capability.cost_class]>costRank[triggerPolicy.max_cost_class]){throw new AssuranceEvaluationRefusalError(`assurance gate ${gate.id} refuses ${capability.cost_class}-cost provider ${providerId} at trigger ${trigger}`)}if(capability.network&&!triggerPolicy.allow_network){throw new AssuranceEvaluationRefusalError(`assurance gate ${gate.id} refuses network provider ${providerId} at trigger ${trigger}`)}}}async function evaluateGateMeasurement(gateId,assertionId,definition,context,definitions){try{return await evaluateMeasurement(definition,context,definitions)}catch(error){if(error instanceof AssuranceSourceResolutionError){const checkLocation=error.check?` check ${error.check}`:"";const measurementId=error.measurement_id??definition.id;const refusal=new AssuranceEvaluationRefusalError(`assurance gate ${gateId} assertion ${assertionId} measurement ${measurementId} source ${error.source_kind}${checkLocation} field ${error.field} could not resolve: ${error.message}`,{gate_id:gateId,assertion_id:assertionId,measurement_id:measurementId,source_kind:error.source_kind,field:error.field,...error.check?{check:error.check}:{}});refusal.cause=error;throw refusal}throw error}}async function evaluateAssuranceGate(gateId,document,context,options){validateAssuranceDocument(document);const gateDefinition=document.gates.find(entry=>entry.id===gateId);if(!gateDefinition)throw new AssuranceEvaluationRefusalError(`assurance gate ${gateId} not found`);if(!gateDefinition.triggers.includes(options.trigger)){throw new AssuranceEvaluationRefusalError(`assurance gate ${gateId} does not declare trigger ${options.trigger}`)}enforceGateProviderPolicy(gateDefinition,document,context,options.trigger);const assertions=await mapWithConcurrency(gateDefinition.assertion_ids,EVALUATION_CONCURRENCY,async id=>{const assertionDefinition=document.assertions.find(entry=>entry.id===id);const measurementDefinition=document.measurements.find(entry=>entry.id===assertionDefinition.measurement_id);let scopedContext=context;if(assertionDefinition.scope.kind==="active"){const terminalStatuses=new Set(context.terminal_statuses??["closed","canceled"]);scopedContext={...context,items:context.items.filter(item=>!terminalStatuses.has(item.status))}}else if(assertionDefinition.scope.kind==="filter"){const scopeMeasurementId=assertionDefinition.scope.measurement_id;const scopeDefinition=document.measurements.find(entry=>entry.id===scopeMeasurementId);const scope=await evaluateGateMeasurement(gateDefinition.id,assertionDefinition.id,scopeDefinition,context,document.measurements);const contributorIds=new Set(scope.contributors);scopedContext={...context,items:context.items.filter(item=>contributorIds.has(item.id))}}const owner=context.items.find(item=>item.id===assertionDefinition.owner_item_id);const ownerTerminal=owner!==void 0&&new Set(context.terminal_statuses??["closed","canceled"]).has(owner.status);return evaluateAssuranceAssertion(assertionDefinition,await evaluateGateMeasurement(gateDefinition.id,assertionDefinition.id,measurementDefinition,scopedContext,document.measurements),{owner_terminal:ownerTerminal})});const blocking=assertions.some(entry=>entry.verdict==="fail"&&entry.enforcement==="block");const warning=assertions.some(entry=>entry.verdict==="fail"&&entry.enforcement==="warn");return{gate_id:gateDefinition.id,tree_id:context.tree_id,trigger:options.trigger,dry_run:options.dry_run===true,evaluated_at:new Date().toISOString(),verdict:blocking?"block":warning?"warn":"pass",exit_code:blocking?1:0,assertions,assertions_total:assertions.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:sumCosts(assertions.map(entry=>entry.cost),Math.max(0,...assertions.map(entry=>entry.cost.duration_ms)))}}function assurancePath(pmRoot){return path.join(pmRoot,"assurance.json")}async function readDocument(pmRoot){const raw=await readFileIfExists(assurancePath(pmRoot));if(raw===null)return createEmptyAssuranceDocument();return parseAssuranceDocument(raw)}function parseAssuranceDocument(raw){try{return validateAssuranceDocument(JSON.parse(raw))}catch(error){throw new PmCliError("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",EXIT_CODE.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(error),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function collectionFor(document,kind){if(kind==="measurement")return document.measurements;if(kind==="assertion")return document.assertions;return document.gates}function validateForKind(kind,definition){if(kind==="measurement")validateMeasurementDefinition(definition);else if(kind==="assertion")validateAssertionDefinition(definition);else validateGateDefinition(definition)}async function listAssuranceDeclarations(pmRoot,kind){const items=structuredClone(collectionFor(await readDocument(pmRoot),kind));return{items,count:items.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function getAssuranceDeclaration(pmRoot,kind,id){const found=collectionFor(await readDocument(pmRoot),kind).find(entry=>entry.id===id);if(!found)throw new TypeError(`assurance ${kind} ${id} not found`);return structuredClone(found)}async function putAssuranceDeclaration(pmRoot,kind,definition,options={}){validateForKind(kind,definition);const settings=await readSettings(pmRoot);const author=resolveAuthor(options.author,settings.author_default);const mutation=await mutateWorkspaceJsonWithHistory({pmRoot,filePath:assurancePath(pmRoot),op:`assurance:${kind}:put`,author,message:options.message,lockTtlSeconds:LOCK_TTL_SECONDS,lockWaitMs:LOCK_WAIT_MS,mutate:beforeRaw=>{const document=beforeRaw===null?createEmptyAssuranceDocument():parseAssuranceDocument(beforeRaw);const collection=collectionFor(document,kind);const index=collection.findIndex(entry=>entry.id===definition.id);const action=index<0?"created":"updated";if(kind==="assertion"&&index>=0&&assuranceAssertionUpdateIsLoosening(collection[index],definition)){const decision=definition.authorization_decision;if(!decision||!options.authorized_decision_ids?.includes(decision)){throw new AssuranceMutationRefusalError(`loosening assertion ${definition.id} requires a verified authorization_decision`)}}if(index<0)collection.push(structuredClone(definition));else collection[index]=structuredClone(definition);validateAssuranceDocument(document);return{raw:`${JSON.stringify(document,null,2)}
2
+ `,result:{changed:true,action,kind,id:definition.id}}}});return{...mutation.result,changed:mutation.changed}}async function putAssuranceDeclarationBundle(pmRoot,bundle,options={}){const candidate=createEmptyAssuranceDocument();candidate.measurements=structuredClone(bundle.measurements);candidate.assertions=structuredClone(bundle.assertions);candidate.gates=structuredClone(bundle.gates);validateAssuranceDocument(candidate);const settings=await readSettings(pmRoot);const author=resolveAuthor(options.author,settings.author_default);const mutation=await mutateWorkspaceJsonWithHistory({pmRoot,filePath:assurancePath(pmRoot),op:"assurance:bundle:apply",author,message:options.message,lockTtlSeconds:LOCK_TTL_SECONDS,lockWaitMs:LOCK_WAIT_MS,mutate:beforeRaw=>{const document=beforeRaw===null?createEmptyAssuranceDocument():parseAssuranceDocument(beforeRaw);const createdIds=[];const unchangedIds=[];const apply=(target,additions,kind)=>{for(const definition of additions){const existing=target.find(entry=>entry.id===definition.id);if(!existing){target.push(structuredClone(definition));createdIds.push(`${kind}:${definition.id}`);continue}if(stableStringify(existing)!==stableStringify(definition)){throw new AssuranceMutationRefusalError(`assurance bundle refuses to replace divergent ${kind} ${definition.id}`)}unchangedIds.push(`${kind}:${definition.id}`)}};apply(document.measurements,candidate.measurements,"measurement");apply(document.assertions,candidate.assertions,"assertion");apply(document.gates,candidate.gates,"gate");validateAssuranceDocument(document);return{raw:`${JSON.stringify(document,null,2)}
3
+ `,result:{changed:createdIds.length>0,created_ids:createdIds,unchanged_ids:unchangedIds}}}});return{...mutation.result,changed:mutation.changed}}async function removeAssuranceDeclaration(pmRoot,kind,id,options={}){const settings=await readSettings(pmRoot);const author=resolveAuthor(options.author,settings.author_default);const mutation=await mutateWorkspaceJsonWithHistory({pmRoot,filePath:assurancePath(pmRoot),op:`assurance:${kind}:remove`,author,message:options.message,lockTtlSeconds:LOCK_TTL_SECONDS,lockWaitMs:LOCK_WAIT_MS,mutate:beforeRaw=>{const document=beforeRaw===null?createEmptyAssuranceDocument():parseAssuranceDocument(beforeRaw);if(kind==="measurement"){const consumers=collectMeasurementReferences(document).get(id);if(consumers&&consumers.length>0){throw new AssuranceMutationRefusalError(`assurance measurement ${id} is referenced by ${consumers.join(", ")}`)}}if(kind==="assertion"&&document.gates.some(entry=>entry.assertion_ids.includes(id))){throw new AssuranceMutationRefusalError(`assurance assertion ${id} is referenced by gate`)}const collection=collectionFor(document,kind);const index=collection.findIndex(entry=>entry.id===id);if(index<0){throw new AssuranceMutationRefusalError(`assurance ${kind} ${id} not found`)}collection.splice(index,1);validateAssuranceDocument(document);return{raw:`${JSON.stringify(document,null,2)}
4
+ `,result:{changed:true,action:"removed",kind,id}}}});return{...mutation.result,changed:mutation.changed}}async function recordAssuranceVerdict(pmRoot,verdict,options={}){if(verdict.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");const settings=await readSettings(pmRoot);await appendWorkspaceAuditEvent({pmRoot,op:"assurance:gate:verdict",author:resolveAuthor(options.author,settings.author_default),context:{assurance_verdict:verdict},message:options.message??`Assurance gate ${verdict.gate_id} returned ${verdict.verdict}`,lockTtlSeconds:LOCK_TTL_SECONDS,lockWaitMs:LOCK_WAIT_MS})}async function listAssuranceVerdicts(pmRoot,options={}){const limit=options.limit??DEFAULT_VERDICT_LIMIT;if(!Number.isInteger(limit)||limit<1||limit>MAX_ASSURANCE_VERDICT_LIMIT){throw new TypeError(`assurance verdict limit must be an integer from 1 through ${MAX_ASSURANCE_VERDICT_LIMIT}`)}const entries=await readHistoryEntries(getWorkspaceHistoryPath(pmRoot),WORKSPACE_HISTORY_ID);return entries.reverse().filter(entry=>entry.op==="assurance:gate:verdict").map(entry=>entry.context?.assurance_verdict).filter(value=>typeof value==="object"&&value!==null&&"gate_id"in value).filter(verdict=>options.gate_id===void 0||verdict.gate_id===options.gate_id).slice(0,limit)}export{ASSURANCE_DOCUMENT_VERSION,ASSURANCE_GATE_TRIGGERS,ASSURANCE_MEASUREMENT_SOURCE_KINDS,assuranceAssertionUpdateIsLoosening,createEmptyAssuranceDocument,evaluateAssuranceAssertion,evaluateAssuranceGate,evaluateMeasurement,getAssuranceDeclaration,listAssuranceDeclarations,listAssuranceVerdicts,putAssuranceDeclaration,putAssuranceDeclarationBundle,recordAssuranceVerdict,removeAssuranceDeclaration,validateAssertionDefinition,validateAssuranceDocument,validateGateDefinition,validateMeasurementDefinition};
1182
5
  //# sourceMappingURL=assurance.js.map
1183
- //# debugId=d4c380ce-031e-5b2d-aaa8-658bb4aa3087