@intentius/chant 0.124.76 → 0.124.78

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 (212) hide show
  1. package/dist/__fixtures__/agent-guard/plywood.d.ts +8 -0
  2. package/dist/__fixtures__/agent-guard/plywood.d.ts.map +1 -0
  3. package/dist/__fixtures__/agent-guard/plywood.js +19 -0
  4. package/dist/__fixtures__/agent-guard/terragucci.d.ts +8 -0
  5. package/dist/__fixtures__/agent-guard/terragucci.d.ts.map +1 -0
  6. package/dist/__fixtures__/agent-guard/terragucci.js +30 -0
  7. package/dist/__fixtures__/gated-ledger.d.ts +10 -0
  8. package/dist/__fixtures__/gated-ledger.d.ts.map +1 -0
  9. package/dist/__fixtures__/gated-ledger.js +51 -0
  10. package/dist/__fixtures__/notify-messages/events.d.ts +9 -0
  11. package/dist/__fixtures__/notify-messages/events.d.ts.map +1 -0
  12. package/dist/__fixtures__/notify-messages/events.js +21 -0
  13. package/dist/__fixtures__/product-words.d.ts +14 -0
  14. package/dist/__fixtures__/product-words.d.ts.map +1 -1
  15. package/dist/__fixtures__/product-words.js +11 -0
  16. package/dist/__fixtures__/terragucci-notify.d.ts +66 -0
  17. package/dist/__fixtures__/terragucci-notify.d.ts.map +1 -0
  18. package/dist/__fixtures__/terragucci-notify.js +133 -0
  19. package/dist/action-pins.d.ts +8 -0
  20. package/dist/action-pins.d.ts.map +1 -1
  21. package/dist/action-pins.js +9 -0
  22. package/dist/agent-guard.d.ts +143 -0
  23. package/dist/agent-guard.d.ts.map +1 -0
  24. package/dist/agent-guard.js +455 -0
  25. package/dist/ci-commit.d.ts +120 -5
  26. package/dist/ci-commit.d.ts.map +1 -1
  27. package/dist/ci-commit.js +214 -23
  28. package/dist/ci-own-jobs.d.ts +81 -0
  29. package/dist/ci-own-jobs.d.ts.map +1 -0
  30. package/dist/ci-own-jobs.js +233 -0
  31. package/dist/ci-product-words.d.ts +18 -4
  32. package/dist/ci-product-words.d.ts.map +1 -1
  33. package/dist/ci-product-words.js +26 -6
  34. package/dist/ci-product.d.ts +40 -1
  35. package/dist/ci-product.d.ts.map +1 -1
  36. package/dist/ci-product.js +40 -1
  37. package/dist/cli/handlers/approve.d.ts +5 -1
  38. package/dist/cli/handlers/approve.d.ts.map +1 -1
  39. package/dist/cli/handlers/approve.js +17 -11
  40. package/dist/cli/handlers/build.d.ts +1 -1
  41. package/dist/cli/handlers/build.d.ts.map +1 -1
  42. package/dist/cli/handlers/build.js +88 -2
  43. package/dist/cli/handlers/commit.d.ts.map +1 -1
  44. package/dist/cli/handlers/commit.js +3 -1
  45. package/dist/cli/handlers/notify-relay.d.ts +18 -1
  46. package/dist/cli/handlers/notify-relay.d.ts.map +1 -1
  47. package/dist/cli/handlers/notify-relay.js +90 -14
  48. package/dist/cli/handlers/pr.d.ts.map +1 -1
  49. package/dist/cli/handlers/pr.js +3 -1
  50. package/dist/cli/handlers/release.d.ts +5 -1
  51. package/dist/cli/handlers/release.d.ts.map +1 -1
  52. package/dist/cli/handlers/release.js +21 -9
  53. package/dist/cli/handlers/run-generate.d.ts.map +1 -1
  54. package/dist/cli/handlers/run-generate.js +2 -1
  55. package/dist/cli/main.d.ts.map +1 -1
  56. package/dist/cli/main.js +21 -1
  57. package/dist/cli/parse-args.d.ts.map +1 -1
  58. package/dist/cli/parse-args.js +60 -4
  59. package/dist/cli/registry.d.ts +16 -0
  60. package/dist/cli/registry.d.ts.map +1 -1
  61. package/dist/components/pr-env-components.d.ts +65 -0
  62. package/dist/components/pr-env-components.d.ts.map +1 -0
  63. package/dist/components/pr-env-components.js +162 -0
  64. package/dist/components/pr-policy.d.ts +15 -0
  65. package/dist/components/pr-policy.d.ts.map +1 -1
  66. package/dist/components/pr-policy.js +24 -1
  67. package/dist/components/release-compile.d.ts +15 -3
  68. package/dist/components/release-compile.d.ts.map +1 -1
  69. package/dist/components/release-compile.js +66 -15
  70. package/dist/config.d.ts +14 -8
  71. package/dist/config.d.ts.map +1 -1
  72. package/dist/config.js +16 -1
  73. package/dist/gate-policy.d.ts +14 -1
  74. package/dist/gate-policy.d.ts.map +1 -1
  75. package/dist/gate-policy.js +16 -6
  76. package/dist/lexicon.d.ts +25 -1
  77. package/dist/lexicon.d.ts.map +1 -1
  78. package/dist/lexicon.js +10 -0
  79. package/dist/lifecycle/gated-op.d.ts +95 -0
  80. package/dist/lifecycle/gated-op.d.ts.map +1 -0
  81. package/dist/lifecycle/gated-op.js +96 -0
  82. package/dist/lifecycle/git.d.ts.map +1 -1
  83. package/dist/lifecycle/git.js +83 -2
  84. package/dist/lifecycle/release-images.d.ts +77 -3
  85. package/dist/lifecycle/release-images.d.ts.map +1 -1
  86. package/dist/lifecycle/release-images.js +132 -6
  87. package/dist/notify-product.d.ts +11 -2
  88. package/dist/notify-product.d.ts.map +1 -1
  89. package/dist/notify-product.js +16 -4
  90. package/dist/notify-relay-repo.d.ts +131 -0
  91. package/dist/notify-relay-repo.d.ts.map +1 -0
  92. package/dist/notify-relay-repo.js +202 -0
  93. package/dist/notify-relay.d.ts +25 -1
  94. package/dist/notify-relay.d.ts.map +1 -1
  95. package/dist/notify-relay.js +27 -2
  96. package/dist/notify.d.ts +36 -4
  97. package/dist/notify.d.ts.map +1 -1
  98. package/dist/notify.js +31 -21
  99. package/dist/notify.schema.json +1 -0
  100. package/dist/op/activities/review-product.d.ts +111 -0
  101. package/dist/op/activities/review-product.d.ts.map +1 -0
  102. package/dist/op/activities/review-product.js +116 -0
  103. package/dist/op/op-waves-capability.js +2 -2
  104. package/dist/policy-engine.d.ts +95 -0
  105. package/dist/policy-engine.d.ts.map +1 -0
  106. package/dist/policy-engine.js +157 -0
  107. package/dist/pr-forge-reads.d.ts +124 -0
  108. package/dist/pr-forge-reads.d.ts.map +1 -0
  109. package/dist/pr-forge-reads.js +322 -0
  110. package/dist/pr-forge.d.ts +14 -0
  111. package/dist/pr-forge.d.ts.map +1 -1
  112. package/dist/pr-forge.js +21 -13
  113. package/dist/pr-plan-note.d.ts +293 -0
  114. package/dist/pr-plan-note.d.ts.map +1 -0
  115. package/dist/pr-plan-note.js +362 -0
  116. package/dist/release-floors.d.ts +9 -1
  117. package/dist/release-floors.d.ts.map +1 -1
  118. package/dist/release-floors.js +9 -1
  119. package/dist/state-export.d.ts +126 -0
  120. package/dist/state-export.d.ts.map +1 -0
  121. package/dist/state-export.js +156 -0
  122. package/dist/state-migration.d.ts +148 -0
  123. package/dist/state-migration.d.ts.map +1 -0
  124. package/dist/state-migration.js +146 -0
  125. package/dist/state-unlock.d.ts +167 -0
  126. package/dist/state-unlock.d.ts.map +1 -0
  127. package/dist/state-unlock.js +196 -0
  128. package/dist/wave-runtime.mjs +332 -332
  129. package/dist/workspace/declaration.schema.json +1 -1
  130. package/dist/workspace/release-workflow.d.ts +10 -0
  131. package/dist/workspace/release-workflow.d.ts.map +1 -1
  132. package/dist/workspace/release-workflow.js +10 -4
  133. package/package.json +1 -1
  134. package/src/__fixtures__/agent-guard/plywood.ts +27 -0
  135. package/src/__fixtures__/agent-guard/terragucci.ts +39 -0
  136. package/src/__fixtures__/gated-ledger.ts +58 -0
  137. package/src/__fixtures__/notify-messages/events.ts +23 -0
  138. package/src/__fixtures__/notify-messages/messages.json +50 -0
  139. package/src/__fixtures__/pr-loop/terragucci-plan.note.golden.md +53 -0
  140. package/src/__fixtures__/pr-loop/terragucci-plan.note.json +83 -0
  141. package/src/__fixtures__/product-words.ts +12 -0
  142. package/src/__fixtures__/review-agent/terragucci-review.json +94 -0
  143. package/src/__fixtures__/terragucci-notify.ts +170 -0
  144. package/src/action-pins.test.ts +12 -1
  145. package/src/action-pins.ts +11 -0
  146. package/src/agent-guard.test.ts +319 -0
  147. package/src/agent-guard.ts +547 -0
  148. package/src/ci-commit.test.ts +213 -2
  149. package/src/ci-commit.ts +258 -27
  150. package/src/ci-own-jobs.test.ts +108 -0
  151. package/src/ci-own-jobs.ts +252 -0
  152. package/src/ci-product-words.ts +35 -7
  153. package/src/ci-product.ts +81 -1
  154. package/src/cli/handlers/approve-cwd.test.ts +112 -0
  155. package/src/cli/handlers/approve.ts +22 -11
  156. package/src/cli/handlers/build-own-jobs.test.ts +80 -0
  157. package/src/cli/handlers/build-pr-loop-control.test.ts +87 -0
  158. package/src/cli/handlers/build-run-group.test.ts +59 -0
  159. package/src/cli/handlers/build.ts +83 -3
  160. package/src/cli/handlers/commit.ts +3 -0
  161. package/src/cli/handlers/notify-relay.ts +99 -17
  162. package/src/cli/handlers/pr.ts +3 -1
  163. package/src/cli/handlers/release.ts +20 -10
  164. package/src/cli/handlers/run-generate.ts +2 -1
  165. package/src/cli/main.ts +21 -1
  166. package/src/cli/parse-args.ts +45 -3
  167. package/src/cli/registry.ts +16 -0
  168. package/src/components/pr-env-components.test.ts +137 -0
  169. package/src/components/pr-env-components.ts +213 -0
  170. package/src/components/pr-policy.test.ts +41 -1
  171. package/src/components/pr-policy.ts +25 -1
  172. package/src/components/release-compile.test.ts +47 -0
  173. package/src/components/release-compile.ts +70 -13
  174. package/src/config.ts +23 -3
  175. package/src/gate-policy-bundle.test.ts +14 -0
  176. package/src/gate-policy.test.ts +7 -0
  177. package/src/gate-policy.ts +22 -7
  178. package/src/lexicon.ts +28 -1
  179. package/src/lifecycle/gated-op.ts +158 -0
  180. package/src/lifecycle/git.test.ts +92 -0
  181. package/src/lifecycle/git.ts +71 -2
  182. package/src/lifecycle/release-images-dockerfile.test.ts +221 -0
  183. package/src/lifecycle/release-images.ts +167 -8
  184. package/src/notify-message-words.test.ts +186 -0
  185. package/src/notify-product.ts +17 -4
  186. package/src/notify-relay-repo.test.ts +284 -0
  187. package/src/notify-relay-repo.ts +234 -0
  188. package/src/notify-relay.test.ts +12 -0
  189. package/src/notify-relay.ts +29 -3
  190. package/src/notify.schema.json +1 -0
  191. package/src/notify.ts +59 -19
  192. package/src/op/activities/review-product.test.ts +116 -0
  193. package/src/op/activities/review-product.ts +200 -0
  194. package/src/op/op-waves-capability.ts +2 -2
  195. package/src/op/schedule-overdue.test.ts +26 -0
  196. package/src/policy-engine.test.ts +162 -0
  197. package/src/policy-engine.ts +200 -0
  198. package/src/pr-forge-reads.test.ts +285 -0
  199. package/src/pr-forge-reads.ts +424 -0
  200. package/src/pr-forge.ts +30 -16
  201. package/src/pr-plan-note.test.ts +105 -0
  202. package/src/pr-plan-note.ts +521 -0
  203. package/src/release-floors.ts +13 -1
  204. package/src/state-export.test.ts +124 -0
  205. package/src/state-export.ts +227 -0
  206. package/src/state-migration.test.ts +133 -0
  207. package/src/state-migration.ts +236 -0
  208. package/src/state-unlock.test.ts +165 -0
  209. package/src/state-unlock.ts +293 -0
  210. package/src/workspace/declaration.schema.json +1 -1
  211. package/src/workspace/release-workflow.test.ts +34 -0
  212. package/src/workspace/release-workflow.ts +19 -4
@@ -0,0 +1,521 @@
1
+ /**
2
+ * A product's plan note (#4810): the pull-request note for a product whose
3
+ * plan job does not run chant's pr loop, rendered from a report the product
4
+ * builds from its own plan run, in the product's words.
5
+ *
6
+ * terragucci plans each root itself and writes its own report, so it has no
7
+ * `PrReport` for `renderPrNote` (./pr-loop.ts). It hands chant a
8
+ * {@link PrPlanNote} instead: the note's rows by unit (a root, or an
9
+ * instance of one root), the totals in the binary's own counting, the named
10
+ * destroys, replacements, refusals, imports and forgets, each group with the
11
+ * diff of its first unit, each unit's whole plan, the wave table and the
12
+ * waves marker, the policy overrides and warnings, the deferred units, the
13
+ * previewed waves and the units planned on another's planned outputs, the
14
+ * report links, and the lines and sections only the product knows about
15
+ * (its notices, a cost table, a blast radius). chant lays them out, links
16
+ * them into the report, and cuts the note to the forge's limit: whole plans
17
+ * go first, then group diffs shrink to attribute names, whichever saves the
18
+ * most first, then blocks drop from the end, and a Cut line names what went.
19
+ *
20
+ * The pr loop's bundle (pr-loop-bundle.test.ts) does not carry this module,
21
+ * so a product's sections do not grow it. {@link renderPrNote} here takes
22
+ * either report and renders a `PrReport` with the pr loop's own renderer,
23
+ * so a plywood or sql-yodeler note is byte for byte what it was.
24
+ */
25
+
26
+ import { renderPrNote as renderPrLoopNote, type PrReport } from "./pr-loop";
27
+ import { GITHUB_COMMENT_LIMIT } from "./plan-summary";
28
+ import { activeProductWords, approveLine, overrideLine, type CiProductWords } from "./ci-product-words";
29
+ import { NEXT_RELEASE } from "./release-floors";
30
+
31
+ /** The first chant with the product plan note (#4810). */
32
+ export const PR_PLAN_NOTE_FLOOR = NEXT_RELEASE;
33
+
34
+ /** The read contract a {@link PrPlanNote} follows. */
35
+ export const PR_PLAN_NOTE_CONTRACT = 1;
36
+
37
+ /** One change line of a group, as chant's plan summary groups them. */
38
+ export interface PrPlanNoteChange {
39
+ line: string;
40
+ count: number;
41
+ differsFrom?: string;
42
+ differsIn?: string[];
43
+ }
44
+
45
+ /** A group of units with the same change. */
46
+ export interface PrPlanNoteGroup {
47
+ id: string;
48
+ units: string[];
49
+ /** The one resource an instance group is of. */
50
+ resource?: string;
51
+ outlier?: boolean;
52
+ noChanges?: boolean;
53
+ /** The group whose change this one adds to; `changes` are then what it adds. */
54
+ extends?: string;
55
+ /** Every change of the group is one on every run: the note shows its attribute names alone. */
56
+ recurring?: boolean;
57
+ /** The group's change lines (or what it adds to `extends`). */
58
+ changes: PrPlanNoteChange[];
59
+ /** The plan text of the group's first unit, as the binary printed it: the note shows it as a `diff` block. */
60
+ diff?: { unit: string; lines: string[] };
61
+ /** Where values differ between the group's units, as `address.path`. */
62
+ varies?: string[];
63
+ }
64
+
65
+ /** A destroy, replacement, refusal, import or forget, kept when the note is cut. */
66
+ export interface PrPlanNoteNamed {
67
+ /** The unit it is in (a root). */
68
+ member: string;
69
+ address?: string;
70
+ deposed?: string;
71
+ action: "delete" | "replace" | "refused" | "import" | "forget";
72
+ /** The word the note shows for the action. Default: destroy, replace, refused to plan, import, forget. */
73
+ word?: string;
74
+ /** The attribute paths that forced a replacement, each joined with `.`. */
75
+ forcedBy?: string[];
76
+ reason?: string;
77
+ }
78
+
79
+ /** A wave's row. A plan names each wave's review digest; an apply names its set digest and approval. */
80
+ export interface PrPlanNoteWave {
81
+ number: number;
82
+ /** How many units it holds. */
83
+ units: number;
84
+ composed?: boolean;
85
+ /** The environments its units are in. Set on every wave when the table shows the column. */
86
+ environments?: string[];
87
+ /** The digest an approval of the wave binds. Present (even null) on any wave puts the table in review form. */
88
+ digest?: string | null;
89
+ /** Whether the gate will hold it for an approval. */
90
+ waits?: boolean;
91
+ /** The waves it plans again after. */
92
+ replansAfter?: number[];
93
+ /** Units whose plan reads a value unknown at plan time, which holds it. */
94
+ unknownBy?: string[];
95
+ /** Units whose hook asks for an approval. */
96
+ heldByHooks?: string[];
97
+ /** What the policy said of the wave: held by its rules, or allowed unattended by them. */
98
+ policy?: { outcome: "held" | "unattended" | string; rules: string[] };
99
+ /** The approval rules at base, each with what it asks for in words. */
100
+ approvalRules?: { units: string[]; asks: string }[];
101
+ /** An apply's set digest and approval, in the other form of the table. */
102
+ setDigest?: string;
103
+ approval?: string;
104
+ }
105
+
106
+ /** A denial a listed approver may override, or the override that stands. */
107
+ export interface PrPlanNoteOverride {
108
+ member: string;
109
+ /** The rules the override names, else those that denied. */
110
+ rules: string[];
111
+ override?: { by: string; at: string; sealed?: boolean; plan: string; reason: string };
112
+ /** Who may override it; an empty list names nobody. */
113
+ overriders: string[];
114
+ }
115
+
116
+ /** A line under the counts that may link into the report. */
117
+ export interface PrPlanNoteFact {
118
+ text: string;
119
+ /** Linked to the report's anchor when the note links report.html itself; else `plain`, or the text alone. */
120
+ link?: { text: string; anchor: string; plain?: string };
121
+ after?: string;
122
+ }
123
+
124
+ /**
125
+ * What a product hands chant for its plan note: everything the note shows,
126
+ * built from the product's own plan run.
127
+ */
128
+ export interface PrPlanNote {
129
+ kind: "plan-note";
130
+ contract: typeof PR_PLAN_NOTE_CONTRACT;
131
+ /** The stage as the heading names it, such as `tf-plan`. */
132
+ stage: string;
133
+ /** A plan of a pull request (not an apply or a drift check). */
134
+ planning?: boolean;
135
+ wave?: number;
136
+ /** The commit planned. */
137
+ head: string;
138
+ /** `instance`: the units are instances of one root. Default: the product's noun. */
139
+ unit?: "member" | "instance";
140
+ units: number;
141
+ /** The run's total in the binary's own counting: a replacement adds one and destroys one. */
142
+ totals?: { add: number; change: number; destroy: number; forget: number; members: number };
143
+ /** The change reaches no unit, so nothing was planned. */
144
+ nothing?: boolean;
145
+ /** Lines about the pipeline itself, such as overdue drift checks. */
146
+ notices?: string[];
147
+ /** The product's lines under them: tips, binaries, cost, the slowest resources. */
148
+ facts?: PrPlanNoteFact[];
149
+ named: PrPlanNoteNamed[];
150
+ overrides?: PrPlanNoteOverride[];
151
+ warnings?: { member: string; text: string }[];
152
+ deferred?: { unit: string; after: string[]; why: string; previewed?: boolean }[];
153
+ waves: PrPlanNoteWave[];
154
+ /** What the waves marker carries beside the waves. */
155
+ previews?: unknown[];
156
+ /** Waves planned at their gate against the preview a pull request showed. */
157
+ previewed?: { wave: number; pullRequest: number | string; units: number; moved: { unit: string; differences: string[] }[] }[];
158
+ /** Units planned on another unit's planned outputs. */
159
+ linked?: { member: string; upstream: string; composed?: boolean; unknown?: string[] }[];
160
+ /** The product's own blocks: `start` before the named changes, `groups` before the groups, `end` after them. Each text as it is shown. */
161
+ sections?: { at: "start" | "groups" | "end"; text: string }[];
162
+ groups: PrPlanNoteGroup[];
163
+ /** Each unit's whole plan, collapsed: its text, its totals line, and its plan file beside the report or at a link. */
164
+ plans?: { member: string; text: string; totals?: string; file?: string; url?: string }[];
165
+ /**
166
+ * Where the report is: `report`, report.html or the run's page when
167
+ * `artifacts`; `run`, the run's page when the run keeps no report;
168
+ * `expires`, when presigned links stop working.
169
+ */
170
+ links?: { report?: string; artifacts?: boolean; run?: string; expires?: string };
171
+ /** A waiting wave's approve line and an override line ask for a signature. */
172
+ sealed?: boolean;
173
+ }
174
+
175
+ /** The plan note's own words; every slot defaults to chant's. */
176
+ export interface PrPlanNoteWords {
177
+ /** The note's last line. */
178
+ footer?: string;
179
+ /** The report page's file name. */
180
+ page?: string;
181
+ /** The artifact the run keeps the report in. */
182
+ artifact?: string;
183
+ /** The line for a run that keeps no report, over `{run}`. */
184
+ noReport?: string;
185
+ /** The waves marker's name. Default `<product>:waves`. */
186
+ marker?: string;
187
+ /** The report's anchors for a unit and a group, over `{id}`. */
188
+ anchors?: { member?: string; group?: string };
189
+ /** The setting that names who may override a denial. */
190
+ overrideKey?: string;
191
+ /** The setting that holds the approval rules. */
192
+ approvalRulesKey?: string;
193
+ /** The stage that applies the plan. */
194
+ applyStage?: string;
195
+ /** The file each unit's plan is kept in. */
196
+ planFile?: string;
197
+ /** The op an override is recorded under. */
198
+ overrideOp?: string;
199
+ }
200
+
201
+ const NOTE_WORDS: Required<Omit<PrPlanNoteWords, "marker">> = {
202
+ footer: "",
203
+ page: "report.html",
204
+ artifact: "chant-pr",
205
+ noReport: "Planned in [this run]({run}), which keeps no report artifact.",
206
+ anchors: { member: "member-{id}", group: "group-{id}" },
207
+ overrideKey: "ci.policy",
208
+ approvalRulesKey: "approval rules",
209
+ applyStage: "apply",
210
+ planFile: "plan.txt",
211
+ overrideOp: "policy-override",
212
+ };
213
+
214
+ /** Options for {@link renderPlanNote}. */
215
+ export interface PlanNoteOptions {
216
+ /** The most characters the note may hold. Default GitHub's 65,536. */
217
+ limit?: number;
218
+ words?: CiProductWords;
219
+ note?: PrPlanNoteWords;
220
+ }
221
+
222
+ /**
223
+ * The note for either report: a `PrReport` as the pr loop renders it, or a
224
+ * product's {@link PrPlanNote}.
225
+ */
226
+ export function renderPrNote(report: PrReport | PrPlanNote, options: NonNullable<Parameters<typeof renderPrLoopNote>[1]> & { note?: PrPlanNoteWords } = {}): string {
227
+ return isPlanNote(report) ? renderPlanNote(report, options) : renderPrLoopNote(report, options);
228
+ }
229
+
230
+ /** Whether `report` is a product's plan note. */
231
+ export function isPlanNote(report: unknown): report is PrPlanNote {
232
+ return typeof report === "object" && report !== null && (report as { kind?: unknown }).kind === "plan-note";
233
+ }
234
+
235
+ const code = (s: string): string => "`" + s.replaceAll("`", "'") + "`";
236
+ const codePoints = (s: string): number => [...s].length;
237
+ const plural = (n: number, one: string, many = `${one}s`): string => `${n} ${n === 1 ? one : many}`;
238
+ const joinAnd = (xs: readonly string[]): string => (xs.length <= 1 ? (xs[0] ?? "") : `${xs.slice(0, -1).join(", ")} and ${xs[xs.length - 1]}`);
239
+ const esc = (s: string): string => s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
240
+ const capital = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1);
241
+ const oneLine = (s: string): string => s.split(/\s+/).join(" ");
242
+ /** A time as the note shows it: `2026-10-15 10:03 UTC`. */
243
+ const utc = (iso: string): string => iso.replace("T", " ").replace(/:\d{2}(\.\d+)?Z$/, " UTC");
244
+
245
+ /**
246
+ * Lines as a `diff` block wants them, as Atlantis comments a plan: each
247
+ * line's change symbol (`+`, `-`, `~`, `-/+`, `+/-`) moves to the first
248
+ * column, so the forge colours additions and removals.
249
+ */
250
+ export function diffLines(lines: readonly string[]): string[] {
251
+ return lines.map((l) => l.replace(/^(\s+)(-\/\+|\+\/-|[-+~])(?= )/, "$2$1"));
252
+ }
253
+
254
+ /** A fenced `diff` block whose fence is longer than any run of backticks in the text. */
255
+ export function diffFence(lines: readonly string[]): string {
256
+ const body = lines.join("\n");
257
+ const longest = Math.max(0, ...[...body.matchAll(/`+/g)].map((m) => m[0].length));
258
+ const fence = "`".repeat(Math.max(3, longest + 1));
259
+ return `${fence}diff\n${body}\n${fence}\n`;
260
+ }
261
+
262
+ /** The waves marker: an HTML comment with no `<` or `>` in its JSON, so nothing in it ends the comment. */
263
+ export function planNoteMarker(name: string, waves: { head: string; waves: { number: number; digest: string | null; waits: boolean }[]; previews?: unknown[] }): string {
264
+ return `<!-- ${name} ${JSON.stringify(waves).replace(/</g, "\\u003c").replace(/>/g, "\\u003e")} -->`;
265
+ }
266
+
267
+ interface Block {
268
+ text: string;
269
+ kind: "line" | "group" | "plan";
270
+ units: number;
271
+ /** A group's text with its attribute names in place of its diff. */
272
+ short?: string;
273
+ member?: string;
274
+ }
275
+
276
+ const ACTION_WORDS: Record<PrPlanNoteNamed["action"], string> = { delete: "destroy", replace: "replace", refused: "refused to plan", forget: "forget", import: "import" };
277
+
278
+ function changeText(l: PrPlanNoteChange): string {
279
+ let t = l.count > 1 ? `${l.line} (x${l.count})` : l.line;
280
+ if (l.differsFrom) t += l.differsIn?.length ? ` [differs from group ${l.differsFrom} in: ${l.differsIn.join(", ")}]` : ` [differs from group ${l.differsFrom}]`;
281
+ return t;
282
+ }
283
+
284
+ /**
285
+ * A product's plan note. Each group links to its anchor in the report and
286
+ * each named change to its unit's. Destroys, replacements and refusals come
287
+ * first and are never dropped for space before a group is. Over the limit,
288
+ * the units' whole plans go and the groups' diffs shrink to their attribute
289
+ * names, whichever saves the most first; then blocks are dropped, whole,
290
+ * from the end. A Cut line names what went.
291
+ */
292
+ export function renderPlanNote(report: PrPlanNote, options: PlanNoteOptions = {}): string {
293
+ const words = options.words ?? activeProductWords();
294
+ const w = { ...NOTE_WORDS, ...options.note, anchors: { ...NOTE_WORDS.anchors, ...options.note?.anchors } };
295
+ const markerName = options.note?.marker ?? `${words.product}:waves`;
296
+ const [one, many] = words.noun;
297
+ const links = report.links ?? {};
298
+ const url = links.report ?? (links.run ? undefined : w.page);
299
+ const artifacts = links.artifacts === true;
300
+ const linkable = url !== undefined && !artifacts;
301
+ const to = (text: string, anchor?: string): string => (url === undefined ? text : `[${text}](${url}${anchor && !artifacts ? `#${anchor}` : ""})`);
302
+ const memberLink = (m: string): string => to(code(m), w.anchors.member!.replace("{id}", m));
303
+ const until = links.expires ? ` The links to the bucket work until ${utc(links.expires)}.` : "";
304
+ const full = url === undefined
305
+ ? w.noReport.replace("{run}", links.run ?? "")
306
+ : artifacts ? `The full report is \`${w.page}\` in the \`${w.artifact}\` artifact of [this run](${url}).` : `[Full report](${url})${until}`;
307
+ const fullReport = url === undefined ? "The full report" : artifacts ? `The full report, in the artifacts of [this run](${url}),` : `[The full report](${url})`;
308
+ const limit = options.limit ?? GITHUB_COMMENT_LIMIT;
309
+ const unitWord = report.unit === "instance" ? "instance" : one;
310
+ const unitWords = report.unit === "instance" ? "instances" : many;
311
+ const destroys = report.named.filter((n) => n.action === "delete" || n.action === "replace").length;
312
+ const refused = report.named.filter((n) => n.action === "refused").length;
313
+ const head: string[] = [`### ${words.product} ${report.stage}${report.wave !== undefined ? `, wave ${report.wave}` : ""}: ${code(report.head.slice(0, 12))}`, ""];
314
+ const parts = [plural(report.groups.length, "group"), plural(destroys, "destroy or replacement", "destroys or replacements")];
315
+ if (refused > 0) parts.push(`${refused} refused`);
316
+ head.push(`${plural(report.units, unitWord, unitWords)}: ${parts.join(", ")}. ${full}`, "");
317
+ const t0 = report.totals;
318
+ if (t0 && t0.members > 0) {
319
+ const counts = [`${t0.add} to add`, `${t0.change} to change`, `${t0.destroy} to destroy`];
320
+ if (t0.forget > 0) counts.push(`${t0.forget} to forget`);
321
+ head.push(`${counts.join(", ")} across ${plural(t0.members, one, many)}`, "");
322
+ }
323
+ if (report.nothing) head.push(`This change reaches no ${one}, so nothing was planned.`, "");
324
+ for (const n of report.notices ?? []) head.push(`> ${n}`, "");
325
+ for (const f of report.facts ?? []) {
326
+ const link = f.link ? (linkable ? `[${f.link.text}](${url}#${f.link.anchor})` : (f.link.plain ?? f.link.text)) : "";
327
+ head.push(`${f.text}${link}${f.after ?? ""}`, "");
328
+ }
329
+
330
+ const blocks: Block[] = [];
331
+ const line = (text: string): void => void blocks.push({ kind: "line", units: 0, text });
332
+ const sections = (at: "start" | "groups" | "end"): void => {
333
+ for (const s of report.sections ?? []) if (s.at === at) line(s.text);
334
+ };
335
+ sections("start");
336
+ if (report.named.length > 0) {
337
+ line(`**Destroys, replacements, refusals, imports and forgets (${report.named.length}):**\n\n`);
338
+ for (const n of report.named) {
339
+ const what = n.address ? `${n.member}: ${n.address}${n.deposed !== undefined ? ` (deposed ${n.deposed})` : ""}` : n.member;
340
+ const forced = n.forcedBy?.length ? `, forced by ${n.forcedBy.map(code).join(", ")}` : "";
341
+ const reason = n.reason ? `: ${oneLine(n.reason)}` : "";
342
+ line(`- ${to(code(what), w.anchors.member!.replace("{id}", n.member))} (${n.word ?? ACTION_WORDS[n.action]}${forced})${reason}\n`);
343
+ }
344
+ line("\n");
345
+ }
346
+ const overrides = report.overrides ?? [];
347
+ if (overrides.length > 0) {
348
+ let t = `**Policy overrides (${overrides.filter((r) => r.override).length} of ${overrides.length} denied):**\n\n`;
349
+ for (const r of overrides) {
350
+ const o = r.override;
351
+ const rules = r.rules.map(code).join(", ") || "its rules";
352
+ t += o
353
+ ? `- ${memberLink(r.member)}: ${rules} overridden by ${o.by} at ${o.at}${o.sealed ? ", sealed" : ""}, for plan ${code(o.plan)}: ${oneLine(o.reason)}${report.planning ? `. ${w.applyStage} applies this plan; this run still fails it` : ""}\n`
354
+ : r.overriders.length === 0
355
+ ? `- ${memberLink(r.member)}: denied by ${rules}. ${w.overrideKey} names nobody who may override it\n`
356
+ : `- ${memberLink(r.member)}: denied by ${rules}. ${r.overriders.join(", ")} may override it once a ${w.applyStage} wave records the denial: ${code(overrideLine(words, { op: w.overrideOp, target: r.member, rules: r.rules, sign: report.sealed === true }))}\n`;
357
+ }
358
+ line(t + "\n");
359
+ }
360
+ const warnings = report.warnings ?? [];
361
+ if (warnings.length > 0) {
362
+ let t = `**Policy warnings (${warnings.length}), which fail nothing:**\n\n`;
363
+ for (const x of warnings) t += `- ${memberLink(x.member)}: ${oneLine(x.text)}\n`;
364
+ line(t + "\n");
365
+ }
366
+ if (report.deferred?.length) {
367
+ let t = `**Planned once what they wait for applies (${report.deferred.length}):**\n\n`;
368
+ for (const d of report.deferred) t += `- ${code(d.unit)}${d.after.length ? ` after ${d.after.map(code).join(", ")}` : ""}: ${d.why}${d.previewed ? " (previewed)" : ""}\n`;
369
+ line(t + "\n");
370
+ }
371
+ const envs = report.waves.some((x) => x.environments !== undefined);
372
+ const envHead = envs ? " Environments |" : "";
373
+ const envRule = envs ? "---|" : "";
374
+ const envCell = (x: PrPlanNoteWave): string => (envs ? ` ${x.environments?.length ? x.environments.join(", ") : "none"} |` : "");
375
+ const Units = capital(many);
376
+ if (report.waves.some((x) => x.digest !== undefined)) {
377
+ let t = `| Wave | ${Units} |${envHead} Digest of its changes | When it applies |\n|---|---|${envRule}---|---|\n`;
378
+ for (const x of report.waves) {
379
+ const again = x.replansAfter?.length ? `plans again once wave ${x.replansAfter.join(", ")} applies, then ` : "";
380
+ const approve = (digest: string): string => approveLine(words, { op: words.op ?? "", gate: words.gateName.replace("{gate}", words.prGate).replace("{k}", String(x.number)), digest, sign: report.sealed === true });
381
+ const when = again
382
+ ? `${again}${x.waits ? "waits for an approval of that plan" : "applies"}`
383
+ : x.waits && x.digest ? `waits for an approval: ${code(approve(x.digest))}` : x.waits ? "waits for an approval" : "applies";
384
+ const unknownBy = x.unknownBy ?? [];
385
+ const policyRules = (x.policy?.rules ?? []).map(code).join(", ");
386
+ const by = x.waits && unknownBy.length
387
+ ? ` (since ${joinAnd(unknownBy.map(code))} ${unknownBy.length === 1 ? "reads" : "read"} a value unknown at plan time)`
388
+ : x.waits && x.heldByHooks?.length ? ` (a hook of ${x.heldByHooks.map(code).join(", ")} asks for one)`
389
+ : x.waits && x.policy?.outcome === "held" ? ` (held by ${policyRules})`
390
+ : x.policy?.outcome === "unattended" ? (x.waits ? ` (the policy allows it unattended, ${policyRules}, and something else holds it)` : ` without an approval: allowed unattended by ${policyRules}`) : "";
391
+ const rules = x.waits && x.approvalRules?.length ? `; ${w.approvalRulesKey}: ${x.approvalRules.map((r) => `${r.units.map(code).join(", ")} ${r.asks}`).join("; ")}` : "";
392
+ t += `| ${x.number} | ${x.units}${x.composed ? ", composed" : ""} |${envCell(x)} ${x.digest ? code(x.digest) : x.replansAfter?.length ? "after the re-plan" : "no change"} | ${when}${by}${rules} |\n`;
393
+ }
394
+ line(t + "\n");
395
+ const previews = report.previews ?? [];
396
+ head.push(planNoteMarker(markerName, { head: report.head, waves: report.waves.map((x) => ({ number: x.number, digest: x.digest ?? null, waits: x.waits === true })), ...(previews.length ? { previews } : {}) }), "");
397
+ } else if (report.waves.length > 0) {
398
+ let t = `| Wave | ${Units} |${envHead} Set digest | Approval |\n|---|---|${envRule}---|---|\n`;
399
+ for (const x of report.waves) t += `| ${x.number} | ${x.units}${x.composed ? ", composed" : ""} |${envCell(x)} ${x.replansAfter?.length ? `none yet: it plans again once wave ${x.replansAfter.join(", ")} applies` : x.setDigest ? code(x.setDigest.slice(0, 19)) : "none"} | ${x.approval ?? ""} |\n`;
400
+ line(t + "\n");
401
+ }
402
+ for (const p of report.previewed ?? []) {
403
+ const moved = p.moved.filter((u) => u.differences.length);
404
+ let t = moved.length
405
+ ? `**Wave ${p.wave} plans differently from the preview in pull request ${p.pullRequest} (${moved.length} of ${p.units}):**\n\n`
406
+ : `**Wave ${p.wave} plans as pull request ${p.pullRequest} previewed it (${plural(p.units, unitWord, unitWords)}).**\n\n`;
407
+ for (const u of moved) for (const d of u.differences) t += `- ${memberLink(u.unit)}: ${d}\n`;
408
+ line(t + "\n");
409
+ }
410
+ const linked = report.linked ?? [];
411
+ if (linked.length > 0) {
412
+ let t = `**Planned on the planned outputs of another ${one} (${linked.length}):**\n\n`;
413
+ for (const x of linked) t += `- ${memberLink(x.member)} reads ${code(x.upstream)}${x.composed ? ", in the composed run" : ""}${x.unknown?.length ? `; ${x.unknown.map(code).join(", ")} known once it applies` : ""}\n`;
414
+ line(t + "\n");
415
+ }
416
+ sections("groups");
417
+ for (const g of report.groups) {
418
+ let title = `${to(`Group ${g.id}`, w.anchors.group!.replace("{id}", g.id))}: ${plural(g.units.length, unitWord, unitWords)}`;
419
+ if (g.resource) title += ` of ${code(g.resource)}`;
420
+ if (g.outlier) title += " (outlier)";
421
+ title += g.noChanges ? ", no changes" : g.extends ? `, group ${g.extends}'s change plus` : g.units.length > 1 ? ", identical change" : ", change";
422
+ if (g.recurring) title += ", on every run";
423
+ const heading = `#### ${title}\n\n`;
424
+ const names = g.changes.length > 0 ? "```\n" + g.changes.map(changeText).join("\n") + "\n```\n\n" : "";
425
+ const shown = g.units.slice(0, 20).map(code).join(", ");
426
+ const members = `${capital(unitWords)}: ${shown}${g.units.length > 20 ? `, and ${g.units.length - 20} more in the report` : ""}\n\n`;
427
+ const diff = g.noChanges || g.recurring ? undefined : g.diff;
428
+ if (!diff) {
429
+ blocks.push({ kind: "group", units: g.units.length, text: heading + names + members });
430
+ continue;
431
+ }
432
+ let t = heading;
433
+ if (g.units.length > 1) t += `As ${code(diff.unit)} plans it:\n\n`;
434
+ t += diffFence(diffLines(diff.lines)) + "\n";
435
+ const differs = g.changes.filter((l) => l.differsFrom);
436
+ for (const l of differs) t += `- ${code(l.line)} differs from group ${l.differsFrom}${l.differsIn?.length ? ` in ${l.differsIn.map(code).join(", ")}` : ""}.\n`;
437
+ const varies = g.varies ?? [];
438
+ if (varies.length > 0) t += `${differs.length > 0 ? "- " : ""}Values differ between its ${unitWords} in ${varies.map(code).join(", ")}.\n`;
439
+ if (differs.length > 0 || varies.length > 0) t += "\n";
440
+ blocks.push({ kind: "group", units: g.units.length, text: t + members, short: heading + names + members });
441
+ }
442
+ sections("end");
443
+ // A unit's plan file: the link given for it, else beside the report page when the note links the page itself.
444
+ const planLink = (member: string): string | undefined => {
445
+ const p = report.plans?.find((x) => x.member === member);
446
+ if (p?.url) return p.url;
447
+ if (!linkable || !p?.file) return undefined;
448
+ const bare = url.split("#")[0]!;
449
+ if (bare.includes("?") || !(bare === w.page || bare.endsWith(`/${w.page}`))) return undefined;
450
+ return bare.slice(0, bare.length - w.page.length) + p.file.split("/").map(encodeURIComponent).join("/");
451
+ };
452
+ let first = true;
453
+ for (const p of report.plans ?? []) {
454
+ const link = planLink(p.member);
455
+ let t = first ? `**Each ${one}'s plan:**\n\n` : "";
456
+ first = false;
457
+ t += `<details><summary><code>${esc(p.member)}</code>${p.totals ? `: ${esc(p.totals)}` : ""}</summary>\n\n`;
458
+ t += diffFence(diffLines(p.text.replace(/\r\n/g, "\n").replace(/^(\s*\n)+/, "").replace(/\s+$/, "").split("\n"))) + "\n";
459
+ if (link) t += `[${w.planFile}](${link})\n\n`;
460
+ t += "</details>\n\n";
461
+ blocks.push({ kind: "plan", units: 0, member: p.member, text: t });
462
+ }
463
+ const top = head.join("\n") + "\n";
464
+ const foot = w.footer ? `\n${w.footer}\n` : "";
465
+ const all = top + blocks.map((b) => b.text).join("") + foot;
466
+ if (codePoints(all) <= limit) return all;
467
+
468
+ const cut = { plans: [] as string[], diffs: 0, groups: 0, units: 0, lines: 0 };
469
+ const notice = (): string => {
470
+ const out: string[] = [];
471
+ if (cut.plans.length > 0) {
472
+ const named = cut.plans.slice(0, 20).map((m) => {
473
+ const link = planLink(m);
474
+ return link ? `[${code(m)}](${link})` : code(m);
475
+ });
476
+ const more = cut.plans.length - named.length;
477
+ out.push(`the whole plans of ${plural(cut.plans.length, one, many)} (${named.join(", ")}${more > 0 ? `, and ${more} more` : ""})`);
478
+ }
479
+ if (cut.groups > 0) out.push(`${plural(cut.groups, "group")} (${plural(cut.units, unitWord, unitWords)})`);
480
+ if (cut.lines > 0) out.push(plural(cut.lines, "line"));
481
+ const clauses: string[] = [];
482
+ if (out.length > 0) clauses.push(`leaves out ${joinAnd(out)}`);
483
+ if (cut.diffs > 0) clauses.push(`shows ${cut.diffs === 1 ? "one group" : `${cut.diffs} groups`} by attribute name, without the diff`);
484
+ return `**Cut:** this note ${clauses.join(" and ")}, to stay within ${limit} characters. ${fullReport} has all of it${report.plans !== undefined ? `, and each ${one}'s ${w.planFile} the whole plan` : ""}.\n`;
485
+ };
486
+ const size = (b: Block): number => codePoints(b.text);
487
+ let used = codePoints(all);
488
+ const over = (): boolean => used + codePoints(notice()) > limit;
489
+ // Whole plans and group diffs, whichever saves the most first: a whole plan before a diff that saves as much, the later of two alike first.
490
+ const candidates = blocks
491
+ .map((b, i) => ({ i, plan: b.kind === "plan", saves: b.kind === "plan" ? size(b) : b.short !== undefined ? size(b) - codePoints(b.short) : 0 }))
492
+ .filter((c) => c.saves > 0)
493
+ .sort((a, b) => b.saves - a.saves || Number(b.plan) - Number(a.plan) || b.i - a.i);
494
+ const gone = new Set<number>();
495
+ for (const c of candidates) {
496
+ if (!over()) break;
497
+ const b = blocks[c.i]!;
498
+ if (c.plan) {
499
+ used -= size(b);
500
+ gone.add(c.i);
501
+ } else {
502
+ used += codePoints(b.short!) - size(b);
503
+ b.text = b.short!;
504
+ b.short = undefined;
505
+ cut.diffs++;
506
+ }
507
+ }
508
+ cut.plans.push(...blocks.filter((_, i) => gone.has(i)).map((b) => b.member!));
509
+ for (let i = blocks.length - 1; i >= 0; i--) if (gone.has(i)) blocks.splice(i, 1);
510
+ // Then whole blocks from the end: groups, and last the destroys.
511
+ while (blocks.length > 0 && over()) {
512
+ const b = blocks.pop()!;
513
+ used -= size(b);
514
+ if (b.kind === "group") {
515
+ cut.groups++;
516
+ cut.units += b.units;
517
+ } else if (b.kind === "plan") cut.plans.unshift(b.member!);
518
+ else cut.lines++;
519
+ }
520
+ return top + blocks.map((b) => b.text).join("") + notice() + foot;
521
+ }
@@ -19,4 +19,16 @@
19
19
  * this constant to the next patch (#4501). The check fails while a floor
20
20
  * still names this constant after its version shipped.
21
21
  */
22
- export const NEXT_RELEASE = "0.124.74";
22
+ export const NEXT_RELEASE = "0.124.78";
23
+
24
+ /** The first chant whose sql lexicon's `yodelCommitSpec("new", ...)` takes `envs`, so `--replace-own` reads those histories as the reader (#4815). */
25
+ export const YODEL_NEW_ENVS_FLOOR = NEXT_RELEASE;
26
+
27
+ /** The first chant whose sql lexicon's `yodelRefusalReply` reads yodel rebase's conflict refusal as yodel prints it, `<a> and the migrations after <p> up to <b>` or `<a> and the chain ending at <b>` (#4821). */
28
+ export const YODEL_CONFLICT_REPLY_FLOOR = NEXT_RELEASE;
29
+
30
+ /** The first chant whose `@intentius/chant/pr-forge-reads` exports the forge reads beside the clients (#4809). */
31
+ export const PR_FORGE_READS_FLOOR = NEXT_RELEASE;
32
+
33
+ /** The first chant whose GitLab `scheduledRuns` takes `schedule`, the selector of an Op's `gitlab.scheduleRule` (#4813). */
34
+ export const SCHEDULED_RUNS_SELECTOR_FLOOR = NEXT_RELEASE;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * #4762: the engine-neutral state export, on an in-memory version source and
3
+ * an in-memory gated-request ledger. Nothing reaches a store or git.
4
+ */
5
+ import { mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { describe, expect, test } from "vitest";
9
+ import { fakeLedger } from "./__fixtures__/gated-ledger";
10
+ import { exportStateVersion, exportRefusal, STATE_EXPORT_FLOOR, StateExportError, type StateVersionSource } from "./state-export";
11
+
12
+ const NO_CI = {};
13
+
14
+ function source(versions: Record<string, string>, current?: string): StateVersionSource & { reads: string[] } {
15
+ const reads: string[] = [];
16
+ return {
17
+ location: "s3://states/net.tfstate",
18
+ reads,
19
+ current: async () => (current ? { exists: true, versionId: current } : Object.keys(versions).length ? { exists: true, off: "bucket versioning is off" } : { exists: false }),
20
+ hasVersion: async (id) => id in versions,
21
+ readVersion: async (id) => {
22
+ reads.push(id);
23
+ return versions[id];
24
+ },
25
+ };
26
+ }
27
+
28
+ const outside = (): string => mkdtempSync(join(tmpdir(), "chant-export-test-"));
29
+
30
+ const base = (ledger: ReturnType<typeof fakeLedger>, src: StateVersionSource, extra: Record<string, unknown> = {}) => ({
31
+ subject: "net",
32
+ by: "ana",
33
+ source: src,
34
+ words: { op: "tf-state-export", approveCommand: (s: string, d: string) => `product approve export ${s} --plan ${d}` },
35
+ rules: { mode: "ledger" as const },
36
+ ledger,
37
+ env: NO_CI,
38
+ now: "2026-11-08T09:00:00Z",
39
+ ...extra,
40
+ });
41
+
42
+ describe("exportStateVersion", () => {
43
+ test("asks without reading the state, then writes the approved version once, mode 0600, and records its digest", async () => {
44
+ const ledger = fakeLedger();
45
+ const src = source({ v1: '{"serial":1}', v2: '{"serial":2}' }, "v2");
46
+ const out = join(outside(), "net.tfstate");
47
+ const first = await exportStateVersion(base(ledger, src, { out }));
48
+ expect(first).toMatchObject({ status: "waiting", exit: 3, version: "v2", location: "s3://states/net.tfstate" });
49
+ expect(first.status === "waiting" && first.command).toBe(`product approve export net --plan ${first.digest}`);
50
+ expect(src.reads).toEqual([]);
51
+
52
+ ledger.approve("bo");
53
+ const second = await exportStateVersion(base(ledger, src, { out, now: "2026-11-08T12:00:00Z" }));
54
+ expect(second).toMatchObject({ status: "written", exit: 0, file: out, version: "v2", approvedBy: "bo", digest: first.digest });
55
+ expect(readFileSync(out, "utf-8")).toBe('{"serial":2}');
56
+ expect(statSync(out).mode & 0o777).toBe(0o600);
57
+ expect(ledger.writes).toEqual(["pending", "applied", "finished:applied"]);
58
+ expect(ledger.details[0]).toMatchObject({ by: "ana", version_id: "v2", approved_by: "bo", location: "s3://states/net.tfstate" });
59
+ expect(String(ledger.details[0]!.content_digest)).toMatch(/^sha256:[0-9a-f]{64}$/);
60
+ expect(JSON.stringify(ledger.details)).not.toContain("serial");
61
+
62
+ const third = await exportStateVersion(base(ledger, src, { out: join(outside(), "again.tfstate") }));
63
+ expect(third).toMatchObject({ status: "spent", exit: 1 });
64
+ expect(src.reads).toEqual(["v2"]);
65
+ });
66
+
67
+ test("an approval by the requester does not count", async () => {
68
+ const ledger = fakeLedger();
69
+ ledger.approve("ana");
70
+ const r = await exportStateVersion(base(ledger, source({ v1: "{}" }, "v1"), { out: join(outside(), "s") }));
71
+ expect(r).toMatchObject({ status: "refused", exit: 3 });
72
+ });
73
+
74
+ test("with no destination the file goes to a new private directory, named by the product", async () => {
75
+ const ledger = fakeLedger();
76
+ ledger.approve("bo");
77
+ const r = await exportStateVersion(base(ledger, source({ "v/1": "{}" }), { version: "v/1", words: { op: "tf-state-export", fileName: (s: string, v: string) => `${s}.${v.replace("/", "_")}.tfstate`, tmpPrefix: "product-export-" } }));
78
+ expect(r.status).toBe("written");
79
+ if (r.status !== "written") return;
80
+ expect(r.file).toMatch(/product-export-[^/]+\/net\.v_1\.tfstate$/);
81
+ });
82
+
83
+ test("refuses a version the store does not keep, a store with no versions, and no state, before asking", async () => {
84
+ const ledger = fakeLedger();
85
+ await expect(exportStateVersion(base(ledger, source({ v1: "{}" }), { version: "v9" }))).rejects.toThrow(/has no version v9/);
86
+ await expect(exportStateVersion(base(ledger, source({ v1: "{}" })))).rejects.toThrow(/keeps no versions.*bucket versioning is off/);
87
+ await expect(exportStateVersion(base(ledger, source({})))).rejects.toThrow(/holds no state/);
88
+ expect(ledger.writes).toEqual([]);
89
+ });
90
+
91
+ test("refuses a CI job, a destination inside a git working tree, and a file that is there", async () => {
92
+ const ledger = fakeLedger();
93
+ const src = source({ v1: "{}" }, "v1");
94
+ await expect(exportStateVersion(base(ledger, src, { env: { GITLAB_CI: "true" } }))).rejects.toThrow(/GITLAB_CI is set/);
95
+ const repo = outside();
96
+ mkdirSync(join(repo, ".git"));
97
+ mkdirSync(join(repo, "sub"));
98
+ await expect(exportStateVersion(base(ledger, src, { out: join(repo, "sub", "net.tfstate") }))).rejects.toBeInstanceOf(StateExportError);
99
+ expect(exportRefusal(join(repo, "sub", "net.tfstate"))).toMatch(/inside the git working tree/);
100
+ const there = join(outside(), "there");
101
+ writeFileSync(there, "x");
102
+ await expect(exportStateVersion(base(ledger, src, { out: there }))).rejects.toThrow(/never writes over a file/);
103
+ const ok = await exportStateVersion(base(ledger, src, { env: { GITLAB_CI: "true" }, allowCi: true, out: join(outside(), "ci") }));
104
+ expect(ok.status).toBe("waiting");
105
+ });
106
+
107
+ test("a version deleted while the request waited fails the request, and writes nothing", async () => {
108
+ const ledger = fakeLedger();
109
+ const versions: Record<string, string> = { v1: "{}" };
110
+ const src = source(versions, "v1");
111
+ const out = join(outside(), "gone");
112
+ await exportStateVersion(base(ledger, src, { out }));
113
+ ledger.approve("bo");
114
+ delete versions.v1;
115
+ src.hasVersion = async () => true;
116
+ const r = await exportStateVersion(base(ledger, src, { out, version: "v1" }));
117
+ expect(r).toMatchObject({ status: "failed", exit: 1 });
118
+ expect(ledger.writes.at(-1)).toBe("finished:failed");
119
+ });
120
+
121
+ test("its floor is the next release", () => {
122
+ expect(STATE_EXPORT_FLOOR).toBe("0.124.77");
123
+ });
124
+ });