@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
@@ -26,6 +26,9 @@ import { z } from "zod";
26
26
  import type { RecordSource } from "../record-source";
27
27
  import { DEFAULT_SIGNERS_PATH, TRUST_CONFIG_PATH, parseAllowedSigners, type ExcludedSigner, type Signer } from "./trust-files";
28
28
  import type { PasskeySigner } from "../../lifecycle/gate-webauthn";
29
+ import { execFileSync } from "node:child_process";
30
+ import { DEFAULT_FULCIO_URL, DEFAULT_SIGNING_AUDIENCE, DEFAULT_TIMESTAMP_URL, keylessVerifier, parseTrustedRoot, type KeylessRoots } from "./keyless";
31
+ import type { DsseSignature, KeylessCheck } from "./dsse";
29
32
 
30
33
  export {
31
34
  DEFAULT_SIGNERS_PATH,
@@ -49,6 +52,30 @@ const repoPath = z
49
52
  message: "a path inside the repository, with / separators and no ..",
50
53
  });
51
54
 
55
+ /** An http or https URL (#4869): an OIDC issuer, a certificate or timestamp authority. */
56
+ const httpUrl = z.string().regex(/^https?:\/\/[^\s]+$/, "an http or https URL");
57
+
58
+ /** A check name a ref rule requires (#4867): it is also part of an override's subject. */
59
+ export const REF_CHECK_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
60
+ /** A ref pattern (#4867): a full ref name, where `*` matches within one `/` segment and `**` matches across them. */
61
+ export const REF_PATTERN = /^refs\/[^\s\\]+$/;
62
+
63
+ /**
64
+ * Checks local evidence never stands in for (#4868): the ones that gate an
65
+ * apply, a release or a gate. A name is refused when it is one of these, or
66
+ * one of these followed by `:` (a wave's `plan:<wave>`).
67
+ */
68
+ export const LOCAL_EVIDENCE_NEVER = ["plan", "policy", "apply", "drift", "release", "gate", "approval", "confirm"] as const;
69
+
70
+ /** Whether local evidence may ever be accepted for `check` (#4868). */
71
+ export function localEvidenceAllowedFor(check: string): boolean {
72
+ return !LOCAL_EVIDENCE_NEVER.some((n) => check === n || check.startsWith(`${n}:`));
73
+ }
74
+
75
+ /** Who signs local evidence (#4868): a person on their machine, or an agent session as itself. */
76
+ export const LOCAL_SIGNER_CLASSES = ["person", "agent"] as const;
77
+ export type LocalSignerClass = (typeof LOCAL_SIGNER_CLASSES)[number];
78
+
52
79
  export const trustConfigSchema = z
53
80
  .object({
54
81
  schema: z.literal(1),
@@ -81,6 +108,40 @@ export const trustConfigSchema = z
81
108
  .strict(),
82
109
  )
83
110
  .optional(),
111
+ /**
112
+ * CI identities that sign runner statements keyless (#4869): each an
113
+ * OIDC issuer and a pattern over the subject alternative name of the
114
+ * certificate the job's token was traded for, which names the
115
+ * repository, the workflow and the ref. `trustedRoot` is a file in
116
+ * sigstore's `trusted_root.json` format with the certificate and
117
+ * timestamp authorities. `fulcio`, `timestamp` and `audience` tell a
118
+ * signing job where to trade its token; sigstore's public instances by
119
+ * default. With `since`, a statement over that commit or any commit not
120
+ * a strict ancestor of it counts only when signed keyless; a runner key's
121
+ * statement over an earlier commit still counts.
122
+ */
123
+ keyless: z
124
+ .object({
125
+ trustedRoot: repoPath,
126
+ identities: z
127
+ .array(
128
+ z
129
+ .object({
130
+ principal: z.string().min(1),
131
+ class: z.enum(["runner", "service"]),
132
+ issuer: httpUrl,
133
+ subject: z.string().min(1),
134
+ })
135
+ .strict(),
136
+ )
137
+ .min(1),
138
+ since: fullCommit.optional(),
139
+ fulcio: httpUrl.optional(),
140
+ timestamp: httpUrl.optional(),
141
+ audience: z.string().min(1).optional(),
142
+ })
143
+ .strict()
144
+ .optional(),
84
145
  /**
85
146
  * Passkeys that sign gate approvals for people (#4646): a WebAuthn
86
147
  * credential's id, its public key as base64url DER SubjectPublicKeyInfo,
@@ -127,6 +188,73 @@ export const trustConfigSchema = z
127
188
  .strict(),
128
189
  )
129
190
  .optional(),
191
+ /**
192
+ * The checks a ref update must carry evidence for (#4867). Each entry
193
+ * names a ref pattern and the checks a commit pushed there needs current
194
+ * runner evidence of, each with what to do without it (`block` refuses
195
+ * the update, `warn` admits it and says what was missing) and the command
196
+ * that produces it. `status` is the commit status a forge requires, by
197
+ * default `chant/ref-gate`. `overrides` says how an override is judged:
198
+ * `sealed` when the signers file at base exists, else `ledger`.
199
+ */
200
+ refs: z
201
+ .array(
202
+ z
203
+ .object({
204
+ ref: z.string().regex(REF_PATTERN, "a full ref name such as refs/heads/main, where * and ** match"),
205
+ checks: z
206
+ .array(
207
+ z
208
+ .object({
209
+ check: z.string().regex(REF_CHECK_NAME, "a check name: letters, digits, . _ : -"),
210
+ action: z.enum(["block", "warn"]).optional(),
211
+ command: z.string().min(1),
212
+ })
213
+ .strict(),
214
+ )
215
+ .min(1),
216
+ status: z.string().min(1).optional(),
217
+ overrides: z.enum(["ledger", "sealed"]).optional(),
218
+ })
219
+ .strict(),
220
+ )
221
+ .optional(),
222
+ /**
223
+ * Local evidence (#4868): keys that sign on a developer's machine, for a
224
+ * person or an agent session, and the checks whose CI run such evidence
225
+ * stands in for. Off for every check not named in `checks`, and never
226
+ * for the checks {@link LOCAL_EVIDENCE_NEVER} names. A local key is
227
+ * never a runner key: local evidence never counts as runner evidence.
228
+ */
229
+ local: z
230
+ .object({
231
+ keys: z
232
+ .array(
233
+ z
234
+ .object({
235
+ principal: z.string().min(1),
236
+ class: z.enum(LOCAL_SIGNER_CLASSES),
237
+ key: z.string().regex(/^ssh-ed25519 [A-Za-z0-9+/]+={0,2}$/, "an ssh-ed25519 public key, with no comment"),
238
+ })
239
+ .strict(),
240
+ )
241
+ .optional(),
242
+ checks: z
243
+ .array(
244
+ z
245
+ .object({
246
+ check: z
247
+ .string()
248
+ .regex(REF_CHECK_NAME, "a check name: letters, digits, . _ : -")
249
+ .refine(localEvidenceAllowedFor, { message: `local evidence never stands in for ${LOCAL_EVIDENCE_NEVER.join(", ")} (or <name>:<wave>)` }),
250
+ from: z.array(z.enum(LOCAL_SIGNER_CLASSES)).min(1).optional(),
251
+ })
252
+ .strict(),
253
+ )
254
+ .optional(),
255
+ })
256
+ .strict()
257
+ .optional(),
130
258
  })
131
259
  .strict();
132
260
 
@@ -135,6 +263,31 @@ export type TrustConfig = z.infer<typeof trustConfigSchema>;
135
263
  /** The role whose holders may change the policy. Without any grant of it, every signer may. */
136
264
  export const ADMIN_ROLE = "admin";
137
265
 
266
+ /** A ref rule of `.chant/trust.json` (#4867), with `action` filled in. */
267
+ export interface RefRule {
268
+ ref: string;
269
+ checks: Array<{ check: string; action: "block" | "warn"; command: string }>;
270
+ status?: string;
271
+ overrides?: "ledger" | "sealed";
272
+ }
273
+
274
+ /** A key that signs local evidence (#4868): a person's or an agent session's. */
275
+ export interface LocalKey {
276
+ principal: string;
277
+ class: LocalSignerClass;
278
+ /** `ssh-ed25519 <base64>`. */
279
+ key: string;
280
+ }
281
+
282
+ /** What `local` in `.chant/trust.json` at base says (#4868), with `from` filled in (default: people only). */
283
+ export interface LocalEvidencePolicy {
284
+ keys: LocalKey[];
285
+ /** Keys left out, and why. */
286
+ excluded: Array<{ principal: string; reason: string }>;
287
+ /** The checks local evidence stands in for, and from whom. */
288
+ checks: Array<{ check: string; from: LocalSignerClass[] }>;
289
+ }
290
+
138
291
  /** A key that signs runner evidence: a service or CI identity. */
139
292
  export interface RunnerKey {
140
293
  principal: string;
@@ -143,6 +296,30 @@ export interface RunnerKey {
143
296
  key: string;
144
297
  }
145
298
 
299
+ /** A CI identity that signs runner statements keyless (#4869), with the trusted root it is verified against. */
300
+ export interface RunnerIdentity {
301
+ principal: string;
302
+ class: "runner" | "service";
303
+ issuer: string;
304
+ /** A pattern over the certificate's subject alternative name: `*` within a `/` segment, `**` across. */
305
+ subject: string;
306
+ roots: KeylessRoots;
307
+ /** Verifies one keyless signature against this identity and its trusted root (./dsse.ts's `TrustedIdentity`). */
308
+ verifyKeyless(message: Buffer, signature: DsseSignature): KeylessCheck;
309
+ }
310
+
311
+ /** A runner as a statement's verifier takes it: a key, or a keyless identity. */
312
+ export type Runner = RunnerKey | RunnerIdentity;
313
+
314
+ /** Where a keyless signing job trades its token (#4869), and from which commit only keyless statements count. */
315
+ export interface KeylessPolicy {
316
+ since?: string;
317
+ fulcio: string;
318
+ timestamp: string;
319
+ audience: string;
320
+ trustedRoot: string;
321
+ }
322
+
146
323
  /** The policy a check applies, as read at base. */
147
324
  export interface TrustPolicy {
148
325
  /** The full commit id the policy was read at, or null when there is no base. */
@@ -157,12 +334,20 @@ export interface TrustPolicy {
157
334
  adopted: Array<{ from?: string; to: string }>;
158
335
  /** Runner and service keys that may sign runner evidence (#2553). */
159
336
  runners: RunnerKey[];
337
+ /** CI identities that sign runner statements keyless (#4869). Absent on a policy built by hand: none. */
338
+ runnerIdentities?: RunnerIdentity[];
339
+ /** The keyless settings (#4869), when `keyless` is set and its trusted root reads. */
340
+ keyless?: KeylessPolicy;
160
341
  /** Runner entries that are not used, and why. */
161
342
  excludedRunners: Array<{ principal: string; reason: string }>;
162
343
  /** Passkeys that sign people's gate approvals (#4646). Absent on a policy built by hand: none. */
163
344
  passkeys?: PasskeySigner[];
164
345
  /** Signers admitted per return (#2552), keyed by return id. They verify that return's commits and seals only. */
165
346
  admitted: Record<string, Signer[]>;
347
+ /** The checks a ref update needs evidence for (#4867). Absent on a policy built by hand: none. */
348
+ refs?: RefRule[];
349
+ /** Local evidence (#4868). Absent on a policy built by hand: no key, no check accepts it. */
350
+ local?: LocalEvidencePolicy;
166
351
  /**
167
352
  * Set on a copy of the policy used for one returned record (#2552): the
168
353
  * return it came back in. A seal by a principal the policy does not list
@@ -179,10 +364,37 @@ export interface TrustPolicy {
179
364
  signersAt?: (commit: string) => { version: number; signers: Signer[] } | null;
180
365
  }
181
366
 
182
- /** Paths whose change is a protected write under `policy`: the config, the signers file and its rotation file (#2553). */
367
+ /** Paths whose change is a protected write under `policy`: the config, the signers file and its rotation file (#2553), and the keyless trusted root (#4869). */
183
368
  export function protectedPaths(policy: TrustPolicy): string[] {
184
369
  const s = policy.signersPath;
185
- return [...new Set([TRUST_CONFIG_PATH, s, posix.join(posix.dirname(s), `${posix.basename(s)}.rotation.json`)])].sort();
370
+ return [...new Set([TRUST_CONFIG_PATH, s, posix.join(posix.dirname(s), `${posix.basename(s)}.rotation.json`), ...(policy.keyless ? [policy.keyless.trustedRoot] : [])])].sort();
371
+ }
372
+
373
+ /**
374
+ * The runners whose statements over `commit` count (#4869): the runner keys
375
+ * and the keyless identities. With `keyless.since`, a runner key counts
376
+ * only for a commit that is a strict ancestor of `since`, the way
377
+ * `ci.green.signedSince` judges tags by position in history; a `since` the
378
+ * clone does not have leaves the keys out. Without `at`, under `since`, only
379
+ * the identities.
380
+ */
381
+ export function runnersAt(policy: TrustPolicy, at?: { repo: string; commit: string }): Runner[] {
382
+ const ids = policy.runnerIdentities ?? [];
383
+ const since = policy.keyless?.since;
384
+ if (!since) return [...policy.runners, ...ids];
385
+ if (!at || !strictAncestor(at.repo, at.commit, since)) return ids;
386
+ return [...policy.runners, ...ids];
387
+ }
388
+
389
+ function strictAncestor(repo: string, commit: string, of: string): boolean {
390
+ try {
391
+ const full = execFileSync("git", ["rev-parse", "--verify", "--quiet", `${commit}^{commit}`], { cwd: repo, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).trim();
392
+ if (full === of) return false;
393
+ execFileSync("git", ["merge-base", "--is-ancestor", full, of], { cwd: repo, stdio: "ignore" });
394
+ return true;
395
+ } catch {
396
+ return false;
397
+ }
186
398
  }
187
399
 
188
400
  /** Principals allowed to change the policy: the admins when any are granted, otherwise every signer. */
@@ -194,7 +406,7 @@ export function policyWriters(policy: TrustPolicy): Set<string> {
194
406
 
195
407
  /** A policy with nothing in it: attestation off. */
196
408
  export function emptyPolicy(base: string | null, problems: string[] = []): TrustPolicy {
197
- return { base, signersPath: DEFAULT_SIGNERS_PATH, active: false, signers: [], excluded: [], roles: {}, adopted: [], runners: [], excludedRunners: [], passkeys: [], admitted: {}, problems };
409
+ return { base, signersPath: DEFAULT_SIGNERS_PATH, active: false, signers: [], excluded: [], roles: {}, adopted: [], runners: [], excludedRunners: [], passkeys: [], admitted: {}, refs: [], local: { keys: [], excluded: [], checks: [] }, problems };
198
410
  }
199
411
 
200
412
  /**
@@ -238,6 +450,7 @@ export function readTrustPolicy(source: RecordSource, base: string | null): Trus
238
450
  runners.push(r);
239
451
  }
240
452
  }
453
+ const { runnerIdentities, keyless } = keylessOf(config, source, humanNames, excludedRunners);
241
454
  return {
242
455
  base,
243
456
  signersPath,
@@ -248,12 +461,59 @@ export function readTrustPolicy(source: RecordSource, base: string | null): Trus
248
461
  adopted: config.adopted ?? [],
249
462
  runners,
250
463
  excludedRunners,
464
+ ...(keyless ? { runnerIdentities, keyless } : {}),
251
465
  passkeys: config.passkeys ?? [],
252
466
  admitted: admittedOf(config),
467
+ refs: (config.refs ?? []).map((r) => ({ ...r, checks: r.checks.map((c) => ({ ...c, action: c.action ?? "block" })) })),
468
+ local: localOf(config, runners),
253
469
  problems: [],
254
470
  };
255
471
  }
256
472
 
473
+ /** The local evidence policy (#4868): a key a runner entry also holds is left out, so one key never speaks as both. */
474
+ function localOf(config: TrustConfig, runners: readonly RunnerKey[]): LocalEvidencePolicy {
475
+ const runnerKeys = new Set([...runners.map((r) => r.key), ...(config.runners ?? []).map((r) => r.key)]);
476
+ const all = config.local?.keys ?? [];
477
+ const keys: LocalKey[] = [];
478
+ const excluded: Array<{ principal: string; reason: string }> = [];
479
+ for (const k of all) {
480
+ if (runnerKeys.has(k.key)) excluded.push({ principal: k.principal, reason: "a runner entry has this key; local evidence is signed by a person's or an agent's key, never a runner's" });
481
+ else if (all.filter((o) => o.key === k.key || o.principal === k.principal).length > 1) excluded.push({ principal: k.principal, reason: "another local key has the same key or principal" });
482
+ else keys.push(k);
483
+ }
484
+ return { keys, excluded, checks: (config.local?.checks ?? []).map((c) => ({ check: c.check, from: c.from ?? ["person"] })) };
485
+ }
486
+
487
+ /**
488
+ * The keyless identities (#4869), each with the trusted root read through
489
+ * `source`. A trusted root that cannot be read leaves every identity out,
490
+ * with the reason in `excluded`; the runner keys still count.
491
+ */
492
+ function keylessOf(config: TrustConfig, source: RecordSource, humanNames: Set<string>, excluded: Array<{ principal: string; reason: string }>): { runnerIdentities: RunnerIdentity[]; keyless?: KeylessPolicy } {
493
+ const k = config.keyless;
494
+ if (!k) return { runnerIdentities: [] };
495
+ // Kept when the root does not read, so `since` still leaves the keys out: fail closed.
496
+ const keyless: KeylessPolicy = { ...(k.since ? { since: k.since } : {}), fulcio: k.fulcio ?? DEFAULT_FULCIO_URL, timestamp: k.timestamp ?? DEFAULT_TIMESTAMP_URL, audience: k.audience ?? DEFAULT_SIGNING_AUDIENCE, trustedRoot: k.trustedRoot };
497
+ let roots: KeylessRoots;
498
+ try {
499
+ const text = readOptional(source, k.trustedRoot);
500
+ if (text === undefined) throw new Error("the file is not there");
501
+ roots = parseTrustedRoot(text);
502
+ } catch (err) {
503
+ for (const i of k.identities) excluded.push({ principal: i.principal, reason: `the keyless trusted root ${k.trustedRoot} cannot be read: ${err instanceof Error ? err.message : String(err)}` });
504
+ return { runnerIdentities: [], keyless };
505
+ }
506
+ const runnerIdentities: RunnerIdentity[] = [];
507
+ for (const i of k.identities) {
508
+ if (humanNames.has(i.principal)) excluded.push({ principal: i.principal, reason: "the signers file lists this principal; a keyless identity is a CI job's, never a signer's" });
509
+ else {
510
+ const verify = keylessVerifier({ ...i, roots });
511
+ runnerIdentities.push({ ...i, roots, verifyKeyless: (message, signature) => verify(message, signature) });
512
+ }
513
+ }
514
+ return { runnerIdentities, keyless };
515
+ }
516
+
257
517
  /** The admitted signers, by return id. Two entries for one return add up. */
258
518
  function admittedOf(config: TrustConfig): Record<string, Signer[]> {
259
519
  const out: Record<string, Signer[]> = {};
@@ -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
+ }