@intentius/chant 0.124.44 → 0.124.46

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 (249) hide show
  1. package/dist/capabilities/aws.paths +148 -0
  2. package/dist/capabilities/base-mappings.json +122 -0
  3. package/dist/capabilities/catalog.d.ts +89 -0
  4. package/dist/capabilities/catalog.d.ts.map +1 -0
  5. package/dist/capabilities/catalog.js +204 -0
  6. package/dist/capabilities/language.d.ts +103 -0
  7. package/dist/capabilities/language.d.ts.map +1 -0
  8. package/dist/capabilities/language.js +335 -0
  9. package/dist/capabilities/matcher.d.ts +65 -0
  10. package/dist/capabilities/matcher.d.ts.map +1 -0
  11. package/dist/capabilities/matcher.js +299 -0
  12. package/dist/capabilities/view.d.ts +207 -0
  13. package/dist/capabilities/view.d.ts.map +1 -0
  14. package/dist/capabilities/view.js +484 -0
  15. package/dist/ci-identity.d.ts +183 -12
  16. package/dist/ci-identity.d.ts.map +1 -1
  17. package/dist/ci-identity.js +362 -53
  18. package/dist/cli/commands/lint.d.ts.map +1 -1
  19. package/dist/cli/commands/lint.js +1 -0
  20. package/dist/cli/handlers/build.d.ts.map +1 -1
  21. package/dist/cli/handlers/build.js +17 -1
  22. package/dist/cli/handlers/declared-graph.d.ts +44 -0
  23. package/dist/cli/handlers/declared-graph.d.ts.map +1 -0
  24. package/dist/cli/handlers/declared-graph.js +87 -0
  25. package/dist/cli/handlers/graph.d.ts +25 -0
  26. package/dist/cli/handlers/graph.d.ts.map +1 -1
  27. package/dist/cli/handlers/graph.js +93 -87
  28. package/dist/cli/handlers/pr-env.d.ts +8 -2
  29. package/dist/cli/handlers/pr-env.d.ts.map +1 -1
  30. package/dist/cli/handlers/pr-env.js +127 -225
  31. package/dist/cli/handlers/pr.d.ts +3 -0
  32. package/dist/cli/handlers/pr.d.ts.map +1 -1
  33. package/dist/cli/handlers/pr.js +1 -0
  34. package/dist/cli/handlers/search-count.d.ts +89 -0
  35. package/dist/cli/handlers/search-count.d.ts.map +1 -0
  36. package/dist/cli/handlers/search-count.js +132 -0
  37. package/dist/cli/handlers/search.d.ts +358 -6
  38. package/dist/cli/handlers/search.d.ts.map +1 -1
  39. package/dist/cli/handlers/search.js +1065 -155
  40. package/dist/cli/main.d.ts.map +1 -1
  41. package/dist/cli/main.js +23 -3
  42. package/dist/cli/mcp/server.d.ts.map +1 -1
  43. package/dist/cli/mcp/server.js +3 -0
  44. package/dist/cli/mcp/tools/capabilities.d.ts +7 -0
  45. package/dist/cli/mcp/tools/capabilities.d.ts.map +1 -0
  46. package/dist/cli/mcp/tools/capabilities.js +27 -0
  47. package/dist/cli/mcp/workspace-tools.d.ts +3 -1
  48. package/dist/cli/mcp/workspace-tools.d.ts.map +1 -1
  49. package/dist/cli/mcp/workspace-tools.js +47 -2
  50. package/dist/cli/parse-args.d.ts.map +1 -1
  51. package/dist/cli/parse-args.js +64 -17
  52. package/dist/cli/registry.d.ts +22 -0
  53. package/dist/cli/registry.d.ts.map +1 -1
  54. package/dist/components/cli-support.d.ts +2 -0
  55. package/dist/components/cli-support.d.ts.map +1 -1
  56. package/dist/components/cli-support.js +4 -2
  57. package/dist/components/fan-out-support.d.ts +3 -0
  58. package/dist/components/fan-out-support.d.ts.map +1 -1
  59. package/dist/components/fan-out-support.js +1 -1
  60. package/dist/components/pr-env-ports.d.ts +29 -0
  61. package/dist/components/pr-env-ports.d.ts.map +1 -0
  62. package/dist/components/pr-env-ports.js +77 -0
  63. package/dist/components/pr-env-run.d.ts +254 -0
  64. package/dist/components/pr-env-run.d.ts.map +1 -0
  65. package/dist/components/pr-env-run.js +376 -0
  66. package/dist/components/pr-environment.d.ts +91 -15
  67. package/dist/components/pr-environment.d.ts.map +1 -1
  68. package/dist/components/pr-environment.js +95 -9
  69. package/dist/components/pr-pipeline.d.ts +10 -1
  70. package/dist/components/pr-pipeline.d.ts.map +1 -1
  71. package/dist/config-environments.d.ts +92 -0
  72. package/dist/config-environments.d.ts.map +1 -0
  73. package/dist/config-environments.js +102 -0
  74. package/dist/config.d.ts +24 -84
  75. package/dist/config.d.ts.map +1 -1
  76. package/dist/config.js +9 -96
  77. package/dist/graph-detail.d.ts.map +1 -1
  78. package/dist/graph-detail.js +15 -3
  79. package/dist/graph-effective.d.ts +33 -2
  80. package/dist/graph-effective.d.ts.map +1 -1
  81. package/dist/graph-effective.js +215 -68
  82. package/dist/graph-ir.d.ts +23 -0
  83. package/dist/graph-ir.d.ts.map +1 -1
  84. package/dist/graph-ir.js +130 -0
  85. package/dist/graph-sub-template.d.ts +11 -0
  86. package/dist/graph-sub-template.d.ts.map +1 -0
  87. package/dist/graph-sub-template.js +19 -0
  88. package/dist/lexicon.d.ts +9 -0
  89. package/dist/lexicon.d.ts.map +1 -1
  90. package/dist/lifecycle/observe.d.ts +28 -0
  91. package/dist/lifecycle/observe.d.ts.map +1 -1
  92. package/dist/lifecycle/observe.js +23 -1
  93. package/dist/lint/rule.d.ts +6 -0
  94. package/dist/lint/rule.d.ts.map +1 -1
  95. package/dist/live-endpoint.d.ts +1 -1
  96. package/dist/live-endpoint.d.ts.map +1 -1
  97. package/dist/live-endpoint.js +1 -1
  98. package/dist/observation.d.ts +48 -1
  99. package/dist/observation.d.ts.map +1 -1
  100. package/dist/observation.js +21 -5
  101. package/dist/op/activities/activity-contracts.d.ts +4 -4
  102. package/dist/op/op-waves.d.ts +17 -0
  103. package/dist/op/op-waves.d.ts.map +1 -1
  104. package/dist/op/op-waves.js +23 -1
  105. package/dist/pr-forge.d.ts +15 -1
  106. package/dist/pr-forge.d.ts.map +1 -1
  107. package/dist/pr-forge.js +28 -16
  108. package/dist/pr-requires.d.ts +5 -1
  109. package/dist/pr-requires.d.ts.map +1 -1
  110. package/dist/wave-runtime.mjs +251 -250
  111. package/dist/workspace/capabilities-contract.d.ts +66 -0
  112. package/dist/workspace/capabilities-contract.d.ts.map +1 -0
  113. package/dist/workspace/capabilities-contract.js +107 -0
  114. package/dist/workspace/capabilities.schema.json +229 -0
  115. package/dist/workspace/ci-cloud-identity.d.ts +3 -1
  116. package/dist/workspace/ci-cloud-identity.d.ts.map +1 -1
  117. package/dist/workspace/ci-cloud-identity.js +16 -1
  118. package/dist/workspace/ci-run.d.ts +35 -8
  119. package/dist/workspace/ci-run.d.ts.map +1 -1
  120. package/dist/workspace/ci-run.js +95 -21
  121. package/dist/workspace/ci-secrets.d.ts.map +1 -1
  122. package/dist/workspace/ci-secrets.js +4 -3
  123. package/dist/workspace/compose-graph.d.ts +9 -0
  124. package/dist/workspace/compose-graph.d.ts.map +1 -1
  125. package/dist/workspace/compose-graph.js +3 -1
  126. package/dist/workspace/conformance/index.d.ts +1 -1
  127. package/dist/workspace/conformance/index.d.ts.map +1 -1
  128. package/dist/workspace/conformance/index.js +39 -2
  129. package/dist/workspace/declaration.d.ts +10 -0
  130. package/dist/workspace/declaration.d.ts.map +1 -1
  131. package/dist/workspace/declaration.js +17 -1
  132. package/dist/workspace/declaration.schema.json +36 -1
  133. package/dist/workspace/graph-cache.d.ts +8 -0
  134. package/dist/workspace/graph-cache.d.ts.map +1 -1
  135. package/dist/workspace/graph-cache.js +27 -3
  136. package/dist/workspace/graph-cli.d.ts +39 -2
  137. package/dist/workspace/graph-cli.d.ts.map +1 -1
  138. package/dist/workspace/graph-cli.js +66 -24
  139. package/dist/workspace/graph.schema.json +148 -0
  140. package/dist/workspace/kind-readers.d.ts +3 -0
  141. package/dist/workspace/kind-readers.d.ts.map +1 -1
  142. package/dist/workspace/kind-readers.js +7 -1
  143. package/dist/workspace/member-commands.d.ts +10 -1
  144. package/dist/workspace/member-commands.d.ts.map +1 -1
  145. package/dist/workspace/member-commands.js +17 -1
  146. package/dist/workspace/nested-graph.d.ts +2 -0
  147. package/dist/workspace/nested-graph.d.ts.map +1 -1
  148. package/dist/workspace/nested-graph.js +32 -1
  149. package/dist/workspace/reason-codes.d.ts +10 -0
  150. package/dist/workspace/reason-codes.d.ts.map +1 -1
  151. package/dist/workspace/reason-codes.js +12 -0
  152. package/dist/workspace/search-cli.d.ts +204 -0
  153. package/dist/workspace/search-cli.d.ts.map +1 -0
  154. package/dist/workspace/search-cli.js +466 -0
  155. package/dist/workspace/search-contract.d.ts +56 -0
  156. package/dist/workspace/search-contract.d.ts.map +1 -0
  157. package/dist/workspace/search-contract.js +70 -0
  158. package/dist/workspace/search.schema.json +822 -0
  159. package/package.json +1 -1
  160. package/src/__snapshots__/okf.test.ts.snap +10 -0
  161. package/src/capabilities/aws.paths +148 -0
  162. package/src/capabilities/base-mappings.json +122 -0
  163. package/src/capabilities/catalog.ts +230 -0
  164. package/src/capabilities/language.test.ts +191 -0
  165. package/src/capabilities/language.ts +373 -0
  166. package/src/capabilities/matcher.ts +315 -0
  167. package/src/capabilities/view-compose.test.ts +76 -0
  168. package/src/capabilities/view.ts +631 -0
  169. package/src/ci-identity-targets.test.ts +275 -0
  170. package/src/ci-identity.ts +394 -61
  171. package/src/cli/commands/lint.ts +1 -0
  172. package/src/cli/handlers/build.ts +15 -1
  173. package/src/cli/handlers/declared-graph.ts +99 -0
  174. package/src/cli/handlers/graph.test.ts +94 -3
  175. package/src/cli/handlers/graph.ts +123 -96
  176. package/src/cli/handlers/pr-env.ts +135 -227
  177. package/src/cli/handlers/pr.ts +4 -0
  178. package/src/cli/handlers/search-build-roots.test.ts +144 -0
  179. package/src/cli/handlers/search-count.test.ts +191 -0
  180. package/src/cli/handlers/search-count.ts +165 -0
  181. package/src/cli/handlers/search-json.test.ts +333 -0
  182. package/src/cli/handlers/search-live.test.ts +387 -0
  183. package/src/cli/handlers/search-paths.test.ts +235 -0
  184. package/src/cli/handlers/search.ts +1312 -166
  185. package/src/cli/main.test.ts +28 -3
  186. package/src/cli/main.ts +23 -3
  187. package/src/cli/mcp/server.test.ts +3 -3
  188. package/src/cli/mcp/server.ts +3 -0
  189. package/src/cli/mcp/tools/capabilities.ts +32 -0
  190. package/src/cli/mcp/workspace-tools.e2e.test.ts +21 -1
  191. package/src/cli/mcp/workspace-tools.ts +47 -2
  192. package/src/cli/parse-args.ts +52 -13
  193. package/src/cli/registry.ts +22 -0
  194. package/src/components/cli-support.ts +6 -1
  195. package/src/components/fan-out-support.ts +4 -1
  196. package/src/components/pr-env-ports.ts +89 -0
  197. package/src/components/pr-env-run-bundle.test.ts +54 -0
  198. package/src/components/pr-env-run.test.ts +290 -0
  199. package/src/components/pr-env-run.ts +563 -0
  200. package/src/components/pr-environment.ts +161 -13
  201. package/src/components/pr-pipeline.ts +10 -1
  202. package/src/config-environments.ts +133 -0
  203. package/src/config.ts +37 -124
  204. package/src/graph-detail.ts +15 -3
  205. package/src/graph-effective.ts +226 -75
  206. package/src/graph-ir.test.ts +163 -0
  207. package/src/graph-ir.ts +147 -0
  208. package/src/graph-sub-template.ts +22 -0
  209. package/src/lexicon.ts +10 -0
  210. package/src/lifecycle/observe.test.ts +27 -1
  211. package/src/lifecycle/observe.ts +43 -1
  212. package/src/lint/rule.ts +6 -0
  213. package/src/live-endpoint.ts +1 -1
  214. package/src/observation.test.ts +25 -0
  215. package/src/observation.ts +69 -5
  216. package/src/op/op-waves.ts +38 -1
  217. package/src/pr-forge-bundle.test.ts +1 -1
  218. package/src/pr-forge.ts +44 -17
  219. package/src/pr-requires.test.ts +43 -6
  220. package/src/pr-requires.ts +5 -1
  221. package/src/workspace/capabilities-contract.test.ts +88 -0
  222. package/src/workspace/capabilities-contract.ts +132 -0
  223. package/src/workspace/capabilities.schema.json +229 -0
  224. package/src/workspace/ci-cloud-identity.test.ts +20 -0
  225. package/src/workspace/ci-cloud-identity.ts +14 -1
  226. package/src/workspace/ci-run.test.ts +74 -1
  227. package/src/workspace/ci-run.ts +122 -29
  228. package/src/workspace/ci-secrets.test.ts +1 -1
  229. package/src/workspace/ci-secrets.ts +4 -3
  230. package/src/workspace/compose-graph.ts +10 -1
  231. package/src/workspace/conformance/conformance.e2e.test.ts +14 -1
  232. package/src/workspace/conformance/index.ts +31 -2
  233. package/src/workspace/declaration.schema.json +36 -1
  234. package/src/workspace/declaration.test.ts +7 -0
  235. package/src/workspace/declaration.ts +24 -2
  236. package/src/workspace/graph-cache.ts +27 -3
  237. package/src/workspace/graph-cli.ts +96 -24
  238. package/src/workspace/graph.schema.json +148 -0
  239. package/src/workspace/kind-readers.e2e.test.ts +28 -0
  240. package/src/workspace/kind-readers.test.ts +1 -1
  241. package/src/workspace/kind-readers.ts +7 -1
  242. package/src/workspace/member-commands.ts +22 -1
  243. package/src/workspace/nested-graph.ts +32 -1
  244. package/src/workspace/reason-codes.test.ts +7 -0
  245. package/src/workspace/reason-codes.ts +12 -0
  246. package/src/workspace/search-cli.e2e.test.ts +305 -0
  247. package/src/workspace/search-cli.ts +591 -0
  248. package/src/workspace/search-contract.ts +95 -0
  249. package/src/workspace/search.schema.json +822 -0
@@ -0,0 +1,563 @@
1
+ /**
2
+ * Running a pull request's environment (#4330): `up`, `down` and `sweep` as
3
+ * functions over an adapter, so a product that plans and applies with a tool
4
+ * chant does not run (terragucci, with Terraform roots under suffixed state
5
+ * keys) keeps its own plan, apply and teardown and takes the rest from chant:
6
+ *
7
+ * - the gate: a non-empty plan applies only once a person's approval of its
8
+ * digest stands under gate `pr-env` (ws-080, ws-104), and an empty one
9
+ * applies at once;
10
+ * - the records on chant/lifecycle (`_pr-envs/records.jsonl`), the TTL and
11
+ * which environments stand ({@link livePrEnvironments});
12
+ * - the ownership check on teardown ({@link teardownRefusal}), and the
13
+ * marker check on every candidate before anything is deleted
14
+ * ({@link tearDownPrEnvironment});
15
+ * - the sweep over expired and closed pull requests;
16
+ * - the report and the note ({@link renderPrEnvNote}).
17
+ *
18
+ * `chant components pr-env` (../cli/handlers/pr-env.ts) runs these with the
19
+ * components adapter and the lexicons' teardown, and the ports over
20
+ * chant/lifecycle and the gate ledger in ./pr-env-ports.ts
21
+ * (`lifecyclePrEnvPorts`). Those ports load the gate and its schema checks,
22
+ * so they live apart: a product that brings its own ports bundles this
23
+ * module without them (pr-env-run-bundle.test.ts).
24
+ */
25
+
26
+ import { spawnSync } from "node:child_process";
27
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
28
+ import { tmpdir } from "node:os";
29
+ import { join } from "node:path";
30
+ import { withoutForgeTokens } from "../ci-handover";
31
+ import type { ChantConfig } from "../config";
32
+ import type { TeardownCandidate, TeardownHole, TeardownOutcome } from "../lexicon";
33
+ import type { ObservationLexicon } from "../lexicon";
34
+ import {
35
+ PR_ENV_EXIT,
36
+ PR_ENV_GATE,
37
+ expired,
38
+ livePrEnvironments,
39
+ prEnvironmentName,
40
+ renderPrEnvNote,
41
+ teardownComplete,
42
+ teardownCounts,
43
+ tearDownPrEnvironment,
44
+ ttlMs,
45
+ type LivePrEnvironment,
46
+ type PrEnvRecord,
47
+ type PrEnvReport,
48
+ type PrEnvReportRow,
49
+ type PrEnvTeardownAdapter,
50
+ type PrEnvTeardownAdapterInput,
51
+ } from "./pr-environment";
52
+
53
+ /** The environment one run works on. */
54
+ export interface PrEnvTarget {
55
+ pr: number;
56
+ /** `pr-<n>`. */
57
+ env: string;
58
+ template: string;
59
+ /** The marker every resource of the environment carries. */
60
+ marker: { stack: string; env: string };
61
+ /** The commit planned and applied: the pull request's head. */
62
+ head: string;
63
+ member?: string;
64
+ /** The op the gate is recorded under: `pr-<n>`, or `pr-<n>-<member>`. */
65
+ op: string;
66
+ endpoint?: string;
67
+ }
68
+
69
+ /** What an adapter's plan came to. */
70
+ export interface PrEnvPlanned {
71
+ /** The digest an approval binds. */
72
+ digest: string;
73
+ /** Nothing changes: the plan applies with no approval (ws-104). */
74
+ empty: boolean;
75
+ /** Something failed to plan, or a hook stopped it: nothing applies. */
76
+ failed?: boolean;
77
+ /** One row per component (a Terraform root, a chant component), in apply order. None: the change reaches nothing deployed, and the environment gets nothing. */
78
+ rows: PrEnvReportRow[];
79
+ message?: string;
80
+ }
81
+
82
+ /** What an adapter's apply came to. */
83
+ export interface PrEnvApplied {
84
+ /**
85
+ * `waiting`: a component read an upstream output that moved, so it waits
86
+ * for the next run. `stopped`: nothing was applied (a before-apply hook
87
+ * failed), so no record is kept.
88
+ */
89
+ status: "applied" | "failed" | "waiting" | "stopped";
90
+ /** The rows again, with each component's status after the apply. */
91
+ rows: PrEnvReportRow[];
92
+ /** Where each component's copy lives, kept on the record for the teardown (a suffixed state key). */
93
+ locations?: Record<string, string>;
94
+ message?: string;
95
+ /** The apply stands, and something after it failed (an after-apply hook): the record says applied and the run exits 1. */
96
+ afterFailure?: string;
97
+ }
98
+
99
+ /** What `up` hands an adapter's apply: the plan, and who approved it. */
100
+ export interface PrEnvApplyInput {
101
+ planned: PrEnvPlanned;
102
+ /** Who approved the digest; absent for an empty plan. */
103
+ approvedBy?: string[];
104
+ }
105
+
106
+ /**
107
+ * The plan and apply of a pull request's environment, which a product
108
+ * supplies. `plan` must not change anything; `apply` applies exactly what
109
+ * `plan` answered, once `up` decided it may.
110
+ */
111
+ export interface PrEnvAdapter {
112
+ plan(target: PrEnvTarget): Promise<PrEnvPlanned>;
113
+ apply(target: PrEnvTarget, input: PrEnvApplyInput): Promise<PrEnvApplied>;
114
+ }
115
+
116
+ /** Where the approval of a digest stands, as `decideGate` answers. */
117
+ export interface PrEnvApproval {
118
+ status: "approved" | "changed" | "pending";
119
+ approvedBy?: string[];
120
+ }
121
+
122
+ /** What the runs read and write, which tests and products replace. */
123
+ export interface PrEnvPorts {
124
+ /** Every record, oldest first. */
125
+ readRecords(): Promise<PrEnvRecord[]>;
126
+ /** Keep one record. A failure should warn: what was applied or torn down stands. */
127
+ appendRecord(record: PrEnvRecord): Promise<void>;
128
+ /** Where the approval of `digest` stands under `gate` of `op`. Throws when the ledger cannot be read. */
129
+ decideGate(input: { op: string; gate: string; digest: string; description: string }): Promise<PrEnvApproval>;
130
+ /** Post the report: the note and the commit status. Absent: nothing is posted. */
131
+ publish?(report: PrEnvReport): Promise<void>;
132
+ /** Whether a pull request is still open, for the sweep. Absent: only the TTL counts. */
133
+ pullRequestState?(pr: number): Promise<"open" | "closed" | "merged">;
134
+ log?(line: string): void;
135
+ warn?(message: string): void;
136
+ }
137
+
138
+ /** What one run came to. */
139
+ export interface PrEnvRunResult {
140
+ /** {@link PR_ENV_EXIT}: 0 done, 1 failed or refused, 3 waiting on an approval. */
141
+ exit: number;
142
+ report: PrEnvReport;
143
+ /** The record kept, when the run kept one. */
144
+ record?: PrEnvRecord;
145
+ }
146
+
147
+ /** The op a pull request's gate is recorded under, as `prOp` in ../pr-loop.ts names it. */
148
+ export function prEnvOp(pr: number, member?: string): string {
149
+ return member ? `pr-${pr}-${member}` : `pr-${pr}`;
150
+ }
151
+
152
+ /** The approve command an adapter's caller prints, the same the note shows. */
153
+ export { prEnvApproveCommand } from "./pr-environment";
154
+
155
+ // ── up ─────────────────────────────────────────────────────────────────────
156
+
157
+ export interface PrEnvUpInput {
158
+ pr: number;
159
+ /** The pull request's head, which is planned and applied. */
160
+ head: string;
161
+ /** `ci.prEnvironment.template`, read at base. */
162
+ template: string;
163
+ /** `ci.prEnvironment.ttl`, read at base: `72h`, `90m`, `7d`. Default 72h. */
164
+ ttl?: string;
165
+ /** The ownership stack every resource's marker names. */
166
+ stack: string;
167
+ member?: string;
168
+ endpoint?: string;
169
+ adapter: PrEnvAdapter;
170
+ ports: PrEnvPorts;
171
+ /** Who the record names. Default `chant`. */
172
+ actor?: string;
173
+ runUrl?: string;
174
+ now?: () => Date;
175
+ }
176
+
177
+ const ttlOf = (ttl: string | undefined): number => (ttl ? ttlMs(ttl) : undefined) ?? ttlMs("72h")!;
178
+
179
+ /**
180
+ * Plan pull request `pr`'s environment through the adapter and apply it once
181
+ * the plan is empty or an approval of its digest stands under gate `pr-env`.
182
+ * An apply that failed part way is kept as live too, so what applied is torn
183
+ * down with the rest.
184
+ */
185
+ export async function prEnvUp(input: PrEnvUpInput): Promise<PrEnvRunResult> {
186
+ const { pr, ports } = input;
187
+ const env = prEnvironmentName(pr);
188
+ const target: PrEnvTarget = {
189
+ pr,
190
+ env,
191
+ template: input.template,
192
+ marker: { stack: input.stack, env },
193
+ head: input.head,
194
+ ...(input.member ? { member: input.member } : {}),
195
+ op: prEnvOp(pr, input.member),
196
+ ...(input.endpoint ? { endpoint: input.endpoint } : {}),
197
+ };
198
+ const base: PrEnvReport = {
199
+ stage: "up",
200
+ pr,
201
+ env,
202
+ ...(input.member ? { member: input.member } : {}),
203
+ template: input.template,
204
+ head: input.head,
205
+ op: target.op,
206
+ gate: PR_ENV_GATE,
207
+ digest: "",
208
+ status: "nothing",
209
+ ...(input.endpoint ? { endpoint: input.endpoint } : {}),
210
+ components: [],
211
+ };
212
+ const settle = async (report: PrEnvReport, exit: number, record?: PrEnvRecord): Promise<PrEnvRunResult> => {
213
+ await ports.publish?.(report);
214
+ return { exit, report, ...(record ? { record } : {}) };
215
+ };
216
+
217
+ let planned: PrEnvPlanned;
218
+ try {
219
+ planned = await input.adapter.plan(target);
220
+ } catch (err) {
221
+ return settle({ ...base, status: "plan-failed", message: messageOf(err) }, PR_ENV_EXIT.failed);
222
+ }
223
+ if (planned.rows.length === 0) {
224
+ ports.log?.(`pr-env up: nothing this change touches is deployed, so ${env} gets nothing`);
225
+ return settle({ ...base, ...(planned.message ? { message: planned.message } : {}) }, PR_ENV_EXIT.done);
226
+ }
227
+ const digest = planned.digest;
228
+ if (planned.failed) {
229
+ return settle({ ...base, digest, status: "plan-failed", ...(planned.message ? { message: planned.message } : {}), components: planned.rows }, PR_ENV_EXIT.failed);
230
+ }
231
+
232
+ // ws-080, ws-104: a non-empty plan applies only under a person's approval of its digest. An empty one passes.
233
+ let approvedBy: string[] | undefined;
234
+ if (!planned.empty) {
235
+ let approval: PrEnvApproval;
236
+ try {
237
+ approval = await ports.decideGate({ op: target.op, gate: PR_ENV_GATE, digest, description: `${env}: ${planned.rows.map((r) => r.component).join(", ")}` });
238
+ } catch (err) {
239
+ return settle({ ...base, digest, status: "failed", message: `could not read the gate ledger, so ${env} does not apply: ${messageOf(err)}`, components: planned.rows }, PR_ENV_EXIT.failed);
240
+ }
241
+ if (approval.status !== "approved") {
242
+ ports.log?.(`pr-env up: ${env} waits for an approval of ${digest}`);
243
+ return settle({ ...base, digest, status: approval.status === "changed" ? "changed" : "waiting", components: planned.rows }, PR_ENV_EXIT.waiting);
244
+ }
245
+ approvedBy = approval.approvedBy ?? [];
246
+ }
247
+
248
+ let applied: PrEnvApplied;
249
+ try {
250
+ applied = await input.adapter.apply(target, { planned, ...(approvedBy ? { approvedBy } : {}) });
251
+ } catch (err) {
252
+ applied = { status: "failed", rows: planned.rows, message: messageOf(err) };
253
+ }
254
+ if (applied.status === "stopped") {
255
+ return settle({ ...base, digest, status: "failed", components: applied.rows, ...(approvedBy ? { approvedBy } : {}), ...(applied.message ? { message: applied.message } : {}) }, PR_ENV_EXIT.failed);
256
+ }
257
+ const ok = applied.status === "applied";
258
+ const now = (input.now ?? (() => new Date()))();
259
+ const expiresAt = new Date(now.getTime() + ttlOf(input.ttl)).toISOString();
260
+ const record: PrEnvRecord = {
261
+ version: 1,
262
+ kind: "up",
263
+ pr,
264
+ env,
265
+ ...(input.member ? { member: input.member } : {}),
266
+ template: input.template,
267
+ marker: { ...target.marker },
268
+ commit: input.head,
269
+ components: planned.rows.map((r) => r.component),
270
+ ...(applied.locations && Object.keys(applied.locations).length > 0 ? { locations: { ...applied.locations } } : {}),
271
+ planDigest: digest,
272
+ result: ok ? "applied" : "failed",
273
+ by: input.actor ?? "chant",
274
+ timestamp: now.toISOString(),
275
+ expiresAt,
276
+ ...(approvedBy ? { approvedBy } : {}),
277
+ releaseTarget: false,
278
+ ...(input.runUrl ? { runUrl: input.runUrl } : {}),
279
+ };
280
+ // A copy that failed part way is live too: what applied is torn down on close or at expiry like the rest.
281
+ await ports.appendRecord(record);
282
+ const message = ok
283
+ ? applied.afterFailure ?? applied.message
284
+ : applied.message ?? (applied.status === "waiting" ? "A component read an upstream output that moved when it applied; run the job again to plan it against the new value." : "A component failed to apply; what applied stays in the environment and is torn down with it.");
285
+ ports.log?.(`pr-env up: ${env} ${ok ? "applied" : applied.status}; it expires ${expiresAt}`);
286
+ return settle(
287
+ { ...base, digest, status: ok ? "applied" : "failed", components: applied.rows, ...(approvedBy ? { approvedBy } : {}), expiresAt, ...(message ? { message } : {}) },
288
+ ok && !applied.afterFailure ? PR_ENV_EXIT.done : PR_ENV_EXIT.failed,
289
+ record,
290
+ );
291
+ }
292
+
293
+ // ── down ───────────────────────────────────────────────────────────────────
294
+
295
+ /** What tears an environment down: the lexicons, and the adapters a product supplies. */
296
+ export interface PrEnvTeardownSources {
297
+ /** The project's config, for its declared environments and stacks. */
298
+ config?: ChantConfig;
299
+ plugins?: ObservationLexicon[];
300
+ adapters?: PrEnvTeardownAdapter[];
301
+ }
302
+
303
+ export interface PrEnvDownInput extends PrEnvTeardownSources {
304
+ pr: number;
305
+ reason: "closed" | "expired";
306
+ member?: string;
307
+ ports: PrEnvPorts;
308
+ /** The environment as the records say it stands. Default: read through `ports`. */
309
+ live?: LivePrEnvironment;
310
+ /** The commit the teardown runs at, for the record. */
311
+ commit: string;
312
+ actor?: string;
313
+ runUrl?: string;
314
+ now?: () => Date;
315
+ }
316
+
317
+ /**
318
+ * Tear down pull request `pr`'s environment: the ownership check first, then
319
+ * only what carries `{ stack, env: "pr-<n>" }`, through the lexicons and the
320
+ * adapters. No gate holds it: closing the pull request, or the TTL the base
321
+ * set, is the decision. A teardown that left something keeps the
322
+ * environment live for the next sweep.
323
+ */
324
+ export async function prEnvDown(input: PrEnvDownInput): Promise<PrEnvRunResult> {
325
+ const { pr, ports, reason } = input;
326
+ const env = prEnvironmentName(pr);
327
+ const live = input.live ?? livePrEnvironments(await ports.readRecords()).get(env);
328
+ const report: PrEnvReport = { stage: "down", pr, env, ...(input.member ? { member: input.member } : {}), template: live?.template ?? "", head: "", op: prEnvOp(pr, input.member), gate: PR_ENV_GATE, digest: "", status: "absent", components: [] };
329
+ if (!live) {
330
+ ports.log?.(`pr-env down: ${env} has no live record, so there is nothing to tear down`);
331
+ await ports.publish?.(report);
332
+ return { exit: PR_ENV_EXIT.done, report };
333
+ }
334
+ const torn = await tearDownPrEnvironment({ pr, live, ...(input.config ? { config: input.config } : {}), ...(input.plugins ? { plugins: input.plugins } : {}), ...(input.adapters ? { adapters: input.adapters } : {}), ...(ports.warn ? { warn: ports.warn } : {}) });
335
+ if ("refusal" in torn) {
336
+ const refused = { ...report, template: live.template, status: "refused" as const, message: torn.refusal };
337
+ await ports.publish?.(refused);
338
+ return { exit: PR_ENV_EXIT.failed, report: refused };
339
+ }
340
+ const { report: result, dropped, marker } = torn;
341
+ const counts = teardownCounts(result);
342
+ const complete = teardownComplete(result);
343
+ const now = (input.now ?? (() => new Date()))();
344
+ const record: PrEnvRecord = {
345
+ version: 1,
346
+ kind: "down",
347
+ pr,
348
+ env,
349
+ ...(live.member ? { member: live.member } : {}),
350
+ template: live.template,
351
+ marker,
352
+ commit: input.commit,
353
+ components: [...new Set(result.outcomes.map((o) => o.lexicon))].sort(),
354
+ planDigest: "",
355
+ result: complete ? "destroyed" : "incomplete",
356
+ by: input.actor ?? "chant",
357
+ timestamp: now.toISOString(),
358
+ reason,
359
+ outcomes: counts,
360
+ releaseTarget: false,
361
+ ...(input.runUrl ? { runUrl: input.runUrl } : {}),
362
+ };
363
+ await ports.appendRecord(record);
364
+ const why: string[] = [];
365
+ if (dropped > 0) why.push(`${dropped} candidate${dropped === 1 ? "" : "s"} whose marker was not ${marker.stack}/${env} left alone`);
366
+ if (result.unimplemented.length > 0) why.push(`no teardown execution in ${result.unimplemented.join(", ")}`);
367
+ if (result.plan.holes.length > 0) why.push(`${result.plan.holes.length} part${result.plan.holes.length === 1 ? "" : "s"} could not be read`);
368
+ for (const o of result.outcomes.filter((x) => x.outcome === "failed")) why.push(`${o.lexicon} ${o.name}: ${o.detail ?? "failed"}`);
369
+ const done: PrEnvReport = { ...report, template: live.template, status: complete ? "destroyed" : "incomplete", outcomes: counts, ...(why.length > 0 ? { message: why.join("; ") } : {}) };
370
+ ports.log?.(`pr-env down: ${env} ${complete ? "torn down" : "not wholly torn down; it stays live and the sweep tries again"} (${counts.deleted} deleted, ${counts.failed} failed, ${counts.skipped} skipped)`);
371
+ await ports.publish?.(done);
372
+ return { exit: complete ? PR_ENV_EXIT.done : PR_ENV_EXIT.failed, report: done, record };
373
+ }
374
+
375
+ // ── sweep ──────────────────────────────────────────────────────────────────
376
+
377
+ export interface PrEnvSweepInput extends PrEnvTeardownSources {
378
+ ports: PrEnvPorts;
379
+ /** Only this member's environments. Default: every environment the records name. */
380
+ member?: string;
381
+ commit: string;
382
+ actor?: string;
383
+ runUrl?: string;
384
+ now?: () => Date;
385
+ }
386
+
387
+ /**
388
+ * Tear down each live environment whose TTL passed, or whose pull request
389
+ * the forge says is closed or merged. A state that cannot be read leaves the
390
+ * TTL to decide. Exits 1 when any teardown did not finish.
391
+ */
392
+ export async function prEnvSweep(input: PrEnvSweepInput): Promise<{ exit: number; results: PrEnvRunResult[] }> {
393
+ const { ports } = input;
394
+ const live = [...livePrEnvironments(await ports.readRecords()).values()].filter((e) => input.member === undefined || e.member === input.member);
395
+ if (live.length === 0) {
396
+ ports.log?.("pr-env sweep: no pull request environment is live");
397
+ return { exit: PR_ENV_EXIT.done, results: [] };
398
+ }
399
+ const now = (input.now ?? (() => new Date()))();
400
+ let exit: number = PR_ENV_EXIT.done;
401
+ const results: PrEnvRunResult[] = [];
402
+ for (const e of live) {
403
+ let reason: "closed" | "expired" | undefined = expired(e, now) ? "expired" : undefined;
404
+ if (!reason && ports.pullRequestState) {
405
+ try {
406
+ if ((await ports.pullRequestState(e.pr)) !== "open") reason = "closed";
407
+ } catch (err) {
408
+ ports.warn?.(`could not read whether #${e.pr} is open (${messageOf(err)}); its TTL still holds`);
409
+ }
410
+ }
411
+ if (!reason) {
412
+ ports.log?.(`pr-env sweep: ${e.env} stays; it expires ${e.expiresAt}`);
413
+ continue;
414
+ }
415
+ const r = await prEnvDown({ ...input, pr: e.pr, reason, live: e, ...(e.member ? { member: e.member } : {}) });
416
+ results.push(r);
417
+ if (r.exit !== PR_ENV_EXIT.done) exit = PR_ENV_EXIT.failed;
418
+ }
419
+ return { exit, results };
420
+ }
421
+
422
+ // ── a teardown command ─────────────────────────────────────────────────────
423
+
424
+ /** `ci.prEnvironment.teardown` (#4330): a command that tears down what no lexicon does. */
425
+ export interface PrEnvTeardownCommand {
426
+ /** The name its outcomes are attributed to. Default `teardown`. */
427
+ name?: string;
428
+ /** Argv. `{env}`, `{pr}` and `{stage}` are filled in. */
429
+ command: string[];
430
+ /** The lexicons it tears down in place of, as {@link PrEnvTeardownAdapter.lexicons}. */
431
+ lexicons?: string[];
432
+ }
433
+
434
+ /** The variables a teardown command reads. */
435
+ export const PR_ENV_TEARDOWN_ENV = {
436
+ /** `owned` or `teardown`. */
437
+ stage: "CHANT_PR_ENV_STAGE",
438
+ /** `pr-<n>`. */
439
+ env: "CHANT_PR_ENV",
440
+ pr: "CHANT_PR_NUMBER",
441
+ stack: "CHANT_PR_ENV_STACK",
442
+ template: "CHANT_PR_ENV_TEMPLATE",
443
+ /** The commit last applied to the environment. */
444
+ commit: "CHANT_PR_ENV_COMMIT",
445
+ /** A JSON file: `{ components, locations }` from the records. */
446
+ live: "CHANT_PR_ENV_LIVE",
447
+ /** `teardown` only: a JSON file holding the candidates to delete. */
448
+ candidates: "CHANT_PR_ENV_CANDIDATES",
449
+ /** The JSON file the command writes its answer to. */
450
+ result: "CHANT_PR_ENV_RESULT",
451
+ } as const;
452
+
453
+ /** Runs one argv in `cwd` with `env` as its whole environment; returns its exit code. Injected so tests run no processes. */
454
+ export type PrEnvTeardownExec = (argv: string[], cwd: string, env: Record<string, string>) => number;
455
+
456
+ const spawnTeardown: PrEnvTeardownExec = (argv, cwd, env) => {
457
+ const r = spawnSync(argv[0]!, argv.slice(1), { cwd, env, stdio: ["ignore", "inherit", "inherit"] });
458
+ if (r.error) throw r.error;
459
+ return r.status ?? 1;
460
+ };
461
+
462
+ const MARKER_OK = (m: unknown): m is { stack: string; env: string } => typeof m === "object" && m !== null && typeof (m as { stack?: unknown }).stack === "string" && typeof (m as { env?: unknown }).env === "string";
463
+
464
+ /** The candidates and holes a teardown command wrote, checked as data. Throws when they do not read. */
465
+ export function readTeardownEnumeration(raw: unknown): { candidates: TeardownCandidate[]; holes: TeardownHole[] } {
466
+ const doc = raw as { candidates?: unknown; holes?: unknown } | null;
467
+ if (typeof doc !== "object" || doc === null || !Array.isArray(doc.candidates)) throw new Error("the teardown command's owned stage wrote no { candidates: [...] }");
468
+ const candidates: TeardownCandidate[] = [];
469
+ for (const c of doc.candidates as Array<Record<string, unknown>>) {
470
+ if (typeof c?.name !== "string" || typeof c.type !== "string" || !MARKER_OK(c.marker)) throw new Error("each candidate needs a name, a type and the marker { stack, env } read back from it");
471
+ candidates.push({ name: c.name, type: c.type, ...(typeof c.physicalId === "string" ? { physicalId: c.physicalId } : {}), marker: { stack: c.marker.stack, env: c.marker.env } });
472
+ }
473
+ const holes: TeardownHole[] = [];
474
+ for (const h of Array.isArray(doc.holes) ? (doc.holes as Array<Record<string, unknown>>) : []) {
475
+ if (typeof h?.name !== "string") continue;
476
+ holes.push({ name: h.name, reason: "read-failed", ...(typeof h.type === "string" ? { type: h.type } : {}), ...(typeof h.detail === "string" ? { detail: h.detail } : {}) });
477
+ }
478
+ return { candidates, holes };
479
+ }
480
+
481
+ /** The outcomes a teardown command wrote, checked as data. A candidate it leaves out counts as failed in core. */
482
+ export function readTeardownOutcomes(raw: unknown): TeardownOutcome[] {
483
+ const doc = raw as { outcomes?: unknown } | null;
484
+ if (typeof doc !== "object" || doc === null || !Array.isArray(doc.outcomes)) throw new Error("the teardown command's teardown stage wrote no { outcomes: [...] }");
485
+ const kinds = new Set(["deleted", "failed", "not-prunable", "retained"]);
486
+ return (doc.outcomes as Array<Record<string, unknown>>)
487
+ .filter((o) => typeof o?.name === "string" && typeof o.outcome === "string" && kinds.has(o.outcome))
488
+ .map((o) => ({ name: o.name as string, outcome: o.outcome as TeardownOutcome["outcome"], ...(typeof o.detail === "string" ? { detail: o.detail } : {}) }));
489
+ }
490
+
491
+ /**
492
+ * `ci.prEnvironment.teardown` as an adapter (#4330). chant runs the command
493
+ * twice, in `cwd`, with the job's environment less every forge token
494
+ * variable, and these besides ({@link PR_ENV_TEARDOWN_ENV}):
495
+ *
496
+ * - `CHANT_PR_ENV_STAGE=owned`: the command writes `{ candidates, holes }`
497
+ * to `CHANT_PR_ENV_RESULT`, each candidate with the marker it read back.
498
+ * - `CHANT_PR_ENV_STAGE=teardown`: it deletes the candidates in
499
+ * `CHANT_PR_ENV_CANDIDATES`, which chant has checked against the marker,
500
+ * and writes `{ outcomes }` to `CHANT_PR_ENV_RESULT`.
501
+ *
502
+ * A non-zero exit, or an answer that does not read, is a hole (`owned`) or a
503
+ * failure for every candidate (`teardown`), so the environment stays live.
504
+ */
505
+ export function commandTeardownAdapter(hook: PrEnvTeardownCommand, opts: { cwd: string; env?: Record<string, string | undefined>; exec?: PrEnvTeardownExec }): PrEnvTeardownAdapter {
506
+ const exec = opts.exec ?? spawnTeardown;
507
+ const name = hook.name ?? "teardown";
508
+ const run = (stage: "owned" | "teardown", input: PrEnvTeardownAdapterInput, candidates?: TeardownCandidate[]): unknown => {
509
+ const dir = mkdtempSync(join(tmpdir(), "chant-pr-env-teardown-"));
510
+ try {
511
+ const result = join(dir, "result.json");
512
+ const liveFile = join(dir, "live.json");
513
+ writeFileSync(liveFile, JSON.stringify({ components: input.live.components, locations: input.live.locations ?? {} }));
514
+ const extra: Record<string, string> = {
515
+ [PR_ENV_TEARDOWN_ENV.stage]: stage,
516
+ [PR_ENV_TEARDOWN_ENV.env]: input.environment,
517
+ [PR_ENV_TEARDOWN_ENV.pr]: String(input.live.pr),
518
+ [PR_ENV_TEARDOWN_ENV.stack]: input.marker.stack,
519
+ [PR_ENV_TEARDOWN_ENV.template]: input.live.template,
520
+ [PR_ENV_TEARDOWN_ENV.commit]: input.live.commit,
521
+ [PR_ENV_TEARDOWN_ENV.live]: liveFile,
522
+ [PR_ENV_TEARDOWN_ENV.result]: result,
523
+ };
524
+ if (candidates) {
525
+ const file = join(dir, "candidates.json");
526
+ writeFileSync(file, JSON.stringify(candidates));
527
+ extra[PR_ENV_TEARDOWN_ENV.candidates] = file;
528
+ }
529
+ const base: Record<string, string> = {};
530
+ for (const [k, v] of Object.entries(withoutForgeTokens(opts.env ?? process.env))) if (v !== undefined) base[k] = v;
531
+ const argv = hook.command.map((a) => a.split("{env}").join(input.environment).split("{pr}").join(String(input.live.pr)).split("{stage}").join(stage));
532
+ const code = exec(argv, opts.cwd, { ...base, ...extra });
533
+ if (code !== 0) throw new Error(`${argv.join(" ")} exited ${code} in its ${stage} stage`);
534
+ let text: string;
535
+ try {
536
+ text = readFileSync(result, "utf-8");
537
+ } catch {
538
+ throw new Error(`${argv.join(" ")} wrote nothing to ${PR_ENV_TEARDOWN_ENV.result} in its ${stage} stage`);
539
+ }
540
+ return JSON.parse(text);
541
+ } finally {
542
+ rmSync(dir, { recursive: true, force: true });
543
+ }
544
+ };
545
+ return {
546
+ name,
547
+ ...(hook.lexicons ? { lexicons: [...hook.lexicons] } : {}),
548
+ async owned(input) {
549
+ return readTeardownEnumeration(run("owned", input));
550
+ },
551
+ async teardown(input) {
552
+ try {
553
+ return { outcomes: readTeardownOutcomes(run("teardown", input, input.candidates)) };
554
+ } catch (err) {
555
+ return { outcomes: input.candidates.map((c) => ({ name: c.name, outcome: "failed" as const, detail: messageOf(err) })) };
556
+ }
557
+ },
558
+ };
559
+ }
560
+
561
+ function messageOf(err: unknown): string {
562
+ return err instanceof Error ? err.message : String(err);
563
+ }