@intentius/chant 0.124.85 → 0.124.87

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 (286) hide show
  1. package/dist/bundle-check.d.ts +102 -0
  2. package/dist/bundle-check.d.ts.map +1 -0
  3. package/dist/bundle-check.js +310 -0
  4. package/dist/chant-install.d.ts +100 -0
  5. package/dist/chant-install.d.ts.map +1 -0
  6. package/dist/chant-install.js +158 -0
  7. package/dist/ci-commit.d.ts +19 -6
  8. package/dist/ci-commit.d.ts.map +1 -1
  9. package/dist/ci-commit.js +23 -4
  10. package/dist/ci-evidence-jobs.d.ts +78 -0
  11. package/dist/ci-evidence-jobs.d.ts.map +1 -0
  12. package/dist/ci-evidence-jobs.js +85 -0
  13. package/dist/ci-image.d.ts +274 -0
  14. package/dist/ci-image.d.ts.map +1 -0
  15. package/dist/ci-image.js +635 -0
  16. package/dist/ci-login.d.ts +150 -0
  17. package/dist/ci-login.d.ts.map +1 -0
  18. package/dist/ci-login.js +240 -0
  19. package/dist/ci-product.d.ts +16 -0
  20. package/dist/ci-product.d.ts.map +1 -1
  21. package/dist/ci-product.js +17 -0
  22. package/dist/cli/commands/import-index.js +2 -2
  23. package/dist/cli/handlers/build.d.ts +8 -0
  24. package/dist/cli/handlers/build.d.ts.map +1 -1
  25. package/dist/cli/handlers/build.js +22 -4
  26. package/dist/cli/handlers/ci-check.d.ts.map +1 -1
  27. package/dist/cli/handlers/ci-check.js +61 -2
  28. package/dist/cli/handlers/ci-evidence.d.ts +3 -0
  29. package/dist/cli/handlers/ci-evidence.d.ts.map +1 -0
  30. package/dist/cli/handlers/ci-evidence.js +174 -0
  31. package/dist/cli/handlers/components.js +3 -3
  32. package/dist/cli/handlers/dead-guards.d.ts +3 -0
  33. package/dist/cli/handlers/dead-guards.d.ts.map +1 -0
  34. package/dist/cli/handlers/dead-guards.js +35 -0
  35. package/dist/cli/handlers/graph.js +4 -4
  36. package/dist/cli/handlers/lifecycle.d.ts +2 -1
  37. package/dist/cli/handlers/lifecycle.d.ts.map +1 -1
  38. package/dist/cli/handlers/lifecycle.js +5 -4
  39. package/dist/cli/handlers/local-chant.d.ts +16 -0
  40. package/dist/cli/handlers/local-chant.d.ts.map +1 -0
  41. package/dist/cli/handlers/local-chant.js +109 -0
  42. package/dist/cli/handlers/operator.js +2 -2
  43. package/dist/cli/handlers/search.js +5 -5
  44. package/dist/cli/main.d.ts.map +1 -1
  45. package/dist/cli/main.js +38 -0
  46. package/dist/cli/parse-args.d.ts.map +1 -1
  47. package/dist/cli/parse-args.js +28 -0
  48. package/dist/cli/registry.d.ts +16 -0
  49. package/dist/cli/registry.d.ts.map +1 -1
  50. package/dist/components/check-hooks.d.ts +49 -0
  51. package/dist/components/check-hooks.d.ts.map +1 -1
  52. package/dist/components/check-hooks.js +64 -4
  53. package/dist/components/check-steps.d.ts +17 -0
  54. package/dist/components/check-steps.d.ts.map +1 -1
  55. package/dist/components/check-steps.js +37 -5
  56. package/dist/components/product-pipeline.d.ts +23 -0
  57. package/dist/components/product-pipeline.d.ts.map +1 -1
  58. package/dist/components/product-pipeline.js +6 -2
  59. package/dist/components/product-plan.d.ts +143 -0
  60. package/dist/components/product-plan.d.ts.map +1 -0
  61. package/dist/components/product-plan.js +145 -0
  62. package/dist/components/release-compile.d.ts.map +1 -1
  63. package/dist/components/release-compile.js +2 -2
  64. package/dist/config.d.ts +39 -1
  65. package/dist/config.d.ts.map +1 -1
  66. package/dist/config.js +35 -3
  67. package/dist/dead-guards.d.ts +82 -0
  68. package/dist/dead-guards.d.ts.map +1 -0
  69. package/dist/dead-guards.js +436 -0
  70. package/dist/discovery/files.d.ts +3 -1
  71. package/dist/discovery/files.d.ts.map +1 -1
  72. package/dist/discovery/files.js +5 -3
  73. package/dist/drift-issue.d.ts +152 -0
  74. package/dist/drift-issue.d.ts.map +1 -0
  75. package/dist/drift-issue.js +167 -0
  76. package/dist/floor-table.d.ts +30 -0
  77. package/dist/floor-table.d.ts.map +1 -0
  78. package/dist/floor-table.data.d.ts +3 -0
  79. package/dist/floor-table.data.d.ts.map +1 -0
  80. package/dist/floor-table.data.js +179 -0
  81. package/dist/floor-table.js +56 -0
  82. package/dist/forge-flags.d.ts +90 -0
  83. package/dist/forge-flags.d.ts.map +1 -0
  84. package/dist/forge-flags.js +184 -0
  85. package/dist/lexicon.d.ts +69 -0
  86. package/dist/lexicon.d.ts.map +1 -1
  87. package/dist/lifecycle/gated-op.d.ts +7 -1
  88. package/dist/lifecycle/gated-op.d.ts.map +1 -1
  89. package/dist/lifecycle/gated-op.js +7 -4
  90. package/dist/local-chant.d.ts +98 -0
  91. package/dist/local-chant.d.ts.map +1 -0
  92. package/dist/local-chant.js +307 -0
  93. package/dist/op/activities/predict-behaviour.js +2 -2
  94. package/dist/op/op-waves-evidence-spec.d.ts +13 -0
  95. package/dist/op/op-waves-evidence-spec.d.ts.map +1 -0
  96. package/dist/op/op-waves-evidence-spec.js +21 -0
  97. package/dist/op/op-waves-evidence.d.ts +40 -0
  98. package/dist/op/op-waves-evidence.d.ts.map +1 -0
  99. package/dist/op/op-waves-evidence.js +58 -0
  100. package/dist/op/op-waves-run.d.ts +4 -0
  101. package/dist/op/op-waves-run.d.ts.map +1 -1
  102. package/dist/op/op-waves-run.js +24 -1
  103. package/dist/op/op-waves.d.ts +17 -1
  104. package/dist/op/op-waves.d.ts.map +1 -1
  105. package/dist/op/op-waves.js +23 -0
  106. package/dist/op/schedule-overdue.d.ts +41 -9
  107. package/dist/op/schedule-overdue.d.ts.map +1 -1
  108. package/dist/op/schedule-overdue.js +154 -25
  109. package/dist/plan-summary.d.ts +25 -0
  110. package/dist/plan-summary.d.ts.map +1 -1
  111. package/dist/plan-summary.js +31 -0
  112. package/dist/pr-plan-note.d.ts +35 -0
  113. package/dist/pr-plan-note.d.ts.map +1 -1
  114. package/dist/pr-plan-note.js +10 -0
  115. package/dist/pr-post.d.ts +23 -0
  116. package/dist/pr-post.d.ts.map +1 -1
  117. package/dist/pr-post.js +125 -3
  118. package/dist/release-floors.d.ts +33 -1
  119. package/dist/release-floors.d.ts.map +1 -1
  120. package/dist/release-floors.js +33 -1
  121. package/dist/state-migration.d.ts +24 -0
  122. package/dist/state-migration.d.ts.map +1 -1
  123. package/dist/state-migration.js +100 -5
  124. package/dist/wave-runtime.mjs +309 -302
  125. package/dist/workspace/ci-green.d.ts.map +1 -1
  126. package/dist/workspace/ci-green.js +4 -3
  127. package/dist/workspace/lexicon-outputs.d.ts.map +1 -1
  128. package/dist/workspace/lexicon-outputs.js +21 -7
  129. package/dist/workspace/reason-codes.d.ts +3 -0
  130. package/dist/workspace/reason-codes.d.ts.map +1 -1
  131. package/dist/workspace/reason-codes.js +4 -0
  132. package/dist/workspace/ref-gate.schema.json +85 -0
  133. package/dist/workspace/search-contract.d.ts +1 -1
  134. package/dist/workspace/search-contract.d.ts.map +1 -1
  135. package/dist/workspace/trust/check-evidence-report.d.ts +58 -0
  136. package/dist/workspace/trust/check-evidence-report.d.ts.map +1 -0
  137. package/dist/workspace/trust/check-evidence-report.js +109 -0
  138. package/dist/workspace/trust/check-evidence.d.ts +160 -0
  139. package/dist/workspace/trust/check-evidence.d.ts.map +1 -0
  140. package/dist/workspace/trust/check-evidence.js +309 -0
  141. package/dist/workspace/trust/ci-tag-statement.d.ts +2 -2
  142. package/dist/workspace/trust/ci-tag-statement.d.ts.map +1 -1
  143. package/dist/workspace/trust/dsse.d.ts +40 -2
  144. package/dist/workspace/trust/dsse.d.ts.map +1 -1
  145. package/dist/workspace/trust/dsse.js +34 -2
  146. package/dist/workspace/trust/evidence.d.ts +2 -2
  147. package/dist/workspace/trust/evidence.d.ts.map +1 -1
  148. package/dist/workspace/trust/keyless-fixture.d.ts +41 -0
  149. package/dist/workspace/trust/keyless-fixture.d.ts.map +1 -0
  150. package/dist/workspace/trust/keyless-fixture.js +161 -0
  151. package/dist/workspace/trust/keyless.d.ts +202 -0
  152. package/dist/workspace/trust/keyless.d.ts.map +1 -0
  153. package/dist/workspace/trust/keyless.js +488 -0
  154. package/dist/workspace/trust/local-evidence.d.ts +123 -0
  155. package/dist/workspace/trust/local-evidence.d.ts.map +1 -0
  156. package/dist/workspace/trust/local-evidence.js +259 -0
  157. package/dist/workspace/trust/op-run-statement.d.ts +2 -2
  158. package/dist/workspace/trust/op-run-statement.d.ts.map +1 -1
  159. package/dist/workspace/trust/policy.d.ts +140 -1
  160. package/dist/workspace/trust/policy.d.ts.map +1 -1
  161. package/dist/workspace/trust/policy.js +197 -3
  162. package/dist/workspace/trust/ref-gate-cli.d.ts +33 -0
  163. package/dist/workspace/trust/ref-gate-cli.d.ts.map +1 -0
  164. package/dist/workspace/trust/ref-gate-cli.js +234 -0
  165. package/dist/workspace/trust/ref-gate-fixture.d.ts +38 -0
  166. package/dist/workspace/trust/ref-gate-fixture.d.ts.map +1 -0
  167. package/dist/workspace/trust/ref-gate-fixture.js +97 -0
  168. package/dist/workspace/trust/ref-gate.d.ts +187 -0
  169. package/dist/workspace/trust/ref-gate.d.ts.map +1 -0
  170. package/dist/workspace/trust/ref-gate.js +432 -0
  171. package/dist/workspace/trust/run-statement.d.ts +3 -3
  172. package/dist/workspace/trust/run-statement.d.ts.map +1 -1
  173. package/dist/workspace/trust/runner-identity.d.ts +56 -0
  174. package/dist/workspace/trust/runner-identity.d.ts.map +1 -0
  175. package/dist/workspace/trust/runner-identity.js +65 -0
  176. package/dist/workspace/trust/trust-files.d.ts.map +1 -1
  177. package/dist/workspace/trust/trust-files.js +25 -1
  178. package/package.json +1 -1
  179. package/src/bundle-check.test.ts +140 -0
  180. package/src/bundle-check.ts +352 -0
  181. package/src/chant-install.test.ts +112 -0
  182. package/src/chant-install.ts +179 -0
  183. package/src/ci-commit.test.ts +45 -0
  184. package/src/ci-commit.ts +38 -4
  185. package/src/ci-evidence-jobs.ts +105 -0
  186. package/src/ci-image.test.ts +506 -0
  187. package/src/ci-image.ts +822 -0
  188. package/src/ci-login.test.ts +235 -0
  189. package/src/ci-login.ts +307 -0
  190. package/src/ci-product.ts +18 -0
  191. package/src/cli/commands/__fixtures__/source-dir-include/chant.config.json +1 -0
  192. package/src/cli/commands/__fixtures__/source-dir-include/infra.ts +1 -0
  193. package/src/cli/commands/__fixtures__/source-dir-include/scripts/run-on-load.ts +3 -0
  194. package/src/cli/commands/__fixtures__/source-dir-root/chant.config.json +1 -0
  195. package/src/cli/commands/__fixtures__/source-dir-root/infra.test.ts +1 -0
  196. package/src/cli/commands/__fixtures__/source-dir-root/infra.ts +1 -0
  197. package/src/cli/commands/__fixtures__/source-dir-root/scripts/run-on-load.ts +3 -0
  198. package/src/cli/commands/__fixtures__/source-dir-scoped/app.ts +3 -0
  199. package/src/cli/commands/__fixtures__/source-dir-scoped/chant.config.json +1 -0
  200. package/src/cli/commands/__fixtures__/source-dir-scoped/infra/net.ts +1 -0
  201. package/src/cli/commands/__fixtures__/source-dir-scoped/scripts/run-on-load.ts +3 -0
  202. package/src/cli/commands/import-index.ts +2 -2
  203. package/src/cli/handlers/build-source-dir.test.ts +64 -0
  204. package/src/cli/handlers/build.ts +21 -4
  205. package/src/cli/handlers/ci-check.ts +60 -3
  206. package/src/cli/handlers/ci-evidence.ts +167 -0
  207. package/src/cli/handlers/components.ts +3 -3
  208. package/src/cli/handlers/dead-guards.ts +37 -0
  209. package/src/cli/handlers/graph.ts +4 -4
  210. package/src/cli/handlers/lifecycle.ts +5 -4
  211. package/src/cli/handlers/local-chant.ts +106 -0
  212. package/src/cli/handlers/operator.ts +2 -2
  213. package/src/cli/handlers/search.ts +5 -5
  214. package/src/cli/main.test.ts +7 -0
  215. package/src/cli/main.ts +38 -0
  216. package/src/cli/parse-args.ts +21 -0
  217. package/src/cli/registry.ts +16 -0
  218. package/src/components/check-evidence-stage.test.ts +80 -0
  219. package/src/components/check-hooks.ts +84 -4
  220. package/src/components/check-local-evidence-stage.test.ts +141 -0
  221. package/src/components/check-steps.ts +56 -6
  222. package/src/components/product-pipeline.ts +28 -3
  223. package/src/components/product-plan.test.ts +87 -0
  224. package/src/components/product-plan.ts +230 -0
  225. package/src/components/release-compile.ts +2 -2
  226. package/src/config.ts +44 -3
  227. package/src/dead-guards.test.ts +206 -0
  228. package/src/dead-guards.ts +446 -0
  229. package/src/discovery/files.ts +5 -3
  230. package/src/drift-issue-bundle.test.ts +31 -0
  231. package/src/drift-issue.test.ts +206 -0
  232. package/src/drift-issue.ts +274 -0
  233. package/src/fit-note.test.ts +44 -0
  234. package/src/floor-table.data.ts +181 -0
  235. package/src/floor-table.ts +77 -0
  236. package/src/forge-flags.test.ts +110 -0
  237. package/src/forge-flags.ts +208 -0
  238. package/src/gate-decision-bundle.test.ts +1 -0
  239. package/src/lexicon.ts +68 -0
  240. package/src/lifecycle/gated-op.ts +10 -5
  241. package/src/local-chant.e2e.test.ts +94 -0
  242. package/src/local-chant.test.ts +162 -0
  243. package/src/local-chant.ts +341 -0
  244. package/src/op/activities/predict-behaviour.ts +2 -2
  245. package/src/op/op-waves-evidence-spec.ts +24 -0
  246. package/src/op/op-waves-evidence.test.ts +130 -0
  247. package/src/op/op-waves-evidence.ts +58 -0
  248. package/src/op/op-waves-run.ts +25 -1
  249. package/src/op/op-waves.ts +31 -1
  250. package/src/op/schedule-overdue.test.ts +85 -0
  251. package/src/op/schedule-overdue.ts +162 -26
  252. package/src/plan-summary.ts +40 -0
  253. package/src/pr-plan-note.ts +34 -0
  254. package/src/pr-post-plan-note.test.ts +146 -0
  255. package/src/pr-post.ts +127 -3
  256. package/src/release-floors.ts +47 -1
  257. package/src/stage-hooks-bundle.test.ts +1 -0
  258. package/src/state-migration.test.ts +52 -1
  259. package/src/state-migration.ts +107 -5
  260. package/src/workspace/ci-green.ts +4 -3
  261. package/src/workspace/lexicon-outputs.ts +23 -6
  262. package/src/workspace/reason-codes.test.ts +3 -0
  263. package/src/workspace/reason-codes.ts +4 -0
  264. package/src/workspace/ref-gate.schema.json +85 -0
  265. package/src/workspace/trust/check-evidence-report.ts +115 -0
  266. package/src/workspace/trust/check-evidence.test.ts +133 -0
  267. package/src/workspace/trust/check-evidence.ts +327 -0
  268. package/src/workspace/trust/ci-tag-statement.ts +2 -2
  269. package/src/workspace/trust/dsse.ts +48 -4
  270. package/src/workspace/trust/evidence.ts +2 -2
  271. package/src/workspace/trust/keyless-fixture.ts +214 -0
  272. package/src/workspace/trust/keyless.test.ts +220 -0
  273. package/src/workspace/trust/keyless.ts +557 -0
  274. package/src/workspace/trust/local-evidence.test.ts +127 -0
  275. package/src/workspace/trust/local-evidence.ts +268 -0
  276. package/src/workspace/trust/op-run-statement.ts +2 -2
  277. package/src/workspace/trust/policy.ts +263 -3
  278. package/src/workspace/trust/ref-gate-cli.ts +244 -0
  279. package/src/workspace/trust/ref-gate-fixture.ts +125 -0
  280. package/src/workspace/trust/ref-gate.e2e.test.ts +76 -0
  281. package/src/workspace/trust/ref-gate.test.ts +247 -0
  282. package/src/workspace/trust/ref-gate.ts +539 -0
  283. package/src/workspace/trust/run-statement.ts +3 -3
  284. package/src/workspace/trust/runner-identity.ts +92 -0
  285. package/src/workspace/trust/trust-files.test.ts +22 -0
  286. package/src/workspace/trust/trust-files.ts +54 -1
@@ -0,0 +1,341 @@
1
+ /**
2
+ * `@intentius/chant/local-chant` (#4787): build a product against a chant
3
+ * checkout instead of its pinned release.
4
+ *
5
+ * terragucci and plywood each carried a 270-line `scripts/chant-local.sh`
6
+ * that did this, and sql-yodeler would have copied it. `chant dev local`
7
+ * runs these functions:
8
+ *
9
+ * 1. find the chant packages the product's package.json files name (and any
10
+ * `with`), plus the chant packages those depend on, in an order where each
11
+ * follows the packages it builds against ({@link packOrder});
12
+ * 2. `npm ci` in the checkout when its lock changed since the last run, then
13
+ * `npm pack` each package (its prepack builds it) into `.chant-local/` in
14
+ * the product, under a fixed name per package;
15
+ * 3. point every package.json of the product at the tarballs, run
16
+ * `npm install --no-save`, and put the manifests and package-lock.json
17
+ * back byte for byte, so the workspace gets the local build everywhere and
18
+ * git sees no change;
19
+ * 4. mark each installed copy's package.json with `chantLocal` (the commit and
20
+ * the checkout), which `checkBundle` and a reader use to tell the local
21
+ * build from the pin, and fail when a copy is not the local build.
22
+ *
23
+ * {@link resetLocalChant} goes back: `npm ci`, then a check that every
24
+ * installed chant package is the version the lock pins, with no mark.
25
+ */
26
+ import { spawnSync } from "node:child_process";
27
+ import { createHash } from "node:crypto";
28
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
29
+ import { join, relative, resolve } from "node:path";
30
+
31
+ /** A chant workspace package that can be packed: not private. */
32
+ export interface ChantPackage {
33
+ name: string;
34
+ version: string;
35
+ /** Relative to the checkout: `packages/core`, `lexicons/k8s`. */
36
+ dir: string;
37
+ /** Its dependencies, peer and optional dependencies, by name. */
38
+ deps: string[];
39
+ }
40
+
41
+ interface Manifest {
42
+ name?: string;
43
+ version?: string;
44
+ private?: boolean;
45
+ workspaces?: string[] | { packages?: string[] };
46
+ dependencies?: Record<string, string>;
47
+ devDependencies?: Record<string, string>;
48
+ peerDependencies?: Record<string, string>;
49
+ optionalDependencies?: Record<string, string>;
50
+ chantLocal?: LocalChantMark;
51
+ }
52
+
53
+ /** The `chantLocal` field `chant dev local` writes into each installed copy's package.json. */
54
+ export interface LocalChantMark {
55
+ /** The checkout's commit, with `+dirty` when tracked files had changes. */
56
+ commit: string;
57
+ /** The checkout. */
58
+ dir: string;
59
+ }
60
+
61
+ export class LocalChantError extends Error {
62
+ override name = "LocalChantError";
63
+ }
64
+
65
+ const readManifest = (file: string): Manifest => JSON.parse(readFileSync(file, "utf8")) as Manifest;
66
+ const isChant = (name: string) => /^@intentius\/chant(?:-[a-z0-9-]+)?$/.test(name);
67
+
68
+ /** The packable packages of a chant checkout, under `packages/` and `lexicons/`, by name. */
69
+ export function chantPackages(chantDir: string): Map<string, ChantPackage> {
70
+ const out = new Map<string, ChantPackage>();
71
+ for (const top of ["packages", "lexicons"]) {
72
+ const base = join(chantDir, top);
73
+ if (!existsSync(base)) continue;
74
+ for (const d of readdirSync(base).sort()) {
75
+ const f = join(base, d, "package.json");
76
+ if (!existsSync(f)) continue;
77
+ const p = readManifest(f);
78
+ if (p.private || !p.name) continue;
79
+ out.set(p.name, {
80
+ name: p.name,
81
+ version: p.version ?? "0.0.0",
82
+ dir: `${top}/${d}`,
83
+ deps: Object.keys({ ...p.dependencies, ...p.peerDependencies, ...p.optionalDependencies }),
84
+ });
85
+ }
86
+ }
87
+ return out;
88
+ }
89
+
90
+ /** The product's package.json files, relative to its root: the root's and each workspace package's. */
91
+ export function productManifests(productDir: string): string[] {
92
+ const root = readManifest(join(productDir, "package.json"));
93
+ const patterns = Array.isArray(root.workspaces) ? root.workspaces : (root.workspaces?.packages ?? []);
94
+ const out = ["package.json"];
95
+ for (const pattern of patterns) {
96
+ const clean = pattern.replace(/\/+$/, "");
97
+ const dirs = clean.endsWith("/*")
98
+ ? (existsSync(join(productDir, clean.slice(0, -2))) ? readdirSync(join(productDir, clean.slice(0, -2))).sort().map((d) => `${clean.slice(0, -2)}/${d}`) : [])
99
+ : [clean];
100
+ for (const d of dirs) if (existsSync(join(productDir, d, "package.json"))) out.push(`${d}/package.json`);
101
+ }
102
+ return [...new Set(out)];
103
+ }
104
+
105
+ /** Every `@intentius/chant*` the product's package.json files name in dependencies, devDependencies or peerDependencies. */
106
+ export function productChantNames(productDir: string): string[] {
107
+ const out = new Set<string>();
108
+ for (const f of productManifests(productDir)) {
109
+ const p = readManifest(join(productDir, f));
110
+ for (const n of Object.keys({ ...p.dependencies, ...p.devDependencies, ...p.peerDependencies })) if (isChant(n)) out.add(n);
111
+ }
112
+ return [...out].sort();
113
+ }
114
+
115
+ /**
116
+ * The packages to pack for `want` and their chant dependencies, each after
117
+ * the packages it depends on, ties by name. Throws on a name the checkout has
118
+ * no package for, and on a cycle.
119
+ */
120
+ export function packOrder(pkgs: Map<string, ChantPackage>, want: Iterable<string>): ChantPackage[] {
121
+ const need = new Set<string>();
122
+ const visit = (n: string) => {
123
+ if (need.has(n)) return;
124
+ const p = pkgs.get(n);
125
+ if (!p) throw new LocalChantError(`the chant checkout has no package ${n}`);
126
+ need.add(n);
127
+ for (const d of p.deps) if (pkgs.has(d)) visit(d);
128
+ };
129
+ for (const n of want) visit(n);
130
+ const out: ChantPackage[] = [];
131
+ const left = new Set(need);
132
+ while (left.size) {
133
+ const ready = [...left].filter((n) => !pkgs.get(n)!.deps.some((d) => d !== n && left.has(d))).sort();
134
+ if (!ready.length) throw new LocalChantError(`dependency cycle among ${[...left].sort().join(", ")}`);
135
+ for (const n of ready) {
136
+ out.push(pkgs.get(n)!);
137
+ left.delete(n);
138
+ }
139
+ }
140
+ return out;
141
+ }
142
+
143
+ /** The fixed tarball name for a package, so a later run replaces it: `@intentius/chant-lexicon-k8s` is `intentius-chant-lexicon-k8s.tgz`. */
144
+ export const tarballName = (name: string) => `${name.replace(/^@/, "").replace(/\//g, "-")}.tgz`;
145
+
146
+ /**
147
+ * One package.json pointed at the tarballs: every dependency, devDependency
148
+ * and optionalDependency `local` names takes its `file:` spec. The root also
149
+ * gets every tarball as a devDependency, so npm replaces a copy only a lexicon
150
+ * reaches (a lexicon's own chant dependencies) instead of keeping a registry
151
+ * release of it.
152
+ */
153
+ export function pointAtTarballs(manifest: Manifest, local: Map<string, string>, isRoot: boolean): Manifest {
154
+ const p: Manifest = structuredClone(manifest);
155
+ for (const k of ["dependencies", "devDependencies", "optionalDependencies"] as const) {
156
+ const deps = p[k];
157
+ if (!deps) continue;
158
+ for (const n of Object.keys(deps)) if (local.has(n)) deps[n] = local.get(n)!;
159
+ }
160
+ if (isRoot) {
161
+ const extra = Object.fromEntries([...local].filter(([n]) => !(n in (p.dependencies ?? {})) && !(n in (p.optionalDependencies ?? {}))));
162
+ p.devDependencies = { ...p.devDependencies, ...extra };
163
+ }
164
+ return p;
165
+ }
166
+
167
+ /** Each installed copy of a chant package under the product: `node_modules/@intentius/*` at the root, in each workspace package, and nested. Links (workspace packages) are left out. */
168
+ export function installedChantCopies(productDir: string): { at: string; name: string }[] {
169
+ const out: { at: string; name: string }[] = [];
170
+ const walk = (nm: string) => {
171
+ const scope = join(nm, "@intentius");
172
+ if (!existsSync(scope)) return;
173
+ for (const d of readdirSync(scope).sort()) {
174
+ const at = join(scope, d);
175
+ if (lstatSync(at).isSymbolicLink() || !existsSync(join(at, "package.json"))) continue;
176
+ walk(join(at, "node_modules"));
177
+ const name = `@intentius/${d}`;
178
+ if (isChant(name)) out.push({ at, name });
179
+ }
180
+ };
181
+ walk(join(productDir, "node_modules"));
182
+ for (const f of productManifests(productDir).slice(1)) walk(join(productDir, f.replace(/package\.json$/, ""), "node_modules"));
183
+ return out;
184
+ }
185
+
186
+ /** How a command runs: throws {@link LocalChantError} when it exits non-zero. */
187
+ export type Runner = (command: string, args: string[], cwd: string) => string;
188
+
189
+ /** Run a command with its stderr on ours and its stdout returned. */
190
+ export const defaultRunner: Runner = (command, args, cwd) => {
191
+ const r = spawnSync(command, args, { cwd, stdio: ["ignore", "pipe", "inherit"], encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
192
+ if (r.error) throw new LocalChantError(`${command} ${args.join(" ")} in ${cwd}: ${r.error.message}`);
193
+ if (r.status !== 0) throw new LocalChantError(`${command} ${args.join(" ")} in ${cwd} exited ${r.status ?? r.signal}`);
194
+ return r.stdout;
195
+ };
196
+
197
+ export interface LocalChantOptions {
198
+ /** The product's root, where its package.json and lock are. */
199
+ productDir: string;
200
+ /** The chant checkout to pack. */
201
+ chantDir: string;
202
+ /** Chant packages to pack besides the ones the product names, such as a lexicon an image installs. */
203
+ with?: string[];
204
+ /** Run `npm ci` in the checkout when its lock changed since the last run (default true). */
205
+ install?: boolean;
206
+ log?: (line: string) => void;
207
+ run?: Runner;
208
+ }
209
+
210
+ export interface LocalChantResult {
211
+ mark: LocalChantMark;
212
+ /** What was packed, in pack order, with each tarball's path. */
213
+ packed: (ChantPackage & { tarball: string })[];
214
+ /** How many installed copies were marked. */
215
+ marked: number;
216
+ /** The tarball directory, `<product>/.chant-local`. */
217
+ outDir: string;
218
+ }
219
+
220
+ /** The checkout's commit, with `+dirty` when tracked files have changes; `unknown` outside git. */
221
+ function checkoutMark(chantDir: string): string {
222
+ const head = spawnSync("git", ["rev-parse", "HEAD"], { cwd: chantDir, encoding: "utf8" });
223
+ if (head.status !== 0) return "unknown";
224
+ const status = spawnSync("git", ["status", "--porcelain", "--untracked-files=no"], { cwd: chantDir, encoding: "utf8" });
225
+ return `${head.stdout.trim()}${status.stdout.trim() ? "+dirty" : ""}`;
226
+ }
227
+
228
+ /** Pack the chant checkout and install it into the product, leaving its package.json files and lock as they were. */
229
+ export function installLocalChant(opts: LocalChantOptions): LocalChantResult {
230
+ const productDir = resolve(opts.productDir);
231
+ const chantDir = resolve(opts.chantDir);
232
+ const log = opts.log ?? ((l: string) => process.stderr.write(`chant dev local: ${l}\n`));
233
+ const run = opts.run ?? defaultRunner;
234
+ if (!existsSync(join(productDir, "package.json"))) throw new LocalChantError(`${productDir} has no package.json`);
235
+ if (!existsSync(join(chantDir, "packages/core/package.json"))) throw new LocalChantError(`${chantDir} is not a chant checkout (no packages/core/package.json)`);
236
+
237
+ const mark: LocalChantMark = { commit: checkoutMark(chantDir), dir: chantDir };
238
+ log(`chant at ${mark.commit} (${chantDir})`);
239
+
240
+ if (opts.install !== false) {
241
+ const lock = join(chantDir, "package-lock.json");
242
+ if (!existsSync(lock)) throw new LocalChantError(`${chantDir} has no package-lock.json to npm ci from`);
243
+ const sum = createHash("sha256").update(readFileSync(lock)).digest("hex");
244
+ const stamp = join(chantDir, "node_modules/.chant-dev-local");
245
+ if (!existsSync(stamp) || readFileSync(stamp, "utf8").trim() !== sum) {
246
+ log("npm ci in the chant checkout");
247
+ run("npm", ["ci", "--no-audit", "--no-fund"], chantDir);
248
+ writeFileSync(stamp, `${sum}\n`);
249
+ }
250
+ }
251
+
252
+ const pkgs = chantPackages(chantDir);
253
+ const order = packOrder(pkgs, [...productChantNames(productDir), ...(opts.with ?? [])]);
254
+ if (!order.length) throw new LocalChantError(`${productDir}'s package.json files name no @intentius/chant package`);
255
+
256
+ const outDir = join(productDir, ".chant-local");
257
+ mkdirSync(join(outDir, "manifests"), { recursive: true });
258
+ const packed: LocalChantResult["packed"] = [];
259
+ for (const p of order) {
260
+ log(`packing ${p.dir}`);
261
+ const out = run("npm", ["pack", "--silent", "--pack-destination", outDir], join(chantDir, p.dir));
262
+ const file = out.trim().split("\n").pop()?.trim() ?? "";
263
+ if (!file || !existsSync(join(outDir, file))) throw new LocalChantError(`npm pack in ${p.dir} wrote no tarball`);
264
+ const fixed = tarballName(p.name);
265
+ if (file !== fixed) renameSync(join(outDir, file), join(outDir, fixed));
266
+ packed.push({ ...p, tarball: join(outDir, fixed) });
267
+ }
268
+ writeFileSync(join(outDir, "commit"), `${mark.commit}\n`);
269
+ writeFileSync(join(outDir, "packages.json"), `${JSON.stringify(packed.map((p) => ({ name: p.name, version: p.version, tarball: relative(productDir, p.tarball) })), null, 2)}\n`);
270
+
271
+ // The workspace packages pin chant too, so installing at the root alone
272
+ // would leave the pinned copies nested under packages/*/node_modules. Point
273
+ // every package.json at the tarballs for one install and put each file
274
+ // back afterwards, the lock with them. --legacy-peer-deps because the pinned
275
+ // lexicons still in the tree want the pinned core as a peer until npm
276
+ // replaces them.
277
+ const local = new Map(packed.map((p) => [p.name, `file:${p.tarball}`]));
278
+ const files = [...productManifests(productDir), ...(existsSync(join(productDir, "package-lock.json")) ? ["package-lock.json"] : [])];
279
+ const saved = new Map(files.map((f) => [f, readFileSync(join(productDir, f))]));
280
+ for (const [f, body] of saved) writeFileSync(join(outDir, "manifests", f.replace(/\//g, "_")), body);
281
+ try {
282
+ for (const f of files) {
283
+ if (!f.endsWith("package.json")) continue;
284
+ const p = pointAtTarballs(JSON.parse(saved.get(f)!.toString("utf8")) as Manifest, local, f === "package.json");
285
+ writeFileSync(join(productDir, f), `${JSON.stringify(p, null, 2)}\n`);
286
+ }
287
+ log(`installing ${packed.length} tarballs with npm install --no-save`);
288
+ run("npm", ["install", "--no-save", "--no-audit", "--no-fund", "--legacy-peer-deps"], productDir);
289
+ } finally {
290
+ for (const [f, body] of saved) writeFileSync(join(productDir, f), body);
291
+ }
292
+
293
+ const versions = new Map(packed.map((p) => [p.name, p.version]));
294
+ const bad: string[] = [];
295
+ let marked = 0;
296
+ for (const { at, name } of installedChantCopies(productDir)) {
297
+ if (!versions.has(name)) continue;
298
+ const f = join(at, "package.json");
299
+ const p = readManifest(f);
300
+ if (p.version !== versions.get(name)) {
301
+ bad.push(`${relative(productDir, at)} is ${p.version}, the checkout's is ${versions.get(name)}`);
302
+ continue;
303
+ }
304
+ p.chantLocal = mark;
305
+ writeFileSync(f, `${JSON.stringify(p, null, 2)}\n`);
306
+ marked++;
307
+ }
308
+ if (bad.length) throw new LocalChantError(`these installed copies are not the local build:\n ${bad.join("\n ")}`);
309
+ log(`marked ${marked} installed chant packages with ${mark.commit}`);
310
+ return { mark, packed, marked, outDir };
311
+ }
312
+
313
+ /** The installed chant copies that differ from what package-lock.json pins, or carry a `chantLocal` mark. */
314
+ export function lockMismatches(productDir: string): string[] {
315
+ const dir = resolve(productDir);
316
+ const lockFile = join(dir, "package-lock.json");
317
+ if (!existsSync(lockFile)) return ["there is no package-lock.json"];
318
+ const lock = (JSON.parse(readFileSync(lockFile, "utf8")) as { packages?: Record<string, { version?: string; link?: boolean }> }).packages ?? {};
319
+ const bad: string[] = [];
320
+ for (const [at, entry] of Object.entries(lock)) {
321
+ if (!/(^|\/)node_modules\/@intentius\/chant[^/]*$/.test(at) || entry.link) continue;
322
+ const f = join(dir, at, "package.json");
323
+ if (!existsSync(f)) {
324
+ bad.push(`${at} is missing`);
325
+ continue;
326
+ }
327
+ const p = readManifest(f);
328
+ if (p.version !== entry.version || p.chantLocal) bad.push(`${at} is ${p.version}${p.chantLocal ? " (local build)" : ""}, the lock says ${entry.version}`);
329
+ }
330
+ return bad;
331
+ }
332
+
333
+ /** Go back to the pin: `npm ci`, then fail when an installed chant package is not what the lock pins. */
334
+ export function resetLocalChant(opts: { productDir: string; log?: (line: string) => void; run?: Runner }): void {
335
+ const dir = resolve(opts.productDir);
336
+ const log = opts.log ?? ((l: string) => process.stderr.write(`chant dev local: ${l}\n`));
337
+ log("reinstalling the pinned versions with npm ci");
338
+ (opts.run ?? defaultRunner)("npm", ["ci", "--no-audit", "--no-fund"], dir);
339
+ const bad = lockMismatches(dir);
340
+ if (bad.length) throw new LocalChantError(`node_modules does not match package-lock.json after npm ci:\n ${bad.join("\n ")}`);
341
+ }
@@ -155,7 +155,7 @@ export function declaredEdgeCoverage(): BehaviourEdgeCoverage {
155
155
  * activity registry imports this module statically.
156
156
  */
157
157
  export async function predictDeclared(projectPath: string, args: PredictBehaviourArgs): Promise<BehaviourResult> {
158
- const { loadChantConfigUpward } = await import("../../config");
158
+ const { loadChantConfigUpward, resolveSourceDir } = await import("../../config");
159
159
  const { loadPlugins, resolveProjectLexicons } = await import("../../cli/plugins");
160
160
  const { build } = await import("../../build");
161
161
  const { buildGraphIr } = await import("../../graph-ir");
@@ -168,7 +168,7 @@ export async function predictDeclared(projectPath: string, args: PredictBehaviou
168
168
  // and nothing to refuse when two lexicons both answer — they are additive.
169
169
  const kinds = plugins.map((p) => p.behaviourKinds).filter((k): k is BehaviourKinds => k !== undefined);
170
170
 
171
- const sourceDir = resolve(projectPath, config.sourceDir ?? ".");
171
+ const sourceDir = resolveSourceDir(projectPath, config);
172
172
  const result = await build(sourceDir, plugins.map((p) => p.serializer));
173
173
  if (result.errors.length > 0) {
174
174
  const messages = result.errors.map((e) => (typeof e === "string" ? e : (e as { message?: string }).message ?? String(e)));
@@ -0,0 +1,24 @@
1
+ /**
2
+ * `evidence` of an Op waves spec (#4870), checked with no import, so the
3
+ * spec's readers in the bundles stay small. The runner side is
4
+ * ./op-waves-evidence.ts.
5
+ */
6
+
7
+ /** `evidence` of an Op waves spec (#4870). */
8
+ export interface OpWavesEvidence {
9
+ /** The checks whose current evidence the applied commit needs, read at base. */
10
+ requires?: string[];
11
+ }
12
+
13
+ /** What is wrong with a spec's `evidence`, empty when nothing is. */
14
+ export function opWavesEvidenceProblems(raw: unknown): string[] {
15
+ if (raw === undefined) return [];
16
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return ["`evidence` must be an object"];
17
+ const r = raw as Record<string, unknown>;
18
+ const problems: string[] = [];
19
+ for (const key of Object.keys(r)) if (key !== "requires") problems.push(`\`evidence.${key}\` is not a setting; \`evidence\` takes \`requires\``);
20
+ if (r.requires !== undefined && (!Array.isArray(r.requires) || r.requires.some((c) => typeof c !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(c)))) {
21
+ problems.push("`evidence.requires` must be a list of check names (letters, digits, `.`, `_`, `:` and `-`, as `refs` in .chant/trust.json names them)");
22
+ }
23
+ return problems;
24
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * #4870: an apply whose spec at base requires a check's evidence refuses a
3
+ * commit without it, and a wave job with a runner key signs its own plan
4
+ * and policy checks. Real local repositories; the spec at base is read with
5
+ * git itself.
6
+ */
7
+
8
+ import { execFileSync } from "node:child_process";
9
+ import { generateKeyPairSync } from "node:crypto";
10
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { describe, expect, test } from "vitest";
14
+ import type { OpWavesSpec } from "./op-waves";
15
+ import { assertOpWavesSpec } from "./op-waves";
16
+ import { runOpWave, type OpWaveRunPort, type OpWaveShowAtBase } from "./op-waves-run";
17
+ import { memoryGateLedgerPort } from "./gate";
18
+ import { CHANT_EXIT } from "../exit-codes";
19
+ import { CapabilityRegistry, type Capability } from "../components/capability";
20
+ import { loadRunnerKey } from "../workspace/trust/dsse";
21
+ import { readCheckEvidence, recordChecks, runnerKeyEvidenceSigner, signChecks } from "../workspace/trust/check-evidence";
22
+ import { signOpWaveChecks } from "./op-waves-evidence";
23
+
24
+ const digest = (n: string) => `sha256:${n.repeat(64)}`;
25
+
26
+ function git(cwd: string, ...args: string[]): string {
27
+ return execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "init.defaultBranch=main", ...args], { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
28
+ }
29
+
30
+ const spec: OpWavesSpec = {
31
+ name: "roots",
32
+ op: "tf-apply",
33
+ step: { kind: "fake-apply", root: "{target}" },
34
+ evidence: { requires: ["plan", "policy"] },
35
+ waves: [{ name: "dev", runs: [{ target: "network" }], gate: "never" }],
36
+ };
37
+
38
+ /** A base commit with the spec and a runner key in .chant/trust.json, and a merge on top of it. */
39
+ function repo(): { cwd: string; base: string; head: string; pem: string } {
40
+ const cwd = mkdtempSync(join(tmpdir(), "chant-4870-waves-"));
41
+ const { privateKey } = generateKeyPairSync("ed25519");
42
+ const pem = privateKey.export({ format: "pem", type: "pkcs8" }).toString();
43
+ git(cwd, "init", "--quiet");
44
+ mkdirSync(join(cwd, ".chant"));
45
+ writeFileSync(join(cwd, ".chant/trust.json"), JSON.stringify({ schema: 1, runners: [{ principal: "ci", class: "runner", key: loadRunnerKey(pem).publicKey }] }));
46
+ writeFileSync(join(cwd, "waves.json"), JSON.stringify(spec));
47
+ git(cwd, "add", ".");
48
+ git(cwd, "commit", "--quiet", "-m", "base");
49
+ const base = git(cwd, "rev-parse", "HEAD");
50
+ writeFileSync(join(cwd, "main.tf"), "# change\n");
51
+ git(cwd, "add", "main.tf");
52
+ git(cwd, "commit", "--quiet", "-m", "merge");
53
+ return { cwd, base, head: git(cwd, "rev-parse", "HEAD"), pem };
54
+ }
55
+
56
+ const atBase: OpWaveShowAtBase = (ref, path, cwd) => {
57
+ const sha = git(cwd, "rev-parse", ref);
58
+ try {
59
+ return { sha, text: execFileSync("git", ["show", `${sha}:${path}`], { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }) };
60
+ } catch {
61
+ return { sha, text: null };
62
+ }
63
+ };
64
+
65
+ function fakeCapability(): { registry: CapabilityRegistry; ran: string[] } {
66
+ const ran: string[] = [];
67
+ const cap: Capability<Record<string, unknown>, unknown> = {
68
+ kind: "fake-apply",
69
+ async plan(_ctx, input) {
70
+ return { member: String(input.root), planDigest: digest("1"), artifact: {} };
71
+ },
72
+ async run(_ctx, input) {
73
+ ran.push(String(input.root));
74
+ return { applied: input.root };
75
+ },
76
+ };
77
+ return { registry: new CapabilityRegistry().register(cap), ran };
78
+ }
79
+
80
+ const runs: OpWaveRunPort = { append: async () => undefined };
81
+
82
+ async function wave(cwd: string, head: string) {
83
+ const { registry, ran } = fakeCapability();
84
+ const logs: string[] = [];
85
+ const result = await runOpWave({ spec, specFile: "waves.json", wave: 1, cwd, head, show: atBase, gates: memoryGateLedgerPort(), capabilities: registry, runs, log: (l) => logs.push(l) });
86
+ return { result, ran, logs };
87
+ }
88
+
89
+ describe("evidence.requires (#4870)", () => {
90
+ test("the spec takes evidence.requires and refuses a name that is not a check's", () => {
91
+ expect(() => assertOpWavesSpec(spec)).not.toThrow();
92
+ expect(() => assertOpWavesSpec({ ...spec, evidence: { requires: ["has space"] } })).toThrow(/evidence.requires/);
93
+ expect(() => assertOpWavesSpec({ ...spec, evidence: { want: [] } as never })).toThrow(/evidence.want/);
94
+ });
95
+
96
+ test("an apply whose policy at base requires the plan check's evidence refuses a commit without it", async () => {
97
+ const { cwd, head } = repo();
98
+ const { result, ran, logs } = await wave(cwd, head);
99
+ expect(result.exitCode).toBe(1);
100
+ expect(ran).toEqual([]);
101
+ const line = logs.find((l) => l.includes("lacks the evidence"));
102
+ expect(line).toContain("plan (no evidence for check plan");
103
+ expect(line).toContain("chant ci evidence sign --check-id policy");
104
+ expect(line).toContain("nothing in it was planned or applied");
105
+ });
106
+
107
+ test("the same commit applies once its tree has current evidence for each required check", async () => {
108
+ const { cwd, base, head, pem } = repo();
109
+ await recordChecks(cwd, await signChecks(cwd, head, [{ check: "plan" }, { check: "policy" }], runnerKeyEvidenceSigner(cwd, base, pem)), { push: false });
110
+ const { result, ran } = await wave(cwd, head);
111
+ expect(result.exitCode).toBe(0);
112
+ expect(ran).toEqual(["network"]);
113
+ });
114
+
115
+ test("a wave job with a runner key signs its plan check, and its policy check only when ci.policy ran and denied nothing", async () => {
116
+ const { cwd, base, head, pem } = repo();
117
+ const logs: string[] = [];
118
+ const env = { CHANT_RUNNER_KEY: pem } as NodeJS.ProcessEnv;
119
+ const none = new Map();
120
+ expect(await signOpWaveChecks({ cwd, head, base, wave: "dev", planDigest: digest("1"), policyRows: none, log: (l) => logs.push(l), env, push: false })).toEqual(["plan:dev"]);
121
+ const passed = new Map([["network", { source: "ci.policy", result: "passed" as const, rules: [] }]]);
122
+ expect(await signOpWaveChecks({ cwd, head, base, wave: "dev", policyRows: passed, log: (l) => logs.push(l), env, push: false })).toEqual(["plan:dev", "policy:dev"]);
123
+ const denied = new Map([["network", { source: "ci.policy", result: "denied" as const, rules: ["r"] }]]);
124
+ expect(await signOpWaveChecks({ cwd, head, base, wave: "dev", policyRows: denied, log: (l) => logs.push(l), env, push: false })).toEqual(["plan:dev"]);
125
+ expect((await readCheckEvidence(cwd, head, base, ["plan:dev", "policy:dev"])).map((v) => v.status)).toEqual(["current", "current"]);
126
+ expect(logs[0]).toBe("wave dev: signed evidence for plan:dev as ci");
127
+ // No key, nothing signed and nothing said.
128
+ expect(await signOpWaveChecks({ cwd, head, base, wave: "dev", policyRows: none, log: (l) => logs.push(l), env: {}, push: false })).toEqual([]);
129
+ });
130
+ });
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Check evidence in an Op waves job (#4870).
3
+ *
4
+ * - `evidence.requires` in the spec at base names the checks whose current
5
+ * evidence a wave's commit needs before anything in it is planned or
6
+ * applied, such as `["plan", "policy"]`, which the pull request's plan
7
+ * note job signed for the head's tree. A commit without it is refused,
8
+ * and the refusal names each missing check. Read at base, so a change
9
+ * cannot drop the rule for its own apply.
10
+ * - With a runner key in `CHANT_RUNNER_KEY`, or `CHANT_RUNNER_IDENTITY=oidc`
11
+ * to sign keyless from the job's OIDC identity (#4869), the deciding job signs its own
12
+ * two named checks once the wave is planned: `plan:<wave>`, and
13
+ * `policy:<wave>` when `ci.policy` ran over the plans and denied nothing.
14
+ * They are attached under `refs/notes/chant/evidence` and pushed, where #4867's ref gate
15
+ * and a later wave read them.
16
+ *
17
+ * See ../workspace/trust/check-evidence.ts.
18
+ */
19
+
20
+ import { execFileSync } from "node:child_process";
21
+ import type { OpRunPolicyRow } from "./runtime";
22
+ export { opWavesEvidenceProblems, type OpWavesEvidence } from "./op-waves-evidence-spec";
23
+ import { CHECK_EVIDENCE_KEY_ENV, missingCheckEvidence, recordChecks, RUNNER_IDENTITY_ENV, runnerEvidenceSigner, signChecks } from "../workspace/trust/check-evidence";
24
+
25
+ function top(cwd: string): string {
26
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
27
+ }
28
+
29
+ /** Why the wave's commit is refused for want of evidence, or null. */
30
+ export async function opWaveEvidenceRefusal(cwd: string, head: string, base: string, requires: readonly string[] | undefined): Promise<string | null> {
31
+ if (!requires || requires.length === 0) return null;
32
+ return missingCheckEvidence(top(cwd), head, base, requires);
33
+ }
34
+
35
+ /**
36
+ * Sign the wave's plan and policy checks when the job has a runner identity.
37
+ * Never fails the wave: a key or identity the policy at base does not list, or a
38
+ * notes push that does not land, is a line in the log.
39
+ */
40
+ export async function signOpWaveChecks(input: { cwd: string; head: string; base: string; wave: string; planDigest?: string; policyRows: ReadonlyMap<string, OpRunPolicyRow>; log: (line: string) => void; env?: NodeJS.ProcessEnv; push?: boolean; fetch?: typeof fetch }): Promise<string[]> {
41
+ const env = input.env ?? process.env;
42
+ if (!env[CHECK_EVIDENCE_KEY_ENV] && !env[RUNNER_IDENTITY_ENV]) return [];
43
+ try {
44
+ const repo = top(input.cwd);
45
+ const signer = (await runnerEvidenceSigner(repo, input.base, { env, ...(input.fetch ? { fetch: input.fetch } : {}) }))!;
46
+ const rows = [...input.policyRows.values()];
47
+ const checks: Array<{ check: string; claim?: string }> = [{ check: `plan:${input.wave}`, ...(input.planDigest ? { claim: input.planDigest } : {}) }];
48
+ if (rows.length > 0 && rows.every((r) => r.result !== "denied")) checks.push({ check: `policy:${input.wave}`, claim: JSON.stringify(rows) });
49
+ const signed = await signChecks(repo, input.head, checks, signer);
50
+ const pushed = await recordChecks(repo, signed, { push: input.push !== false });
51
+ if (input.push !== false && !pushed.pushed && pushed.pushWarning) input.log(`wave ${input.wave}: ${pushed.pushWarning}`);
52
+ input.log(`wave ${input.wave}: signed evidence for ${signed.map((s) => s.check).join(", ")} as ${signer.principal}`);
53
+ return signed.map((s) => s.check);
54
+ } catch (err) {
55
+ input.log(`wave ${input.wave}: no check evidence signed: ${err instanceof Error ? err.message : String(err)}`);
56
+ return [];
57
+ }
58
+ }
@@ -90,6 +90,8 @@ import type { GateSigners } from "../lifecycle/gate-seal";
90
90
  import { ciRunIdFromEnv } from "./gate-run-locator";
91
91
  import { appendRunRecord, DEFAULT_RUN_ENV } from "../lifecycle/run-ledger";
92
92
  import { LifecyclePushLostError, pushLifecycleRebasing } from "../lifecycle/git";
93
+ import { opWaveEvidenceRefusal, signOpWaveChecks } from "./op-waves-evidence";
94
+ import { opWavesEvidenceProblems, type OpWavesEvidence } from "./op-waves-evidence-spec";
93
95
  import { resolveCiJob } from "../lifecycle/release-ledger";
94
96
  import type { OpRunPolicyRow, OpRunRecordInput, OpRunStepRecord, OpRunWave, OpRunWavePlan, OpRunWaveTarget } from "./runtime";
95
97
  import { opWaveRunHookList, opWaveRunHooksProblems, runOpWaveAfterApply, runOpWaveBeforeApply, runOpWaveBeforePlan, type OpWaveRunHooks } from "./op-waves-run-hooks";
@@ -644,6 +646,20 @@ export interface OpWaveBaseRules {
644
646
  pullRequestGate?: string;
645
647
  /** `approvals.preview` at base: the wave applies what the merged pull request's head recorded, or refuses (exit 4). */
646
648
  preview?: boolean;
649
+ /** `evidence.requires` at base (#4870): the checks whose current evidence the wave's commit needs. */
650
+ evidenceRequires?: string[];
651
+ /** Set when `evidence` at base cannot be read: the wave fails rather than apply without the checks it asks for. */
652
+ evidenceRefused?: string;
653
+ }
654
+
655
+ /** `evidence` at base (#4870), or why it cannot be read. */
656
+ function evidenceAtBase(spec: OpWavesSpec, where: string): Pick<OpWaveBaseRules, "evidenceRequires" | "evidenceRefused"> {
657
+ const raw = (spec as { evidence?: unknown }).evidence;
658
+ if (raw === undefined) return {};
659
+ const problems = opWavesEvidenceProblems(raw);
660
+ if (problems.length > 0) return { evidenceRefused: `the evidence rules in ${where} cannot be read (${problems.join("; ")})` };
661
+ const requires = (raw as OpWavesEvidence).requires ?? [];
662
+ return requires.length > 0 ? { evidenceRequires: [...requires] } : {};
647
663
  }
648
664
 
649
665
  const noHooks = (): Record<OpWaveHookMoment, OpWaveHook[]> =>
@@ -676,7 +692,7 @@ export function readOpWavePolicy(
676
692
  const spend = (spec as { approvals?: { spend?: unknown } }).approvals?.spend === true;
677
693
  const neverOverMcp = (spec as { neverOverMcp?: unknown }).neverOverMcp === true;
678
694
  // #3836: the gate's decision point, the spec's for a wave the base does not have yet.
679
- const asks = { ...pointAtBase(spec, name, `${specFile} at ${sha.slice(0, 12)}`), ...quorumAtBase(spec, `${specFile} at ${sha.slice(0, 12)}`), ...holdsAtBase(spec, `${specFile} at ${sha.slice(0, 12)}`), ...pullRequestGateAtBase(spec), ...(spec.approvals?.preview === true ? { preview: true } : {}) };
695
+ const asks = { ...pointAtBase(spec, name, `${specFile} at ${sha.slice(0, 12)}`), ...quorumAtBase(spec, `${specFile} at ${sha.slice(0, 12)}`), ...holdsAtBase(spec, `${specFile} at ${sha.slice(0, 12)}`), ...evidenceAtBase(spec, `${specFile} at ${sha.slice(0, 12)}`), ...pullRequestGateAtBase(spec), ...(spec.approvals?.preview === true ? { preview: true } : {}) };
680
696
  const wave = spec.waves.find((w) => w.name === name);
681
697
  if (!wave) return { ...absent, spend, neverOverMcp, ...asks };
682
698
  const policy = wave.gate ?? "always";
@@ -2596,6 +2612,12 @@ async function planOpWave(options: RunOpWaveOptions, { k, pass }: WaveAttempt<Ru
2596
2612
  // #4290: rules at base that cannot be read fail the wave; fewer approvers never stand in for them.
2597
2613
  if (rules.quorumRefused) return { end: failed(ctx, `wave ${k} (${wave.name}): ${rules.quorumRefused}, so nothing in it was planned or applied`) };
2598
2614
  if (rules.quorum && rules.point) return { end: failed(ctx, `wave ${k} (${wave.name}): approvals.quorum and a decision point are both set at ${base.slice(0, 12)}; a gate that asks a point takes its deciders from the point, so nothing in it was planned or applied`) };
2615
+ // #4870: the checks whose evidence the commit needs, read at base, before anything is planned.
2616
+ if (rules.evidenceRefused) return { end: failed(ctx, `wave ${k} (${wave.name}): ${rules.evidenceRefused}, so nothing in it was planned or applied`) };
2617
+ if (rules.evidenceRequires) {
2618
+ const refused = await opWaveEvidenceRefusal(cwd, options.head ?? "HEAD", base, rules.evidenceRequires);
2619
+ if (refused) return { end: failed(ctx, `wave ${k} (${wave.name}): ${refused}, so nothing in it was planned or applied`) };
2620
+ }
2599
2621
  if (JSON.stringify(spec.approvals?.quorum ?? null) !== JSON.stringify(rules.quorum ?? null)) {
2600
2622
  log(`wave ${k} (${wave.name}): its approval rules are read at ${base.slice(0, 12)}, and this change's differ; the ones at base hold`);
2601
2623
  }
@@ -2654,6 +2676,8 @@ async function planOpWave(options: RunOpWaveOptions, { k, pass }: WaveAttempt<Ru
2654
2676
  // #4613: the decision names the shared policy commit its runs were judged by.
2655
2677
  if (held.policySource) decision.ciPolicySource = held.policySource;
2656
2678
  }
2679
+ // #4870: with a runner key, the wave's plan and policy checks are signed over its commit.
2680
+ await signOpWaveChecks({ cwd, head: options.head ?? "HEAD", base, wave: wave.name, planDigest: opWaveSetDigest(spec, members), policyRows, log });
2657
2681
  // #4614: the after-plan hooks in the job's process, before the set digest and the gate.
2658
2682
  const inProcess = await runAfterPlan(ctx, members, parts, policyRows);
2659
2683
  if (inProcess.failed) return { end: failed(ctx, `${inProcess.failed}, so nothing in wave ${k} was approved or applied`) };