@intentius/chant 0.124.108 → 0.124.110

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 (342) hide show
  1. package/dist/__golden__/wave-loop/fan-out-applied.json +12 -6
  2. package/dist/__golden__/wave-loop/fan-out-apply-fails.json +8 -4
  3. package/dist/__golden__/wave-loop/fan-out-gated.json +4 -2
  4. package/dist/__golden__/wave-loop/fan-out-no-members.json +16 -8
  5. package/dist/__golden__/wave-loop/fan-out-plan-fails.json +8 -4
  6. package/dist/__golden__/wave-loop/fan-out-same-root.json +4 -2
  7. package/dist/agent-facts.d.ts +130 -0
  8. package/dist/agent-facts.js +196 -0
  9. package/dist/change-risk.d.ts +216 -0
  10. package/dist/change-risk.js +304 -0
  11. package/dist/change-set.d.ts +8 -0
  12. package/dist/ci-agent-alert.d.ts +139 -0
  13. package/dist/ci-agent-alert.js +342 -0
  14. package/dist/ci-agent-triggers.d.ts +152 -0
  15. package/dist/ci-agent-triggers.js +232 -0
  16. package/dist/ci-agent-verify-failed.d.ts +149 -0
  17. package/dist/ci-agent-verify-failed.js +191 -0
  18. package/dist/ci-agent.d.ts +136 -8
  19. package/dist/ci-agent.js +353 -26
  20. package/dist/ci-comment-commands.d.ts +8 -0
  21. package/dist/ci-comment-commands.js +17 -1
  22. package/dist/ci-comment-reject.d.ts +70 -0
  23. package/dist/ci-comment-reject.js +135 -0
  24. package/dist/ci-comment-replies.d.ts +3 -1
  25. package/dist/ci-comment-replies.js +6 -0
  26. package/dist/ci-estate/delivery.d.ts +25 -3
  27. package/dist/ci-estate/delivery.js +28 -9
  28. package/dist/ci-estate/page.d.ts +7 -3
  29. package/dist/ci-estate/page.js +19 -4
  30. package/dist/ci-estate/rows.d.ts +14 -2
  31. package/dist/ci-estate/rows.js +9 -1
  32. package/dist/ci-estate.d.ts +5 -2
  33. package/dist/ci-estate.js +3 -2
  34. package/dist/ci-handover.d.ts +2 -7
  35. package/dist/ci-handover.js +3 -20
  36. package/dist/ci-jobs.d.ts +6 -0
  37. package/dist/ci-jobs.js +17 -0
  38. package/dist/ci-note-commands.d.ts +2 -0
  39. package/dist/ci-note-commands.js +12 -1
  40. package/dist/ci-product-words.d.ts +151 -1
  41. package/dist/ci-product-words.js +1390 -3
  42. package/dist/ci-product.d.ts +100 -4
  43. package/dist/ci-product.js +99 -3
  44. package/dist/ci-respond-run.d.ts +9 -0
  45. package/dist/ci-respond-run.js +35 -4
  46. package/dist/ci-respond-summary-env.d.ts +56 -0
  47. package/dist/ci-respond-summary-env.js +81 -0
  48. package/dist/ci-respond-summary.d.ts +103 -0
  49. package/dist/ci-respond-summary.js +243 -0
  50. package/dist/ci-respond.d.ts +4 -2
  51. package/dist/ci-respond.js +4 -2
  52. package/dist/cli/command-group.js +1 -1
  53. package/dist/cli/commands/lint.js +21 -3
  54. package/dist/cli/handlers/agent.js +49 -4
  55. package/dist/cli/handlers/approve.js +3 -1
  56. package/dist/cli/handlers/build.d.ts +97 -1
  57. package/dist/cli/handlers/build.js +251 -3
  58. package/dist/cli/handlers/fan-out.js +55 -0
  59. package/dist/cli/handlers/graph.d.ts +14 -0
  60. package/dist/cli/handlers/graph.js +58 -3
  61. package/dist/cli/handlers/lifecycle-health.d.ts +7 -0
  62. package/dist/cli/handlers/lifecycle-health.js +47 -9
  63. package/dist/cli/handlers/lifecycle.js +4 -1
  64. package/dist/cli/handlers/notify-relay.d.ts +2 -2
  65. package/dist/cli/handlers/notify-relay.js +67 -7
  66. package/dist/cli/handlers/pipeline-agent.d.ts +30 -0
  67. package/dist/cli/handlers/pipeline-agent.js +255 -0
  68. package/dist/cli/handlers/pipeline-artifacts.d.ts +39 -0
  69. package/dist/cli/handlers/pipeline-artifacts.js +203 -0
  70. package/dist/cli/handlers/pipeline.d.ts +16 -0
  71. package/dist/cli/handlers/pipeline.js +112 -0
  72. package/dist/cli/handlers/pr-comment.js +4 -0
  73. package/dist/cli/handlers/pr-notes.js +4 -1
  74. package/dist/cli/handlers/pr.d.ts +20 -0
  75. package/dist/cli/handlers/pr.js +114 -11
  76. package/dist/cli/handlers/promote.js +792 -47
  77. package/dist/cli/handlers/reject.d.ts +84 -0
  78. package/dist/cli/handlers/reject.js +216 -0
  79. package/dist/cli/handlers/release.js +4 -2
  80. package/dist/cli/handlers/replan.d.ts +54 -0
  81. package/dist/cli/handlers/replan.js +177 -0
  82. package/dist/cli/handlers/run-generate.d.ts +5 -0
  83. package/dist/cli/handlers/run-generate.js +31 -4
  84. package/dist/cli/handlers/run-wave.js +15 -2
  85. package/dist/cli/handlers/run.js +4 -2
  86. package/dist/cli/handlers/stage.d.ts +35 -0
  87. package/dist/cli/handlers/stage.js +90 -0
  88. package/dist/cli/lsp/server.js +4 -0
  89. package/dist/cli/main.js +88 -8
  90. package/dist/cli/parse-args.js +35 -2
  91. package/dist/cli/registry.d.ts +12 -0
  92. package/dist/components/auto-release.d.ts +2 -0
  93. package/dist/components/auto-release.js +1 -0
  94. package/dist/components/capability.d.ts +40 -0
  95. package/dist/components/cli-support.d.ts +21 -1
  96. package/dist/components/cli-support.js +28 -6
  97. package/dist/components/component.d.ts +23 -4
  98. package/dist/components/component.schema.json +28 -0
  99. package/dist/components/declared-reads.d.ts +44 -4
  100. package/dist/components/declared-reads.js +80 -3
  101. package/dist/components/discover.d.ts +8 -0
  102. package/dist/components/discover.js +1 -1
  103. package/dist/components/driver.d.ts +13 -0
  104. package/dist/components/driver.js +23 -2
  105. package/dist/components/environment-sets.d.ts +229 -0
  106. package/dist/components/environment-sets.js +338 -0
  107. package/dist/components/fan-out-canary.d.ts +47 -0
  108. package/dist/components/fan-out-canary.js +58 -0
  109. package/dist/components/fan-out-run.d.ts +17 -0
  110. package/dist/components/fan-out-run.js +14 -1
  111. package/dist/components/fan-out-support.d.ts +7 -0
  112. package/dist/components/fan-out-support.js +1 -1
  113. package/dist/components/groups.d.ts +8 -1
  114. package/dist/components/groups.js +19 -1
  115. package/dist/components/index.d.ts +5 -2
  116. package/dist/components/index.js +4 -1
  117. package/dist/components/pr-cost.d.ts +28 -0
  118. package/dist/components/pr-cost.js +53 -0
  119. package/dist/components/pr-pipeline.d.ts +33 -0
  120. package/dist/components/pr-pipeline.js +32 -5
  121. package/dist/components/pr-policy.d.ts +33 -2
  122. package/dist/components/pr-policy.js +5 -2
  123. package/dist/components/pr-risk.d.ts +42 -0
  124. package/dist/components/pr-risk.js +74 -0
  125. package/dist/components/product-pipeline.d.ts +43 -0
  126. package/dist/components/product-pipeline.js +67 -1
  127. package/dist/components/promote.d.ts +6 -0
  128. package/dist/components/promote.js +13 -0
  129. package/dist/components/release-compile.js +3 -1
  130. package/dist/components/release-gate.d.ts +6 -1
  131. package/dist/components/release-gate.js +10 -2
  132. package/dist/components/step-environments.d.ts +236 -0
  133. package/dist/components/step-environments.js +392 -0
  134. package/dist/components/upstream-replan.d.ts +201 -0
  135. package/dist/components/upstream-replan.js +249 -0
  136. package/dist/components/verify-step.d.ts +30 -0
  137. package/dist/components/verify-step.js +27 -0
  138. package/dist/components/wave-plan.js +6 -2
  139. package/dist/config-environments.d.ts +4 -2
  140. package/dist/control/dispatch.d.ts +15 -0
  141. package/dist/control/dispatch.js +28 -4
  142. package/dist/cost-estimate.d.ts +188 -0
  143. package/dist/cost-estimate.js +363 -0
  144. package/dist/drift-record.d.ts +36 -0
  145. package/dist/drift-record.js +44 -0
  146. package/dist/engine-facts.d.ts +105 -0
  147. package/dist/engine-facts.js +111 -0
  148. package/dist/exit-codes.d.ts +4 -3
  149. package/dist/exit-codes.js +4 -3
  150. package/dist/flag-params.d.ts +2 -2
  151. package/dist/flag-params.js +9 -4
  152. package/dist/floor-table.data.js +53 -0
  153. package/dist/forge-token-vars.d.ts +12 -0
  154. package/dist/forge-token-vars.js +25 -0
  155. package/dist/gate-decision.d.ts +3 -1
  156. package/dist/gate-decision.js +3 -1
  157. package/dist/gated-waves.d.ts +2 -0
  158. package/dist/gated-waves.js +1 -0
  159. package/dist/graph-ir.d.ts +30 -0
  160. package/dist/graph-ir.js +33 -1
  161. package/dist/graph-refs.d.ts +26 -0
  162. package/dist/graph-refs.js +34 -3
  163. package/dist/graph-schema/graph.schema.json +136 -0
  164. package/dist/health.d.ts +65 -0
  165. package/dist/health.js +62 -0
  166. package/dist/lexicon.d.ts +188 -1
  167. package/dist/lifecycle/disruption.d.ts +14 -1
  168. package/dist/lifecycle/disruption.js +5 -1
  169. package/dist/lifecycle/gate-change-set.d.ts +8 -0
  170. package/dist/lifecycle/gate-change-set.js +2 -1
  171. package/dist/lifecycle/gate-ledger.d.ts +26 -0
  172. package/dist/lifecycle/gate-rejection.d.ts +82 -0
  173. package/dist/lifecycle/gate-rejection.js +93 -0
  174. package/dist/lifecycle/gate-seal.d.ts +3 -3
  175. package/dist/lifecycle/gate-seal.js +5 -5
  176. package/dist/lifecycle/observe.d.ts +17 -0
  177. package/dist/lifecycle/observe.js +10 -1
  178. package/dist/lifecycle/release-cut.js +4 -0
  179. package/dist/lifecycle/release-ledger.d.ts +8 -0
  180. package/dist/lifecycle/release-risk.d.ts +137 -0
  181. package/dist/lifecycle/release-risk.js +214 -0
  182. package/dist/lifecycle/release-store.d.ts +9 -0
  183. package/dist/lifecycle/release-store.js +4 -0
  184. package/dist/lifecycle/stage-log.d.ts +85 -0
  185. package/dist/lifecycle/stage-log.js +141 -0
  186. package/dist/lint/canary-checks.d.ts +31 -0
  187. package/dist/lint/canary-checks.js +45 -0
  188. package/dist/lint/rule.d.ts +1 -0
  189. package/dist/lint/rules/evl012-pipeline-fold.d.ts +14 -0
  190. package/dist/lint/rules/evl012-pipeline-fold.js +30 -0
  191. package/dist/lint/rules/index.d.ts +1 -0
  192. package/dist/lint/rules/index.js +3 -0
  193. package/dist/notify-relay-repo.d.ts +54 -0
  194. package/dist/notify-relay-repo.js +84 -0
  195. package/dist/notify-relay.d.ts +53 -3
  196. package/dist/notify-relay.js +96 -3
  197. package/dist/notify.d.ts +57 -1
  198. package/dist/notify.js +7 -1
  199. package/dist/notify.schema.json +61 -3
  200. package/dist/observation.d.ts +34 -0
  201. package/dist/observation.js +14 -1
  202. package/dist/op/activities/review-agent.d.ts +39 -2
  203. package/dist/op/activities/review-agent.js +88 -5
  204. package/dist/op/agent-permit.d.ts +88 -0
  205. package/dist/op/agent-permit.js +97 -0
  206. package/dist/op/gate-approval-base.d.ts +8 -0
  207. package/dist/op/gate-approval-base.js +9 -0
  208. package/dist/op/gate-approval.d.ts +30 -1
  209. package/dist/op/gate-approval.js +23 -2
  210. package/dist/op/gate-quorum.d.ts +114 -8
  211. package/dist/op/gate-quorum.js +198 -21
  212. package/dist/op/gate-reject.d.ts +79 -0
  213. package/dist/op/gate-reject.js +96 -0
  214. package/dist/op/gate-summary.js +1 -1
  215. package/dist/op/gate.d.ts +28 -3
  216. package/dist/op/gate.js +55 -13
  217. package/dist/op/generate-pipeline.d.ts +15 -1
  218. package/dist/op/generate-pipeline.js +32 -5
  219. package/dist/op/index.d.ts +11 -6
  220. package/dist/op/index.js +10 -5
  221. package/dist/op/local-executor.d.ts +2 -0
  222. package/dist/op/local-executor.js +23 -4
  223. package/dist/op/op-waves-after-plan.d.ts +23 -0
  224. package/dist/op/op-waves-after-plan.js +12 -1
  225. package/dist/op/op-waves-capability-spec.d.ts +14 -0
  226. package/dist/op/op-waves-capability-spec.js +46 -6
  227. package/dist/op/op-waves-capability.d.ts +21 -13
  228. package/dist/op/op-waves-capability.js +22 -59
  229. package/dist/op/op-waves-environment-sets.d.ts +41 -0
  230. package/dist/op/op-waves-environment-sets.js +82 -0
  231. package/dist/op/op-waves-quorum-warnings.d.ts +53 -0
  232. package/dist/op/op-waves-quorum-warnings.js +90 -0
  233. package/dist/op/op-waves-release-port.d.ts +7 -0
  234. package/dist/op/op-waves-release-port.js +15 -3
  235. package/dist/op/op-waves-release.d.ts +15 -0
  236. package/dist/op/op-waves-release.js +15 -0
  237. package/dist/op/op-waves-run.d.ts +37 -3
  238. package/dist/op/op-waves-run.js +141 -18
  239. package/dist/op/op-waves-soak.d.ts +57 -0
  240. package/dist/op/op-waves-soak.js +111 -0
  241. package/dist/op/op-waves-split.d.ts +4 -0
  242. package/dist/op/op-waves-split.js +4 -0
  243. package/dist/op/op-waves.d.ts +67 -4
  244. package/dist/op/op-waves.js +71 -3
  245. package/dist/pipeline/agent-ajv.d.ts +4 -0
  246. package/dist/pipeline/agent-ajv.js +14 -0
  247. package/dist/pipeline/agent-steps.d.ts +329 -0
  248. package/dist/pipeline/agent-steps.js +602 -0
  249. package/dist/pipeline/artifacts.d.ts +264 -0
  250. package/dist/pipeline/artifacts.js +425 -0
  251. package/dist/pipeline/diff.d.ts +45 -0
  252. package/dist/pipeline/diff.js +177 -0
  253. package/dist/pipeline/fold.d.ts +43 -0
  254. package/dist/pipeline/fold.js +140 -0
  255. package/dist/pipeline/generate.d.ts +52 -0
  256. package/dist/pipeline/generate.js +120 -0
  257. package/dist/pipeline/product.d.ts +225 -0
  258. package/dist/pipeline/product.js +257 -0
  259. package/dist/pipeline/promote.d.ts +404 -0
  260. package/dist/pipeline/promote.js +694 -0
  261. package/dist/pipeline/read.d.ts +37 -0
  262. package/dist/pipeline/read.js +58 -0
  263. package/dist/pipeline/rendered.d.ts +25 -0
  264. package/dist/pipeline/rendered.js +53 -0
  265. package/dist/pipeline/soak-checks.d.ts +80 -0
  266. package/dist/pipeline/soak-checks.js +254 -0
  267. package/dist/pipeline/soak-gate.d.ts +97 -0
  268. package/dist/pipeline/soak-gate.js +176 -0
  269. package/dist/pipeline/soak-sources.d.ts +17 -0
  270. package/dist/pipeline/soak-sources.js +42 -0
  271. package/dist/pipeline/soak.d.ts +260 -0
  272. package/dist/pipeline/soak.js +378 -0
  273. package/dist/pipeline/spec.d.ts +724 -0
  274. package/dist/pipeline/spec.js +567 -0
  275. package/dist/pipeline/stage-ledger.d.ts +187 -0
  276. package/dist/pipeline/stage-ledger.js +185 -0
  277. package/dist/pipeline/stage-waves.d.ts +114 -0
  278. package/dist/pipeline/stage-waves.js +161 -0
  279. package/dist/pipeline/stages.d.ts +64 -0
  280. package/dist/pipeline/stages.js +174 -0
  281. package/dist/pipeline/verify-rollback.d.ts +277 -0
  282. package/dist/pipeline/verify-rollback.js +393 -0
  283. package/dist/pipeline.d.ts +142 -0
  284. package/dist/pipeline.js +143 -0
  285. package/dist/pr-loop.d.ts +22 -0
  286. package/dist/pr-loop.js +8 -0
  287. package/dist/pr-plan-note.d.ts +15 -1
  288. package/dist/pr-plan-note.js +8 -0
  289. package/dist/pr-post.d.ts +31 -0
  290. package/dist/pr-post.js +89 -0
  291. package/dist/release-floors.d.ts +1 -1
  292. package/dist/release-floors.js +1 -1
  293. package/dist/report-store/audit.schema.json +50 -0
  294. package/dist/report-store/dora.schema.json +331 -0
  295. package/dist/report-store/estate.schema.json +96 -0
  296. package/dist/report-store/run.schema.json +14 -0
  297. package/dist/report-store.d.ts +151 -0
  298. package/dist/report-store.js +344 -0
  299. package/dist/run-event.d.ts +7 -2
  300. package/dist/wave-runtime.mjs +458 -404
  301. package/dist/workspace/catalog-edges.js +3 -3
  302. package/dist/workspace/change-set.schema.json +4 -0
  303. package/dist/workspace/ci-cloud-identity.d.ts +4 -0
  304. package/dist/workspace/ci-cloud-identity.js +30 -0
  305. package/dist/workspace/ci-run.js +17 -2
  306. package/dist/workspace/ci-secrets.d.ts +3 -1
  307. package/dist/workspace/ci-secrets.js +7 -1
  308. package/dist/workspace/compose-graph.d.ts +1 -1
  309. package/dist/workspace/compose-graph.js +3 -1
  310. package/dist/workspace/declaration.d.ts +27 -0
  311. package/dist/workspace/declaration.js +35 -0
  312. package/dist/workspace/declaration.schema.json +56 -0
  313. package/dist/workspace/graph-cli.js +26 -0
  314. package/dist/workspace/graph.schema.json +5 -1
  315. package/dist/workspace/identity-gate-rule.d.ts +4 -0
  316. package/dist/workspace/identity-gate-rule.js +2 -2
  317. package/dist/workspace/identity-reject-rule.d.ts +14 -0
  318. package/dist/workspace/identity-reject-rule.js +24 -0
  319. package/dist/workspace/identity.d.ts +3 -0
  320. package/dist/workspace/identity.js +2 -1
  321. package/dist/workspace/nested-graph.js +2 -0
  322. package/dist/workspace/pr-report.schema.json +65 -0
  323. package/dist/workspace/promotion-order.d.ts +19 -4
  324. package/dist/workspace/promotion-order.js +26 -4
  325. package/dist/workspace/release-train.d.ts +14 -0
  326. package/dist/workspace/release-train.js +32 -0
  327. package/dist/workspace/run-event.schema.json +2 -2
  328. package/dist/workspace/stack-read-edges.d.ts +19 -0
  329. package/dist/workspace/stack-read-edges.js +54 -0
  330. package/dist/workspace/status-gates.d.ts +51 -1
  331. package/dist/workspace/status-gates.js +60 -0
  332. package/dist/workspace/status-stages.d.ts +223 -0
  333. package/dist/workspace/status-stages.js +279 -0
  334. package/dist/workspace/status.d.ts +45 -1
  335. package/dist/workspace/status.js +109 -5
  336. package/dist/workspace/status.schema.json +283 -2
  337. package/dist/workspace/train-cut.js +5 -2
  338. package/dist/workspace/train-shell.d.ts +18 -0
  339. package/dist/workspace/train-shell.js +43 -0
  340. package/dist/workspace/trust/seal.d.ts +7 -0
  341. package/dist/workspace/trust/seal.js +9 -0
  342. package/package.json +5 -1
@@ -0,0 +1,188 @@
1
+ /**
2
+ * The cost estimate of a plan (#5334): a command the user names, run once
3
+ * per member over the plan document its capability wrote, read in one of
4
+ * two shapes, and summed. The same record serves the plan note
5
+ * (`PrReport.cost`, `PrPlanNote.cost`), a policy's `input.cost`, and a
6
+ * wave's cost hold (`holds.cost`, `./op/op-waves-capability.ts`).
7
+ *
8
+ * Both engines hand the command the same thing: `terraform-apply`'s plan
9
+ * names its `show -json` as `artifact.planJson`, and `pulumi-up`'s names
10
+ * its preview JSON there (#5341). `{planJson}` in the command is that
11
+ * file, `{target}` the member and `{plan}` the plan file when the step
12
+ * names one. The presets are the terraform lexicon's `terraformCostHold`
13
+ * (infracost) and the pulumi lexicon's `pulumiCostHold` (a command of the
14
+ * user's).
15
+ *
16
+ * The estimate informs and adds approvals; it never removes one. With
17
+ * `approveAbove` set, a plan whose monthly change is over it, or with a
18
+ * member that could not be priced, is `over`, and the pull request's apply
19
+ * then needs an approval of its own digest, as a policy hold asks. Nothing
20
+ * here lets a plan apply without a person. A failed estimate never fails
21
+ * the plan. It is off until `ci.cost` (or `holds.cost`) is set.
22
+ *
23
+ * The command never sees what the plan keeps secret (#5416). Each plan
24
+ * document is copied with its sensitive values replaced (`redactPlanJson`),
25
+ * and `{planJson}` names the copy, which keeps the original's file name. The
26
+ * command runs with the forge tokens left out of its environment
27
+ * (`costEnv`), by name and by value. A product names more to remove with
28
+ * `redactEnv` (variables whose values are secret) and `dropEnv` (variables to
29
+ * leave out), on an op wave's `holds.cost` and the pulumi and terraform
30
+ * presets: names only, so a secret's value never sits in the spec. Both hold for every caller: the plan
31
+ * note, a policy's `input.cost`, an op wave's `holds.cost` and the pulumi
32
+ * cost hold, so a product's `run wave` job needs no hook of its own.
33
+ *
34
+ * A run can have an environment of its own beside the job's (#5433): an op
35
+ * wave's run gets the `env` its product's `runHooks.beforePlan` gave it,
36
+ * where a product puts a value it reads per run, such as a root's secrets.
37
+ * `CostRun.env` carries it, and the names `redactEnv`, `dropEnv` and the
38
+ * forge tokens hold there are redacted and dropped as the job's are. The
39
+ * command still runs with the job's environment, never the run's.
40
+ *
41
+ * The module imports only node built-ins and `./forge-token-vars`'s token names,
42
+ * so the pull-request loop's bundle carries it (`pr-loop-bundle.test.ts`).
43
+ */
44
+ /** The estimate shapes the command may print. */
45
+ export declare const COST_ESTIMATE_FORMATS: readonly ["infracost", "chant"];
46
+ export type CostEstimateFormat = (typeof COST_ESTIMATE_FORMATS)[number];
47
+ /**
48
+ * `ci.cost` in the workspace declaration (#5334), read at base: the same
49
+ * fields as a wave's `holds.cost`, with `approveAbove` optional.
50
+ */
51
+ export interface CostEstimateSettings {
52
+ /** Argv, run once per member that changes something, with `{planJson}`, `{target}` and `{plan}` filled in. It prints the estimate on standard output. */
53
+ command: string[];
54
+ /** `infracost`: `infracost breakdown --format json`'s document. `chant`: `{ "monthlyDelta": <number>, "monthlyTotal"?, "pastMonthlyTotal"?, "currency"? }`. Default `infracost`. */
55
+ format?: CostEstimateFormat;
56
+ /** The currency the amounts are in. Default the estimate's, else `USD`. */
57
+ currency?: string;
58
+ /** The monthly change above which the plan needs an approval of its own. Absent: the estimate only informs. */
59
+ approveAbove?: number;
60
+ }
61
+ /** What is wrong with a `ci.cost` (or `holds.cost`) value, empty when nothing is. `where` names it; `approveAbove` is required when `requireAmount` is set. */
62
+ export declare function costEstimateProblems(where: string, value: unknown, requireAmount?: boolean): string[];
63
+ /** What one estimate printed: the monthly change, and the totals when it gave them. */
64
+ export interface CostFigures {
65
+ monthlyDelta: number;
66
+ /** The monthly cost once the plan applies. */
67
+ monthlyTotal?: number;
68
+ /** The monthly cost before it. */
69
+ pastMonthlyTotal?: number;
70
+ currency?: string;
71
+ }
72
+ /** One member's estimate, or why it has none. */
73
+ export type MemberCost = ({
74
+ member: string;
75
+ } & CostFigures) | {
76
+ member: string;
77
+ error: string;
78
+ };
79
+ /**
80
+ * A plan's cost estimate (#5334): each member that changes something, the
81
+ * sum of their monthly change, and whether it is over `approveAbove`. What
82
+ * the note shows, and what a policy reads as `input.cost`.
83
+ */
84
+ export interface CostEstimate {
85
+ /** The command's first word, such as `infracost`. */
86
+ estimator: string;
87
+ format: CostEstimateFormat;
88
+ currency: string;
89
+ /** The monthly change summed over the members priced. */
90
+ monthlyDelta: number;
91
+ /** The totals summed, when every member priced gave them. */
92
+ monthlyTotal?: number;
93
+ pastMonthlyTotal?: number;
94
+ /** Each member priced or not, in plan order. */
95
+ members: MemberCost[];
96
+ /** The members with no estimate, sorted. */
97
+ unestimated: string[];
98
+ /** The setting at base, or null when unset. */
99
+ approveAbove: number | null;
100
+ /** With `approveAbove`: the change is over it, or a member has no estimate, so the plan needs an approval of its own. Always false without it. */
101
+ over: boolean;
102
+ }
103
+ /** `input.cost`: the plan's (or the wave's) estimate, and with a per-member policy run, that member's own. */
104
+ export interface PolicyCost extends CostEstimate {
105
+ /** The member the policy run is over, when it runs per member (a wave's `holds.policy`). */
106
+ member?: MemberCost;
107
+ }
108
+ /** The figures an estimate gives, in `format`. Throws when it gives no monthly change. */
109
+ export declare function readCostEstimate(format: CostEstimateFormat, stdout: string): CostFigures;
110
+ /** The engine's plan document a capability's artifact names (`artifact.planJson`), when it names one that exists. */
111
+ export declare function planJsonOf(artifact: unknown, cwd: string): string | undefined;
112
+ /** How the estimate command ran. `status` is null when it did not start. */
113
+ export type CostEstimateExec = (argv: string[], cwd: string, env?: NodeJS.ProcessEnv) => {
114
+ status: number | null;
115
+ stdout: string;
116
+ stderr: string;
117
+ };
118
+ /**
119
+ * What a product names for the cost command to lose, as names only: a
120
+ * secret's value reaches the job through a variable (the environment set's
121
+ * `secrets`, #5348, or a variable the job reads), so the spec holds the
122
+ * variable's name and the value is read from the job's environment when the
123
+ * estimate runs.
124
+ */
125
+ export interface CostEnvOptions {
126
+ /** Variables whose values are secret: each value is replaced by `[redacted]` in the plan copy, and the variable is left out of the command's environment, by name and by value. */
127
+ redactEnv?: readonly string[];
128
+ /** Variables left out of the command's environment, by name and by value, beside the forge tokens. A value they hold is replaced by `[redacted]` in the plan copy too. */
129
+ dropEnv?: readonly string[];
130
+ }
131
+ /**
132
+ * `env` as the estimate command gets it (#5416): less every forge token, by
133
+ * name (`FORGE_TOKEN_VARS`) and by value, so a variable another name holds a
134
+ * token in goes too. Any other variable is kept. With `runEnv`, a run's own
135
+ * environment (#5433), the values it holds under those names go by value too.
136
+ */
137
+ export declare function costEnv(env: NodeJS.ProcessEnv, extra?: CostEnvOptions, runEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
138
+ /** What stands where a sensitive value was (#5416). */
139
+ export declare const COST_REDACTED = "[redacted]";
140
+ /**
141
+ * A plan document with every sensitive value replaced by `COST_REDACTED`
142
+ * (#5416). It reads what terraform and OpenTofu mark (`before_sensitive`,
143
+ * `after_sensitive`, `sensitive_values`, a sensitive output) and what Pulumi
144
+ * wraps as a secret, then replaces each value it covered wherever else the
145
+ * document repeats it (a binary does not mark every copy), and the values of
146
+ * `extra`, such as the forge tokens the environment holds. The input is not
147
+ * changed.
148
+ */
149
+ export declare function redactPlanJson(plan: unknown, extra?: readonly string[]): unknown;
150
+ /** A member to price: its capability's artifact, and whether its plan changes nothing. `plan` fills `{plan}` when given, else the artifact's `planFile`. */
151
+ export interface CostRun {
152
+ member: string;
153
+ artifact?: unknown;
154
+ empty: boolean;
155
+ plan?: string;
156
+ /**
157
+ * The run's own environment beside the job's (#5433), such as the `env` a
158
+ * product's `runHooks.beforePlan` gave an op wave's run. The values the
159
+ * forge tokens, `redactEnv` and `dropEnv` hold in it are redacted from the
160
+ * plan copy and dropped from the command's environment. The command does
161
+ * not run with it.
162
+ */
163
+ env?: NodeJS.ProcessEnv;
164
+ }
165
+ /**
166
+ * Run `settings.command` over each run that changes something (#4545, #5334).
167
+ * The command reads a redacted copy of the plan document and runs without
168
+ * the forge tokens (#5416), and with `redactEnv` and `dropEnv` also the
169
+ * values and variables a product names, read from the job's environment and
170
+ * the run's own (`CostRun.env`, #5433). A run with no estimate says why.
171
+ */
172
+ export declare function priceRuns(settings: Pick<CostEstimateSettings, "command" | "format"> & CostEnvOptions, runs: readonly CostRun[], cwd: string, exec?: CostEstimateExec): MemberCost[];
173
+ /** Sum the members' estimates into one record, against `approveAbove` when the settings give it. */
174
+ export declare function costEstimateOf(settings: CostEstimateSettings, members: readonly MemberCost[]): CostEstimate;
175
+ /** Price each run and sum them (#5334): {@link priceRuns}, then {@link costEstimateOf}. */
176
+ export declare function estimateCosts(settings: CostEstimateSettings, runs: readonly CostRun[], cwd: string, exec?: CostEstimateExec): CostEstimate;
177
+ /** `input.cost` for a policy run (#5334): the estimate, and with `member` that member's own figures. */
178
+ export declare function policyCost(estimate: CostEstimate, member?: string): PolicyCost;
179
+ /** An amount as the note shows it: `+12.50 USD`. */
180
+ export declare function signedAmount(n: number, currency: string): string;
181
+ /**
182
+ * The note's cost section (#5334): the plan's monthly change, a row per
183
+ * member, why a member has no estimate, and, with `approveAbove`, whether
184
+ * the plan needs an approval of its own. `noun` is the product's word for a
185
+ * member, such as `root` or `stack`. A product's plan note hands the record
186
+ * over as data, so each value is checked as it is written.
187
+ */
188
+ export declare function costEstimateLines(estimate: CostEstimate, noun?: string): string[];
@@ -0,0 +1,363 @@
1
+ /**
2
+ * The cost estimate of a plan (#5334): a command the user names, run once
3
+ * per member over the plan document its capability wrote, read in one of
4
+ * two shapes, and summed. The same record serves the plan note
5
+ * (`PrReport.cost`, `PrPlanNote.cost`), a policy's `input.cost`, and a
6
+ * wave's cost hold (`holds.cost`, `./op/op-waves-capability.ts`).
7
+ *
8
+ * Both engines hand the command the same thing: `terraform-apply`'s plan
9
+ * names its `show -json` as `artifact.planJson`, and `pulumi-up`'s names
10
+ * its preview JSON there (#5341). `{planJson}` in the command is that
11
+ * file, `{target}` the member and `{plan}` the plan file when the step
12
+ * names one. The presets are the terraform lexicon's `terraformCostHold`
13
+ * (infracost) and the pulumi lexicon's `pulumiCostHold` (a command of the
14
+ * user's).
15
+ *
16
+ * The estimate informs and adds approvals; it never removes one. With
17
+ * `approveAbove` set, a plan whose monthly change is over it, or with a
18
+ * member that could not be priced, is `over`, and the pull request's apply
19
+ * then needs an approval of its own digest, as a policy hold asks. Nothing
20
+ * here lets a plan apply without a person. A failed estimate never fails
21
+ * the plan. It is off until `ci.cost` (or `holds.cost`) is set.
22
+ *
23
+ * The command never sees what the plan keeps secret (#5416). Each plan
24
+ * document is copied with its sensitive values replaced (`redactPlanJson`),
25
+ * and `{planJson}` names the copy, which keeps the original's file name. The
26
+ * command runs with the forge tokens left out of its environment
27
+ * (`costEnv`), by name and by value. A product names more to remove with
28
+ * `redactEnv` (variables whose values are secret) and `dropEnv` (variables to
29
+ * leave out), on an op wave's `holds.cost` and the pulumi and terraform
30
+ * presets: names only, so a secret's value never sits in the spec. Both hold for every caller: the plan
31
+ * note, a policy's `input.cost`, an op wave's `holds.cost` and the pulumi
32
+ * cost hold, so a product's `run wave` job needs no hook of its own.
33
+ *
34
+ * A run can have an environment of its own beside the job's (#5433): an op
35
+ * wave's run gets the `env` its product's `runHooks.beforePlan` gave it,
36
+ * where a product puts a value it reads per run, such as a root's secrets.
37
+ * `CostRun.env` carries it, and the names `redactEnv`, `dropEnv` and the
38
+ * forge tokens hold there are redacted and dropped as the job's are. The
39
+ * command still runs with the job's environment, never the run's.
40
+ *
41
+ * The module imports only node built-ins and `./forge-token-vars`'s token names,
42
+ * so the pull-request loop's bundle carries it (`pr-loop-bundle.test.ts`).
43
+ */
44
+ import { spawnSync } from "node:child_process";
45
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
46
+ import { tmpdir } from "node:os";
47
+ import { basename, join } from "node:path";
48
+ import { FORGE_TOKEN_VARS } from "./forge-token-vars.js";
49
+ /** The estimate shapes the command may print. */
50
+ export const COST_ESTIMATE_FORMATS = ["infracost", "chant"];
51
+ /** What is wrong with a `ci.cost` (or `holds.cost`) value, empty when nothing is. `where` names it; `approveAbove` is required when `requireAmount` is set. */
52
+ export function costEstimateProblems(where, value, requireAmount = false) {
53
+ if (value === null || typeof value !== "object" || Array.isArray(value))
54
+ return [`\`${where}\` must be { "command": [...], "approveAbove"${requireAmount ? "" : "?"}: <number>, "format"?, "currency"? }`];
55
+ const c = value;
56
+ const problems = [];
57
+ if (!Array.isArray(c.command) || c.command.length === 0 || !c.command.every((a) => typeof a === "string" && a !== ""))
58
+ problems.push(`\`${where}.command\` must be argv, a non-empty list of strings`);
59
+ if ((requireAmount || c.approveAbove !== undefined) && (typeof c.approveAbove !== "number" || !Number.isFinite(c.approveAbove) || c.approveAbove < 0))
60
+ problems.push(`\`${where}.approveAbove\` must be a monthly amount of 0 or more`);
61
+ if (c.format !== undefined && !COST_ESTIMATE_FORMATS.includes(c.format))
62
+ problems.push(`\`${where}.format\` must be ${COST_ESTIMATE_FORMATS.join(" or ")}`);
63
+ if (c.currency !== undefined && (typeof c.currency !== "string" || !/^[A-Z]{3}$/.test(c.currency)))
64
+ problems.push(`\`${where}.currency\` must be a three-letter currency code, such as "USD"`);
65
+ for (const key of Object.keys(c))
66
+ if (!["command", "approveAbove", "format", "currency"].includes(key))
67
+ problems.push(`\`${where}.${key}\` is not a setting`);
68
+ return problems;
69
+ }
70
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v)) ? Number(v) : undefined);
71
+ /** The figures an estimate gives, in `format`. Throws when it gives no monthly change. */
72
+ export function readCostEstimate(format, stdout) {
73
+ const doc = JSON.parse(stdout);
74
+ if (doc === null || typeof doc !== "object" || Array.isArray(doc))
75
+ throw new Error("the estimate is not a JSON object");
76
+ const currency = typeof doc.currency === "string" ? { currency: doc.currency } : {};
77
+ if (format === "chant") {
78
+ const delta = num(doc.monthlyDelta);
79
+ if (delta === undefined)
80
+ throw new Error("the estimate has no monthlyDelta");
81
+ const total = num(doc.monthlyTotal);
82
+ const past = num(doc.pastMonthlyTotal);
83
+ return { monthlyDelta: delta, ...(total !== undefined ? { monthlyTotal: total } : {}), ...(past !== undefined ? { pastMonthlyTotal: past } : {}), ...currency };
84
+ }
85
+ // infracost breakdown --format json: diffTotalMonthlyCost, else totalMonthlyCost less pastTotalMonthlyCost.
86
+ const diff = num(doc.diffTotalMonthlyCost);
87
+ const total = num(doc.totalMonthlyCost);
88
+ const past = num(doc.pastTotalMonthlyCost);
89
+ const delta = diff ?? (total !== undefined ? total - (past ?? 0) : undefined);
90
+ if (delta === undefined)
91
+ throw new Error("the infracost document has no diffTotalMonthlyCost or totalMonthlyCost");
92
+ return { monthlyDelta: delta, ...(total !== undefined ? { monthlyTotal: total } : {}), ...(past !== undefined ? { pastMonthlyTotal: past } : {}), ...currency };
93
+ }
94
+ /** The engine's plan document a capability's artifact names (`artifact.planJson`), when it names one that exists. */
95
+ export function planJsonOf(artifact, cwd) {
96
+ const p = artifact?.planJson;
97
+ if (typeof p !== "string" || p === "")
98
+ return undefined;
99
+ const path = p.startsWith("/") ? p : join(cwd, p);
100
+ return existsSync(path) ? path : undefined;
101
+ }
102
+ /** The plan file a capability's artifact names (`planFile`), for `{plan}`. */
103
+ function planFileOf(artifact, cwd) {
104
+ const p = artifact?.planFile;
105
+ if (typeof p !== "string" || p === "")
106
+ return "";
107
+ return p.startsWith("/") ? p : join(cwd, p);
108
+ }
109
+ /**
110
+ * `env` as the estimate command gets it (#5416): less every forge token, by
111
+ * name (`FORGE_TOKEN_VARS`) and by value, so a variable another name holds a
112
+ * token in goes too. Any other variable is kept. With `runEnv`, a run's own
113
+ * environment (#5433), the values it holds under those names go by value too.
114
+ */
115
+ export function costEnv(env, extra = {}, runEnv) {
116
+ const names = new Set([...FORGE_TOKEN_VARS, ...(extra.redactEnv ?? []), ...(extra.dropEnv ?? [])]);
117
+ // #5433: a value a run's own environment holds under one of the names goes too, whichever variable of the job's holds it.
118
+ const held = new Set([...names].flatMap((name) => [env[name] ?? "", runEnv?.[name] ?? ""]).filter((v) => v !== ""));
119
+ const out = {};
120
+ for (const [name, value] of Object.entries(env)) {
121
+ if (names.has(name))
122
+ continue;
123
+ if (value !== undefined && held.has(value))
124
+ continue;
125
+ out[name] = value;
126
+ }
127
+ return out;
128
+ }
129
+ const defaultExec = (argv, cwd, env = costEnv(process.env)) => {
130
+ const r = spawnSync(argv[0], argv.slice(1), { cwd, env, encoding: "utf-8", maxBuffer: 64 * 1024 * 1024, timeout: 300000 });
131
+ return { status: r.error ? null : r.status, stdout: r.stdout ?? "", stderr: `${r.stderr ?? ""}${r.error ? r.error.message : ""}` };
132
+ };
133
+ /** What stands where a sensitive value was (#5416). */
134
+ export const COST_REDACTED = "[redacted]";
135
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
136
+ /** Replace what `mark` marks `true` in `value`; `mark` mirrors the value's shape, as terraform's `*_sensitive` does. */
137
+ function cover(value, mark) {
138
+ if (value === undefined)
139
+ return value;
140
+ if (mark === true)
141
+ return value === null ? null : COST_REDACTED;
142
+ if (Array.isArray(mark) && Array.isArray(value))
143
+ return value.map((v, i) => cover(v, mark[i]));
144
+ if (isObject(mark) && isObject(value)) {
145
+ const out = { ...value };
146
+ for (const k of Object.keys(mark))
147
+ if (k in out)
148
+ out[k] = cover(out[k], mark[k]);
149
+ return out;
150
+ }
151
+ return value;
152
+ }
153
+ /** Pulumi's secret wrapper: an object holding this key is a secret, and its other keys hold the value or its ciphertext. */
154
+ const PULUMI_SECRET_SIG = "4dabf18193072939515e22adb298388d";
155
+ /** Walk `plan`, covering each value a plan marks sensitive. */
156
+ function coverMarked(node) {
157
+ if (Array.isArray(node))
158
+ return node.map(coverMarked);
159
+ if (!isObject(node))
160
+ return node;
161
+ if (PULUMI_SECRET_SIG in node)
162
+ return COST_REDACTED;
163
+ const out = {};
164
+ for (const [k, v] of Object.entries(node))
165
+ out[k] = coverMarked(v);
166
+ // terraform: a change's before/after and a resource's values carry a sibling that marks what is sensitive.
167
+ for (const [value, mark] of [["before", "before_sensitive"], ["after", "after_sensitive"], ["values", "sensitive_values"]]) {
168
+ if (value in out && mark in node)
169
+ out[value] = cover(out[value], node[mark]);
170
+ }
171
+ // terraform: an output marked sensitive.
172
+ if (node.sensitive === true && "value" in out)
173
+ out.value = cover(out.value, true);
174
+ return out;
175
+ }
176
+ /** The string leaves of `raw` at each place `safe` holds the redaction mark. */
177
+ function coveredStrings(raw, safe, out) {
178
+ if (safe === COST_REDACTED) {
179
+ const leaves = (v) => {
180
+ if (typeof v === "string") {
181
+ if (v !== "" && v !== COST_REDACTED)
182
+ out.add(v);
183
+ }
184
+ else if (Array.isArray(v))
185
+ v.forEach(leaves);
186
+ else if (isObject(v))
187
+ Object.values(v).forEach(leaves);
188
+ };
189
+ leaves(raw);
190
+ }
191
+ else if (Array.isArray(raw) && Array.isArray(safe))
192
+ raw.forEach((r, i) => coveredStrings(r, safe[i], out));
193
+ else if (isObject(raw) && isObject(safe))
194
+ for (const k of Object.keys(raw))
195
+ if (k in safe)
196
+ coveredStrings(raw[k], safe[k], out);
197
+ }
198
+ /** `value` with each of `secrets` replaced where a string is one, and cut out of a longer string when it is eight characters or more. */
199
+ function scrub(value, secrets) {
200
+ if (typeof value === "string") {
201
+ if (secrets.includes(value))
202
+ return COST_REDACTED;
203
+ let text = value;
204
+ for (const secret of secrets)
205
+ if (secret.length >= 8)
206
+ text = text.split(secret).join(COST_REDACTED);
207
+ return text;
208
+ }
209
+ if (Array.isArray(value))
210
+ return value.map((v) => scrub(v, secrets));
211
+ if (isObject(value))
212
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, scrub(v, secrets)]));
213
+ return value;
214
+ }
215
+ /**
216
+ * A plan document with every sensitive value replaced by `COST_REDACTED`
217
+ * (#5416). It reads what terraform and OpenTofu mark (`before_sensitive`,
218
+ * `after_sensitive`, `sensitive_values`, a sensitive output) and what Pulumi
219
+ * wraps as a secret, then replaces each value it covered wherever else the
220
+ * document repeats it (a binary does not mark every copy), and the values of
221
+ * `extra`, such as the forge tokens the environment holds. The input is not
222
+ * changed.
223
+ */
224
+ export function redactPlanJson(plan, extra = []) {
225
+ const marked = coverMarked(plan);
226
+ const found = new Set(extra.filter((v) => v !== ""));
227
+ coveredStrings(plan, marked, found);
228
+ const secrets = [...found].sort((a, b) => b.length - a.length);
229
+ return secrets.length === 0 ? marked : scrub(marked, secrets);
230
+ }
231
+ /** The values of the forge tokens `env` holds, and of the variables `extra` names, in the job's environment and the run's own (#5433). */
232
+ function tokenValues(env, extra = {}, runEnv) {
233
+ return [...FORGE_TOKEN_VARS, ...(extra.redactEnv ?? []), ...(extra.dropEnv ?? [])].flatMap((name) => [env[name] ?? "", runEnv?.[name] ?? ""]).filter((v) => v !== "");
234
+ }
235
+ /**
236
+ * Run `settings.command` over each run that changes something (#4545, #5334).
237
+ * The command reads a redacted copy of the plan document and runs without
238
+ * the forge tokens (#5416), and with `redactEnv` and `dropEnv` also the
239
+ * values and variables a product names, read from the job's environment and
240
+ * the run's own (`CostRun.env`, #5433). A run with no estimate says why.
241
+ */
242
+ export function priceRuns(settings, runs, cwd, exec = defaultExec) {
243
+ const format = settings.format ?? "infracost";
244
+ const out = [];
245
+ let work;
246
+ try {
247
+ for (const run of runs) {
248
+ if (run.empty)
249
+ continue;
250
+ const original = planJsonOf(run.artifact, cwd);
251
+ if (settings.command.some((a) => a.includes("{planJson}")) && !original) {
252
+ out.push({ member: run.member, error: "its plan names no plan document to price" });
253
+ continue;
254
+ }
255
+ let planJson = original;
256
+ if (original) {
257
+ try {
258
+ const redacted = JSON.stringify(redactPlanJson(JSON.parse(readFileSync(original, "utf-8")), tokenValues(process.env, settings, run.env)));
259
+ // One directory per member, so two members' documents of one name never meet, and the copy keeps the name the estimator knows it by.
260
+ work ?? (work = mkdtempSync(join(tmpdir(), "chant-cost-")));
261
+ const dir = mkdtempSync(join(work, "m-"));
262
+ planJson = join(dir, basename(original));
263
+ writeFileSync(planJson, redacted, { mode: 0o600 });
264
+ }
265
+ catch (err) {
266
+ out.push({ member: run.member, error: `the plan document could not be read to redact it: ${err instanceof Error ? err.message : String(err)}` });
267
+ continue;
268
+ }
269
+ }
270
+ const plan = run.plan ?? planFileOf(run.artifact, cwd);
271
+ const argv = settings.command.map((a) => a.replaceAll("{target}", run.member).replaceAll("{plan}", plan).replaceAll("{planJson}", planJson ?? ""));
272
+ const r = exec(argv, cwd, costEnv(process.env, settings, run.env));
273
+ if (r.status !== 0) {
274
+ out.push({ member: run.member, error: `${argv[0]} ${r.status === null ? "did not run" : `exited ${r.status}`}: ${(r.stderr || r.stdout).trim().split("\n").slice(-2).join(" ")}` });
275
+ continue;
276
+ }
277
+ try {
278
+ out.push({ member: run.member, ...readCostEstimate(format, r.stdout) });
279
+ }
280
+ catch (err) {
281
+ out.push({ member: run.member, error: `the estimate cannot be read: ${err instanceof Error ? err.message : String(err)}` });
282
+ }
283
+ }
284
+ }
285
+ finally {
286
+ if (work)
287
+ rmSync(work, { recursive: true, force: true });
288
+ }
289
+ return out;
290
+ }
291
+ const cents = (n) => Math.round(n * 100) / 100;
292
+ /** Sum the members' estimates into one record, against `approveAbove` when the settings give it. */
293
+ export function costEstimateOf(settings, members) {
294
+ const priced = members.filter((c) => "monthlyDelta" in c);
295
+ const unestimated = members.filter((c) => "error" in c).map((c) => c.member).sort();
296
+ const monthlyDelta = cents(priced.reduce((sum, c) => sum + c.monthlyDelta, 0));
297
+ const totals = priced.length > 0 && priced.every((c) => c.monthlyTotal !== undefined);
298
+ const pasts = priced.length > 0 && priced.every((c) => c.pastMonthlyTotal !== undefined);
299
+ const approveAbove = settings.approveAbove ?? null;
300
+ return {
301
+ estimator: settings.command[0] ?? "",
302
+ format: settings.format ?? "infracost",
303
+ currency: settings.currency ?? priced.find((c) => c.currency)?.currency ?? "USD",
304
+ monthlyDelta,
305
+ ...(totals ? { monthlyTotal: cents(priced.reduce((s, c) => s + c.monthlyTotal, 0)) } : {}),
306
+ ...(pasts ? { pastMonthlyTotal: cents(priced.reduce((s, c) => s + c.pastMonthlyTotal, 0)) } : {}),
307
+ members: [...members],
308
+ unestimated,
309
+ approveAbove,
310
+ over: approveAbove !== null && (monthlyDelta > approveAbove || unestimated.length > 0),
311
+ };
312
+ }
313
+ /** Price each run and sum them (#5334): {@link priceRuns}, then {@link costEstimateOf}. */
314
+ export function estimateCosts(settings, runs, cwd, exec) {
315
+ return costEstimateOf(settings, priceRuns(settings, runs, cwd, exec));
316
+ }
317
+ /** `input.cost` for a policy run (#5334): the estimate, and with `member` that member's own figures. */
318
+ export function policyCost(estimate, member) {
319
+ const own = member === undefined ? undefined : estimate.members.find((m) => m.member === member);
320
+ return { ...estimate, members: estimate.members.map((m) => ({ ...m })), unestimated: [...estimate.unestimated], ...(own ? { member: { ...own } } : {}) };
321
+ }
322
+ /** An amount as the note shows it: `+12.50 USD`. */
323
+ export function signedAmount(n, currency) {
324
+ if (typeof n !== "number" || !Number.isFinite(n))
325
+ return `? ${currency}`;
326
+ return `${n >= 0 ? "+" : "-"}${Math.abs(n).toFixed(2)} ${currency}`;
327
+ }
328
+ const code = (s) => "`" + String(s).replaceAll("`", "'") + "`";
329
+ const plain = (s) => String(s).split(/\s+/).join(" ").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("|", "\\|");
330
+ const amount = (n, currency) => (typeof n === "number" && Number.isFinite(n) ? `${n.toFixed(2)} ${currency}` : "");
331
+ /**
332
+ * The note's cost section (#5334): the plan's monthly change, a row per
333
+ * member, why a member has no estimate, and, with `approveAbove`, whether
334
+ * the plan needs an approval of its own. `noun` is the product's word for a
335
+ * member, such as `root` or `stack`. A product's plan note hands the record
336
+ * over as data, so each value is checked as it is written.
337
+ */
338
+ export function costEstimateLines(estimate, noun = "member") {
339
+ const c = plain(estimate.currency ?? "USD");
340
+ const members = (Array.isArray(estimate.members) ? estimate.members : []).filter((m) => typeof m === "object" && m !== null);
341
+ const total = amount(estimate.monthlyTotal, c);
342
+ const out = ["", `**Cost (${code(estimate.estimator)}):** ${signedAmount(estimate.monthlyDelta, c)} a month${total ? `, ${total} a month once it applies` : ""}.`];
343
+ if (members.length > 0) {
344
+ out.push("", `| ${noun.charAt(0).toUpperCase()}${noun.slice(1)} | Monthly change | Monthly total |`, "|---|---:|---:|");
345
+ for (const m of members) {
346
+ const mc = typeof m.currency === "string" ? plain(m.currency) : c;
347
+ if ("error" in m)
348
+ out.push(`| ${code(m.member)} | not estimated | |`);
349
+ else
350
+ out.push(`| ${code(m.member)} | ${signedAmount(m.monthlyDelta, mc)} | ${amount(m.monthlyTotal, mc)} |`);
351
+ }
352
+ }
353
+ const failed = members.filter((m) => "error" in m);
354
+ if (failed.length > 0)
355
+ out.push("", ...failed.map((m) => `- ${code(m.member)} was not estimated: ${plain(m.error)}`));
356
+ if (typeof estimate.approveAbove === "number") {
357
+ const limit = amount(estimate.approveAbove, c);
358
+ out.push("", estimate.over === true
359
+ ? `The monthly change is over ${limit}${failed.length > 0 ? ", or cannot be known in full" : ""}, so this plan needs an approval of its own digest.`
360
+ : `The monthly change is within ${limit}.`);
361
+ }
362
+ return out;
363
+ }
@@ -71,6 +71,7 @@ import type { DeepDiffResult } from "./lifecycle/deep-diff.js";
71
71
  import type { LiveDiffResult } from "./lifecycle/live-diff.js";
72
72
  import type { ComponentStatusRow } from "./lifecycle/status.js";
73
73
  import { type UnobservedReason } from "./observation.js";
74
+ import type { EngineFacts } from "./engine-facts.js";
74
75
  /** The schema a drift document names in `$schema`. */
75
76
  export declare const DRIFT_SCHEMA_ID = "https://intentius.io/chant/schemas/workspace/drift/v1/drift.schema.json";
76
77
  /** The document's version. */
@@ -126,6 +127,41 @@ export declare const DRIFT_OWNERSHIP_VERDICTS: readonly DriftOwnershipVerdict[];
126
127
  export type DriftOwnershipBy = "marker" | "derived" | "record" | "cache" | "state" | "label";
127
128
  /** Every ownership basis. */
128
129
  export declare const DRIFT_OWNERSHIP_BY: readonly DriftOwnershipBy[];
130
+ /**
131
+ * The graph's ownership words (#4520): `facts.ownership` on a graph node, as
132
+ * choudoufu's `live-graph` and plunge's `graph --json` print it, and as
133
+ * `graph.schema.json` lists it.
134
+ */
135
+ export type EngineOwnership = NonNullable<EngineFacts["ownership"]>;
136
+ /**
137
+ * The one mapping between the two ownership vocabularies (#5333). A drift
138
+ * record keeps its own words in `ownership.verdict`; a graph node keeps the
139
+ * engine's in `facts.ownership`. Each verdict reads as one graph word:
140
+ *
141
+ * | drift verdict | `facts.ownership` | why |
142
+ * |---|---|---|
143
+ * | `owned` | `bound` | the member's marker, record or state holds it |
144
+ * | `foreign` | `foreign` | someone else holds it |
145
+ * | `adoptable` | `unowned` | nobody's marker is on it, and this member could adopt it |
146
+ * | `unknown` | none | the read could not say; the graph leaves the fact out |
147
+ *
148
+ * The graph's fourth word, `pending`, is no verdict: a drift record says it
149
+ * with `status: "pending"` and no `ownership` ({@link engineOwnershipOfDrift}).
150
+ */
151
+ export declare const DRIFT_VERDICT_ENGINE_OWNERSHIP: Readonly<Record<DriftOwnershipVerdict, EngineOwnership | null>>;
152
+ /**
153
+ * A drift record's ownership in the graph's words: its verdict through
154
+ * {@link DRIFT_VERDICT_ENGINE_OWNERSHIP}, or `pending` for a `pending` record
155
+ * with no verdict. Undefined when the record says nothing the graph has a
156
+ * word for.
157
+ */
158
+ export declare function engineOwnershipOfDrift(record: Pick<DriftRecord, "status" | "ownership">): EngineOwnership | undefined;
159
+ /**
160
+ * A graph node's `facts.ownership` as a drift verdict, the inverse of
161
+ * {@link DRIFT_VERDICT_ENGINE_OWNERSHIP}. `pending` has none: the drift
162
+ * record for it is `status: "pending"` with no `ownership`.
163
+ */
164
+ export declare function driftVerdictOfEngineOwnership(ownership: EngineOwnership): DriftOwnershipVerdict | undefined;
129
165
  /**
130
166
  * One attribute that differs. `before` is what was expected (the record, the
131
167
  * snapshot, the declaration) and `after` what the read found. A path in the
@@ -114,6 +114,50 @@ export const DRIFT_OWNERSHIP_VERDICTS = Object.keys(OWNERSHIP_VERDICT_WITNESS);
114
114
  const OWNERSHIP_BY_WITNESS = { marker: true, derived: true, record: true, cache: true, state: true, label: true };
115
115
  /** Every ownership basis. */
116
116
  export const DRIFT_OWNERSHIP_BY = Object.keys(OWNERSHIP_BY_WITNESS);
117
+ /**
118
+ * The one mapping between the two ownership vocabularies (#5333). A drift
119
+ * record keeps its own words in `ownership.verdict`; a graph node keeps the
120
+ * engine's in `facts.ownership`. Each verdict reads as one graph word:
121
+ *
122
+ * | drift verdict | `facts.ownership` | why |
123
+ * |---|---|---|
124
+ * | `owned` | `bound` | the member's marker, record or state holds it |
125
+ * | `foreign` | `foreign` | someone else holds it |
126
+ * | `adoptable` | `unowned` | nobody's marker is on it, and this member could adopt it |
127
+ * | `unknown` | none | the read could not say; the graph leaves the fact out |
128
+ *
129
+ * The graph's fourth word, `pending`, is no verdict: a drift record says it
130
+ * with `status: "pending"` and no `ownership` ({@link engineOwnershipOfDrift}).
131
+ */
132
+ export const DRIFT_VERDICT_ENGINE_OWNERSHIP = {
133
+ owned: "bound",
134
+ foreign: "foreign",
135
+ adoptable: "unowned",
136
+ unknown: null,
137
+ };
138
+ /**
139
+ * A drift record's ownership in the graph's words: its verdict through
140
+ * {@link DRIFT_VERDICT_ENGINE_OWNERSHIP}, or `pending` for a `pending` record
141
+ * with no verdict. Undefined when the record says nothing the graph has a
142
+ * word for.
143
+ */
144
+ export function engineOwnershipOfDrift(record) {
145
+ if (record.ownership)
146
+ return DRIFT_VERDICT_ENGINE_OWNERSHIP[record.ownership.verdict] ?? undefined;
147
+ return record.status === "pending" ? "pending" : undefined;
148
+ }
149
+ /**
150
+ * A graph node's `facts.ownership` as a drift verdict, the inverse of
151
+ * {@link DRIFT_VERDICT_ENGINE_OWNERSHIP}. `pending` has none: the drift
152
+ * record for it is `status: "pending"` with no `ownership`.
153
+ */
154
+ export function driftVerdictOfEngineOwnership(ownership) {
155
+ for (const verdict of DRIFT_OWNERSHIP_VERDICTS) {
156
+ if (DRIFT_VERDICT_ENGINE_OWNERSHIP[verdict] === ownership)
157
+ return verdict;
158
+ }
159
+ return undefined;
160
+ }
117
161
  /** A record {@link driftRecord} refused, naming the record and the rule. */
118
162
  export class DriftRecordError extends Error {
119
163
  constructor(rule, message) {