@patronage/factory-ci 1.0.0-alpha.4 → 1.0.0-alpha.41

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 (54) hide show
  1. package/README.md +713 -11
  2. package/dist/.build-fingerprint.json +3 -0
  3. package/dist/alchemy/index.d.ts +1174 -0
  4. package/dist/alchemy/index.js +2142 -0
  5. package/dist/bundle-alchemy-entry-CT5hCphA.js +112 -0
  6. package/dist/execute-alchemy-entry-B0lBN-YZ.js +160 -0
  7. package/dist/execute-alchemy-entry-B397GSk5.d.ts +134 -0
  8. package/dist/index.d.ts +1218 -93
  9. package/dist/index.js +2841 -333
  10. package/package.json +28 -10
  11. package/src/actions.ts +13 -0
  12. package/src/alchemy/child-diagnostics.ts +148 -0
  13. package/src/alchemy/credential-preflight.ts +428 -0
  14. package/src/alchemy/destroy-postcondition.ts +103 -0
  15. package/src/alchemy/evaluate-stack.ts +153 -0
  16. package/src/alchemy/first-deploy-authorization.ts +194 -0
  17. package/src/alchemy/index.ts +144 -0
  18. package/src/alchemy/lifecycle-failure.ts +174 -0
  19. package/src/alchemy/lifecycle.ts +1330 -0
  20. package/src/alchemy/local-emulation.ts +89 -0
  21. package/src/alchemy/plan-effects.ts +510 -0
  22. package/src/alchemy/retained-identity.ts +248 -0
  23. package/src/alchemy/secret-name-policy.ts +96 -0
  24. package/src/alchemy/stage-policy.ts +269 -0
  25. package/src/alchemy/state-tree.ts +168 -0
  26. package/src/alchemy/url-implies-auth.ts +264 -0
  27. package/src/alchemy-baseline.ts +75 -0
  28. package/src/bundle-alchemy-entry.ts +5 -0
  29. package/src/candidate-impact-workflow.ts +110 -0
  30. package/src/candidate-lifecycle.ts +29 -0
  31. package/src/cursor-oidc.ts +33 -0
  32. package/src/execute-alchemy-entry.ts +128 -8
  33. package/src/factory-workflow.ts +83 -40
  34. package/src/github-app-token.ts +131 -22
  35. package/src/github-transport.ts +186 -0
  36. package/src/impact-demand-condition.ts +67 -0
  37. package/src/index.ts +174 -0
  38. package/src/lifecycle-contract-lane.ts +113 -0
  39. package/src/merge-freeze-job.ts +253 -0
  40. package/src/pinned-action.ts +30 -0
  41. package/src/pr-status-hud-workflow.ts +96 -0
  42. package/src/preview-cleanup-topology.ts +115 -0
  43. package/src/preview-proof-inventory.ts +1092 -0
  44. package/src/preview-proof-lifecycle.ts +328 -0
  45. package/src/preview-receipt-workflow.ts +83 -0
  46. package/src/production-impact-workflow.ts +181 -0
  47. package/src/proof-reuse-gate.ts +297 -63
  48. package/src/proof-reuse-presentation.ts +131 -0
  49. package/src/push-identity-workflow.ts +463 -0
  50. package/src/runnable-cli.ts +27 -0
  51. package/src/verify-runner-policy.ts +290 -0
  52. package/src/vitest-profile-reader.test.ts +208 -0
  53. package/src/vitest-profile-reader.ts +225 -0
  54. package/src/vitest-profile.ts +631 -0
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The child environment a local-emulation Alchemy run needs (#1168).
3
+ *
4
+ * Alchemy refuses to start when `CLOUDFLARE_ACCOUNT_ID` is missing or
5
+ * malformed, even for a run that only drives the local emulator and calls no
6
+ * Cloudflare API. Every project worked around that by handing the child a real
7
+ * account id and a real token, so a purely local run carried live credentials.
8
+ * This module hands it a sentinel pair instead: a well-formed account id that
9
+ * addresses no account, and a token that is not a token.
10
+ *
11
+ * The helper never reads a real credential. It reads one variable — the
12
+ * live-binding opt-in — and nothing else. The presence of a real credential in
13
+ * the parent environment is never the signal: a developer who is logged in to
14
+ * Cloudflare still gets the sentinel pair unless the opt-in says otherwise.
15
+ *
16
+ * Scrubbing an ambient token out of the child is the launcher's job, not this
17
+ * module's. This module owns the environment shape only.
18
+ */
19
+
20
+ import { HOSTED_CLOUDFLARE_CREDENTIAL_NAMES } from "./credential-preflight.ts";
21
+ import { isLocalEmulationStage } from "./stage-policy.ts";
22
+
23
+ const [ACCOUNT_ID_NAME, API_TOKEN_NAME] = HOSTED_CLOUDFLARE_CREDENTIAL_NAMES;
24
+
25
+ /**
26
+ * A well-formed Cloudflare account id that addresses no account.
27
+ *
28
+ * Alchemy validates the value against `/^[0-9a-f]{32}$/i` and rejects
29
+ * placeholders such as `""` or `dummy` with an authentication error before any
30
+ * run starts. The check is `validateAccountId`, in
31
+ * `alchemy/lib/Cloudflare/Auth/AuthProvider.js` at 2.0.0-beta.76 and in
32
+ * `alchemy/lib/Cloudflare/Auth/AuthConfig.js` at 2.0.0-beta.77. The file name
33
+ * moves; the pattern is the same in both. Thirty-two zeros pass that shape
34
+ * check and route to nothing.
35
+ */
36
+ const SENTINEL_ACCOUNT_ID = "0".repeat(32);
37
+
38
+ /**
39
+ * A token that is not a token. It is spelled as words, so no secret scanner
40
+ * reads it as a credential and no reader mistakes it for one. Any API call
41
+ * made with it fails, which is the intended outcome: a local-emulation run
42
+ * must reach no Cloudflare account.
43
+ */
44
+ const SENTINEL_API_TOKEN = "factory-ci-local-emulation-no-cloudflare-token";
45
+
46
+ /**
47
+ * The one way a real credential reaches a local-emulation child. Set it to a
48
+ * non-empty value and this helper returns no sentinel, so whatever
49
+ * `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` the parent carries pass
50
+ * through untouched and the run may bind a live Cloudflare resource.
51
+ */
52
+ const LIVE_BINDING_OPT_IN = "FACTORY_CI_LIVE_CLOUDFLARE_BINDING";
53
+
54
+ /**
55
+ * Build the Cloudflare variables a local-emulation child is launched with.
56
+ *
57
+ * Returns exactly two variables for the local-emulation stage, or no variables
58
+ * when the live-binding opt-in is set. The result is an overlay: merge it over
59
+ * the child environment the launcher has otherwise assembled.
60
+ *
61
+ * Throws for any other stage. A non-local stage deploys to a real account, so
62
+ * a sentinel there would break that deploy, and returning nothing instead
63
+ * would let a caller believe a local run was protected when it was not.
64
+ */
65
+ export const localEmulationEnvironment = (options: {
66
+ /**
67
+ * Where the opt-in is read from. Defaults to this process's environment. No
68
+ * other variable is read.
69
+ */
70
+ readonly environment?: Readonly<Record<string, string | undefined>>;
71
+ /** The Alchemy stage the child runs. */
72
+ readonly stage: string;
73
+ }): Readonly<Record<string, string>> => {
74
+ const { environment = process.env, stage } = options;
75
+ if (!isLocalEmulationStage(stage)) {
76
+ throw new Error(
77
+ `localEmulationEnvironment is only for the local-emulation stage, not "${stage}".`
78
+ );
79
+ }
80
+ // A variable set to whitespace is how an unset variable arrives through a
81
+ // shell that exports it anyway, so it does not count as an opt-in.
82
+ if ((environment[LIVE_BINDING_OPT_IN] ?? "").trim().length > 0) {
83
+ return {};
84
+ }
85
+ return {
86
+ [ACCOUNT_ID_NAME]: SENTINEL_ACCOUNT_ID,
87
+ [API_TOKEN_NAME]: SENTINEL_API_TOKEN,
88
+ };
89
+ };
@@ -0,0 +1,510 @@
1
+ /**
2
+ * The plan-output adapter (#1077): the one reader of what the installed
3
+ * Alchemy CLI prints for a plan.
4
+ *
5
+ * Alchemy has no structured plan output at the fleet baseline, so the plan
6
+ * is read from the lines `formatPlanLines` in `alchemy/src/Cli/LoggingCli.ts`
7
+ * prints: one `Plan:` summary, one `[fqn] action` line per resource, one
8
+ * `[fqn/name] action` line per binding of that resource, and one
9
+ * `[fqn] run|drop [action]` line per task. Paitronage and HQ each wrote this
10
+ * reader; this is the one copy, and it is bound to the Alchemy version whose
11
+ * renderer it reads. A consumer running a different Alchemy is refused by
12
+ * `runAlchemyLifecycle` before any child runs, so a renderer change cannot
13
+ * be read as a plan with different effects.
14
+ *
15
+ * The renderer logs every line through Effect's pretty console logger, so a
16
+ * line arrives as `[HH:MM:SS.mmm] INFO (#1): <line>`, and coloured when the
17
+ * child inherits `FORCE_COLOR`. Both wrappers are stripped before a line is
18
+ * read. The captured output under `tests/fixtures/plan-output/beta-81/` is
19
+ * the evidence for every shape this file reads.
20
+ *
21
+ * The adapter fails on anything it does not recognise: no summary, two
22
+ * summaries, an action outside the known set, a summary it cannot parse, a
23
+ * summary whose counts do not equal the lines under it, or rows the summary
24
+ * can place in more than one way. An effect it could not account for is
25
+ * never reported as zero.
26
+ *
27
+ * Two readings share that work. `parsePlanEffects` answers what the plan
28
+ * does, which is what the lifecycle's admission rules read. `canonicalPlan`
29
+ * answers what the plan *is*, as a stable string: the rows the renderer
30
+ * printed and the reading of them, with the per-run logger metadata it also
31
+ * prints left out. `firstDeployPlanHash` hashes that string, so a plan
32
+ * reviewed at one moment and deployed at another is the same plan (#1232).
33
+ */
34
+
35
+ import { ALCHEMY_BASELINE } from "../alchemy-baseline.ts";
36
+
37
+ /** The Alchemy version whose plan renderer this adapter reads. */
38
+ export const PLAN_OUTPUT_ALCHEMY_VERSION: string = ALCHEMY_BASELINE.alchemy;
39
+
40
+ /**
41
+ * Every action a resource row can carry. The first six are the actions the
42
+ * summary counts, in the order the renderer prints them; `noop` rows print
43
+ * under the summary but are never counted in it.
44
+ */
45
+ export const PLAN_ACTIONS = [
46
+ "create",
47
+ "update",
48
+ "adopted",
49
+ "replace",
50
+ "delete",
51
+ "orphaned",
52
+ "noop",
53
+ ] as const;
54
+
55
+ export type PlanAction = (typeof PLAN_ACTIONS)[number];
56
+
57
+ /** The actions the summary counts. */
58
+ const SUMMARY_ACTIONS = PLAN_ACTIONS.filter(
59
+ (action): action is Exclude<PlanAction, "noop"> => action !== "noop"
60
+ );
61
+
62
+ /** One top-level resource row of a plan. */
63
+ export interface PlanResourceEffect {
64
+ readonly action: PlanAction;
65
+ /**
66
+ * The fully qualified name Alchemy printed in the row's tag: the namespace
67
+ * path and the logical id joined by `/`. A top-level resource's FQN is its
68
+ * logical id. This is the identity Alchemy persists the resource under.
69
+ */
70
+ readonly id: string;
71
+ }
72
+
73
+ export type PlanTaskAction = "drop" | "run";
74
+
75
+ /** One task (`Action`) row of a plan. A task with nothing to do prints no row. */
76
+ export interface PlanTaskEffect {
77
+ readonly action: PlanTaskAction;
78
+ /** The task's fully qualified name, as printed in the row's tag. */
79
+ readonly id: string;
80
+ }
81
+
82
+ export interface PlanEffects {
83
+ /**
84
+ * Resource count per action. The six summary actions are what the summary
85
+ * line states; `noop` is counted from the rows, as the summary omits it.
86
+ */
87
+ readonly counts: Readonly<Record<PlanAction, number>>;
88
+ /** Every resource row, in the order printed. */
89
+ readonly resources: readonly PlanResourceEffect[];
90
+ /** Binding rows with a change, as the summary's `N binding changes` states. */
91
+ readonly bindingChanges: number;
92
+ /** Every task row, in the order printed. */
93
+ readonly tasks: readonly PlanTaskEffect[];
94
+ }
95
+
96
+ export type PlanEffectsRejection =
97
+ | "no-summary"
98
+ | "multiple-summaries"
99
+ | "unknown-action"
100
+ | "summary-unrecognized"
101
+ | "count-mismatch"
102
+ | "ambiguous-rows"
103
+ | "effects-under-no-changes";
104
+
105
+ /** The adapter could not read the output. `reason` is the whole detail. */
106
+ export class PlanEffectsError extends Error {
107
+ readonly reason: PlanEffectsRejection;
108
+
109
+ constructor(reason: PlanEffectsRejection) {
110
+ super(`Alchemy plan output was not readable: ${reason}.`);
111
+ this.name = "PlanEffectsError";
112
+ this.reason = reason;
113
+ }
114
+ }
115
+
116
+ const ACTION_SET: ReadonlySet<string> = new Set(PLAN_ACTIONS);
117
+ const BINDING_ACTIONS: ReadonlySet<string> = new Set([
118
+ "create",
119
+ "noop",
120
+ "unbind",
121
+ "update",
122
+ ]);
123
+ const TASK_ACTIONS: ReadonlySet<string> = new Set(["drop", "run"]);
124
+
125
+ const ansiPattern = new RegExp(
126
+ `${String.fromCodePoint(27)}\\[[0-?]*[ -/]*[@-~]`,
127
+ "gu"
128
+ );
129
+
130
+ /**
131
+ * The prefix Effect's pretty console logger puts before every line the
132
+ * renderer logs. Optional, so output that was not logged through it (an
133
+ * apply session's stack output, a scripted CLI in a test) reads the same.
134
+ */
135
+ const EFFECT_LOG_PREFIX =
136
+ /^\[\d{2}:\d{2}:\d{2}\.\d{3}\] (?:ALL|TRACE|DEBUG|INFO|WARN|ERROR|FATAL|NONE) \(#\d+\)(?: [^:]+)?:(?: |$)/u;
137
+
138
+ const ROW_PATTERN = /^\[(?<tag>[^\]]+)\]\s+(?<action>\S+)/u;
139
+ const TASK_ROW_PATTERN = /^\[(?<tag>[^\]]+)\]\s+(?<action>\S+)\s+\[action\]$/u;
140
+ const SUMMARY_PREFIX = "Plan:";
141
+ /** Every resource row is `noop`; there may be rows. */
142
+ const NO_CHANGES = "Plan: no changes";
143
+ /** The stack declares nothing and persists nothing; there are no rows. */
144
+ const NO_RESOURCES = "Plan: no resources";
145
+ const SUMMARY_ACTION_ITEM =
146
+ /^(?<count>\d+) to (?<action>create|update|adopted|replace|delete|orphaned)$/u;
147
+ const SUMMARY_BINDINGS_ITEM = /^(?<count>\d+) binding changes$/u;
148
+ const SUMMARY_TASKS_ITEM = /^(?<count>\d+) tasks$/u;
149
+
150
+ const zeroCounts = (): Record<PlanAction, number> => ({
151
+ adopted: 0,
152
+ create: 0,
153
+ delete: 0,
154
+ noop: 0,
155
+ orphaned: 0,
156
+ replace: 0,
157
+ update: 0,
158
+ });
159
+
160
+ const isPlanAction = (action: string): action is PlanAction =>
161
+ ACTION_SET.has(action);
162
+
163
+ const isTaskAction = (action: string): action is PlanTaskAction =>
164
+ TASK_ACTIONS.has(action);
165
+
166
+ /** What the summary states, and what the rows must add up to. */
167
+ interface Stated {
168
+ readonly bindingChanges: number;
169
+ readonly counts: Record<PlanAction, number>;
170
+ readonly tasks: number;
171
+ }
172
+
173
+ /** One `[tag] action` line that is a resource row or a binding row. */
174
+ interface Row {
175
+ readonly action: string;
176
+ readonly tag: string;
177
+ }
178
+
179
+ interface Rows {
180
+ readonly rows: readonly Row[];
181
+ readonly tasks: readonly PlanTaskEffect[];
182
+ }
183
+
184
+ interface Reading {
185
+ readonly bindingChanges: number;
186
+ readonly resources: readonly PlanResourceEffect[];
187
+ }
188
+
189
+ /**
190
+ * The rows under the summary, up to the first line that is not a row. An
191
+ * apply session prints its progress after a blank line, so that line ends
192
+ * the plan. A task row is told apart by its `[action]` suffix; a resource
193
+ * row and a binding row are told apart by `readRows` below.
194
+ */
195
+ const rowsUnder = (lines: readonly string[], summaryIndex: number): Rows => {
196
+ const rows: Row[] = [];
197
+ const tasks: PlanTaskEffect[] = [];
198
+ for (const line of lines.slice(summaryIndex + 1)) {
199
+ const task = TASK_ROW_PATTERN.exec(line)?.groups;
200
+ if (task?.tag !== undefined && task.action !== undefined) {
201
+ if (!isTaskAction(task.action)) {
202
+ throw new PlanEffectsError("unknown-action");
203
+ }
204
+ tasks.push({ action: task.action, id: task.tag });
205
+ continue;
206
+ }
207
+ const row = ROW_PATTERN.exec(line)?.groups;
208
+ if (row?.tag === undefined || row.action === undefined) {
209
+ break;
210
+ }
211
+ if (!(isPlanAction(row.action) || BINDING_ACTIONS.has(row.action))) {
212
+ throw new PlanEffectsError("unknown-action");
213
+ }
214
+ rows.push({ action: row.action, tag: row.tag });
215
+ }
216
+ return { rows, tasks };
217
+ };
218
+
219
+ /**
220
+ * The one reading of the rows as resources and bindings whose counts equal
221
+ * the summary. No such reading is a count mismatch; two are refused as
222
+ * ambiguous rather than guessed.
223
+ *
224
+ * A binding row is tagged `<resource fqn>/<name>` and printed directly under
225
+ * its resource, so it always extends the FQN of the last resource row. A
226
+ * resource inside a namespace is tagged the same way, and when it follows a
227
+ * resource whose FQN is its namespace path the two rows look alike:
228
+ * `prefix/plan.txt` under the fixtures prints `[Parent/bound] create` and
229
+ * `[Parent/Zed] create` under `[Parent] create`. The renderer gives no other
230
+ * evidence, so a row that extends the last resource's FQN is read both ways
231
+ * and the summary decides: it counts resources per action and the binding
232
+ * rows with a change, and only a reading that adds up to it survives.
233
+ *
234
+ * A `noop` row is counted by neither, so the summary cannot place it. Such a
235
+ * row extending the last resource's FQN is read as a binding: a `noop` row
236
+ * drives no decision (`runAlchemyLifecycle` reads only rows with work), and
237
+ * a plan's bindings are far more often `noop` than its namespaced resources
238
+ * are named after a sibling. `prefix/noop.txt` is that residual.
239
+ *
240
+ * The search counts readings, stopping at two, and is memoised on what the
241
+ * rest of the rows can depend on: the position, the last resource's FQN,
242
+ * and the `create` and `update` resources read so far (every other counted
243
+ * row is a resource, `unbind` is a binding, and `noop` is placed by rule, so
244
+ * those tallies follow from the position). A plan with many resources each
245
+ * followed by rows that extend its FQN then costs the product of the row
246
+ * count and the two tallies, not the product of the readings of each group.
247
+ * The first reading found is kept; every branch is on a row with work, so a
248
+ * second reading always places a row with work differently.
249
+ */
250
+ const readRows = (rows: readonly Row[], stated: Stated): Reading => {
251
+ const seen = zeroCounts();
252
+ const resources: PlanResourceEffect[] = [];
253
+ let bindingChanges = 0;
254
+ let first: readonly PlanResourceEffect[] | undefined;
255
+ const memo = new Map<string, number>();
256
+ const visit = (index: number, owner?: string): number => {
257
+ const row = rows[index];
258
+ if (row === undefined) {
259
+ if (
260
+ bindingChanges !== stated.bindingChanges ||
261
+ SUMMARY_ACTIONS.some((action) => seen[action] !== stated.counts[action])
262
+ ) {
263
+ return 0;
264
+ }
265
+ first ??= [...resources];
266
+ return 1;
267
+ }
268
+ const key = JSON.stringify([index, owner, seen.create, seen.update]);
269
+ const known = memo.get(key);
270
+ if (known !== undefined) {
271
+ return known;
272
+ }
273
+ let readings = 0;
274
+ const { action, tag } = row;
275
+ const extendsOwner = owner !== undefined && tag.startsWith(`${owner}/`);
276
+ if (extendsOwner && BINDING_ACTIONS.has(action)) {
277
+ if (action === "noop") {
278
+ return visit(index + 1, owner);
279
+ }
280
+ bindingChanges += 1;
281
+ if (bindingChanges <= stated.bindingChanges) {
282
+ readings += visit(index + 1, owner);
283
+ }
284
+ bindingChanges -= 1;
285
+ }
286
+ if (readings < 2 && isPlanAction(action)) {
287
+ seen[action] += 1;
288
+ resources.push({ action, id: tag });
289
+ if (action === "noop" || seen[action] <= stated.counts[action]) {
290
+ readings += visit(index + 1, tag);
291
+ }
292
+ resources.pop();
293
+ seen[action] -= 1;
294
+ }
295
+ const capped = Math.min(readings, 2);
296
+ memo.set(key, capped);
297
+ return capped;
298
+ };
299
+ const readings = visit(0);
300
+ if (first === undefined || readings === 0) {
301
+ throw new PlanEffectsError("count-mismatch");
302
+ }
303
+ if (readings > 1) {
304
+ throw new PlanEffectsError("ambiguous-rows");
305
+ }
306
+ return { bindingChanges: stated.bindingChanges, resources: first };
307
+ };
308
+
309
+ /**
310
+ * The counts the summary states, in the order Alchemy prints them: the six
311
+ * actions, then `N binding changes`, then `N tasks`, each only when non-zero.
312
+ * The summary is rebuilt from what was read and must equal the line, so a
313
+ * summary with an extra clause, a repeated part, or a different order is
314
+ * refused instead of partially read.
315
+ */
316
+ const countsStated = (summary: string): Stated => {
317
+ const counts = zeroCounts();
318
+ let bindingChanges = 0;
319
+ let tasks = 0;
320
+ for (const item of summary.slice(SUMMARY_PREFIX.length).trim().split(", ")) {
321
+ const action = SUMMARY_ACTION_ITEM.exec(item)?.groups;
322
+ const bindings = SUMMARY_BINDINGS_ITEM.exec(item)?.groups;
323
+ const taskCount = SUMMARY_TASKS_ITEM.exec(item)?.groups;
324
+ if (action?.action && isPlanAction(action.action)) {
325
+ counts[action.action] = Number(action.count);
326
+ } else if (bindings) {
327
+ bindingChanges = Number(bindings.count);
328
+ } else if (taskCount) {
329
+ tasks = Number(taskCount.count);
330
+ } else {
331
+ throw new PlanEffectsError("summary-unrecognized");
332
+ }
333
+ }
334
+ const canonical = [
335
+ ...SUMMARY_ACTIONS.filter((action) => counts[action] > 0).map(
336
+ (action) => `${counts[action]} to ${action}`
337
+ ),
338
+ ...(bindingChanges > 0 ? [`${bindingChanges} binding changes`] : []),
339
+ ...(tasks > 0 ? [`${tasks} tasks`] : []),
340
+ ].join(", ");
341
+ if (canonical === "" || `${SUMMARY_PREFIX} ${canonical}` !== summary) {
342
+ throw new PlanEffectsError("summary-unrecognized");
343
+ }
344
+ return { bindingChanges, counts, tasks };
345
+ };
346
+
347
+ /** The summary line and the rows under it, before either is interpreted. */
348
+ interface PlanLines extends Rows {
349
+ readonly summary: string;
350
+ }
351
+
352
+ /**
353
+ * Split the output into the one summary line and the rows under it. This is
354
+ * the whole of what the renderer's output is read as; `planEffects` below
355
+ * interprets it, and `canonicalPlan` serialises it.
356
+ */
357
+ const planLines = (output: string): PlanLines => {
358
+ const lines = output
359
+ .replaceAll(ansiPattern, "")
360
+ .split("\n")
361
+ .map((line) => line.replace(EFFECT_LOG_PREFIX, "").trim());
362
+ const summaryIndexes = lines.flatMap((line, index) =>
363
+ line.startsWith(SUMMARY_PREFIX) ? [index] : []
364
+ );
365
+ if (summaryIndexes.length === 0) {
366
+ throw new PlanEffectsError("no-summary");
367
+ }
368
+ if (summaryIndexes.length > 1) {
369
+ throw new PlanEffectsError("multiple-summaries");
370
+ }
371
+ const summaryIndex = summaryIndexes[0] ?? 0;
372
+ return {
373
+ summary: lines[summaryIndex] ?? "",
374
+ ...rowsUnder(lines, summaryIndex),
375
+ };
376
+ };
377
+
378
+ /** What the summary and the rows under it say the plan does. */
379
+ const planEffects = ({ rows, summary, tasks }: PlanLines): PlanEffects => {
380
+ if (summary === NO_RESOURCES) {
381
+ if (rows.length > 0 || tasks.length > 0) {
382
+ throw new PlanEffectsError("effects-under-no-changes");
383
+ }
384
+ return {
385
+ bindingChanges: 0,
386
+ counts: zeroCounts(),
387
+ resources: [],
388
+ tasks: [],
389
+ };
390
+ }
391
+
392
+ const stated =
393
+ summary === NO_CHANGES
394
+ ? { bindingChanges: 0, counts: zeroCounts(), tasks: 0 }
395
+ : countsStated(summary);
396
+ if (tasks.length !== stated.tasks) {
397
+ throw new PlanEffectsError("count-mismatch");
398
+ }
399
+ const { bindingChanges, resources } = readRows(rows, stated);
400
+ const counts = zeroCounts();
401
+ for (const { action } of resources) {
402
+ counts[action] += 1;
403
+ }
404
+ return { bindingChanges, counts, resources, tasks };
405
+ };
406
+
407
+ /**
408
+ * Read one plan from Alchemy CLI output.
409
+ *
410
+ * Throws `PlanEffectsError` on output the adapter cannot account for. The
411
+ * output itself never appears in the error.
412
+ */
413
+ export const parsePlanEffects = (output: string): PlanEffects =>
414
+ planEffects(planLines(output));
415
+
416
+ /** One row of the canonical form. `tag` is the row's tag, verbatim. */
417
+ interface CanonicalRow {
418
+ readonly action: string;
419
+ readonly kind: "row" | "task";
420
+ readonly tag: string;
421
+ }
422
+
423
+ const compareText = (left: string, right: string): number => {
424
+ if (left < right) {
425
+ return -1;
426
+ }
427
+ return left > right ? 1 : 0;
428
+ };
429
+
430
+ const compareCanonicalRows = (
431
+ left: CanonicalRow,
432
+ right: CanonicalRow
433
+ ): number =>
434
+ compareText(left.kind, right.kind) ||
435
+ compareText(left.tag, right.tag) ||
436
+ compareText(left.action, right.action);
437
+
438
+ const compareResources = (
439
+ left: PlanResourceEffect,
440
+ right: PlanResourceEffect
441
+ ): number =>
442
+ compareText(left.id, right.id) || compareText(left.action, right.action);
443
+
444
+ /**
445
+ * The plan as a stable string: what the renderer said about the plan, with
446
+ * what it said about the run that printed it left out.
447
+ *
448
+ * A plan carries no resource properties — the renderer prints a summary and
449
+ * one `[tag] action` row per resource, binding and task, and nothing else.
450
+ * So the canonical form is the summary line, every row under it as
451
+ * `{ action, kind, tag }`, and the reading of those rows `parsePlanEffects`
452
+ * arrives at (`resources` and `bindingChanges`). What is left out is the
453
+ * logger's timestamps and fiber ids, the `Plan ready (2.9s)` duration, ANSI
454
+ * colour, and everything after the rows: per-run facts about the process,
455
+ * not about the plan, and hashing them is why a reviewed plan could never be
456
+ * deployed (#1232).
457
+ *
458
+ * The rows and the reading each say something the other does not, so both
459
+ * are kept:
460
+ *
461
+ * - Every row is kept, including binding rows and `noop` rows, because
462
+ * `PlanEffects` reduces bindings to a count. A binding renamed with the
463
+ * count unchanged is one `PlanEffects` value and two row multisets.
464
+ * - The reading is kept because the rows alone do not say which of them are
465
+ * resources. A binding row and a namespaced resource row print alike —
466
+ * `[Parent/bound] create` and `[Parent/Zed] create` under
467
+ * `[Parent] create` — and only print order and the summary's counts tell
468
+ * them apart. Sorting the rows drops the order, so swapping those two rows
469
+ * is two plans creating different resources over one row multiset. The
470
+ * resource list the summary forces is what separates them.
471
+ *
472
+ * Together they pin the bindings too: the rows are the whole multiset and
473
+ * the resources are a sub-multiset of it, so the bindings are what remains.
474
+ *
475
+ * Rows and resources are both sorted, keeping duplicates, because print
476
+ * order is the renderer's traversal and authorizes nothing on its own: a
477
+ * plan that printed the same resources and bindings in another order must
478
+ * not read as a different plan.
479
+ *
480
+ * The full `parsePlanEffects` validation runs first, so anything the adapter
481
+ * refuses is refused here too (`PlanEffectsError`). Output it cannot account
482
+ * for is never canonicalised, and so is never authorized. `rowsUnder` stops
483
+ * at the first line that is not a row, so a log line interleaved into the
484
+ * rows on a chattier run drops the rows after it: an uncounted (`noop`) row
485
+ * lost that way changes the hash, and a row with work lost that way fails
486
+ * the summary's counts (`count-mismatch`). Either way the run is refused
487
+ * rather than admitted on less than the plan.
488
+ */
489
+ export const canonicalPlan = (output: string): string => {
490
+ const lines = planLines(output);
491
+ const { bindingChanges, resources } = planEffects(lines);
492
+ const rows: readonly CanonicalRow[] = [
493
+ ...lines.rows.map(({ action, tag }) => ({
494
+ action,
495
+ kind: "row" as const,
496
+ tag,
497
+ })),
498
+ ...lines.tasks.map(({ action, id }) => ({
499
+ action,
500
+ kind: "task" as const,
501
+ tag: id,
502
+ })),
503
+ ].toSorted(compareCanonicalRows);
504
+ return JSON.stringify({
505
+ bindingChanges,
506
+ resources: resources.toSorted(compareResources),
507
+ rows,
508
+ summary: lines.summary,
509
+ });
510
+ };