@intentius/chant 0.124.76 → 0.124.77

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 (146) 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/agent-guard.d.ts +143 -0
  11. package/dist/agent-guard.d.ts.map +1 -0
  12. package/dist/agent-guard.js +456 -0
  13. package/dist/ci-commit.d.ts +54 -3
  14. package/dist/ci-commit.d.ts.map +1 -1
  15. package/dist/ci-commit.js +69 -7
  16. package/dist/ci-own-jobs.d.ts +81 -0
  17. package/dist/ci-own-jobs.d.ts.map +1 -0
  18. package/dist/ci-own-jobs.js +234 -0
  19. package/dist/ci-product.d.ts +39 -0
  20. package/dist/ci-product.d.ts.map +1 -1
  21. package/dist/ci-product.js +40 -0
  22. package/dist/cli/handlers/approve.d.ts +5 -1
  23. package/dist/cli/handlers/approve.d.ts.map +1 -1
  24. package/dist/cli/handlers/approve.js +17 -11
  25. package/dist/cli/handlers/build.d.ts +1 -1
  26. package/dist/cli/handlers/build.d.ts.map +1 -1
  27. package/dist/cli/handlers/build.js +88 -2
  28. package/dist/cli/handlers/commit.d.ts.map +1 -1
  29. package/dist/cli/handlers/commit.js +3 -1
  30. package/dist/cli/handlers/notify-relay.d.ts +18 -1
  31. package/dist/cli/handlers/notify-relay.d.ts.map +1 -1
  32. package/dist/cli/handlers/notify-relay.js +90 -14
  33. package/dist/cli/handlers/pr.d.ts.map +1 -1
  34. package/dist/cli/handlers/pr.js +3 -1
  35. package/dist/cli/handlers/release.d.ts +5 -1
  36. package/dist/cli/handlers/release.d.ts.map +1 -1
  37. package/dist/cli/handlers/release.js +17 -5
  38. package/dist/cli/handlers/run-generate.d.ts.map +1 -1
  39. package/dist/cli/handlers/run-generate.js +2 -1
  40. package/dist/cli/main.d.ts.map +1 -1
  41. package/dist/cli/main.js +21 -1
  42. package/dist/cli/parse-args.d.ts.map +1 -1
  43. package/dist/cli/parse-args.js +60 -4
  44. package/dist/cli/registry.d.ts +16 -0
  45. package/dist/cli/registry.d.ts.map +1 -1
  46. package/dist/components/pr-env-components.d.ts +65 -0
  47. package/dist/components/pr-env-components.d.ts.map +1 -0
  48. package/dist/components/pr-env-components.js +163 -0
  49. package/dist/components/pr-policy.d.ts +15 -0
  50. package/dist/components/pr-policy.d.ts.map +1 -1
  51. package/dist/components/pr-policy.js +24 -1
  52. package/dist/components/release-compile.d.ts +15 -3
  53. package/dist/components/release-compile.d.ts.map +1 -1
  54. package/dist/components/release-compile.js +66 -15
  55. package/dist/gate-policy.d.ts +14 -1
  56. package/dist/gate-policy.d.ts.map +1 -1
  57. package/dist/gate-policy.js +16 -6
  58. package/dist/lexicon.d.ts +17 -1
  59. package/dist/lexicon.d.ts.map +1 -1
  60. package/dist/lexicon.js +1 -0
  61. package/dist/lifecycle/gated-op.d.ts +95 -0
  62. package/dist/lifecycle/gated-op.d.ts.map +1 -0
  63. package/dist/lifecycle/gated-op.js +96 -0
  64. package/dist/lifecycle/git.d.ts.map +1 -1
  65. package/dist/lifecycle/git.js +83 -2
  66. package/dist/notify-relay-repo.d.ts +131 -0
  67. package/dist/notify-relay-repo.d.ts.map +1 -0
  68. package/dist/notify-relay-repo.js +202 -0
  69. package/dist/notify-relay.d.ts +25 -1
  70. package/dist/notify-relay.d.ts.map +1 -1
  71. package/dist/notify-relay.js +28 -2
  72. package/dist/op/op-waves-capability.js +2 -2
  73. package/dist/policy-engine.d.ts +95 -0
  74. package/dist/policy-engine.d.ts.map +1 -0
  75. package/dist/policy-engine.js +158 -0
  76. package/dist/release-floors.d.ts +1 -1
  77. package/dist/release-floors.js +1 -1
  78. package/dist/state-export.d.ts +126 -0
  79. package/dist/state-export.d.ts.map +1 -0
  80. package/dist/state-export.js +157 -0
  81. package/dist/state-migration.d.ts +148 -0
  82. package/dist/state-migration.d.ts.map +1 -0
  83. package/dist/state-migration.js +147 -0
  84. package/dist/state-unlock.d.ts +167 -0
  85. package/dist/state-unlock.d.ts.map +1 -0
  86. package/dist/state-unlock.js +197 -0
  87. package/dist/wave-runtime.mjs +329 -329
  88. package/dist/workspace/declaration.schema.json +1 -1
  89. package/dist/workspace/release-workflow.d.ts +10 -0
  90. package/dist/workspace/release-workflow.d.ts.map +1 -1
  91. package/dist/workspace/release-workflow.js +8 -3
  92. package/package.json +1 -1
  93. package/src/__fixtures__/agent-guard/plywood.ts +27 -0
  94. package/src/__fixtures__/agent-guard/terragucci.ts +39 -0
  95. package/src/__fixtures__/gated-ledger.ts +58 -0
  96. package/src/agent-guard.test.ts +320 -0
  97. package/src/agent-guard.ts +548 -0
  98. package/src/ci-commit.test.ts +50 -2
  99. package/src/ci-commit.ts +93 -9
  100. package/src/ci-own-jobs.test.ts +109 -0
  101. package/src/ci-own-jobs.ts +253 -0
  102. package/src/ci-product.ts +81 -0
  103. package/src/cli/handlers/approve-cwd.test.ts +112 -0
  104. package/src/cli/handlers/approve.ts +22 -11
  105. package/src/cli/handlers/build-own-jobs.test.ts +80 -0
  106. package/src/cli/handlers/build-pr-loop-control.test.ts +88 -0
  107. package/src/cli/handlers/build-run-group.test.ts +60 -0
  108. package/src/cli/handlers/build.ts +83 -3
  109. package/src/cli/handlers/commit.ts +3 -0
  110. package/src/cli/handlers/notify-relay.ts +99 -17
  111. package/src/cli/handlers/pr.ts +3 -1
  112. package/src/cli/handlers/release.ts +15 -5
  113. package/src/cli/handlers/run-generate.ts +2 -1
  114. package/src/cli/main.ts +21 -1
  115. package/src/cli/parse-args.ts +45 -3
  116. package/src/cli/registry.ts +16 -0
  117. package/src/components/pr-env-components.test.ts +138 -0
  118. package/src/components/pr-env-components.ts +214 -0
  119. package/src/components/pr-policy.test.ts +41 -1
  120. package/src/components/pr-policy.ts +25 -1
  121. package/src/components/release-compile.test.ts +47 -0
  122. package/src/components/release-compile.ts +70 -13
  123. package/src/gate-policy-bundle.test.ts +14 -0
  124. package/src/gate-policy.test.ts +7 -0
  125. package/src/gate-policy.ts +22 -7
  126. package/src/lexicon.ts +18 -1
  127. package/src/lifecycle/gated-op.ts +158 -0
  128. package/src/lifecycle/git.test.ts +92 -0
  129. package/src/lifecycle/git.ts +71 -2
  130. package/src/notify-relay-repo.test.ts +284 -0
  131. package/src/notify-relay-repo.ts +234 -0
  132. package/src/notify-relay.test.ts +12 -0
  133. package/src/notify-relay.ts +30 -3
  134. package/src/op/op-waves-capability.ts +2 -2
  135. package/src/policy-engine.test.ts +163 -0
  136. package/src/policy-engine.ts +201 -0
  137. package/src/release-floors.ts +1 -1
  138. package/src/state-export.test.ts +125 -0
  139. package/src/state-export.ts +228 -0
  140. package/src/state-migration.test.ts +134 -0
  141. package/src/state-migration.ts +237 -0
  142. package/src/state-unlock.test.ts +166 -0
  143. package/src/state-unlock.ts +294 -0
  144. package/src/workspace/declaration.schema.json +1 -1
  145. package/src/workspace/release-workflow.test.ts +34 -0
  146. package/src/workspace/release-workflow.ts +17 -3
@@ -0,0 +1,138 @@
1
+ /**
2
+ * #4762: a pull request's environment of separately planned components,
3
+ * through prEnvUp and prEnvDown with in-memory ports and a component planner
4
+ * that records what it was asked. No engine, ledger or forge is reached.
5
+ */
6
+ import { describe, expect, test } from "vitest";
7
+ import { NEXT_RELEASE } from "../release-floors";
8
+ import { componentsPrEnvAdapter, componentsPrEnvTeardown, PR_ENV_COMPONENTS_FLOOR, type PrEnvComponentPlan } from "./pr-env-components";
9
+ import { prEnvDown, prEnvUp, type PrEnvApproval, type PrEnvPorts } from "./pr-env-run";
10
+ import { livePrEnvironments, type PrEnvRecord } from "./pr-environment";
11
+
12
+ const HEAD = "b".repeat(40);
13
+ const NOW = () => new Date("2026-11-08T10:00:00.000Z");
14
+
15
+ function ports(approval: PrEnvApproval, records: PrEnvRecord[] = []): PrEnvPorts & { records: PrEnvRecord[]; digests: string[] } {
16
+ const digests: string[] = [];
17
+ return {
18
+ records,
19
+ digests,
20
+ readRecords: async () => [...records],
21
+ appendRecord: async (r) => void records.push(r),
22
+ decideGate: async (input) => {
23
+ digests.push(input.digest);
24
+ return approval;
25
+ },
26
+ };
27
+ }
28
+
29
+ /** A planner over named components: each plans `changes` creates at `<name>-<env>`, unless told to fail. */
30
+ function planner(opts: { changes?: number; failPlan?: string; failApply?: string } = {}) {
31
+ const applied: string[] = [];
32
+ const planned: string[] = [];
33
+ const plan = (name: string, env: string, destroy = false): PrEnvComponentPlan => {
34
+ planned.push(`${destroy ? "destroy " : ""}${name}`);
35
+ if (name === opts.failPlan) return { component: name, planDigest: "", create: 0, update: 0, replace: 0, delete: 0, error: "plan failed", apply: async () => {} };
36
+ return {
37
+ component: name,
38
+ planDigest: `sha256:${name}${destroy ? "-destroy" : ""}`,
39
+ create: destroy ? 0 : (opts.changes ?? 1),
40
+ update: 0,
41
+ replace: 0,
42
+ delete: destroy ? 1 : 0,
43
+ location: `s3://acme/${name}-${env}.tfstate`,
44
+ apply: async () => {
45
+ if (name === opts.failApply) throw new Error("apply broke");
46
+ applied.push(`${destroy ? "destroy " : ""}${name}`);
47
+ },
48
+ };
49
+ };
50
+ return { applied, planned, plan };
51
+ }
52
+
53
+ const up = (p: PrEnvPorts, adapter: ReturnType<typeof componentsPrEnvAdapter>) => prEnvUp({ pr: 7, head: HEAD, template: "copy", stack: "product", adapter, ports: p, now: NOW });
54
+
55
+ describe("componentsPrEnvAdapter", () => {
56
+ test("plans every component, waits for an approval of the set digest, then applies in order and records where each copy is", async () => {
57
+ const pl = planner();
58
+ const adapter = componentsPrEnvAdapter({ components: async () => ["network", "app"], plan: (n, _i, t) => Promise.resolve(pl.plan(n, t.env)) });
59
+ const waiting = ports({ status: "pending" });
60
+ const first = await up(waiting, adapter);
61
+ expect(first.exit).toBe(3);
62
+ expect(pl.applied).toEqual([]);
63
+ const p = ports({ status: "approved", approvedBy: ["bo"] });
64
+ const second = await up(p, adapter);
65
+ expect(second.exit).toBe(0);
66
+ expect(p.digests).toEqual(waiting.digests);
67
+ expect(pl.applied).toEqual(["network", "app"]);
68
+ expect(p.records[0]).toMatchObject({ components: ["network", "app"], locations: { network: "s3://acme/network-pr-7.tfstate", app: "s3://acme/app-pr-7.tfstate" }, result: "applied" });
69
+ });
70
+
71
+ test("an empty plan applies with no approval, and no components gives the environment nothing", async () => {
72
+ const pl = planner({ changes: 0 });
73
+ const p = ports({ status: "pending" });
74
+ expect((await up(p, componentsPrEnvAdapter({ components: async () => ["app"], plan: (n, _i, t) => Promise.resolve(pl.plan(n, t.env)) }))).exit).toBe(0);
75
+ expect(p.digests).toEqual([]);
76
+ expect(pl.applied).toEqual(["app"]);
77
+ const none = await up(ports({ status: "pending" }), componentsPrEnvAdapter({ components: async () => [], plan: async () => pl.plan("x", "pr-7"), nothing: () => "no root matches" }));
78
+ expect(none.report).toMatchObject({ status: "nothing", message: "no root matches" });
79
+ });
80
+
81
+ test("a component that does not plan stops the environment, and one that does not apply stops the rest", async () => {
82
+ const pl = planner({ failPlan: "app" });
83
+ const failedPlan = await up(ports({ status: "approved" }), componentsPrEnvAdapter({ components: async () => ["network", "app"], plan: (n, _i, t) => Promise.resolve(pl.plan(n, t.env)) }));
84
+ expect(failedPlan.report.status).toBe("plan-failed");
85
+ expect(pl.applied).toEqual([]);
86
+ const pa = planner({ failApply: "network" });
87
+ const p = ports({ status: "approved" });
88
+ const failedApply = await up(p, componentsPrEnvAdapter({ components: async () => ["network", "app"], plan: (n, _i, t) => Promise.resolve(pa.plan(n, t.env)) }));
89
+ expect(failedApply.exit).toBe(1);
90
+ expect(failedApply.report.components.map((c) => c.status)).toEqual(["failed", "not applied"]);
91
+ expect(p.records[0]!.result).toBe("failed");
92
+ });
93
+
94
+ test("a refusal thrown while planning is kept for the caller", async () => {
95
+ const adapter = componentsPrEnvAdapter({ components: async () => ["app"], plan: async () => Promise.reject(new Error("a cloud block")) });
96
+ const r = await up(ports({ status: "approved" }), adapter);
97
+ expect(r.report.status).toBe("plan-failed");
98
+ expect(adapter.refused?.message).toBe("a cloud block");
99
+ });
100
+ });
101
+
102
+ describe("componentsPrEnvTeardown", () => {
103
+ test("destroys the components it owns in reverse apply order, and leaves a hole for a location that is not the environment's", async () => {
104
+ const pl = planner();
105
+ const p = ports({ status: "approved" });
106
+ await up(p, componentsPrEnvAdapter({ components: async () => ["network", "app", "dns"], plan: (n, _i, t) => Promise.resolve(pl.plan(n, t.env)) }));
107
+ const rec = p.records[0]!;
108
+ rec.locations!.dns = "s3://acme/dns.tfstate";
109
+ let released = 0;
110
+ const teardown = componentsPrEnvTeardown({
111
+ name: "product",
112
+ type: "terraform_root",
113
+ owns: (location, env) => location.endsWith(`-${env}.tfstate`),
114
+ checkout: async () => ({ plan: async (n) => pl.plan(n, "pr-7", true), done: () => void released++ }),
115
+ });
116
+ const down = await prEnvDown({ pr: 7, reason: "closed", ports: p, adapters: [teardown], commit: HEAD, now: NOW });
117
+ expect(pl.applied.filter((a) => a.startsWith("destroy"))).toEqual(["destroy app", "destroy network"]);
118
+ expect(released).toBe(1);
119
+ expect(down.report.status).toBe("incomplete");
120
+ expect(livePrEnvironments(p.records).get("pr-7")?.teardownIncomplete).toBe(true);
121
+ });
122
+
123
+ test("a destroy that fails is that component's failure alone", async () => {
124
+ const pl = planner({ failApply: "app" });
125
+ const p = ports({ status: "approved" });
126
+ await up(p, componentsPrEnvAdapter({ components: async () => ["network"], plan: (n, _i, t) => Promise.resolve(pl.plan(n, t.env)) }));
127
+ p.records[0]!.components.push("app");
128
+ p.records[0]!.locations!.app = "s3://acme/app-pr-7.tfstate";
129
+ const teardown = componentsPrEnvTeardown({ name: "product", type: "terraform_root", owns: () => true, checkout: async () => ({ plan: async (n) => pl.plan(n, "pr-7", true) }) });
130
+ const down = await prEnvDown({ pr: 7, reason: "closed", ports: p, adapters: [teardown], commit: HEAD, now: NOW });
131
+ expect(pl.applied).toContain("destroy network");
132
+ expect(down.report.status).toBe("incomplete");
133
+ });
134
+
135
+ test("its floor is the next release", () => {
136
+ expect(PR_ENV_COMPONENTS_FLOOR).toBe(NEXT_RELEASE);
137
+ });
138
+ });
@@ -0,0 +1,214 @@
1
+ /**
2
+ * A pull request's environment made of separately planned components
3
+ * (#4762): the adapter and teardown `prEnvUp`, `prEnvDown` and `prEnvSweep`
4
+ * (./pr-env-run.ts) take, built from one function that plans a component.
5
+ *
6
+ * Engine-neutral. An engine supplies {@link PrEnvComponentPlan}s: a
7
+ * component's plan, what it changes, where its copy lives, and how to apply
8
+ * that plan. The terraform lexicon plans each root's copy under a suffixed
9
+ * state key (`@intentius/chant-lexicon-terraform/pr-env`); a Pulumi review
10
+ * stack, or a database branch per pull request, plans the same way. The
11
+ * rules they share live here:
12
+ *
13
+ * - every component plans before anything applies, and one that does not
14
+ * plan stops the whole environment;
15
+ * - the digest an approval binds is the set digest over each component's
16
+ * plan digest, as a wave's is;
17
+ * - the plans apply in order, and the first that fails stops the rest, with
18
+ * what applied kept on the record so the teardown finds it;
19
+ * - the teardown takes only the components whose recorded location the
20
+ * engine says is the environment's own (`owns`), and destroys them in the
21
+ * reverse of the order they applied in, since a later one may read an
22
+ * earlier one's outputs.
23
+ */
24
+ import { waveSetDigest } from "../gated-waves";
25
+ import type { TeardownOutcome } from "../lexicon";
26
+ import { NEXT_RELEASE } from "../release-floors";
27
+ import type { PrEnvAdapter, PrEnvPlanned, PrEnvTarget } from "./pr-env-run";
28
+ import type { LivePrEnvironment, PrEnvReportRow, PrEnvTeardownAdapter } from "./pr-environment";
29
+
30
+ /** The first chant with the component adapter and teardown, and the terraform lexicon's copies on them (#4762). */
31
+ export const PR_ENV_COMPONENTS_FLOOR = NEXT_RELEASE;
32
+
33
+ /** One component's plan, as an engine answers it. */
34
+ export interface PrEnvComponentPlan {
35
+ component: string;
36
+ /** The plan's digest, which the environment's set digest covers. Empty when it did not plan. */
37
+ planDigest: string;
38
+ create: number;
39
+ update: number;
40
+ replace: number;
41
+ delete: number;
42
+ /** Where its copy lives, kept on the record for the teardown, such as a suffixed state key. */
43
+ location?: string;
44
+ /** Why it did not plan. */
45
+ error?: string;
46
+ /** Apply exactly this plan. Throws when it fails. */
47
+ apply(): Promise<void>;
48
+ }
49
+
50
+ const changes = (p: PrEnvComponentPlan): number => p.create + p.update + p.replace + p.delete;
51
+
52
+ const rowOf = (p: PrEnvComponentPlan, status: string): PrEnvReportRow => ({
53
+ component: p.component,
54
+ status,
55
+ create: p.create,
56
+ update: p.update,
57
+ replace: p.replace,
58
+ delete: p.delete,
59
+ ...(p.location ? { location: p.location } : {}),
60
+ });
61
+
62
+ const messageOf = (e: unknown): string => (e instanceof Error ? e.message : String(e));
63
+
64
+ export interface PrEnvComponentsInput {
65
+ /** The components of this environment, in apply order. None: the change reaches nothing, and the environment gets nothing. */
66
+ components(target: PrEnvTarget): Promise<string[]>;
67
+ /** Plan one component. An error it answers is a plan that failed; a throw refuses the environment and is kept in `refused`. */
68
+ plan(component: string, index: number, target: PrEnvTarget): Promise<PrEnvComponentPlan>;
69
+ /** What an environment with no components says. */
70
+ nothing?: (target: PrEnvTarget) => string;
71
+ log?: (line: string) => void;
72
+ }
73
+
74
+ /**
75
+ * The adapter `prEnvUp` takes, over a component planner. `refused` holds an
76
+ * error `components` or `plan` threw, which `prEnvUp` reports as a failed
77
+ * plan, so a caller that treats it as a config error can raise it.
78
+ */
79
+ export function componentsPrEnvAdapter(input: PrEnvComponentsInput): PrEnvAdapter & { refused?: Error } {
80
+ const log = input.log ?? (() => {});
81
+ let plans: PrEnvComponentPlan[] = [];
82
+ const adapter: PrEnvAdapter & { refused?: Error } = {
83
+ async plan(target): Promise<PrEnvPlanned> {
84
+ try {
85
+ const names = await input.components(target);
86
+ if (names.length === 0) {
87
+ const message = input.nothing?.(target) ?? `nothing in this change has a copy in ${target.env}`;
88
+ log(message);
89
+ return { digest: "", empty: true, rows: [], message };
90
+ }
91
+ plans = [];
92
+ for (const [i, name] of names.entries()) {
93
+ const p = await input.plan(name, i, target);
94
+ plans.push(p);
95
+ log(p.error ? `${p.component}: ${p.error}` : `${p.component}: ${changes(p)} to change${p.location ? ` at ${p.location}` : ""}`);
96
+ }
97
+ const failed = plans.filter((p) => p.error);
98
+ if (failed.length > 0) {
99
+ const message = `${failed.map((p) => p.component).join(", ")} did not plan, so nothing of ${target.env} applies`;
100
+ return { digest: "", empty: false, failed: true, rows: plans.map((p) => rowOf(p, p.error ? "plan-failed" : "planned")), message };
101
+ }
102
+ const digest = waveSetDigest(plans.map((p) => ({ member: p.component, planDigest: p.planDigest })));
103
+ return { digest, empty: plans.every((p) => changes(p) === 0), rows: plans.map((p) => rowOf(p, "planned")) };
104
+ } catch (e) {
105
+ adapter.refused = e instanceof Error ? e : new Error(String(e));
106
+ throw e;
107
+ }
108
+ },
109
+ async apply() {
110
+ const rows: PrEnvReportRow[] = [];
111
+ let failed: string | undefined;
112
+ for (const p of plans) {
113
+ if (failed) {
114
+ rows.push(rowOf(p, "not applied"));
115
+ continue;
116
+ }
117
+ try {
118
+ await p.apply();
119
+ rows.push(rowOf(p, "applied"));
120
+ log(`applied ${p.component}${p.location ? ` at ${p.location}` : ""}`);
121
+ } catch (e) {
122
+ failed = `${p.component} did not apply: ${messageOf(e)}`;
123
+ rows.push(rowOf(p, "failed"));
124
+ log(`FAILED ${failed}`);
125
+ }
126
+ }
127
+ const locations = Object.fromEntries(plans.filter((p) => p.location).map((p) => [p.component, p.location!]));
128
+ return { status: failed ? "failed" : "applied", rows, ...(Object.keys(locations).length ? { locations } : {}), ...(failed ? { message: failed } : {}) };
129
+ },
130
+ };
131
+ return adapter;
132
+ }
133
+
134
+ /** What a teardown plans the destroys with: the code the environment applied from, prepared, and released after. */
135
+ export interface PrEnvTeardownCheckout {
136
+ /** Plan one component's destroy. An error it answers, or a throw, fails that component alone. */
137
+ plan(component: string, index: number): Promise<PrEnvComponentPlan>;
138
+ /** Release what the checkout holds, after every destroy. */
139
+ done?(): void;
140
+ }
141
+
142
+ export interface PrEnvComponentsTeardownInput {
143
+ /** The name outcomes are attributed to. */
144
+ name: string;
145
+ /** The lexicons this teardown stands in for. */
146
+ lexicons?: string[];
147
+ /** The candidates' resource type, such as `terraform_root`. */
148
+ type: string;
149
+ /** Whether a component's recorded location is this environment's own copy and not the component's own state. */
150
+ owns(location: string, env: string): boolean;
151
+ /** Prepare the code the environment last applied from (`live.commit`). */
152
+ checkout(live: LivePrEnvironment): Promise<PrEnvTeardownCheckout>;
153
+ log?: (line: string) => void;
154
+ }
155
+
156
+ /**
157
+ * The teardown `prEnvDown` and `prEnvSweep` take, over a component planner.
158
+ * A component whose recorded location the engine does not own, or that has
159
+ * no location recorded, is a hole, so nothing at a component's own state is
160
+ * destroyed.
161
+ */
162
+ export function componentsPrEnvTeardown(input: PrEnvComponentsTeardownInput): PrEnvTeardownAdapter {
163
+ const log = input.log ?? (() => {});
164
+ return {
165
+ name: input.name,
166
+ ...(input.lexicons ? { lexicons: input.lexicons } : {}),
167
+ async owned({ live, marker }) {
168
+ const candidates = [];
169
+ const holes = [];
170
+ for (const name of live.components) {
171
+ const location = live.locations?.[name] ?? "";
172
+ if (location && input.owns(location, live.env)) candidates.push({ name, type: input.type, physicalId: location, marker: { stack: marker.stack, env: live.env } });
173
+ else holes.push({ name, type: input.type, reason: "read-failed" as const, detail: location ? `its recorded location ${location} is not ${live.env}'s own copy` : `the location of its copy in ${live.env} is not recorded` });
174
+ }
175
+ return { candidates, holes };
176
+ },
177
+ async teardown({ candidates, live }) {
178
+ const outcomes: TeardownOutcome[] = [];
179
+ const order = [...live.components].reverse();
180
+ const rank = (name: string): number => (order.includes(name) ? order.indexOf(name) : order.length);
181
+ const checkout = await input.checkout(live);
182
+ try {
183
+ for (const [i, c] of [...candidates].sort((a, b) => rank(a.name) - rank(b.name)).entries()) {
184
+ const failed = (detail: string): void => {
185
+ log(`FAILED ${c.name}: ${detail}`);
186
+ outcomes.push({ name: c.name, type: input.type, outcome: "failed", detail });
187
+ };
188
+ let p: PrEnvComponentPlan;
189
+ try {
190
+ p = await checkout.plan(c.name, i);
191
+ } catch (e) {
192
+ failed(messageOf(e));
193
+ continue;
194
+ }
195
+ if (p.error) {
196
+ failed(p.error);
197
+ continue;
198
+ }
199
+ try {
200
+ await p.apply();
201
+ } catch (e) {
202
+ failed(`the destroy did not apply: ${messageOf(e)}`);
203
+ continue;
204
+ }
205
+ log(`destroyed ${c.name}'s copy${p.location ? ` at ${p.location}` : ""}`);
206
+ outcomes.push({ name: c.name, type: input.type, outcome: "deleted", detail: `destroyed${p.location ? ` at ${p.location}` : ""}, plan ${p.planDigest}` });
207
+ }
208
+ } finally {
209
+ checkout.done?.();
210
+ }
211
+ return { outcomes };
212
+ },
213
+ };
214
+ }
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { afterAll, describe, expect, test } from "vitest";
8
8
  import { execFileSync } from "node:child_process";
9
+ import { createHash } from "node:crypto";
9
10
  import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
10
11
  import { join } from "node:path";
11
12
  import { tmpdir } from "node:os";
@@ -16,7 +17,7 @@ import { overrideDigest } from "../override-gate";
16
17
  import type { GatePolicyExec } from "../gate-policy";
17
18
  import type { FoundComment, MarkerMatch, PrForge } from "../pr-forge";
18
19
  import { reviewMarker, reviewNoteBody } from "../op/activities/review-agent";
19
- import { decidePrPolicyOverride, policyReviewOf, prLoopPolicyAt, prPolicyReport, REVIEW_NOTE_AUTHORS, runPrPolicy, spendPrPolicyOverride, type PrPolicyInput } from "./pr-policy";
20
+ import { decidePrPolicyOverride, policyReviewOf, prLoopPolicyAt, preparePrPolicyEngine, prPolicyReport, REVIEW_NOTE_AUTHORS, runPrPolicy, spendPrPolicyOverride, type PrPolicyInput } from "./pr-policy";
20
21
 
21
22
  const scratch: string[] = [];
22
23
  afterAll(() => {
@@ -206,3 +207,42 @@ describe("input.review: a policy reads the review's risk (#4326)", () => {
206
207
  expect(runPrPolicy(read, { ...input(base), review: await policyReviewOf(forgeWith([]), 7) }, denyHighRisk)!.result).toBe("passed");
207
208
  });
208
209
  });
210
+
211
+ describe("ci.policy.install: the engine at chant's pinned release (#4774)", () => {
212
+ const pin = (body: Uint8Array) => ({
213
+ cache: tmp(),
214
+ platform: "linux-x64" as const,
215
+ version: "1.0.0",
216
+ sha256: { "linux-x64": createHash("sha256").update(body).digest("hex") },
217
+ probe: () => false,
218
+ });
219
+
220
+ test("the engine is installed, and the policy runs it from the cache", async () => {
221
+ const { repo, base } = repoWithPolicy();
222
+ const read = { ...prLoopPolicyAt(repo, base), settings: { engine: "opa" as const, path: "policy", install: true } };
223
+ const urls: string[] = [];
224
+ const body = new Uint8Array(Buffer.from("opa"));
225
+ const prepared = await preparePrPolicyEngine(read, { ...pin(body), download: async (url) => (urls.push(url), body) });
226
+ expect(urls).toEqual(["https://github.com/open-policy-agent/opa/releases/download/v1.0.0/opa_linux_amd64_static"]);
227
+ expect(prepared.binary).toMatch(/opa-1\.0\.0-linux-x64\/opa$/);
228
+ let ran = "";
229
+ const verdict = runPrPolicy(prepared, input(base), (argv) => ((ran = argv[0]!), { status: 0, stdout: opaOut({}), stderr: "" }))!;
230
+ expect(ran).toBe(prepared.binary);
231
+ expect(verdict.result).toBe("passed");
232
+ expect(await preparePrPolicyEngine(prepared, { download: async () => { throw new Error("fetched twice"); } })).toBe(prepared);
233
+ });
234
+
235
+ test("an engine that cannot be installed is an error, which stops the apply", async () => {
236
+ const { repo, base } = repoWithPolicy();
237
+ const read = { ...prLoopPolicyAt(repo, base), settings: { engine: "opa" as const, path: "policy", install: true } };
238
+ const prepared = await preparePrPolicyEngine(read, { ...pin(new Uint8Array([1])), download: async () => new Uint8Array([2]) });
239
+ expect(prepared.error).toMatch(/^ci.policy.install: opa could not be installed: opa 1.0.0 from .* does not match its pinned sha256/);
240
+ expect(runPrPolicy(prepared, input(base), () => ({ status: 0, stdout: opaOut({}), stderr: "" }))).toMatchObject({ result: "error" });
241
+ });
242
+
243
+ test("without install nothing is fetched", async () => {
244
+ const { repo, base } = repoWithPolicy();
245
+ const read = prLoopPolicyAt(repo, base);
246
+ expect(await preparePrPolicyEngine(read, { download: async () => { throw new Error("fetched"); } })).toBe(read);
247
+ });
248
+ });
@@ -29,6 +29,11 @@
29
29
  * per job (`../policy-source.ts`), and the commit its ref named goes on the
30
30
  * verdict and the report, so a decision names the rules it used. A source
31
31
  * that cannot be fetched is an error, and nothing applies.
32
+ *
33
+ * `ci.policy.install` (#4774) fetches conftest or OPA at chant's pinned
34
+ * release when the engine is not on PATH ({@link preparePrPolicyEngine},
35
+ * `../policy-engine.ts`). An engine that cannot be installed is an error,
36
+ * and nothing applies.
32
37
  */
33
38
 
34
39
  import { readDeclaration, WorkspaceReadError } from "../workspace/declaration";
@@ -43,6 +48,7 @@ import {
43
48
  type GatePolicySettings,
44
49
  type GatePolicyVerdict,
45
50
  } from "../gate-policy";
51
+ import { policyEngineBinary, type PolicyEngineBinaryOptions } from "../policy-engine";
46
52
  import type { ChangeSetDocument } from "../change-set";
47
53
  import type { GateLedgerPort } from "../op/gate";
48
54
  import type { PrPolicyReport } from "../pr-loop";
@@ -67,6 +73,24 @@ export interface PrLoopPolicy {
67
73
  error?: string;
68
74
  /** A line for the log when no policy runs because the base has no declaration, or could not be read. */
69
75
  note?: string;
76
+ /** The engine's executable with `ci.policy.install`, set by {@link preparePrPolicyEngine}. */
77
+ binary?: string;
78
+ }
79
+
80
+ /**
81
+ * With `ci.policy.install` (#4774): the read with the engine's executable,
82
+ * the one on PATH or chant's pinned release, installed. An engine that
83
+ * cannot be installed makes every run an error. Any other read is returned
84
+ * as it is.
85
+ */
86
+ export async function preparePrPolicyEngine(read: PrLoopPolicy, options: PolicyEngineBinaryOptions = {}): Promise<PrLoopPolicy> {
87
+ if (!read.settings?.install || read.settings.command || read.error !== undefined || read.binary) return read;
88
+ const engine = read.settings.engine ?? "conftest";
89
+ try {
90
+ return { ...read, binary: await policyEngineBinary(engine, options) };
91
+ } catch (err) {
92
+ return { ...read, error: `ci.policy.install: ${engine} could not be installed: ${err instanceof Error ? err.message : String(err)}` };
93
+ }
70
94
  }
71
95
 
72
96
  /** Whether the working tree's declaration names a `ci.policy`. */
@@ -192,7 +216,7 @@ export function runPrPolicy(read: PrLoopPolicy, input: PrPolicyInput, exec?: Gat
192
216
  return { result: "error", engine, denials: [], rules: [], holds: [], warnings: [], error: read.source ? `the policy directory ${path} does not exist in ${where}` : exported.error, ...source };
193
217
  }
194
218
  try {
195
- return { ...checkGatePolicy({ settings: read.settings, input, policyDir: exported.dir, cwd: process.cwd(), ...(exec ? { exec } : {}) }), ...source };
219
+ return { ...checkGatePolicy({ settings: read.settings, input, policyDir: exported.dir, cwd: process.cwd(), ...(exec ? { exec } : {}), ...(read.binary ? { binary: read.binary } : {}) }), ...source };
196
220
  } finally {
197
221
  exported.cleanup();
198
222
  }
@@ -7,6 +7,8 @@ import { describe, test, expect } from "vitest";
7
7
  import { withTestDir } from "@intentius/chant-test-utils";
8
8
  import { mkdirSync, writeFileSync } from "node:fs";
9
9
  import { join } from "node:path";
10
+ import { pathToFileURL } from "node:url";
11
+ import { REPO } from "../workspace/__fixtures__/contract-repo";
10
12
  import { CapabilityRegistry, type DeployContext } from "./capability";
11
13
  import type { DriverComponent } from "./driver";
12
14
  import {
@@ -15,6 +17,7 @@ import {
15
17
  compileEnvironment,
16
18
  recordedInputRefs,
17
19
  ReleaseCompileError,
20
+ spawnTargetCompiler,
18
21
  templateRefs,
19
22
  withOnlyArchiveSteps,
20
23
  } from "./release-compile";
@@ -179,3 +182,47 @@ describe("buildReleaseArtifacts", () => {
179
182
  });
180
183
  });
181
184
  });
185
+
186
+ describe("spawnTargetCompiler (#4764)", () => {
187
+ const CHANT = [process.execPath, "--import", pathToFileURL(join(REPO, "node_modules", "tsx", "dist", "loader.mjs")).href, join(REPO, "packages", "core", "src", "cli", "main.ts")];
188
+
189
+ /** A component file that, with `--json` on the command line, prints a JSON document of its own on load; with `exit`, it then exits 0, as terragucci's scripts/coverage-gaps.ts did. */
190
+ function printingProject(dir: string, exit: boolean): void {
191
+ writeFileSync(
192
+ join(dir, "api.component.ts"),
193
+ `if (process.argv.includes("--json")) {
194
+ console.log(JSON.stringify({ gaps: [], total: 0 }));
195
+ ${exit ? "process.exit(0);" : ""}
196
+ }
197
+ export const api = { name: "api", dependsOn: [], deploy: [{ phase: "Apply", steps: [{ kind: "cfn-deploy", template: "api.template.json" }] }] };
198
+ `,
199
+ );
200
+ writeFileSync(join(dir, "api.template.json"), `{"Resources":{}}`);
201
+ }
202
+
203
+ test("refuses by environment when a module the project loads prints JSON and exits, in place of the target", async () => {
204
+ await withTestDir(async (dir) => {
205
+ printingProject(dir, true);
206
+ const err = await spawnTargetCompiler({ projectDir: dir }, CHANT).compile("staging").catch((e: unknown) => e);
207
+ expect(err).toBeInstanceOf(ReleaseCompileError);
208
+ expect((err as Error).message).toMatch(/compiling "staging" printed something that is not a target/);
209
+ });
210
+ }, 60_000);
211
+
212
+ test("refuses by environment when the file the child writes is not a target", async () => {
213
+ await withTestDir(async (dir) => {
214
+ const child = [process.execPath, "-e", `require("node:fs").writeFileSync(process.env.CHANT_RELEASE_COMPILE_RESULT, JSON.stringify({ gaps: [] }))`];
215
+ await expect(spawnTargetCompiler({ projectDir: dir }, child).compile("prod")).rejects.toThrow(/compiling "prod" printed something that is not a target: its env is undefined/);
216
+ });
217
+ });
218
+
219
+ test("compiles the target when a module the project loads prints JSON and goes on", async () => {
220
+ await withTestDir(async (dir) => {
221
+ printingProject(dir, false);
222
+ const target = await spawnTargetCompiler({ projectDir: dir }, CHANT).compile("staging");
223
+ expect(target.env).toBe("staging");
224
+ expect(target.components).toEqual(["api"]);
225
+ expect(target.templates).toEqual([{ component: "api", path: "api.template.json", content: `{"Resources":{}}` }]);
226
+ });
227
+ }, 60_000);
228
+ });