@intentius/chant 0.124.85 → 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,538 @@
1
+ /**
2
+ * The ref gate (#4867): a ref update is refused when the commit lacks the
3
+ * runner evidence the policy at base requires for that ref.
4
+ *
5
+ * chant judges evidence at the green tick, a land, a gate and a release cut,
6
+ * all after the push. A change that was never going to pass still reached
7
+ * the remote and started CI. The gate judges it at the ref update instead,
8
+ * from three places that all call {@link decideRefUpdate}:
9
+ *
10
+ * - a plain git remote: the `pre-receive` hook `chant workspace ref-gate
11
+ * install` writes, which refuses the push;
12
+ * - a forge: `chant workspace ref-gate status`, a commit status the forge
13
+ * requires, so the merge is refused where the push can't be;
14
+ * - the developer's side: the `pre-push` hook, which refuses before the
15
+ * network and records the request for an override.
16
+ *
17
+ * The rules are `refs` in `.chant/trust.json`, read at base like every other
18
+ * part of the trust policy (./policy.ts): the old tip of the ref, so a change
19
+ * can neither drop a check nor add the runner key that signs its own
20
+ * evidence. Evidence is the runner evidence of ./evidence.ts, kept as git
21
+ * notes on the commit under {@link EVIDENCE_NOTES_REF}, one envelope per
22
+ * line, and verified offline against the runner keys at base. A check has
23
+ * current evidence when an envelope for it verifies and every record it
24
+ * names hashes the same at the pushed commit; an envelope that names no
25
+ * records counts only for a commit with the tree it was signed over.
26
+ *
27
+ * An override is the override gate's (../../override-gate.ts): a person
28
+ * the overriders file at base lists records a reasoned approval of one
29
+ * commit and one check, subject `ref-gate-<sha12>-<check>`, and it is spent
30
+ * by the first ref update it admits. Every decision is a line of the gate's
31
+ * ledger, a JSON-lines file in the git directory ({@link refGateLedgerPath}),
32
+ * since a pre-receive hook may not move a ref.
33
+ */
34
+
35
+ import { execFileSync, spawnSync } from "node:child_process";
36
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
37
+ import { dirname, isAbsolute, join } from "node:path";
38
+ import type { ReasonCode } from "../reason-codes";
39
+ import { verifyEvidence, type EvidenceErrorCode } from "./evidence";
40
+ import { policyAtBase } from "./provenance";
41
+ import type { RefRule, TrustPolicy } from "./policy";
42
+ import {
43
+ OVERRIDE_APPLIED,
44
+ OVERRIDE_LEDGER,
45
+ OVERRIDERS_PATH,
46
+ decideOverride,
47
+ overrideCommand,
48
+ overridersAt,
49
+ parseAppliedOverrides,
50
+ type AppliedOverrideRecord,
51
+ } from "../../override-gate";
52
+ import { parseGateLedger } from "../../lifecycle/gate-ledger";
53
+ import { gateSignersAt } from "../../gate-decision";
54
+ import type { GateSigners } from "../../lifecycle/gate-seal";
55
+
56
+ /** Where runner evidence for a commit is kept (#4867): a git note on the commit, one DSSE envelope per line. */
57
+ export const EVIDENCE_NOTES_REF = "refs/notes/chant/evidence";
58
+ /** The ledger branch whose override lines the gate reads. */
59
+ export const LIFECYCLE_REF = "refs/heads/chant/lifecycle";
60
+ /** The commit status a forge requires when the rule names none. */
61
+ export const REF_GATE_STATUS = "chant/ref-gate";
62
+ /** git's id for no object, in hook input. */
63
+ const ZERO = /^0+$/;
64
+
65
+ /** Why the gate cannot decide at all. Each is in `reason-codes.ts` and `ref-gate.schema.json`. */
66
+ export const REF_GATE_ERROR_CODES = ["not-a-git-repository", "revision-unknown", "trust-policy-unreadable", "ref-update-invalid"] as const satisfies readonly ReasonCode[];
67
+ export type RefGateErrorCode = (typeof REF_GATE_ERROR_CODES)[number];
68
+
69
+ /** Why a required check has no current evidence. The envelope codes are those of `evidence verify`. */
70
+ export const REF_GATE_CHECK_CODES = [
71
+ "ref-evidence-missing",
72
+ "ref-evidence-stale",
73
+ "envelope-invalid",
74
+ "envelope-untrusted",
75
+ "evidence-payload-type",
76
+ "evidence-statement-invalid",
77
+ "evidence-runner-mismatch",
78
+ ] as const satisfies readonly ReasonCode[];
79
+ export type RefGateCheckCode = (typeof REF_GATE_CHECK_CODES)[number];
80
+
81
+ /** One ref update, as a hook reads it. `null` is git's zero id: a ref created (`old`) or deleted (`new`). */
82
+ export interface RefUpdate {
83
+ ref: string;
84
+ old: string | null;
85
+ new: string | null;
86
+ }
87
+
88
+ export interface OverrideUsed {
89
+ subject: string;
90
+ by: string;
91
+ at: string;
92
+ reason: string;
93
+ digest: string;
94
+ }
95
+
96
+ /** A required check, judged. */
97
+ export interface CheckVerdict {
98
+ check: string;
99
+ action: "block" | "warn";
100
+ /** The command that produces the evidence. */
101
+ command: string;
102
+ status: "current" | "stale" | "missing" | "overridden";
103
+ /** Why it has no current evidence. Absent when it has. */
104
+ code?: RefGateCheckCode;
105
+ reason: string;
106
+ /** The runner whose evidence counted. */
107
+ runner?: string;
108
+ /** The override it was let through under. */
109
+ override?: OverrideUsed;
110
+ /** The subject an override of this check names. */
111
+ subject: string;
112
+ }
113
+
114
+ export interface RefDecision {
115
+ ref: string;
116
+ old: string | null;
117
+ new: string | null;
118
+ /** The commit the policy was read at, or null when there is none. */
119
+ base: string | null;
120
+ decision: "admit" | "refuse";
121
+ /** The commit status a forge requires for this ref, when a rule matched. */
122
+ status: string | null;
123
+ checks: CheckVerdict[];
124
+ /** Set when the gate could not decide; the update is then refused. */
125
+ error?: { code: RefGateErrorCode; message: string };
126
+ }
127
+
128
+ function git(repo: string, args: string[]): string {
129
+ return execFileSync("git", args, { cwd: repo, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
130
+ }
131
+
132
+ function tryGit(repo: string, args: string[]): string | undefined {
133
+ const r = spawnSync("git", args, { cwd: repo, encoding: "utf-8", maxBuffer: 256 * 1024 * 1024 });
134
+ return r.status === 0 ? r.stdout : undefined;
135
+ }
136
+
137
+ /** The commit `rev` names, peeled, or undefined. */
138
+ export function commitOf(repo: string, rev: string): string | undefined {
139
+ return tryGit(repo, ["rev-parse", "--verify", "-q", `${rev}^{commit}`])?.trim() || undefined;
140
+ }
141
+
142
+ /** A ref pattern as a RegExp: `**` matches across `/`, `*` within one segment. */
143
+ export function refPatternRegExp(pattern: string): RegExp {
144
+ const body = pattern
145
+ .split("**")
146
+ .map((part) => part.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*"))
147
+ .join(".*");
148
+ return new RegExp(`^${body}$`);
149
+ }
150
+
151
+ /**
152
+ * The checks the policy requires for `ref`: every matching rule's, each check
153
+ * once. A check two rules name is `block` when either blocks it; the first
154
+ * rule that names a status or an override mode gives it.
155
+ */
156
+ export function rulesFor(policy: Pick<TrustPolicy, "refs">, ref: string): { matched: boolean; checks: RefRule["checks"]; status: string; overrides?: "ledger" | "sealed" } {
157
+ const matching = (policy.refs ?? []).filter((r) => refPatternRegExp(r.ref).test(ref));
158
+ const checks = new Map<string, RefRule["checks"][number]>();
159
+ for (const r of matching) {
160
+ for (const c of r.checks) {
161
+ const before = checks.get(c.check);
162
+ if (!before) checks.set(c.check, { ...c });
163
+ else if (c.action === "block") before.action = "block";
164
+ }
165
+ }
166
+ const overrides = matching.find((r) => r.overrides)?.overrides;
167
+ return {
168
+ matched: matching.length > 0,
169
+ checks: [...checks.values()],
170
+ status: matching.find((r) => r.status)?.status ?? REF_GATE_STATUS,
171
+ ...(overrides ? { overrides } : {}),
172
+ };
173
+ }
174
+
175
+ // ── evidence notes ───────────────────────────────────────────────────────
176
+
177
+ /** The envelopes in a note's text: one per line, or the whole note as one envelope or an array of them. */
178
+ export function parseEvidenceNote(text: string): unknown[] {
179
+ try {
180
+ const whole = JSON.parse(text) as unknown;
181
+ return Array.isArray(whole) ? whole : [whole];
182
+ } catch {
183
+ const out: unknown[] = [];
184
+ for (const line of text.split("\n").map((l) => l.trim()).filter(Boolean)) {
185
+ try {
186
+ out.push(JSON.parse(line));
187
+ } catch {
188
+ out.push(line);
189
+ }
190
+ }
191
+ return out;
192
+ }
193
+ }
194
+
195
+ /** The note on `commit` in the notes commit `notes`, which may fan its paths out. */
196
+ function noteText(repo: string, notes: string, commit: string): string | undefined {
197
+ const list = tryGit(repo, ["ls-tree", "-r", "--full-tree", notes]);
198
+ if (!list) return undefined;
199
+ for (const line of list.split("\n")) {
200
+ const tab = line.indexOf("\t");
201
+ if (tab < 0) continue;
202
+ if (line.slice(tab + 1).replace(/\//g, "") !== commit) continue;
203
+ const blob = line.slice(0, tab).split(" ")[2];
204
+ return tryGit(repo, ["cat-file", "blob", blob]);
205
+ }
206
+ return undefined;
207
+ }
208
+
209
+ /** The envelopes attached to `commit`, read from the notes commit `notes` (default: {@link EVIDENCE_NOTES_REF}'s tip). */
210
+ export function evidenceFor(repo: string, commit: string, notes?: string | null): unknown[] {
211
+ const tip = notes === undefined ? commitOf(repo, EVIDENCE_NOTES_REF) : notes;
212
+ if (!tip) return [];
213
+ const text = noteText(repo, tip, commit);
214
+ return text === undefined ? [] : parseEvidenceNote(text);
215
+ }
216
+
217
+ /**
218
+ * Attach `envelope` to `commit` as one line of its evidence note. Pushing `refs/notes/chant/evidence` is the caller's.
219
+ * `notesRef` is another notes ref, for local evidence (#4868), which the ref gate never reads.
220
+ */
221
+ export function attachEvidence(repo: string, commit: string, envelope: unknown, notesRef: string = EVIDENCE_NOTES_REF): void {
222
+ git(repo, [...notesIdentity(repo), "notes", `--ref=${notesRef}`, "append", "-m", JSON.stringify(envelope), commit]);
223
+ }
224
+
225
+ /**
226
+ * A notes commit needs an author and a committer, and a CI job often has no
227
+ * git identity configured, so `git notes append` failed there ("Author
228
+ * identity unknown"). Where the repository names none, the evidence notes
229
+ * are written as chant's. The envelope's signature, not the notes commit's
230
+ * author, says who signed the evidence.
231
+ */
232
+ function notesIdentity(repo: string): string[] {
233
+ const named = (key: string) => !!tryGit(repo, ["config", "--get", key])?.trim();
234
+ return [
235
+ ...(named("user.name") || process.env.GIT_AUTHOR_NAME ? [] : ["-c", "user.name=chant evidence"]),
236
+ ...(named("user.email") || process.env.GIT_AUTHOR_EMAIL ? [] : ["-c", "user.email=chant-evidence@localhost"]),
237
+ ];
238
+ }
239
+
240
+ /** The check an envelope claims to be for, read without verifying, so a refusal can say which check a bad envelope was meant for. */
241
+ function claimedCheck(envelope: unknown): string | undefined {
242
+ try {
243
+ const payload = (envelope as { payload?: unknown }).payload;
244
+ if (typeof payload !== "string") return undefined;
245
+ const check = (JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as { predicate?: { check?: unknown } }).predicate?.check;
246
+ return typeof check === "string" ? check : undefined;
247
+ } catch {
248
+ return undefined;
249
+ }
250
+ }
251
+
252
+ type Judged = { status: "current"; runner: string } | { status: "stale" | "missing"; code: RefGateCheckCode; reason: string };
253
+
254
+ /** The best evidence among `envelopes` for `check` at `commit`: current beats stale beats an envelope that does not verify beats none. */
255
+ function judgeCheck(repo: string, policy: TrustPolicy, envelopes: readonly unknown[], check: string, commit: string, tree: string): Judged {
256
+ let stale: string | undefined;
257
+ let bad: { code: EvidenceErrorCode; reason: string } | undefined;
258
+ for (const env of envelopes) {
259
+ const v = verifyEvidence(env, policy.runners, repo, commit);
260
+ if (!v.ok) {
261
+ if (claimedCheck(env) === check && !bad) bad = { code: v.code, reason: v.reason };
262
+ continue;
263
+ }
264
+ if (v.statement.predicate.check !== check) continue;
265
+ const signedAt = v.statement.predicate.commit.slice(0, 8);
266
+ if (v.subjects.length === 0 && v.statement.predicate.tree !== tree) {
267
+ stale ??= `the evidence from ${v.runner} names no records and was signed over another tree, at ${signedAt}`;
268
+ continue;
269
+ }
270
+ if (v.status === "current") return { status: "current", runner: v.runner };
271
+ const changed = v.subjects.filter((s) => !s.matches).map((s) => (s.now === null ? `${s.name} is gone` : `${s.name} changed`));
272
+ stale ??= `the evidence from ${v.runner} was signed at ${signedAt}, and since then ${changed.join(", ")}`;
273
+ }
274
+ if (stale) return { status: "stale", code: "ref-evidence-stale", reason: stale };
275
+ if (bad) return { status: "missing", code: bad.code as RefGateCheckCode, reason: `an envelope for ${check} does not count: ${bad.reason}` };
276
+ return { status: "missing", code: "ref-evidence-missing", reason: `no evidence for ${check} is attached to ${commit.slice(0, 8)} under ${EVIDENCE_NOTES_REF}` };
277
+ }
278
+
279
+ // ── overrides ────────────────────────────────────────────────────────────
280
+
281
+ /** The subject an override of `check` for `commit` names. */
282
+ export function refGateSubject(commit: string, check: string): string {
283
+ return `ref-gate-${commit.slice(0, 12)}-${check}`;
284
+ }
285
+
286
+ function blobAt(repo: string, rev: string, path: string): string | undefined {
287
+ return tryGit(repo, ["cat-file", "blob", `${rev}:${path}`]);
288
+ }
289
+
290
+ // ── the decision ─────────────────────────────────────────────────────────
291
+
292
+ export interface RefGateInput {
293
+ /** The repository, bare or not. */
294
+ repo: string;
295
+ update: RefUpdate;
296
+ /** The commit the policy is read at: the ref's old tip, or the default branch for a new ref. Null: no policy, nothing required. */
297
+ base: string | null;
298
+ /** The notes commit evidence is read from. Default: {@link EVIDENCE_NOTES_REF}'s tip. */
299
+ notes?: string | null;
300
+ /** The `chant/lifecycle` commit override lines are read from. Default: {@link LIFECYCLE_REF}'s tip. */
301
+ lifecycle?: string | null;
302
+ /** Overrides already spent, from the gate's own ledger ({@link spentOverrides}). */
303
+ spent?: readonly AppliedOverrideRecord[];
304
+ /** ISO-8601 now. */
305
+ now?: string;
306
+ }
307
+
308
+ /** Decide one ref update against the policy at base. Never throws for a policy or an envelope it can't read: it refuses. */
309
+ export function decideRefUpdate(input: RefGateInput): RefDecision {
310
+ const { repo, update } = input;
311
+ const head = { ref: update.ref, old: update.old, new: update.new, base: input.base };
312
+ const refuse = (code: RefGateErrorCode, message: string): RefDecision => ({ ...head, decision: "refuse", status: null, checks: [], error: { code, message } });
313
+ if (input.base === null) return { ...head, decision: "admit", status: null, checks: [] };
314
+ const policy = policyAtBase(repo, { commit: input.base, from: "flag" });
315
+ if (policy.problems.length > 0) return refuse("trust-policy-unreadable", `the policy at base ${input.base.slice(0, 8)} cannot be read, so the gate refuses every update: ${policy.problems.join("; ")}`);
316
+ const rules = rulesFor(policy, update.ref);
317
+ if (!rules.matched) return { ...head, decision: "admit", status: null, checks: [] };
318
+ // A deletion carries no commit to judge; a forge or the remote protects deletions on its own.
319
+ if (update.new === null) return { ...head, decision: "admit", status: rules.status, checks: [] };
320
+ const commit = commitOf(repo, update.new);
321
+ if (!commit) return refuse("revision-unknown", `${update.new} is not a commit this repository holds`);
322
+ const tree = git(repo, ["rev-parse", `${commit}^{tree}`]).trim();
323
+ const envelopes = evidenceFor(repo, commit, input.notes);
324
+
325
+ const lifecycle = input.lifecycle === undefined ? commitOf(repo, LIFECYCLE_REF) : input.lifecycle;
326
+ const ledgerText = lifecycle ? blobAt(repo, lifecycle, OVERRIDE_LEDGER) : undefined;
327
+ const appliedText = lifecycle ? blobAt(repo, lifecycle, OVERRIDE_APPLIED) : undefined;
328
+ const ledger = ledgerText ? parseGateLedger(ledgerText) : { resolutions: [], pending: [] };
329
+ const applied = [...(appliedText ? parseAppliedOverrides(appliedText) : []), ...(input.spent ?? [])];
330
+ const overriders = overridersAt(repo, input.base);
331
+ const mode = rules.overrides ?? (policy.active ? "sealed" : "ledger");
332
+ let signers: GateSigners | undefined;
333
+
334
+ const checks: CheckVerdict[] = rules.checks.map((c) => {
335
+ const subject = refGateSubject(commit, c.check);
336
+ const judged = judgeCheck(repo, policy, envelopes, c.check, commit, tree);
337
+ const base = { check: c.check, action: c.action, command: c.command, subject };
338
+ if (judged.status === "current") return { ...base, status: "current", reason: `current evidence from ${judged.runner}`, runner: judged.runner };
339
+ if (c.action === "block") {
340
+ if (mode === "sealed" && !signers) signers = gateSignersAt(repo, input.base!);
341
+ const verdict = decideOverride({
342
+ ledger,
343
+ applied,
344
+ subject,
345
+ planDigest: commit,
346
+ rules: [c.check],
347
+ overriders: overriders.principals,
348
+ overridersPath: OVERRIDERS_PATH,
349
+ mode,
350
+ ...(signers ? { signers } : {}),
351
+ ...(input.now ? { now: input.now } : {}),
352
+ });
353
+ if (verdict.status === "overridden") {
354
+ const o = verdict.override;
355
+ return { ...base, status: "overridden", code: judged.code, reason: `${judged.reason}; let through under ${o.by}'s override: ${o.reason}`, override: { subject, by: o.by, at: o.at, reason: o.reason, digest: o.digest } };
356
+ }
357
+ const why = verdict.refusals.length ? `; ${verdict.refusals.join("; ")}` : "";
358
+ return { ...base, status: judged.status, code: judged.code, reason: `${judged.reason}${why}` };
359
+ }
360
+ return { ...base, status: judged.status, code: judged.code, reason: judged.reason };
361
+ });
362
+ const refused = checks.some((c) => c.action === "block" && (c.status === "missing" || c.status === "stale"));
363
+ return { ...head, decision: refused ? "refuse" : "admit", status: rules.status, checks };
364
+ }
365
+
366
+ // ── the ledger ───────────────────────────────────────────────────────────
367
+
368
+ /** Where a decision is made: the remote's hook, the developer's hook, a forge status job or a plain check. */
369
+ export type RefGateSite = "pre-receive" | "pre-push" | "status" | "check";
370
+
371
+ /** A line of the gate's ledger. */
372
+ export interface RefGateLedgerLine extends RefDecision {
373
+ version: 1;
374
+ kind: "ref-update";
375
+ site: RefGateSite;
376
+ timestamp: string;
377
+ /** Set on every line of a push the remote refused as a whole: an override it would have spent stays unspent. */
378
+ push?: "refused";
379
+ }
380
+
381
+ /** The gate's ledger file in the git directory of `repo`, `<git dir>/chant/ref-gate.jsonl`. */
382
+ export function refGateLedgerPath(repo: string): string {
383
+ const dir = git(repo, ["rev-parse", "--git-common-dir"]).trim();
384
+ return join(isAbsolute(dir) ? dir : join(repo, dir), "chant", "ref-gate.jsonl");
385
+ }
386
+
387
+ export function appendRefGateLedger(path: string, lines: readonly RefGateLedgerLine[]): void {
388
+ if (lines.length === 0) return;
389
+ mkdirSync(dirname(path), { recursive: true });
390
+ appendFileSync(path, lines.map((l) => JSON.stringify(l)).join("\n") + "\n");
391
+ }
392
+
393
+ export function readRefGateLedger(path: string): RefGateLedgerLine[] {
394
+ if (!existsSync(path)) return [];
395
+ const out: RefGateLedgerLine[] = [];
396
+ for (const line of readFileSync(path, "utf-8").split("\n").filter((l) => l.trim())) {
397
+ try {
398
+ const r = JSON.parse(line) as RefGateLedgerLine;
399
+ if (r.version === 1 && r.kind === "ref-update") out.push(r);
400
+ } catch {
401
+ continue;
402
+ }
403
+ }
404
+ return out;
405
+ }
406
+
407
+ /** The overrides the ledger's admitted updates spent: an update the remote took, or a status that passed, under an override. A pre-push or a plain check spends nothing. */
408
+ export function spentOverrides(lines: readonly RefGateLedgerLine[]): AppliedOverrideRecord[] {
409
+ const out: AppliedOverrideRecord[] = [];
410
+ for (const l of lines) {
411
+ if (l.decision !== "admit" || l.push === "refused" || (l.site !== "pre-receive" && l.site !== "status")) continue;
412
+ for (const c of l.checks) {
413
+ if (!c.override) continue;
414
+ out.push({ version: 1, kind: "applied", op: "policy-override", gate: c.override.subject, planDigest: c.override.digest, approvedAt: c.override.at, approvedBy: c.override.by, timestamp: l.timestamp, ...(l.new ? { commit: l.new } : {}) });
415
+ }
416
+ }
417
+ return out;
418
+ }
419
+
420
+ // ── hook input ───────────────────────────────────────────────────────────
421
+
422
+ const OBJECT_ID = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
423
+ const oid = (s: string): string | null => (ZERO.test(s) ? null : s);
424
+
425
+ /** pre-receive's stdin: `<old> <new> <ref>` per line. */
426
+ export function parsePreReceive(text: string): RefUpdate[] {
427
+ return text
428
+ .split("\n")
429
+ .map((l) => l.trim())
430
+ .filter(Boolean)
431
+ .map((line) => {
432
+ const [old, nu, ref, ...rest] = line.split(/\s+/);
433
+ if (rest.length || !old || !nu || !ref || !OBJECT_ID.test(old) || !OBJECT_ID.test(nu)) throw new RefUpdateInputError(`not a pre-receive line: ${JSON.stringify(line)}`);
434
+ return { ref, old: oid(old), new: oid(nu) };
435
+ });
436
+ }
437
+
438
+ /** pre-push's stdin: `<local ref> <local sha> <remote ref> <remote sha>` per line, as updates of the remote ref. */
439
+ export function parsePrePush(text: string): RefUpdate[] {
440
+ return text
441
+ .split("\n")
442
+ .map((l) => l.trim())
443
+ .filter(Boolean)
444
+ .map((line) => {
445
+ const [, local, ref, remote, ...rest] = line.split(/\s+/);
446
+ if (rest.length || !local || !ref || !remote || !OBJECT_ID.test(local) || !OBJECT_ID.test(remote)) throw new RefUpdateInputError(`not a pre-push line: ${JSON.stringify(line)}`);
447
+ return { ref, old: oid(remote), new: oid(local) };
448
+ });
449
+ }
450
+
451
+ export class RefUpdateInputError extends Error {}
452
+
453
+ // ── the sites ────────────────────────────────────────────────────────────
454
+
455
+ export interface SiteResult {
456
+ ok: boolean;
457
+ decisions: RefDecision[];
458
+ ledger: string;
459
+ }
460
+
461
+ /**
462
+ * The remote's pre-receive hook: decide every update of the push, with the
463
+ * notes and the `chant/lifecycle` tip the push itself brings when it brings
464
+ * them, and write one ledger line per update. git refuses the whole push when
465
+ * the hook fails, so overrides are spent only when every update is admitted.
466
+ */
467
+ export function runPreReceive(repo: string, stdin: string, opts: { ledger?: string; now?: string } = {}): SiteResult {
468
+ const updates = parsePreReceive(stdin);
469
+ const pushed = (ref: string): string | null | undefined => {
470
+ const u = updates.find((x) => x.ref === ref);
471
+ return u ? (u.new ? commitOf(repo, u.new) ?? null : null) : undefined;
472
+ };
473
+ const notes = pushed(EVIDENCE_NOTES_REF);
474
+ const lifecycle = pushed(LIFECYCLE_REF);
475
+ const ledger = opts.ledger ?? refGateLedgerPath(repo);
476
+ const spent = spentOverrides(readRefGateLedger(ledger));
477
+ const now = opts.now ?? new Date().toISOString();
478
+ const decisions: RefDecision[] = [];
479
+ for (const u of updates) {
480
+ const base = u.old ? commitOf(repo, u.old) ?? null : commitOf(repo, "HEAD") ?? null;
481
+ const d = decideRefUpdate({ repo, update: u, base, ...(notes !== undefined ? { notes } : {}), ...(lifecycle !== undefined ? { lifecycle } : {}), spent, now });
482
+ decisions.push(d);
483
+ // Two refs of one push may not spend one override twice.
484
+ spent.push(...spentOverrides([{ ...d, version: 1, kind: "ref-update", site: "pre-receive", timestamp: now }]));
485
+ }
486
+ const ok = decisions.every((d) => d.decision === "admit");
487
+ appendRefGateLedger(ledger, decisions.map((d) => ({ ...d, version: 1, kind: "ref-update", site: "pre-receive", timestamp: now, ...(ok ? {} : { push: "refused" as const }) })));
488
+ return { ok, decisions, ledger };
489
+ }
490
+
491
+ /**
492
+ * The developer's pre-push hook: the same decision against the local
493
+ * repository, before the network. The policy is read at the remote's tip
494
+ * when the repository holds it, else at the default base. It spends nothing.
495
+ */
496
+ export function runPrePush(repo: string, stdin: string, opts: { ledger?: string; now?: string; base?: (repo: string) => string | null } = {}): SiteResult {
497
+ const updates = parsePrePush(stdin);
498
+ const ledger = opts.ledger ?? refGateLedgerPath(repo);
499
+ const now = opts.now ?? new Date().toISOString();
500
+ const decisions = updates.map((u) => {
501
+ const base = (u.old ? commitOf(repo, u.old) : undefined) ?? opts.base?.(repo) ?? null;
502
+ return decideRefUpdate({ repo, update: u, base, now });
503
+ });
504
+ appendRefGateLedger(ledger, decisions.map((d) => ({ ...d, version: 1, kind: "ref-update", site: "pre-push", timestamp: now })));
505
+ return { ok: decisions.every((d) => d.decision === "admit"), decisions, ledger };
506
+ }
507
+
508
+ // ── words ────────────────────────────────────────────────────────────────
509
+
510
+ const short = (s: string | null): string => (s ? s.slice(0, 8) : "(none)");
511
+
512
+ /** What the gate says about one decision: each missing check and its command, and how to override a blocked one. */
513
+ export function describeDecision(d: RefDecision): string[] {
514
+ const out: string[] = [];
515
+ const verb = d.decision === "admit" ? "admitted" : "refused";
516
+ out.push(`chant ref gate: ${verb} ${d.ref} ${short(d.old)}..${short(d.new)}`);
517
+ if (d.error) {
518
+ out.push(` ${d.error.message} (${d.error.code})`);
519
+ return out;
520
+ }
521
+ for (const c of d.checks) {
522
+ if (c.status === "current") {
523
+ out.push(` ${c.check}: ${c.reason}`);
524
+ continue;
525
+ }
526
+ const what = c.status === "overridden" ? "overridden" : c.action === "warn" ? "warning" : "missing";
527
+ out.push(` ${c.check} (${what}): ${c.reason}${c.code ? ` (${c.code})` : ""}`);
528
+ if (c.status !== "overridden") out.push(` run: ${c.command}`);
529
+ }
530
+ const blocked = d.checks.filter((c) => c.action === "block" && (c.status === "missing" || c.status === "stale"));
531
+ if (blocked.length > 0) {
532
+ out.push(` Attach each check's evidence to ${short(d.new)} (chant workspace ref-gate attach --envelope <file> --at ${short(d.new)}) and push ${EVIDENCE_NOTES_REF} with the ref.`);
533
+ out.push(` To let ${short(d.new)} through without a check, a person listed in ${OVERRIDERS_PATH} at base can override it once the request is recorded`);
534
+ out.push(` (the pre-push hook records it, or chant workspace ref-gate check --ref ${d.ref} --at ${short(d.new)}):`);
535
+ for (const c of blocked) out.push(` ${overrideCommand(c.subject, [c.check])}`);
536
+ }
537
+ return out;
538
+ }
@@ -21,7 +21,23 @@ const cases: Array<[string, unknown]> = [
21
21
  runners: [{ principal: "ci", class: "runner", key: ed }],
22
22
  admitted: [{ return: "ret-0123456789ab", signers: [{ principal: "dana", key: "ssh-rsa AAAAB3Nza==" }], note: "n" }],
23
23
  passkeys: [{ principal: "github:erin", id: "cred-1_x", publicKey: "MCowBQYDK2VwAyEA", rpId: "example.com", origins: ["https://example.com"] }],
24
+ refs: [{ ref: "refs/heads/main", checks: [{ check: "plan", action: "block", command: "chant ci run plan" }, { check: "lint", command: "npm run lint" }], status: "chant/ref-gate", overrides: "ledger" }],
24
25
  }],
26
+ ["local evidence", { schema: 1, local: { keys: [{ principal: "alice", class: "person", key: ed }, { principal: "agent:s1", class: "agent", key: ed }], checks: [{ check: "fmt" }, { check: "lint", from: ["person", "agent"] }] } }],
27
+ ["an empty local", { schema: 1, local: {} }],
28
+ ["local evidence for plan", { schema: 1, local: { checks: [{ check: "plan" }] } }],
29
+ ["local evidence for a wave's policy", { schema: 1, local: { checks: [{ check: "policy:wave-1" }] } }],
30
+ ["local evidence for apply", { schema: 1, local: { checks: [{ check: "apply" }] } }],
31
+ ["local evidence for drift", { schema: 1, local: { checks: [{ check: "drift" }] } }],
32
+ ["a local key of a runner's class", { schema: 1, local: { keys: [{ principal: "ci", class: "runner", key: ed }] } }],
33
+ ["local evidence from nobody", { schema: 1, local: { checks: [{ check: "fmt", from: [] }] } }],
34
+ ["local with an extra key", { schema: 1, local: { checks: [], skip: true } }],
35
+ ["a ref rule with no checks", { schema: 1, refs: [{ ref: "refs/heads/main", checks: [] }] }],
36
+ ["a ref rule on a short ref name", { schema: 1, refs: [{ ref: "main", checks: [{ check: "plan", command: "x" }] }] }],
37
+ ["a ref check with no command", { schema: 1, refs: [{ ref: "refs/heads/main", checks: [{ check: "plan" }] }] }],
38
+ ["a ref check with another action", { schema: 1, refs: [{ ref: "refs/heads/main", checks: [{ check: "plan", action: "deny", command: "x" }] }] }],
39
+ ["a ref check name with a slash", { schema: 1, refs: [{ ref: "refs/heads/main", checks: [{ check: "a/b", command: "x" }] }] }],
40
+ ["a ref rule with an extra key", { schema: 1, refs: [{ ref: "refs/heads/main", checks: [{ check: "plan", command: "x" }], extra: 1 }] }],
25
41
  ["a passkey with no origins", { schema: 1, passkeys: [{ principal: "e", id: "c", publicKey: "k", rpId: "example.com", origins: [] }] }],
26
42
  ["a passkey whose key is padded base64", { schema: 1, passkeys: [{ principal: "e", id: "c", publicKey: "k+/=", rpId: "example.com", origins: ["https://example.com"] }] }],
27
43
  ["a passkey with an extra key", { schema: 1, passkeys: [{ principal: "e", id: "c", publicKey: "k", rpId: "example.com", origins: ["https://example.com"], alg: -8 }] }],
@@ -202,7 +202,7 @@ export function trustConfigProblems(raw: unknown): string[] {
202
202
  const check = (field: string, ok: boolean, message: string) => {
203
203
  if (!ok) problems.push(`${field}: ${message}`);
204
204
  };
205
- check("/", only(raw, ["schema", "signers", "roles", "adopted", "runners", "passkeys", "admitted"]), "unknown key");
205
+ check("/", only(raw, ["schema", "signers", "roles", "adopted", "runners", "passkeys", "admitted", "refs", "local"]), "unknown key");
206
206
  check("schema", raw.schema === 1, "expected 1");
207
207
  check("signers", optional(raw.signers, isRepoPath), "a path inside the repository, with / separators and no ..");
208
208
  check(
@@ -255,5 +255,45 @@ export function trustConfigProblems(raw: unknown): string[] {
255
255
  ),
256
256
  "admitted signers, by return id",
257
257
  );
258
+ check(
259
+ "refs",
260
+ optional(raw.refs, (a) =>
261
+ Array.isArray(a) &&
262
+ a.every(
263
+ (e) =>
264
+ isObject(e) && only(e, ["ref", "checks", "status", "overrides"]) &&
265
+ typeof e.ref === "string" && /^refs\/[^\s\\]+$/.test(e.ref) &&
266
+ optional(e.status, nonEmpty) && optional(e.overrides, (o) => o === "ledger" || o === "sealed") &&
267
+ Array.isArray(e.checks) && e.checks.length > 0 &&
268
+ e.checks.every(
269
+ (c) =>
270
+ isObject(c) && only(c, ["check", "action", "command"]) &&
271
+ typeof c.check === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(c.check) &&
272
+ optional(c.action, (x) => x === "block" || x === "warn") && nonEmpty(c.command),
273
+ ),
274
+ ),
275
+ ),
276
+ "ref rules: a ref pattern and the checks it requires, each with a command",
277
+ );
278
+ // #4868: keep in step with LOCAL_EVIDENCE_NEVER in ./policy.ts.
279
+ const never = ["plan", "policy", "apply", "drift", "release", "gate", "approval", "confirm"];
280
+ check(
281
+ "local",
282
+ optional(raw.local, (l) =>
283
+ isObject(l) && only(l, ["keys", "checks"]) &&
284
+ optional(l.keys, (a) => Array.isArray(a) && a.every((e) => isObject(e) && only(e, ["principal", "class", "key"]) && nonEmpty(e.principal) && (e.class === "person" || e.class === "agent") && typeof e.key === "string" && SSH_ED25519.test(e.key))) &&
285
+ optional(l.checks, (a) =>
286
+ Array.isArray(a) &&
287
+ a.every(
288
+ (c) =>
289
+ isObject(c) && only(c, ["check", "from"]) &&
290
+ typeof c.check === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(c.check) &&
291
+ !never.some((n) => c.check === n || (c.check as string).startsWith(`${n}:`)) &&
292
+ optional(c.from, (f) => Array.isArray(f) && f.length > 0 && f.every((x) => x === "person" || x === "agent")),
293
+ ),
294
+ ),
295
+ ),
296
+ "local evidence: person or agent keys, and the checks it stands in for (never plan, policy, apply, drift, release, gate, approval, confirm)",
297
+ );
258
298
  return problems;
259
299
  }