@intentius/chant 0.124.84 → 0.124.86

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 (254) 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 +54 -0
  11. package/dist/ci-evidence-jobs.d.ts.map +1 -0
  12. package/dist/ci-evidence-jobs.js +55 -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 +57 -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 +171 -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 +137 -0
  60. package/dist/components/product-plan.d.ts.map +1 -0
  61. package/dist/components/product-plan.js +143 -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 +178 -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 +38 -0
  98. package/dist/op/op-waves-evidence.d.ts.map +1 -0
  99. package/dist/op/op-waves-evidence.js +57 -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 +31 -1
  119. package/dist/release-floors.d.ts.map +1 -1
  120. package/dist/release-floors.js +31 -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 +305 -298
  125. package/dist/workspace/lexicon-outputs.d.ts.map +1 -1
  126. package/dist/workspace/lexicon-outputs.js +21 -7
  127. package/dist/workspace/reason-codes.d.ts +3 -0
  128. package/dist/workspace/reason-codes.d.ts.map +1 -1
  129. package/dist/workspace/reason-codes.js +4 -0
  130. package/dist/workspace/ref-gate.schema.json +85 -0
  131. package/dist/workspace/search-contract.d.ts +1 -1
  132. package/dist/workspace/search-contract.d.ts.map +1 -1
  133. package/dist/workspace/trust/check-evidence-report.d.ts +51 -0
  134. package/dist/workspace/trust/check-evidence-report.d.ts.map +1 -0
  135. package/dist/workspace/trust/check-evidence-report.js +102 -0
  136. package/dist/workspace/trust/check-evidence.d.ts +126 -0
  137. package/dist/workspace/trust/check-evidence.d.ts.map +1 -0
  138. package/dist/workspace/trust/check-evidence.js +237 -0
  139. package/dist/workspace/trust/local-evidence.d.ts +120 -0
  140. package/dist/workspace/trust/local-evidence.d.ts.map +1 -0
  141. package/dist/workspace/trust/local-evidence.js +259 -0
  142. package/dist/workspace/trust/policy.d.ts +84 -0
  143. package/dist/workspace/trust/policy.d.ts.map +1 -1
  144. package/dist/workspace/trust/policy.js +94 -1
  145. package/dist/workspace/trust/ref-gate-cli.d.ts +33 -0
  146. package/dist/workspace/trust/ref-gate-cli.d.ts.map +1 -0
  147. package/dist/workspace/trust/ref-gate-cli.js +234 -0
  148. package/dist/workspace/trust/ref-gate-fixture.d.ts +38 -0
  149. package/dist/workspace/trust/ref-gate-fixture.d.ts.map +1 -0
  150. package/dist/workspace/trust/ref-gate-fixture.js +97 -0
  151. package/dist/workspace/trust/ref-gate.d.ts +187 -0
  152. package/dist/workspace/trust/ref-gate.d.ts.map +1 -0
  153. package/dist/workspace/trust/ref-gate.js +430 -0
  154. package/dist/workspace/trust/trust-files.d.ts.map +1 -1
  155. package/dist/workspace/trust/trust-files.js +18 -1
  156. package/package.json +1 -1
  157. package/src/bundle-check.test.ts +140 -0
  158. package/src/bundle-check.ts +352 -0
  159. package/src/chant-install.test.ts +112 -0
  160. package/src/chant-install.ts +179 -0
  161. package/src/ci-commit.test.ts +45 -0
  162. package/src/ci-commit.ts +38 -4
  163. package/src/ci-evidence-jobs.ts +67 -0
  164. package/src/ci-image.test.ts +506 -0
  165. package/src/ci-image.ts +822 -0
  166. package/src/ci-login.test.ts +235 -0
  167. package/src/ci-login.ts +307 -0
  168. package/src/ci-product.ts +18 -0
  169. package/src/cli/commands/__fixtures__/source-dir-include/chant.config.json +1 -0
  170. package/src/cli/commands/__fixtures__/source-dir-include/infra.ts +1 -0
  171. package/src/cli/commands/__fixtures__/source-dir-include/scripts/run-on-load.ts +3 -0
  172. package/src/cli/commands/__fixtures__/source-dir-root/chant.config.json +1 -0
  173. package/src/cli/commands/__fixtures__/source-dir-root/infra.test.ts +1 -0
  174. package/src/cli/commands/__fixtures__/source-dir-root/infra.ts +1 -0
  175. package/src/cli/commands/__fixtures__/source-dir-root/scripts/run-on-load.ts +3 -0
  176. package/src/cli/commands/__fixtures__/source-dir-scoped/app.ts +3 -0
  177. package/src/cli/commands/__fixtures__/source-dir-scoped/chant.config.json +1 -0
  178. package/src/cli/commands/__fixtures__/source-dir-scoped/infra/net.ts +1 -0
  179. package/src/cli/commands/__fixtures__/source-dir-scoped/scripts/run-on-load.ts +3 -0
  180. package/src/cli/commands/import-index.ts +2 -2
  181. package/src/cli/handlers/build-source-dir.test.ts +64 -0
  182. package/src/cli/handlers/build.ts +21 -4
  183. package/src/cli/handlers/ci-check.ts +56 -3
  184. package/src/cli/handlers/ci-evidence.ts +162 -0
  185. package/src/cli/handlers/components.ts +3 -3
  186. package/src/cli/handlers/dead-guards.ts +37 -0
  187. package/src/cli/handlers/graph.ts +4 -4
  188. package/src/cli/handlers/lifecycle.ts +5 -4
  189. package/src/cli/handlers/local-chant.ts +106 -0
  190. package/src/cli/handlers/operator.ts +2 -2
  191. package/src/cli/handlers/search.ts +5 -5
  192. package/src/cli/main.test.ts +7 -0
  193. package/src/cli/main.ts +38 -0
  194. package/src/cli/parse-args.ts +21 -0
  195. package/src/cli/registry.ts +16 -0
  196. package/src/components/check-evidence-stage.test.ts +80 -0
  197. package/src/components/check-hooks.ts +84 -4
  198. package/src/components/check-local-evidence-stage.test.ts +141 -0
  199. package/src/components/check-steps.ts +56 -6
  200. package/src/components/product-pipeline.ts +28 -3
  201. package/src/components/product-plan.test.ts +87 -0
  202. package/src/components/product-plan.ts +226 -0
  203. package/src/components/release-compile.ts +2 -2
  204. package/src/config.ts +44 -3
  205. package/src/dead-guards.test.ts +206 -0
  206. package/src/dead-guards.ts +446 -0
  207. package/src/discovery/files.ts +5 -3
  208. package/src/drift-issue-bundle.test.ts +31 -0
  209. package/src/drift-issue.test.ts +206 -0
  210. package/src/drift-issue.ts +274 -0
  211. package/src/fit-note.test.ts +44 -0
  212. package/src/floor-table.data.ts +180 -0
  213. package/src/floor-table.ts +77 -0
  214. package/src/forge-flags.test.ts +110 -0
  215. package/src/forge-flags.ts +208 -0
  216. package/src/gate-decision-bundle.test.ts +1 -0
  217. package/src/lexicon.ts +68 -0
  218. package/src/lifecycle/gated-op.ts +10 -5
  219. package/src/local-chant.e2e.test.ts +94 -0
  220. package/src/local-chant.test.ts +162 -0
  221. package/src/local-chant.ts +341 -0
  222. package/src/op/activities/predict-behaviour.ts +2 -2
  223. package/src/op/op-waves-evidence-spec.ts +24 -0
  224. package/src/op/op-waves-evidence.test.ts +130 -0
  225. package/src/op/op-waves-evidence.ts +57 -0
  226. package/src/op/op-waves-run.ts +25 -1
  227. package/src/op/op-waves.ts +31 -1
  228. package/src/op/schedule-overdue.test.ts +85 -0
  229. package/src/op/schedule-overdue.ts +162 -26
  230. package/src/plan-summary.ts +40 -0
  231. package/src/pr-plan-note.ts +34 -0
  232. package/src/pr-post-plan-note.test.ts +146 -0
  233. package/src/pr-post.ts +127 -3
  234. package/src/release-floors.ts +44 -1
  235. package/src/stage-hooks-bundle.test.ts +1 -0
  236. package/src/state-migration.test.ts +52 -1
  237. package/src/state-migration.ts +107 -5
  238. package/src/workspace/lexicon-outputs.ts +23 -6
  239. package/src/workspace/reason-codes.test.ts +3 -0
  240. package/src/workspace/reason-codes.ts +4 -0
  241. package/src/workspace/ref-gate.schema.json +85 -0
  242. package/src/workspace/trust/check-evidence-report.ts +106 -0
  243. package/src/workspace/trust/check-evidence.test.ts +133 -0
  244. package/src/workspace/trust/check-evidence.ts +257 -0
  245. package/src/workspace/trust/local-evidence.test.ts +127 -0
  246. package/src/workspace/trust/local-evidence.ts +266 -0
  247. package/src/workspace/trust/policy.ts +134 -1
  248. package/src/workspace/trust/ref-gate-cli.ts +244 -0
  249. package/src/workspace/trust/ref-gate-fixture.ts +125 -0
  250. package/src/workspace/trust/ref-gate.e2e.test.ts +76 -0
  251. package/src/workspace/trust/ref-gate.test.ts +247 -0
  252. package/src/workspace/trust/ref-gate.ts +538 -0
  253. package/src/workspace/trust/trust-files.test.ts +16 -0
  254. package/src/workspace/trust/trust-files.ts +41 -1
@@ -0,0 +1,244 @@
1
+ /**
2
+ * `chant workspace ref-gate` (#4867): refuse a ref update that lacks the
3
+ * evidence the policy at base requires. See ./ref-gate.ts.
4
+ *
5
+ * - `pre-receive` and `pre-push` are what the hooks `install` writes run;
6
+ * they read git's hook input on standard input.
7
+ * - `check --ref <ref>` decides one update from a checkout, and records the
8
+ * request for an override of each blocked check, as `pre-push` does.
9
+ * - `status --ref <ref>` decides the update a merge would make and sets the
10
+ * commit status the forge requires, so the forge refuses the merge.
11
+ * - `attach --envelope <file>` attaches runner evidence to a commit.
12
+ * - `install --hook pre-receive|pre-push` writes the hook.
13
+ *
14
+ * With `--json` each prints the `ref-gate.schema.json` document.
15
+ */
16
+
17
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { formatError, formatSuccess } from "../../cli/format";
20
+ import type { CommandContext } from "../../cli/registry";
21
+ import { readerVersion } from "../declaration";
22
+ import {
23
+ appendRefGateLedger,
24
+ attachEvidence,
25
+ commitOf,
26
+ decideRefUpdate,
27
+ describeDecision,
28
+ readRefGateLedger,
29
+ refGateLedgerPath,
30
+ RefUpdateInputError,
31
+ runPrePush,
32
+ runPreReceive,
33
+ spentOverrides,
34
+ type RefDecision,
35
+ type RefGateErrorCode,
36
+ type RefGateSite,
37
+ } from "./ref-gate";
38
+ import { resolveBase } from "./provenance";
39
+ import { spawnSync } from "node:child_process";
40
+
41
+ export const REF_GATE_CONTRACT_VERSION = 1;
42
+ export const REF_GATE_OUTPUT_SCHEMA_ID = "https://intentius.io/chant/schemas/workspace/ref-gate/v1/ref-gate.schema.json";
43
+ /** The line a hook chant writes carries, so `install` knows it may replace it. */
44
+ export const REF_GATE_HOOK_MARK = "# chant ref gate (#4867)";
45
+ /** How long a recorded request for an override stands. */
46
+ const OVERRIDE_REQUEST_HOURS = 72;
47
+
48
+ const USAGE =
49
+ "chant workspace ref-gate check --ref <ref> [--at <rev>] [--base <rev>] [--dry-run] [--ledger <file>] [--json]\n" +
50
+ " chant workspace ref-gate status --ref <ref> [--at <rev>] [--base <rev>] [--dry-run] [--ledger <file>] [--json]\n" +
51
+ " chant workspace ref-gate pre-receive|pre-push [--ledger <file>] [--dry-run] [--json] (git hook input on stdin)\n" +
52
+ " chant workspace ref-gate attach --envelope <file> [--at <rev>]\n" +
53
+ " chant workspace ref-gate install --hook pre-receive|pre-push [--git-dir <dir>] [--chant <command>]";
54
+
55
+ function head(): { $schema: string; contract: number; chant: string } {
56
+ return { $schema: REF_GATE_OUTPUT_SCHEMA_ID, contract: REF_GATE_CONTRACT_VERSION, chant: readerVersion() };
57
+ }
58
+
59
+ function fail(json: boolean | undefined, code: RefGateErrorCode, message: string): number {
60
+ if (json) console.log(JSON.stringify({ ...head(), error: { code, message } }, null, 2));
61
+ else console.error(formatError({ message: `${message} (${code})` }));
62
+ return 1;
63
+ }
64
+
65
+ function usage(message: string): number {
66
+ console.error(formatError({ message, hint: USAGE }));
67
+ return 1;
68
+ }
69
+
70
+ /** The git directory of the current directory, bare or not, and the work tree root when there is one. */
71
+ function repoHere(): { repo: string; bare: boolean } | null {
72
+ const r = spawnSync("git", ["rev-parse", "--is-bare-repository", "--show-toplevel"], { encoding: "utf-8" });
73
+ if (r.status !== 0) {
74
+ const g = spawnSync("git", ["rev-parse", "--absolute-git-dir"], { encoding: "utf-8" });
75
+ return g.status === 0 ? { repo: g.stdout.trim(), bare: true } : null;
76
+ }
77
+ const [bare, top] = r.stdout.trim().split("\n");
78
+ if (bare === "true" || !top) {
79
+ const g = spawnSync("git", ["rev-parse", "--absolute-git-dir"], { encoding: "utf-8" });
80
+ return { repo: g.stdout.trim(), bare: true };
81
+ }
82
+ return { repo: top, bare: false };
83
+ }
84
+
85
+ function print(json: boolean | undefined, decisions: RefDecision[], ledger: string | undefined, stream: "out" | "err"): void {
86
+ const ok = decisions.every((d) => d.decision === "admit");
87
+ if (json) {
88
+ console.log(JSON.stringify({ ...head(), ok, ...(ledger ? { ledger } : {}), decisions }, null, 2));
89
+ return;
90
+ }
91
+ for (const d of decisions) {
92
+ if (d.status === null && d.checks.length === 0 && !d.error) continue;
93
+ const text = describeDecision(d).join("\n");
94
+ if (stream === "err" || d.decision === "refuse") console.error(text);
95
+ else console.log(text);
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Record the request for an override of each blocked check, unless one
101
+ * stands, so a person can answer it with `chant approve policy-override`.
102
+ * Needs a checkout with `chant/lifecycle`; a failure to record is said and
103
+ * does not change the decision.
104
+ */
105
+ async function recordRequests(repo: string, decisions: RefDecision[], now: string): Promise<void> {
106
+ const blocked = decisions.flatMap((d) => d.checks.filter((c) => c.action === "block" && (c.status === "missing" || c.status === "stale")).map((c) => ({ d, c })));
107
+ if (blocked.length === 0) return;
108
+ const { readOverrideLedger, recordOverrideDenial } = await import("../../lifecycle/override-ledger");
109
+ const { recordedDenials } = await import("../../override-gate");
110
+ try {
111
+ const standing = recordedDenials((await readOverrideLedger({ cwd: repo })).pending);
112
+ for (const { d, c } of blocked) {
113
+ const s = standing.find((x) => x.gate === c.subject);
114
+ if (s && Date.parse(s.expiresAt) > Date.parse(now) && s.plan === d.new) continue;
115
+ await recordOverrideDenial(
116
+ {
117
+ subject: c.subject,
118
+ planDigest: d.new!,
119
+ rules: [c.check],
120
+ timestamp: now,
121
+ expiresAt: new Date(Date.parse(now) + OVERRIDE_REQUEST_HOURS * 3_600_000).toISOString(),
122
+ description: `update of ${d.ref} to ${d.new!.slice(0, 12)}, which has no current evidence for ${c.check}`,
123
+ },
124
+ { cwd: repo },
125
+ );
126
+ }
127
+ console.error(`chant ref gate: the request for an override of ${blocked.map((b) => b.c.subject).join(", ")} is recorded on chant/lifecycle; push chant/lifecycle with the override.`);
128
+ } catch (err) {
129
+ console.error(`chant ref gate: could not record the request for an override: ${err instanceof Error ? err.message : String(err)}`);
130
+ }
131
+ }
132
+
133
+ export async function runWorkspaceRefGate(ctx: CommandContext): Promise<number> {
134
+ const { args } = ctx;
135
+ const sub = args.extraPositional;
136
+ const subs = ["check", "status", "pre-receive", "pre-push", "attach", "install"];
137
+ if (!sub || !subs.includes(sub)) return usage(sub ? `Unknown ref-gate subcommand: ${sub}` : `chant workspace ref-gate needs one of ${subs.join(", ")}`);
138
+ const here = repoHere();
139
+ if (!here) return fail(args.json, "not-a-git-repository", "the ref gate judges git ref updates, and this directory is not in a git repository");
140
+ const now = new Date().toISOString();
141
+
142
+ if (sub === "install") return install(here.repo, args.hook, args.gitDir, args.ciChant);
143
+
144
+ if (sub === "attach") {
145
+ if (!args.envelope) return usage("--envelope <file> is required");
146
+ const commit = commitOf(here.repo, args.at ?? "HEAD");
147
+ if (!commit) return fail(args.json, "revision-unknown", `--at ${args.at ?? "HEAD"} names no commit`);
148
+ let envelope: unknown;
149
+ try {
150
+ envelope = JSON.parse(readFileSync(args.envelope, "utf-8"));
151
+ } catch (err) {
152
+ return usage(`--envelope ${args.envelope} could not be read as JSON: ${err instanceof Error ? err.message : String(err)}`);
153
+ }
154
+ attachEvidence(here.repo, commit, envelope);
155
+ console.error(formatSuccess(`attached the evidence to ${commit.slice(0, 8)}; push refs/notes/chant/evidence with the ref`));
156
+ return 0;
157
+ }
158
+
159
+ if (sub === "pre-receive" || sub === "pre-push") {
160
+ const stdin = readFileSync(0, "utf-8");
161
+ try {
162
+ if (sub === "pre-receive") {
163
+ const r = runPreReceive(here.repo, stdin, { ...(args.ledger ? { ledger: args.ledger } : {}), now });
164
+ print(args.json, r.decisions, r.ledger, "err");
165
+ return r.ok ? 0 : 1;
166
+ }
167
+ const r = runPrePush(here.repo, stdin, { ...(args.ledger ? { ledger: args.ledger } : {}), now, base: (repo) => resolveBase(repo).commit });
168
+ print(args.json, r.decisions, r.ledger, "err");
169
+ if (!r.ok && !args.dryRun && !here.bare) await recordRequests(here.repo, r.decisions, now);
170
+ return r.ok ? 0 : 1;
171
+ } catch (err) {
172
+ if (err instanceof RefUpdateInputError) return fail(args.json, "ref-update-invalid", err.message);
173
+ throw err;
174
+ }
175
+ }
176
+
177
+ // check and status: one update, from a checkout or a CI job.
178
+ if (!args.ref || !args.ref.startsWith("refs/")) return usage("--ref <ref> is required, as a full ref name such as refs/heads/main");
179
+ const at = commitOf(here.repo, args.at ?? "HEAD");
180
+ if (!at) return fail(args.json, "revision-unknown", `--at ${args.at ?? "HEAD"} names no commit`);
181
+ const resolved = resolveBase(here.repo, args.base);
182
+ if (args.base !== undefined && !resolved.commit) return fail(args.json, "revision-unknown", resolved.problem ?? `--base ${args.base} names no commit`);
183
+ const site: RefGateSite = sub === "status" ? "status" : "check";
184
+ const ledger = args.ledger ?? refGateLedgerPath(here.repo);
185
+ const spent = spentOverrides(readRefGateLedger(ledger));
186
+ const d = decideRefUpdate({ repo: here.repo, update: { ref: args.ref, old: resolved.commit, new: at }, base: resolved.commit, spent, now });
187
+ if (!args.dryRun) appendRefGateLedger(ledger, [{ ...d, version: 1, kind: "ref-update", site, timestamp: now }]);
188
+ print(args.json, [d], args.dryRun ? undefined : ledger, "out");
189
+ if (site === "check" && d.decision === "refuse" && !args.dryRun && !here.bare) await recordRequests(here.repo, [d], now);
190
+ if (site === "status" && d.status !== null) {
191
+ if (args.dryRun) {
192
+ console.error(`chant ref gate: would set ${d.status} to ${d.decision === "admit" ? "success" : "failure"} on ${at.slice(0, 8)}`);
193
+ } else {
194
+ const { detectForge, forgeFromEnv } = await import("../../pr-forge");
195
+ const kind = detectForge();
196
+ if (!kind) {
197
+ console.error(formatError({ message: `no forge detected, so ${d.status} was not set`, hint: "run it in a GitHub, GitLab or Forgejo job, or pass --dry-run" }));
198
+ return 1;
199
+ }
200
+ await postRefGateStatus(forgeFromEnv(kind), d);
201
+ }
202
+ }
203
+ return d.decision === "admit" ? 0 : 1;
204
+ }
205
+
206
+ /** The commit status a forge requires for `d`'s ref: `success` when it is admitted, `failure` naming the missing checks when not. */
207
+ export async function postRefGateStatus(forge: { setStatus(sha: string, status: { context: string; state: "success" | "failure"; description: string }): Promise<void> }, d: RefDecision): Promise<void> {
208
+ if (d.status === null || d.new === null) return;
209
+ const missing = d.checks.filter((c) => c.action === "block" && (c.status === "missing" || c.status === "stale"));
210
+ const overridden = d.checks.filter((c) => c.status === "overridden").map((c) => c.check);
211
+ const description = d.error
212
+ ? `refused: ${d.error.code}`
213
+ : missing.length > 0
214
+ ? `missing evidence: ${missing.map((c) => `${c.check} (run ${c.command})`).join(", ")}`
215
+ : `evidence current${overridden.length ? `; overridden: ${overridden.join(", ")}` : ""}`;
216
+ await forge.setStatus(d.new, { context: d.status, state: d.decision === "admit" ? "success" : "failure", description });
217
+ }
218
+
219
+ /** The hook script: it runs `chant` (or `command`) with the hook's arguments and input. */
220
+ export function refGateHook(hook: "pre-receive" | "pre-push", command = "chant"): string {
221
+ return `#!/bin/sh\n${REF_GATE_HOOK_MARK}\nexec ${command} workspace ref-gate ${hook} "$@"\n`;
222
+ }
223
+
224
+ function install(repo: string, hook: string | undefined, gitDir: string | undefined, command: string | undefined): number {
225
+ if (hook !== "pre-receive" && hook !== "pre-push") return usage("--hook pre-receive (on the remote) or --hook pre-push (in a checkout) is required");
226
+ let dir = gitDir;
227
+ if (!dir) {
228
+ const r = spawnSync("git", ["rev-parse", "--git-path", "hooks"], { cwd: repo, encoding: "utf-8" });
229
+ dir = r.status === 0 ? join(repo, r.stdout.trim()) : join(repo, "hooks");
230
+ if (r.status === 0 && r.stdout.trim().startsWith("/")) dir = r.stdout.trim();
231
+ } else {
232
+ dir = join(dir, "hooks");
233
+ }
234
+ const path = join(dir, hook);
235
+ if (existsSync(path) && !readFileSync(path, "utf-8").includes(REF_GATE_HOOK_MARK)) {
236
+ console.error(formatError({ message: `${path} exists and is not chant's ref gate hook; it was left as it is`, hint: `call ${command ?? "chant"} workspace ref-gate ${hook} from it` }));
237
+ return 1;
238
+ }
239
+ mkdirSync(dir, { recursive: true });
240
+ writeFileSync(path, refGateHook(hook, command));
241
+ chmodSync(path, 0o755);
242
+ console.error(formatSuccess(`wrote ${path}`));
243
+ return 0;
244
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Test support for the ref gate (#4867): a checkout and a bare remote, a
3
+ * runner key, fake runner evidence signed with it, and override lines on
4
+ * `chant/lifecycle`. Isolated from the user's git config. The temporary
5
+ * directories are left in the system's temp directory.
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 { dirname, join } from "node:path";
13
+ import { loadRunnerKey } from "./dsse";
14
+ import { buildStatement, signEvidence } from "./evidence";
15
+ import { attachEvidence, EVIDENCE_NOTES_REF, refGateSubject } from "./ref-gate";
16
+ import { OVERRIDE_OP, overrideDigest } from "../../override-gate";
17
+
18
+ export interface RunnerKeyPair {
19
+ pem: string;
20
+ pub: string;
21
+ }
22
+
23
+ export function runnerKey(): RunnerKeyPair {
24
+ const { privateKey } = generateKeyPairSync("ed25519");
25
+ const pem = privateKey.export({ format: "pem", type: "pkcs8" }).toString();
26
+ return { pem, pub: loadRunnerKey(pem).publicKey };
27
+ }
28
+
29
+ export const RUNNER = "ci@example.test";
30
+
31
+ export class GateRepos {
32
+ readonly root: string;
33
+ readonly work: string;
34
+ readonly origin: string;
35
+ readonly home: string;
36
+
37
+ constructor(label: string) {
38
+ this.root = mkdtempSync(join(tmpdir(), `chant-4867-${label}-`));
39
+ this.work = join(this.root, "work");
40
+ this.origin = join(this.root, "origin.git");
41
+ this.home = join(this.root, "home");
42
+ mkdirSync(this.home);
43
+ this.run(this.root, ["init", "-q", "--bare", "-b", "main", this.origin]);
44
+ this.run(this.root, ["init", "-q", "-b", "main", this.work]);
45
+ this.git(["remote", "add", "origin", this.origin]);
46
+ }
47
+
48
+ env(): NodeJS.ProcessEnv {
49
+ return {
50
+ PATH: process.env.PATH ?? "",
51
+ HOME: this.home,
52
+ GIT_CONFIG_GLOBAL: join(this.home, "gitconfig"),
53
+ GIT_CONFIG_NOSYSTEM: "1",
54
+ GIT_AUTHOR_NAME: "t",
55
+ GIT_AUTHOR_EMAIL: "t@example.test",
56
+ GIT_COMMITTER_NAME: "t",
57
+ GIT_COMMITTER_EMAIL: "t@example.test",
58
+ };
59
+ }
60
+
61
+ run(cwd: string, args: string[], input?: string): string {
62
+ return execFileSync("git", args, { cwd, env: this.env(), input, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
63
+ }
64
+
65
+ git(args: string[], input?: string): string {
66
+ return this.run(this.work, args, input);
67
+ }
68
+
69
+ write(path: string, text: string): void {
70
+ mkdirSync(dirname(join(this.work, path)), { recursive: true });
71
+ writeFileSync(join(this.work, path), text);
72
+ }
73
+
74
+ commit(message: string): string {
75
+ this.git(["add", "-A"]);
76
+ this.git(["commit", "-q", "--no-gpg-sign", "--allow-empty", "-m", message]);
77
+ return this.git(["rev-parse", "HEAD"]).trim();
78
+ }
79
+
80
+ /** Push `refspecs` to the bare remote with no hook in the way, and return git's output. */
81
+ push(...refspecs: string[]): string {
82
+ return this.run(this.work, ["push", "-q", "origin", ...refspecs]);
83
+ }
84
+
85
+ /** Sign evidence for `check` at `at` over `paths`, with `key`, and attach it to `to` (default `at`). */
86
+ sign(key: RunnerKeyPair, check: string, at: string, paths: string[], to = at): unknown {
87
+ const statement = buildStatement({ repo: this.work, commit: at, paths, runner: RUNNER, check });
88
+ const { key: k, publicKey } = loadRunnerKey(key.pem);
89
+ const envelope = signEvidence(statement, k, publicKey);
90
+ attachEvidence(this.work, to, envelope);
91
+ return envelope;
92
+ }
93
+
94
+ notesTip(): string {
95
+ return this.git(["rev-parse", EVIDENCE_NOTES_REF]).trim();
96
+ }
97
+
98
+ /** Write `chant/lifecycle` holding a request for an override of `check` on `commit` and `by`'s override of it. */
99
+ override(commit: string, check: string, by: string, reason: string, at = "2026-11-09T10:00:00.000Z"): string {
100
+ const subject = refGateSubject(commit, check);
101
+ const digest = overrideDigest(subject, commit, [check]);
102
+ const pending = { version: 1, kind: "pending", op: OVERRIDE_OP, gate: subject, timestamp: "2026-11-09T09:00:00.000Z", expiresAt: "2026-11-12T09:00:00.000Z", planDigest: digest, plan: commit, rules: [check] };
103
+ const resolution = { version: 1, kind: "resolution", op: OVERRIDE_OP, gate: subject, resolvedBy: by, timestamp: at, note: reason, planDigest: digest };
104
+ const blob = this.git(["hash-object", "-w", "--stdin"], `${JSON.stringify(pending)}\n${JSON.stringify(resolution)}\n`).trim();
105
+ const gates = this.git(["mktree"], `100644 blob ${blob}\t${OVERRIDE_OP}.jsonl\n`).trim();
106
+ const tree = this.git(["mktree"], `040000 tree ${gates}\t_gates\n`).trim();
107
+ const c = this.git(["commit-tree", tree, "-m", "ledger"]).trim();
108
+ this.git(["update-ref", "refs/heads/chant/lifecycle", c]);
109
+ return c;
110
+ }
111
+ }
112
+
113
+ /** `.chant/trust.json` with one runner and a ref rule for `refs/heads/main` and `refs/heads/release/*`. */
114
+ export function trustJson(runner: RunnerKeyPair, checks: Array<{ check: string; action?: "block" | "warn"; command: string }>, extra: Record<string, unknown> = {}): string {
115
+ return JSON.stringify(
116
+ {
117
+ schema: 1,
118
+ runners: [{ principal: RUNNER, class: "runner", key: runner.pub }],
119
+ refs: [{ ref: "refs/heads/main", checks }, { ref: "refs/heads/release/*", checks }],
120
+ ...extra,
121
+ },
122
+ null,
123
+ 2,
124
+ );
125
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * #4867, end to end: chant's hooks on a bare repository and a checkout, with
3
+ * real `git push`. The pre-receive hook refuses a push to a protected ref
4
+ * whose commit has no current evidence for a `block` check, naming the check
5
+ * and its command, and admits it once the evidence is pushed with it. The
6
+ * pre-push hook refuses the same push before it leaves the checkout.
7
+ */
8
+
9
+ import { spawnSync } from "node:child_process";
10
+ import { join } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { describe, expect, test } from "vitest";
13
+ import { REPO } from "../__fixtures__/contract-repo";
14
+ import { EVIDENCE_NOTES_REF } from "./ref-gate";
15
+ import { GateRepos, runnerKey, trustJson } from "./ref-gate-fixture";
16
+
17
+ const CHANT = `${process.execPath} --import ${pathToFileURL(join(REPO, "node_modules/tsx/dist/loader.mjs")).href} ${join(REPO, "packages/core/src/cli/main.ts")}`;
18
+
19
+ function chant(r: GateRepos, cwd: string, argv: string[]) {
20
+ return spawnSync("/bin/sh", ["-c", `${CHANT} "$@"`, "chant", ...argv], { cwd, env: r.env(), encoding: "utf-8" });
21
+ }
22
+
23
+ function setup(label: string) {
24
+ const r = new GateRepos(label);
25
+ const ci = runnerKey();
26
+ r.write(".chant/trust.json", trustJson(ci, [{ check: "plan", command: "chant ci run plan" }, { check: "policy", command: "chant ci run policy" }]));
27
+ r.write("records/n1.md", "one\n");
28
+ const base = r.commit("policy");
29
+ r.push("main");
30
+ r.write("app/a.txt", "change\n");
31
+ const head = r.commit("a change");
32
+ return { r, ci, base, head };
33
+ }
34
+
35
+ const push = (r: GateRepos, ...refspecs: string[]) => spawnSync("git", ["push", "origin", ...refspecs], { cwd: r.work, env: r.env(), encoding: "utf-8" });
36
+
37
+ describe("the ref gate's hooks", () => {
38
+ test("a bare repository with chant's pre-receive hook refuses a push without evidence and admits it with", () => {
39
+ const { r, ci, base, head } = setup("e2e-receive");
40
+ const installed = chant(r, r.work, ["workspace", "ref-gate", "install", "--hook", "pre-receive", "--git-dir", r.origin, "--chant", CHANT]);
41
+ expect(installed.status, installed.stderr).toBe(0);
42
+
43
+ const refused = push(r, `${head}:refs/heads/main`);
44
+ expect(refused.status).not.toBe(0);
45
+ expect(refused.stderr).toContain("refused refs/heads/main");
46
+ expect(refused.stderr).toContain("plan (missing)");
47
+ expect(refused.stderr).toContain("run: chant ci run plan");
48
+ expect(refused.stderr).toContain("run: chant ci run policy");
49
+ expect(r.run(r.origin, ["rev-parse", "main"]).trim()).toBe(base);
50
+
51
+ r.sign(ci, "plan", head, ["records/n1.md"]);
52
+ const half = push(r, EVIDENCE_NOTES_REF, `${head}:refs/heads/main`);
53
+ expect(half.status).not.toBe(0);
54
+ expect(half.stderr).toContain("run: chant ci run policy");
55
+ expect(half.stderr).not.toContain("run: chant ci run plan");
56
+
57
+ r.sign(ci, "policy", head, ["records/n1.md"]);
58
+ const admitted = push(r, EVIDENCE_NOTES_REF, `${head}:refs/heads/main`);
59
+ expect(admitted.status, admitted.stderr).toBe(0);
60
+ expect(r.run(r.origin, ["rev-parse", "main"]).trim()).toBe(head);
61
+ }, 60_000);
62
+
63
+ test("chant's pre-push hook refuses the same push before the network", () => {
64
+ const { r, ci, base, head } = setup("e2e-push");
65
+ const installed = chant(r, r.work, ["workspace", "ref-gate", "install", "--hook", "pre-push", "--chant", CHANT]);
66
+ expect(installed.status, installed.stderr).toBe(0);
67
+ const refused = push(r, `${head}:refs/heads/main`);
68
+ expect(refused.status).not.toBe(0);
69
+ expect(refused.stderr).toContain("run: chant ci run plan");
70
+ expect(r.run(r.origin, ["rev-parse", "main"]).trim()).toBe(base);
71
+ r.sign(ci, "plan", head, ["records/n1.md"]);
72
+ r.sign(ci, "policy", head, ["records/n1.md"]);
73
+ const admitted = push(r, EVIDENCE_NOTES_REF, `${head}:refs/heads/main`);
74
+ expect(admitted.status, admitted.stderr).toBe(0);
75
+ }, 60_000);
76
+ });