@patronage/factory-ci 0.1.3 → 0.2.1

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.
@@ -0,0 +1,664 @@
1
+ /**
2
+ * The GitHub-side **proof-reuse gate** (ADR 0022, #309, #317).
3
+ *
4
+ * It answers one question, before checkout and before install: may this job
5
+ * reuse the local verification the factory already published for *this exact
6
+ * head*? Refusing runs hosted CI; it never fails the candidate. Three
7
+ * repositories had independently grown their own answer to that question and
8
+ * had already drifted apart, so the answer lives here once, with the App
9
+ * identity, check name, step identity, output names, guard, and every trust
10
+ * predicate fixed rather than consumer-configurable.
11
+ *
12
+ * What a consumer chooses is only *what its guarded surface requires*: the
13
+ * plain profile command objects that surface selects. Everything else below is
14
+ * the same for every consumer and every surface.
15
+ */
16
+
17
+ /**
18
+ * Escaped so the emitted text carries a GitHub Actions expression rather than
19
+ * this file carrying a JavaScript template hole.
20
+ */
21
+ const githubExpression = (expression: string): string =>
22
+ `\${{ ${expression} }}`;
23
+
24
+ /** A braced shell expansion that has to survive TypeScript interpolation. */
25
+ const shellExpansion = (expression: string): string => `\${${expression}}`;
26
+
27
+ /**
28
+ * Single-quote a value for the emitted script. Every non-literal value that
29
+ * reaches the script goes through this.
30
+ *
31
+ * `JSON.stringify` is *not* a shell quoter — it escapes `"` and `\` and leaves
32
+ * `'` untouched — so interpolating a JSON document straight into a
33
+ * single-quoted assignment lets one apostrophe in a profile command name close
34
+ * the assignment and run the remainder as shell. Names are charset-validated
35
+ * before they get here; this is the second layer, so the interpolation stays
36
+ * safe if that validation is ever loosened.
37
+ */
38
+ const shellSingleQuote = (value: string): string =>
39
+ `'${value.replaceAll("'", String.raw`'\''`)}'`;
40
+
41
+ /**
42
+ * The check run the gate reads. Fixed: `patronage-factory/pr-verify` is also
43
+ * postable as a *commit status* by any token with write access, so only the
44
+ * Checks API is ever consulted and only under this exact name.
45
+ */
46
+ export const FACTORY_PROOF_GATE_CHECK_NAME = "patronage-factory/pr-verify";
47
+
48
+ /**
49
+ * The Patronage Factory GitHub App, pinned (ADR 0022). A runner has no
50
+ * operator user config to read the producing App identity from, and the
51
+ * identity is a trust predicate, so it is not a repository variable a consumer
52
+ * can point somewhere else. Neither the id nor the slug is a secret: GitHub
53
+ * returns `app.id` on every check run it serves.
54
+ */
55
+ export const FACTORY_PROOF_GATE_APP_ID = "4314840";
56
+
57
+ /** Step id the guard condition refers to. */
58
+ export const FACTORY_PROOF_GATE_STEP_ID = "factory-proof";
59
+
60
+ /**
61
+ * The shell the gate runs under, and it is a correctness requirement rather
62
+ * than a preference.
63
+ *
64
+ * GitHub's default for a `run:` step is `bash -e {0}`: **errexit comes from
65
+ * the invocation, not from the script**, and no `set +e` in the script body
66
+ * can be relied on to express the intent because the abort happens at the
67
+ * failing command. The whole fail-open design below — every path reaching one
68
+ * final `GITHUB_OUTPUT` write, no `set -e` — is void under that default. It
69
+ * was: the gate died at a `read` returning 1 at EOF, two seconds in, with no
70
+ * stdout, no verdict and no `reason`, so reuse collapsed to never *and* the
71
+ * signal built to reveal that could not fire (#319).
72
+ *
73
+ * A `shell:` value containing `{0}` is used verbatim by the runner, so this
74
+ * form supplies no `-e`. The shorthand `shell: bash` must never be used here:
75
+ * it expands to `bash --noprofile --norc -eo pipefail {0}`. `pipefail` is set
76
+ * by the script itself.
77
+ *
78
+ * The script is additionally written to survive errexit anyway. Both layers
79
+ * are deliberate: this one states the contract, that one means a runner which
80
+ * ignores it still gets a decision.
81
+ */
82
+ export const FACTORY_PROOF_GATE_SHELL = "bash --noprofile --norc {0}";
83
+
84
+ /** Output the verdict is written to. `true` — and only `true` — skips. */
85
+ export const FACTORY_PROOF_GATE_OUTPUT = "reuse-proof";
86
+
87
+ /**
88
+ * Machine-readable refusal category. Fleet-status reads this: it is what makes
89
+ * a reuse-collapses-to-never regression visible instead of hidden behind
90
+ * fail-open, which by construction looks exactly like healthy full CI.
91
+ */
92
+ export const FACTORY_PROOF_GATE_REASON_OUTPUT = "reason";
93
+
94
+ /**
95
+ * Recorded verification mode, when the gate could read one. Diagnostic
96
+ * metadata only — never an authorization condition (ADR 0022). A reduced-mode
97
+ * proof that executed every command the surface requires is reusable.
98
+ */
99
+ export const FACTORY_PROOF_GATE_MODE_OUTPUT = "mode";
100
+
101
+ /**
102
+ * Guard for every step the gate protects. Deliberately `!= 'true'` and not
103
+ * `== 'false'`: an unset, empty, or garbled output must run the suite.
104
+ */
105
+ export const FACTORY_PROOF_GATE_GUARD = `steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_OUTPUT} != 'true'`;
106
+
107
+ /**
108
+ * Pull requests only. A push to a protected branch must never skip: deploy
109
+ * gates wait for a green required check at the *merged* SHA, and no local
110
+ * proof was ever written for that tree.
111
+ */
112
+ export const FACTORY_PROOF_GATE_IF = "github.event_name == 'pull_request'";
113
+
114
+ /**
115
+ * The complete refusal vocabulary. Deliberately few, because these are the
116
+ * only distinctions the gate can honestly make from one Checks API read.
117
+ *
118
+ * - `proven` a covering, passing, unambiguous proof for this exact head
119
+ * - `none` no App-verified factory check run at this commit
120
+ * - `pending` the newest generation had not completed when this job read it
121
+ * - `failed` the newest generation records no pass
122
+ * - `unreadable` it passed but carries no binding for this repository and head
123
+ * - `incomplete` it passed but did not execute every required command
124
+ * - `ambiguous` two newest generations share the greatest start time
125
+ * - `error` the gate could not reach a decision (fail open)
126
+ *
127
+ * There is no `reduced`: mode stopped being an authorization condition in
128
+ * ADR 0022, so a narrower run that still executed every required command is
129
+ * indistinguishable from a full one *for this surface*, which is the point.
130
+ */
131
+ export const FACTORY_PROOF_GATE_REASONS = [
132
+ "proven",
133
+ "none",
134
+ "pending",
135
+ "failed",
136
+ "unreadable",
137
+ "incomplete",
138
+ "ambiguous",
139
+ "error",
140
+ ] as const;
141
+
142
+ export type FactoryProofGateReason =
143
+ (typeof FACTORY_PROOF_GATE_REASONS)[number];
144
+
145
+ /**
146
+ * One entry of a consumer's `verification.commands` (ADR 0021). Only the two
147
+ * load-bearing fields are declared: `name` is the command *identity* the proof
148
+ * records in `executedCommands`, `command` is the string the static coverage
149
+ * assertion matches against the work a reused proof would skip.
150
+ */
151
+ export interface ProofReuseCommand {
152
+ readonly command: string;
153
+ readonly name: string;
154
+ }
155
+
156
+ /**
157
+ * Command identities are baked into the emitted script, so their charset is a
158
+ * safety property, not a style rule. `surface` has always gone through
159
+ * `safeLabel` for this reason; `name` needs the same treatment.
160
+ *
161
+ * Deliberately a strict allow-list rather than a quote-escaper: a name is an
162
+ * identifier, and every identity across the fleet's profiles today is
163
+ * `[a-z0-9:-]`. Anything outside this — hostile or merely a stray apostrophe —
164
+ * makes the whole selection unusable, which degrades to the refusing script.
165
+ * A stray apostrophe reaching interpolation would otherwise kill the step with
166
+ * a bash syntax error *before* the single `GITHUB_OUTPUT` write, so reuse
167
+ * would collapse to never with no `reason` written at all — the silent
168
+ * regression the vocabulary exists to make visible.
169
+ */
170
+ const COMMAND_IDENTITY = /^\w[\w.:@/-]*$/u;
171
+ const COMMAND_IDENTITY_MAX_LENGTH = 120;
172
+
173
+ const isProofReuseCommand = (value: unknown): value is ProofReuseCommand => {
174
+ if (!(value && typeof value === "object")) {
175
+ return false;
176
+ }
177
+ const entry = value as Record<string, unknown>;
178
+ return (
179
+ typeof entry.command === "string" &&
180
+ entry.command.length > 0 &&
181
+ typeof entry.name === "string" &&
182
+ entry.name.length <= COMMAND_IDENTITY_MAX_LENGTH &&
183
+ COMMAND_IDENTITY.test(entry.name)
184
+ );
185
+ };
186
+
187
+ /**
188
+ * The command identities a guarded surface requires, derived from the profile
189
+ * command objects that surface selected. This is the single derivation: the
190
+ * gate script and the static coverage assertion both go through it, so a
191
+ * consumer can never have one notion of "required" at generation time and
192
+ * another at assertion time.
193
+ *
194
+ * `undefined` means the selection is unusable — not an array, empty, or
195
+ * carrying an entry whose `command` is blank or whose `name` is not a plain
196
+ * command identity, or carrying duplicate names. A name is the executable
197
+ * authorization identity recorded in proof, so two commands may never collapse
198
+ * behind one. An empty required set would make *every* passing proof trivially
199
+ * covering, so it is never silently treated as "requires nothing"; callers
200
+ * must refuse instead.
201
+ */
202
+ export const proofReuseRequiredCommands = (
203
+ commands: readonly ProofReuseCommand[]
204
+ ): readonly string[] | undefined => {
205
+ if (!(Array.isArray(commands) && commands.length > 0)) {
206
+ return;
207
+ }
208
+ if (!commands.every(isProofReuseCommand)) {
209
+ return;
210
+ }
211
+ const names = commands.map(({ name }) => name);
212
+ if (new Set(names).size !== names.length) {
213
+ return;
214
+ }
215
+ return names.toSorted();
216
+ };
217
+
218
+ /**
219
+ * jq program: every page of the Checks API result in, three sanitized lines
220
+ * (`reason`, `mode`, missing commands) out.
221
+ *
222
+ * The input is what `gh api --paginate` actually writes: the pages
223
+ * *concatenated* as a stream of top-level response objects, not merged into
224
+ * one document and not wrapped in an array. That is why the script invokes
225
+ * `jq -s` and why this program opens with `.[] | (.check_runs // [])[]`. A
226
+ * test double that emits `[{ "check_runs": [...] }]` instead is a different
227
+ * shape: `jq` fails with `Cannot index array with string ("check_runs")`, the
228
+ * script lands on `reason=error`, and — because the gate fails open — the
229
+ * result looks exactly like healthy full CI. Stub `gh` with a bare response
230
+ * object per page.
231
+ *
232
+ * `binding` recovers the machine-readable payload from `output.text`
233
+ * (preferred) or `output.summary`, which the factory writes as a fenced JSON
234
+ * document. Anything unparseable degrades to `null`, and therefore to a
235
+ * refusal.
236
+ *
237
+ * This is the *second* parser of that payload: `parsePrVerifyCheckPayload`
238
+ * (`software-factory/src/pr-verify-check-payload.ts`) regex-extracts the fenced
239
+ * block, while this one strips fence lines and `fromjson`s what remains. The
240
+ * one input that separates them is prose around the fence, which parses there
241
+ * and refuses here. Both halves of that are asserted in the test suite rather
242
+ * than asserted here in prose — the exact shape the renderer emits is proven,
243
+ * and the divergent shape is proven to fail safe. Two parsers of one payload
244
+ * can drift; what must not drift silently is which direction they drift in.
245
+ *
246
+ * Ordering is by `started_at` alone, normalized to whole seconds. Two
247
+ * generations that share the greatest start time are `ambiguous` rather than
248
+ * arbitrarily resolved: the gate cannot tell which one describes the tree, and
249
+ * silently picking either is exactly the kind of coin-flip authorization this
250
+ * whole mechanism exists to remove. Sub-second precision is dropped so
251
+ * `…:00Z` and `…:00.000Z` compare equal; two genuine verification generations
252
+ * starting within the same second at the same head is not a real state, and
253
+ * collapsing them errs toward refusing.
254
+ *
255
+ * The comparison is lexical, which is correct only for fixed-width UTC. A
256
+ * `+HH:MM` offset would sort by its literal text rather than by its instant,
257
+ * and an absent `started_at` would sort to the bottom. The Checks API returns
258
+ * neither today, so this is guarded rather than merely noted: every candidate
259
+ * must carry a canonical UTC timestamp, and one that does not makes the newest
260
+ * generation unestablishable, which is `ambiguous`. Refusing costs a hosted
261
+ * run; ranking an unorderable set could authorize the wrong one.
262
+ */
263
+ const GATE_JQ = String.raw`
264
+ def binding:
265
+ [ .output.text, .output.summary ]
266
+ | map(select(type == "string"))
267
+ | map(split("\n") | map(select(startswith("${"```"}") | not)) | join("\n"))
268
+ | map(. as $body | try ($body | fromjson) catch null)
269
+ | map(select(type == "object"))
270
+ | .[0];
271
+
272
+ def startedAt: (.started_at // "") | tostring;
273
+
274
+ def rankable:
275
+ test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z$");
276
+
277
+ [ .[]
278
+ | (.check_runs // [])[]
279
+ | select(.name == $name)
280
+ | select(((.app.id // "") | tostring) == $app)
281
+ | { started: startedAt,
282
+ status: (.status // ""),
283
+ conclusion: (.conclusion // ""),
284
+ binding: binding }
285
+ ] as $runs
286
+ | ($runs | map(.started | rankable) | all) as $orderable
287
+ | ($runs | map(.started | sub("\\.[0-9]+Z$"; "Z")) | max) as $newest
288
+ | [ $runs[] | select((.started | sub("\\.[0-9]+Z$"; "Z")) == $newest) ] as $generation
289
+ | (if ($runs | length) == 0 then ["none", "", ""]
290
+ elif ($orderable | not) then ["ambiguous", "", ""]
291
+ elif ($generation | length) != 1 then ["ambiguous", "", ""]
292
+ else
293
+ $generation[0] as $run
294
+ | (if ($run.binding | type) == "object" then $run.binding else {} end) as $proof
295
+ | (($proof.mode // "") | tostring) as $mode
296
+ | (($proof.executedCommands // []) | map(select(type == "string"))) as $executed
297
+ | ($required - $executed) as $missing
298
+ | (if $run.status != "completed" then "pending"
299
+ elif $run.conclusion != "success" then "failed"
300
+ elif (($run.binding | type) != "object")
301
+ or ($proof.kind != "pr-verify-proof-binding")
302
+ or ($proof.schemaVersion != 1)
303
+ or ($proof.headSha != $sha)
304
+ or ($proof.repository != $repository) then "unreadable"
305
+ elif $proof.outcome != "passed" then "failed"
306
+ elif ($required | length) == 0 then "incomplete"
307
+ elif ($missing | length) != 0 then "incomplete"
308
+ else "proven"
309
+ end) as $reason
310
+ | [$reason, $mode, ($missing | join(", "))]
311
+ end)
312
+ | map(gsub("[\\r\\n\\t]"; " "))
313
+ | join("\n")
314
+ `.trim();
315
+
316
+ /**
317
+ * Every refusal ends on the same line. `pr:verify` is the command that
318
+ * produces the proof this job looks for, so it is the corrective action
319
+ * whatever the refusal was.
320
+ *
321
+ * It is phrased as an option, not a reprimand. A pull request opened by hand
322
+ * has no factory proof and never will; the full suite running for it is the
323
+ * designed behavior, not a mistake to report.
324
+ */
325
+ const CORRECTIVE_LINE =
326
+ "Run `psf pr:verify` before publishing to reuse local proof and avoid a duplicate server run.";
327
+
328
+ /**
329
+ * Emitted when a consumer's command selection is unusable. Mirrors the
330
+ * retired hosted docs-only detector: a malformed profile slice degrades to the
331
+ * conservative answer at *runtime* rather than throwing at generation time,
332
+ * because the input is JSON that may be absent or reshaped. The loud signal is
333
+ * the static coverage assertion, plus `reason=error` on the step output.
334
+ */
335
+ const UNUSABLE_SELECTION_SCRIPT = String.raw`{
336
+ printf '${FACTORY_PROOF_GATE_OUTPUT}=false\n'
337
+ printf '${FACTORY_PROOF_GATE_REASON_OUTPUT}=error\n'
338
+ } >> "${shellExpansion("GITHUB_OUTPUT:-/dev/null")}"`;
339
+
340
+ /** Surface labels reach markdown, so only a plain, bounded label survives. */
341
+ const safeLabel = (surface: string): string => {
342
+ const cleaned = (typeof surface === "string" ? surface : "")
343
+ .replaceAll(/[^\w -]/gu, "")
344
+ .trim()
345
+ .slice(0, 60);
346
+ return cleaned.length > 0 ? cleaned : "verification";
347
+ };
348
+
349
+ const gateScript = (required: readonly string[], surface: string): string =>
350
+ String.raw`
351
+ set -uo pipefail
352
+
353
+ CHECK_NAME=${shellSingleQuote(FACTORY_PROOF_GATE_CHECK_NAME)}
354
+ FACTORY_APP_ID=${shellSingleQuote(FACTORY_PROOF_GATE_APP_ID)}
355
+ REQUIRED_COMMANDS=${shellSingleQuote(JSON.stringify(required))}
356
+ SURFACE=${shellSingleQuote(surface)}
357
+
358
+ reason=error
359
+ detail=''
360
+ mode=''
361
+ missing=''
362
+
363
+ # filter=all with full pagination is load-bearing (ADR 0022). GitHub's
364
+ # default "latest" filter is ordered by completion, so a newer generation
365
+ # that is still running can be hidden behind an older completed one — the
366
+ # gate would then read a stale pass as current.
367
+ if [ -z "${shellExpansion("HEAD_SHA:-")}" ]; then
368
+ detail='no pull request head SHA'
369
+ elif [ -z "${shellExpansion("GITHUB_REPOSITORY:-")}" ]; then
370
+ detail='no repository name'
371
+ elif ! response=$(gh api --method GET --paginate \
372
+ "repos/$GITHUB_REPOSITORY/commits/$HEAD_SHA/check-runs" \
373
+ -f "check_name=$CHECK_NAME" \
374
+ -f filter=all \
375
+ -f per_page=100 2>&1); then
376
+ detail="checks API unreadable: $response"
377
+ elif ! finding=$(printf '%s' "$response" | jq -r -s \
378
+ --arg name "$CHECK_NAME" \
379
+ --arg app "$FACTORY_APP_ID" \
380
+ --arg sha "$HEAD_SHA" \
381
+ --arg repository "$GITHUB_REPOSITORY" \
382
+ --argjson required "$REQUIRED_COMMANDS" \
383
+ '${GATE_JQ}' 2>&1); then
384
+ detail="unreadable proof binding: $finding"
385
+ else
386
+ # Three separate reads, not one IFS split: tab is IFS whitespace, so a
387
+ # split would collapse the empty fields the vocabulary relies on.
388
+ #
389
+ # The trailing "|| :" on each read is load-bearing. "missing" is empty for
390
+ # every verdict except "incomplete", so jq's third field is the empty
391
+ # string, command substitution strips the trailing newline, and the third
392
+ # read reaches EOF -- having correctly assigned "" -- and returns 1. Under
393
+ # an errexit shell that return value kills the step before the single
394
+ # GITHUB_OUTPUT write below, which is exactly how this gate failed in
395
+ # hosted CI on every decidable verdict while every test passed (#319).
396
+ {
397
+ IFS= read -r reason || :
398
+ IFS= read -r mode || :
399
+ IFS= read -r missing || :
400
+ } <<< "$finding"
401
+ case "$reason" in
402
+ proven | none | pending | failed | unreadable | incomplete | ambiguous) ;;
403
+ *)
404
+ detail="unexpected gate result: $reason"
405
+ reason=error
406
+ ;;
407
+ esac
408
+ fi
409
+
410
+ # The binding is App-verified, but it still reaches markdown. Only a plain
411
+ # lowercase token is quoted back; anything else is reported as unknown.
412
+ case "$mode" in
413
+ '') ;;
414
+ *[!a-z-]*) mode='unknown' ;;
415
+ esac
416
+
417
+ verdict=false
418
+ if [ "$reason" = 'proven' ]; then
419
+ verdict=true
420
+ fi
421
+
422
+ # detail can carry arbitrary gh or jq error text. Collapse it to one bounded
423
+ # line so it cannot restructure the summary it is written into.
424
+ detail=$(printf '%s' "$detail" | tr '\n\r\t' ' ' | cut -c1-240)
425
+ missing=$(printf '%s' "$missing" | tr '\n\r\t' ' ' | cut -c1-240)
426
+
427
+ SUMMARY="${shellExpansion("GITHUB_STEP_SUMMARY:-/dev/null")}"
428
+ say() { printf '%s\n' "$1" >> "$SUMMARY"; }
429
+
430
+ say "## Proof reuse: $SURFACE"
431
+ say ''
432
+
433
+ case "$reason" in
434
+ proven)
435
+ echo "Factory proof: reusing local verification of $HEAD_SHA; skipping the $SURFACE suite."
436
+ say "Skipped. The factory already verified this exact commit, so this job did not run the $SURFACE suite a second time."
437
+ say ''
438
+ say "- Reused proof: the \`$CHECK_NAME\` check run published by the pinned factory GitHub App."
439
+ say "- Covers head: \`$HEAD_SHA\`"
440
+ say "- Recorded mode: \`$mode\` (diagnostic only), outcome \`passed\`."
441
+ ;;
442
+ none)
443
+ say 'Ran the full suite. No trusted factory proof covers this commit.'
444
+ say ''
445
+ say "The factory GitHub App has published no \`$CHECK_NAME\` check run at head \`$HEAD_SHA\`. Proof is keyed to the commit, so proof written for any other commit is not visible here. A pull request opened by hand carries no factory proof at all, which is normal."
446
+ say ''
447
+ say '${CORRECTIVE_LINE}'
448
+ ;;
449
+ pending)
450
+ say 'Ran the full suite. The factory proof for this commit had not finished when this job read it.'
451
+ say ''
452
+ say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` was still in progress. The gate reads one snapshot at job start and does not wait."
453
+ say ''
454
+ say "Let \`psf pr:verify\` finish before publishing, so its proof is on the commit before this job reads it."
455
+ ;;
456
+ failed)
457
+ say 'Ran the full suite. The factory proof for this commit records no pass.'
458
+ say ''
459
+ say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` finished without a passing conclusion, so it establishes nothing about this tree."
460
+ say ''
461
+ say '${CORRECTIVE_LINE}'
462
+ ;;
463
+ unreadable)
464
+ say 'Ran the full suite. The factory check run for this commit carries no proof this job can read.'
465
+ say ''
466
+ say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` passed, but it carries no machine-readable binding naming this repository and this head, or one written to a schema this job does not recognize."
467
+ say ''
468
+ say '${CORRECTIVE_LINE}'
469
+ ;;
470
+ incomplete)
471
+ say "Ran the full suite. The factory proof for this commit does not cover every command the $SURFACE surface requires."
472
+ say ''
473
+ say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` passed, but its \`executedCommands\` is missing: \`$missing\`"
474
+ say ''
475
+ say '${CORRECTIVE_LINE}'
476
+ ;;
477
+ ambiguous)
478
+ say 'Ran the full suite. The newest factory proof for this commit is ambiguous.'
479
+ say ''
480
+ say "Two \`$CHECK_NAME\` check runs at head \`$HEAD_SHA\` share the greatest start time, so there is no single newest generation to trust. The gate refuses rather than picking one."
481
+ say ''
482
+ say '${CORRECTIVE_LINE}'
483
+ ;;
484
+ *)
485
+ say 'Ran the full suite. The proof gate could not reach a decision.'
486
+ say ''
487
+ say 'The gate fails open by design: when it cannot tell whether proof exists, every command runs. Nothing about this pull request is implied.'
488
+ say ''
489
+ say " $detail"
490
+ ;;
491
+ esac
492
+ say ''
493
+
494
+ if [ "$verdict" != 'true' ]; then
495
+ echo "No reusable factory proof for ${shellExpansion("HEAD_SHA:-<unknown>")}; running the $SURFACE suite ($reason). $detail"
496
+ fi
497
+
498
+ # The only write. A crash before this line leaves the output unset, the guard
499
+ # reads empty, and every guarded step runs — the fail-open path.
500
+ {
501
+ printf '${FACTORY_PROOF_GATE_OUTPUT}=%s\n' "$verdict"
502
+ printf '${FACTORY_PROOF_GATE_REASON_OUTPUT}=%s\n' "$reason"
503
+ printf '${FACTORY_PROOF_GATE_MODE_OUTPUT}=%s\n' "$mode"
504
+ } >> "${shellExpansion("GITHUB_OUTPUT:-/dev/null")}"
505
+ `.trim();
506
+
507
+ export interface FactoryProofGateOptions {
508
+ /**
509
+ * The profile command objects this guarded surface selected. A consumer with
510
+ * distinct core and docs jobs selects distinct sets, and each job's gate
511
+ * therefore requires a different coverage.
512
+ */
513
+ readonly commands: readonly ProofReuseCommand[];
514
+ /** Names the suite in the job summary. Changes no trust decision. */
515
+ readonly surface: string;
516
+ }
517
+
518
+ /**
519
+ * The gate script. Exported so it can be executed directly under test against
520
+ * a stubbed `gh`, rather than only asserted against as workflow text — the
521
+ * script is the security boundary, and asserting on generated YAML would leave
522
+ * its actual decisions untested.
523
+ *
524
+ * Note the deliberate absence of `set -e`: every failure path has to reach the
525
+ * final write, and that write must emit `false`. Omitting it is necessary but
526
+ * not sufficient — the runner supplies `-e` unless the step declares
527
+ * `FACTORY_PROOF_GATE_SHELL` — so the script is also written to reach that
528
+ * write under errexit, and the tests execute it both ways.
529
+ */
530
+ export const factoryProofGateScript = ({
531
+ commands,
532
+ surface,
533
+ }: FactoryProofGateOptions): string => {
534
+ const required = proofReuseRequiredCommands(commands);
535
+ return required
536
+ ? gateScript(required, safeLabel(surface))
537
+ : UNUSABLE_SELECTION_SCRIPT;
538
+ };
539
+
540
+ export interface FactoryProofGateStep {
541
+ readonly continueOnError: true;
542
+ readonly env: Readonly<{
543
+ GH_TOKEN: string;
544
+ HEAD_SHA: string;
545
+ }>;
546
+ readonly id: typeof FACTORY_PROOF_GATE_STEP_ID;
547
+ readonly if: typeof FACTORY_PROOF_GATE_IF;
548
+ readonly name: string;
549
+ readonly run: string;
550
+ readonly shell: typeof FACTORY_PROOF_GATE_SHELL;
551
+ }
552
+
553
+ /**
554
+ * The step itself, structurally accepted by gagen's `step()` without adding a
555
+ * gagen runtime dependency. It belongs first in the job it guards: one Checks
556
+ * API read with the default `GITHUB_TOKEN` (`checks: read`), no checkout, no
557
+ * install, so a proven head costs a runner nothing beyond job startup.
558
+ *
559
+ * A **step, not a job**, and that is not a style preference. A separate gate
560
+ * job that errored would leave the guarded job `skipped`, and a summary job
561
+ * that only fails on `failure`/`cancelled` would still report green — a Checks
562
+ * API outage would silently skip verification. As a step it fails open by
563
+ * construction: the step errors, the output is never written, the guard reads
564
+ * empty, and every command runs.
565
+ */
566
+ export const factoryProofGateStep = (
567
+ options: FactoryProofGateOptions
568
+ ): FactoryProofGateStep =>
569
+ Object.freeze({
570
+ continueOnError: true as const,
571
+ env: Object.freeze({
572
+ GH_TOKEN: githubExpression("secrets.GITHUB_TOKEN"),
573
+ HEAD_SHA: githubExpression("github.event.pull_request.head.sha"),
574
+ }),
575
+ id: FACTORY_PROOF_GATE_STEP_ID,
576
+ if: FACTORY_PROOF_GATE_IF,
577
+ name: "Check for factory proof of this head",
578
+ run: factoryProofGateScript(options),
579
+ // Never omit: the runner's default `run:` shell supplies `-e`, which
580
+ // voids the fail-open design. See FACTORY_PROOF_GATE_SHELL.
581
+ shell: FACTORY_PROOF_GATE_SHELL,
582
+ });
583
+
584
+ export interface ProofReuseCoverageInput {
585
+ /** The same selection handed to the gate for this surface. */
586
+ readonly commands: readonly ProofReuseCommand[];
587
+ /**
588
+ * @deprecated Ignored. Consumer prose cannot authorize executable coverage;
589
+ * retained only so the 0.2.1 security patch remains source-compatible.
590
+ */
591
+ readonly equivalents?: Readonly<Record<string, string>>;
592
+ /**
593
+ * The command strings the consumer's workflow would skip when the gate says
594
+ * `true`, already resolved to the leaves that actually run. Extracting them
595
+ * is the consumer's job: this package never parses workflow source, because
596
+ * doing so is what killed #288.
597
+ */
598
+ readonly skipped: readonly string[];
599
+ /** Names the surface in the failure message. */
600
+ readonly surface?: string;
601
+ }
602
+
603
+ export interface ProofReuseCoverageReport {
604
+ /** True only when the selection is usable *and* nothing is uncovered. */
605
+ readonly covered: boolean;
606
+ /** Command identities derived from the selection; empty when unusable. */
607
+ readonly requiredCommands: readonly string[];
608
+ /** Skipped command strings no selected profile command accounts for. */
609
+ readonly uncovered: readonly string[];
610
+ }
611
+
612
+ /**
613
+ * The static coverage assertion, as a report.
614
+ *
615
+ * Runtime command coverage is authoritative — the gate's `incomplete` refusal
616
+ * is the backstop that cannot be bypassed. This is the compile-time guard in
617
+ * front of it: it fails a consumer's build the moment a workflow skips work
618
+ * that no selected profile command runs, rather than letting the drift show up
619
+ * as CI quietly verifying nothing. The drift is real history: #227 wired a
620
+ * workspace member into CI while the profile never learned about it.
621
+ */
622
+ export const proofReuseCoverage = ({
623
+ commands,
624
+ skipped,
625
+ }: ProofReuseCoverageInput): ProofReuseCoverageReport => {
626
+ const requiredCommands = proofReuseRequiredCommands(commands) ?? [];
627
+ const proven = new Set(
628
+ requiredCommands.length > 0
629
+ ? commands.map(({ command }) => command.trim())
630
+ : []
631
+ );
632
+ const uncovered = [
633
+ ...new Set(
634
+ (Array.isArray(skipped) ? skipped : [])
635
+ .map((command) => String(command).trim())
636
+ .filter((command) => command.length > 0 && !proven.has(command))
637
+ ),
638
+ ].toSorted();
639
+
640
+ return Object.freeze({
641
+ covered: requiredCommands.length > 0 && uncovered.length === 0,
642
+ requiredCommands,
643
+ uncovered,
644
+ });
645
+ };
646
+
647
+ /** `proofReuseCoverage`, as a build failure. */
648
+ export const assertProofReuseCoverage = (
649
+ input: ProofReuseCoverageInput
650
+ ): ProofReuseCoverageReport => {
651
+ const report = proofReuseCoverage(input);
652
+ if (report.covered) {
653
+ return report;
654
+ }
655
+
656
+ const surface = safeLabel(input.surface ?? "");
657
+ const problem =
658
+ report.requiredCommands.length === 0
659
+ ? "selects no usable profile commands, so any passing proof would trivially cover it"
660
+ : `skips work no selected profile command runs: ${report.uncovered.join(", ")}`;
661
+ throw new Error(
662
+ `Proof-reuse coverage failed: the ${surface} surface ${problem}. Add the command to software-factory.profile.json (and to this surface's selection), or stop skipping it.`
663
+ );
664
+ };