@patronage/factory-ci 1.0.0-alpha.4 → 1.0.0-alpha.41

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 (54) hide show
  1. package/README.md +713 -11
  2. package/dist/.build-fingerprint.json +3 -0
  3. package/dist/alchemy/index.d.ts +1174 -0
  4. package/dist/alchemy/index.js +2142 -0
  5. package/dist/bundle-alchemy-entry-CT5hCphA.js +112 -0
  6. package/dist/execute-alchemy-entry-B0lBN-YZ.js +160 -0
  7. package/dist/execute-alchemy-entry-B397GSk5.d.ts +134 -0
  8. package/dist/index.d.ts +1218 -93
  9. package/dist/index.js +2841 -333
  10. package/package.json +28 -10
  11. package/src/actions.ts +13 -0
  12. package/src/alchemy/child-diagnostics.ts +148 -0
  13. package/src/alchemy/credential-preflight.ts +428 -0
  14. package/src/alchemy/destroy-postcondition.ts +103 -0
  15. package/src/alchemy/evaluate-stack.ts +153 -0
  16. package/src/alchemy/first-deploy-authorization.ts +194 -0
  17. package/src/alchemy/index.ts +144 -0
  18. package/src/alchemy/lifecycle-failure.ts +174 -0
  19. package/src/alchemy/lifecycle.ts +1330 -0
  20. package/src/alchemy/local-emulation.ts +89 -0
  21. package/src/alchemy/plan-effects.ts +510 -0
  22. package/src/alchemy/retained-identity.ts +248 -0
  23. package/src/alchemy/secret-name-policy.ts +96 -0
  24. package/src/alchemy/stage-policy.ts +269 -0
  25. package/src/alchemy/state-tree.ts +168 -0
  26. package/src/alchemy/url-implies-auth.ts +264 -0
  27. package/src/alchemy-baseline.ts +75 -0
  28. package/src/bundle-alchemy-entry.ts +5 -0
  29. package/src/candidate-impact-workflow.ts +110 -0
  30. package/src/candidate-lifecycle.ts +29 -0
  31. package/src/cursor-oidc.ts +33 -0
  32. package/src/execute-alchemy-entry.ts +128 -8
  33. package/src/factory-workflow.ts +83 -40
  34. package/src/github-app-token.ts +131 -22
  35. package/src/github-transport.ts +186 -0
  36. package/src/impact-demand-condition.ts +67 -0
  37. package/src/index.ts +174 -0
  38. package/src/lifecycle-contract-lane.ts +113 -0
  39. package/src/merge-freeze-job.ts +253 -0
  40. package/src/pinned-action.ts +30 -0
  41. package/src/pr-status-hud-workflow.ts +96 -0
  42. package/src/preview-cleanup-topology.ts +115 -0
  43. package/src/preview-proof-inventory.ts +1092 -0
  44. package/src/preview-proof-lifecycle.ts +328 -0
  45. package/src/preview-receipt-workflow.ts +83 -0
  46. package/src/production-impact-workflow.ts +181 -0
  47. package/src/proof-reuse-gate.ts +297 -63
  48. package/src/proof-reuse-presentation.ts +131 -0
  49. package/src/push-identity-workflow.ts +463 -0
  50. package/src/runnable-cli.ts +27 -0
  51. package/src/verify-runner-policy.ts +290 -0
  52. package/src/vitest-profile-reader.test.ts +208 -0
  53. package/src/vitest-profile-reader.ts +225 -0
  54. package/src/vitest-profile.ts +631 -0
@@ -3,7 +3,9 @@
3
3
  *
4
4
  * It answers one question, before checkout and before install: may this job
5
5
  * reuse the local verification the factory already published for *this exact
6
- * head*? Refusing runs hosted CI; it never fails the candidate. Three
6
+ * head*? It asks that only on a pull request, so every default-branch push
7
+ * executes the full hosted suite (#863). Refusing runs hosted CI; it never
8
+ * fails the candidate. Three
7
9
  * repositories had independently grown their own answer to that question and
8
10
  * had already drifted apart, so the answer lives here once, with the App
9
11
  * identity, check name, step identity, output names, guard, and every trust
@@ -57,6 +59,15 @@ export const FACTORY_PROOF_GATE_APP_ID = "4314840";
57
59
  /** Step id the guard condition refers to. */
58
60
  export const FACTORY_PROOF_GATE_STEP_ID = "factory-proof";
59
61
 
62
+ /**
63
+ * Human-visible name of the gate step as the Actions jobs API serves it. A
64
+ * read-only run analyzer (`psf ci:analyze`, #647) matches on this name to
65
+ * classify a run as proof-reuse versus full fallback, so it is exported from
66
+ * exactly the module that writes it — matching on a re-typed copy would drift.
67
+ */
68
+ export const FACTORY_PROOF_GATE_STEP_NAME =
69
+ "Check for factory proof of this head";
70
+
60
71
  /**
61
72
  * The shell the gate runs under, and it is a correctness requirement rather
62
73
  * than a preference.
@@ -98,6 +109,9 @@ export const FACTORY_PROOF_GATE_REASON_OUTPUT = "reason";
98
109
  */
99
110
  export const FACTORY_PROOF_GATE_MODE_OUTPUT = "mode";
100
111
 
112
+ /** Exact Checks API URL of the proof generation selected by the gate. */
113
+ export const FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT = "source-check-url";
114
+
101
115
  /**
102
116
  * Guard for every step the gate protects. Deliberately `!= 'true'` and not
103
117
  * `== 'false'`: an unset, empty, or garbled output must run the suite.
@@ -105,23 +119,36 @@ export const FACTORY_PROOF_GATE_MODE_OUTPUT = "mode";
105
119
  export const FACTORY_PROOF_GATE_GUARD = `steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_OUTPUT} != 'true'`;
106
120
 
107
121
  /**
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.
122
+ * Pull requests only — the gate's single condition (#873, default since #863,
123
+ * the only mode since the merge-target opt-out was deleted).
124
+ *
125
+ * A merge target's guarantee is about the whole tree, not the diff. A
126
+ * candidate proof only ever binds the diff the candidate was scoped to, so
127
+ * reusing it on the merged commit proves less than the merge target needs.
128
+ * #931 is that defect observed — a `main` push reused a candidate proof,
129
+ * executed no command, and left a red package unnoticed for three days. Every
130
+ * default-branch push therefore executes the full hosted suite, whatever
131
+ * proof exists.
132
+ *
133
+ * Which branches trigger the workflow at all stays repository-owned. This
134
+ * condition only keeps the gate from consulting proof outside a pull request.
111
135
  */
112
136
  export const FACTORY_PROOF_GATE_IF = "github.event_name == 'pull_request'";
113
137
 
114
138
  /**
115
139
  * The complete refusal vocabulary. Deliberately few, because these are the
116
- * only distinctions the gate can honestly make from one Checks API read.
140
+ * only distinctions the gate can honestly make from its Checks API reads.
117
141
  *
118
142
  * - `proven` a covering, passing, unambiguous proof for this exact head
119
143
  * - `none` no App-verified factory check run at this commit
120
144
  * - `pending` the newest generation had not completed when this job read it
121
145
  * - `failed` the newest generation records no pass
122
146
  * - `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
147
+ * - `incomplete` its executed plus stamp-authorized released commands do not
148
+ * cover every required command
149
+ * - `ambiguous` two different generations share the newest instant, the
150
+ * newest repeats another run's verdict with no proof time to
151
+ * tell them apart, or a run's start time cannot be ranked
125
152
  * - `error` the gate could not reach a decision (fail open)
126
153
  *
127
154
  * There is no `reduced`: mode stopped being an authorization condition in
@@ -170,6 +197,14 @@ export interface ProofReuseCommand {
170
197
  const COMMAND_IDENTITY = /^\w[\w.:@/-]*$/u;
171
198
  const COMMAND_IDENTITY_MAX_LENGTH = 120;
172
199
 
200
+ /**
201
+ * The impact-stamp interpretation the paired factory packages currently
202
+ * share. A release recorded under any other version is an unmodelled input and
203
+ * cannot subtract hosted work. This is intentionally fail-closed and moves in
204
+ * lockstep with the proof/check-payload producer.
205
+ */
206
+ const TRUSTED_IMPACT_STAMP_VERSION = 4;
207
+
173
208
  const isProofReuseCommand = (value: unknown): value is ProofReuseCommand => {
174
209
  if (!(value && typeof value === "object")) {
175
210
  return false;
@@ -216,8 +251,53 @@ export const proofReuseRequiredCommands = (
216
251
  };
217
252
 
218
253
  /**
219
- * jq program: every page of the Checks API result in, three sanitized lines
220
- * (`reason`, `mode`, missing commands) out.
254
+ * Resolve command *identities* to their `ProofReuseCommand` objects (ADR
255
+ * 0021).
256
+ *
257
+ * Selection by name is deliberately a consumer decision (proof-surfaces.ts in
258
+ * software-factory-hq, the `paitronage:verify` filter in paitronage's
259
+ * `verify.ts`): only the consumer knows which named commands a guarded
260
+ * surface requires. What both of those implementations independently
261
+ * hand-rolled is the same lookup — find each name in the profile's command
262
+ * catalog, and refuse to silently shrink the required set when a name has no
263
+ * entry. That lookup is what this function is: the mechanic, not the
264
+ * selection.
265
+ *
266
+ * Throwing at generation time (rather than returning `undefined` or an empty
267
+ * array) is deliberate: a name with no catalog entry is a mistake in the
268
+ * generator source, not a runtime condition a consumer should have to check
269
+ * for, and a required set that quietly loses an entry is exactly what makes a
270
+ * passing proof trivially "covering".
271
+ *
272
+ * `selectionLabel` names the failure, nothing else: it is not part of the
273
+ * selection this function resolves, only prose a consumer supplies for its
274
+ * own thrown error (e.g. HQ's surface name, "core" or "docs"). The message
275
+ * deliberately says "the profile's command catalog" rather than naming
276
+ * `software-factory.profile.json`: a fleet-generic library must not assume
277
+ * every consumer's catalog is that exact file, so this wording differs
278
+ * on purpose from the HQ-local message it replaced.
279
+ */
280
+ export const resolveProofReuseCommands = (
281
+ catalog: readonly ProofReuseCommand[],
282
+ names: readonly string[],
283
+ selectionLabel?: string
284
+ ): readonly ProofReuseCommand[] =>
285
+ names.map((name) => {
286
+ const command = catalog.find((entry) => entry.name === name);
287
+ if (!command) {
288
+ const location = selectionLabel
289
+ ? `Proof-reuse selection for the ${selectionLabel} surface names`
290
+ : "Proof-reuse selection names";
291
+ throw new Error(
292
+ `${location} "${name}", which the profile's command catalog does not define.`
293
+ );
294
+ }
295
+ return { command: command.command, name: command.name };
296
+ });
297
+
298
+ /**
299
+ * jq program: every page of the Checks API result in, four sanitized lines
300
+ * (`reason`, `mode`, uncovered commands, source URL) out.
221
301
  *
222
302
  * The input is what `gh api --paginate` actually writes: the pages
223
303
  * *concatenated* as a stream of top-level response objects, not merged into
@@ -243,22 +323,45 @@ export const proofReuseRequiredCommands = (
243
323
  * and the divergent shape is proven to fail safe. Two parsers of one payload
244
324
  * can drift; what must not drift silently is which direction they drift in.
245
325
  *
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.
326
+ * Ordering is by the proof's own generation, never by when a run reached
327
+ * GitHub (#1409). It is the rule `fetchPrVerifyProofBinding` applies
328
+ * (`software-factory/src/github-check-runs.ts`), mirrored here because this
329
+ * reader is jq in generated CI and cannot import it:
330
+ *
331
+ * - A run whose binding is bound to this head and repository and transports a
332
+ * typed proof (`verificationProof`) is ordered at the `endedAt` that proof
333
+ * records. Such runs with the same binding, status and conclusion are one
334
+ * generation posted more than once (`pr:verify` posts, `pr:publish`
335
+ * re-posts). So a re-post of an older pass never outranks a newer failure,
336
+ * and a post plus its re-post is no tie.
337
+ * - Any other run is its own generation at its `started_at`: an unbound one,
338
+ * or a bound one with no typed proof (over the text cap, or written before
339
+ * proofs travelled). The factory records a proof before it posts it, so
340
+ * that is the latest its proof could have been recorded.
341
+ * - Such a run carries no generation identity, so it is never grouped. Two
342
+ * separate executions with the same command names and verdict post the same
343
+ * compact binding, and so does a re-post. When the newest generation is one
344
+ * of these and repeats another run's verdict (binding, status and
345
+ * conclusion), it could be a re-post of an older verdict or a new one, so it
346
+ * is `ambiguous`. Proofs that size are rare; refusing costs a hosted run.
347
+ *
348
+ * Two different generations that share the newest instant are `ambiguous`
349
+ * rather than arbitrarily resolved: the gate cannot tell which one describes
350
+ * the tree, and silently picking either is exactly the kind of coin-flip
351
+ * authorization this whole mechanism exists to remove. Instants are
352
+ * normalized to whole seconds so `…:00Z` and `…:00.000Z` compare equal; two
353
+ * genuine verification generations within the same second at the same head
354
+ * is not a real state, and collapsing them errs toward refusing.
254
355
  *
255
356
  * The comparison is lexical, which is correct only for fixed-width UTC. A
256
357
  * `+HH:MM` offset would sort by its literal text rather than by its instant,
257
358
  * and an absent `started_at` would sort to the bottom. The Checks API returns
258
359
  * 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.
360
+ * must carry a canonical UTC `started_at`, and one that does not makes the
361
+ * newest generation unestablishable, which is `ambiguous`. A proof `endedAt`
362
+ * that is not canonical UTC is not a clock, and its run falls back to
363
+ * `started_at`. Refusing costs a hosted run; ranking an unorderable set could
364
+ * authorize the wrong one.
262
365
  */
263
366
  const GATE_JQ = String.raw`
264
367
  def binding:
@@ -274,6 +377,42 @@ def startedAt: (.started_at // "") | tostring;
274
377
  def rankable:
275
378
  test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z$");
276
379
 
380
+ def wholeSecond: sub("\\.[0-9]+Z$"; "Z");
381
+
382
+ def bound:
383
+ (.binding | type) == "object"
384
+ and .binding.kind == "pr-verify-proof-binding"
385
+ and .binding.schemaVersion == 1
386
+ and .binding.headSha == $sha
387
+ and .binding.repository == $repository;
388
+
389
+ def recordedAt:
390
+ if bound then
391
+ (.binding.verificationProof | if type == "object" then .endedAt else null end)
392
+ | if type == "string" and rankable then . else null end
393
+ else null
394
+ end;
395
+
396
+ def sameVerdict($other):
397
+ bound
398
+ and .status == $other.status
399
+ and .conclusion == $other.conclusion
400
+ and .binding == $other.binding;
401
+
402
+ def nonemptyString:
403
+ type == "string" and length > 0;
404
+
405
+ def distinctNames:
406
+ (map(.name) | length) == (map(.name) | unique | length);
407
+
408
+ def releaseAuthorized($release; $commands; $stamp):
409
+ ([ $commands[] | select(.name == $release.name) ]) as $commandRows
410
+ | ([ $stamp.targets[] | select(.name == $release.impactTarget) ]) as $targetRows
411
+ | ($commandRows | length) == 1
412
+ and $commandRows[0].impactTarget == $release.impactTarget
413
+ and ($targetRows | length) == 1
414
+ and $targetRows[0].impact == "not-affected";
415
+
277
416
  [ .[]
278
417
  | (.check_runs // [])[]
279
418
  | select(.name == $name)
@@ -281,20 +420,74 @@ def rankable:
281
420
  | { started: startedAt,
282
421
  status: (.status // ""),
283
422
  conclusion: (.conclusion // ""),
423
+ url: ((.html_url // "") | tostring),
284
424
  binding: binding }
285
425
  ] as $runs
286
426
  | ($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", "", ""]
427
+ | [ $runs[]
428
+ | recordedAt as $recorded
429
+ | . + { at: (($recorded // .started) | wholeSecond), recorded: ($recorded != null) }
430
+ ] as $observed
431
+ | ( [ $observed[] | select(.recorded | not) ]
432
+ + ( [ $observed[] | select(.recorded) ]
433
+ | group_by([.status, .conclusion, .binding])
434
+ | map(.[0]) ) ) as $generations
435
+ | ($generations | map(.at) | max) as $newest
436
+ | [ $generations[] | select(.at == $newest) ] as $generation
437
+ | (if ($runs | length) == 0 then ["none", "", "", ""]
438
+ elif ($orderable | not) then ["ambiguous", "", "", ""]
439
+ elif ($generation | length) != 1 then ["ambiguous", "", "", ""]
440
+ elif ($generation[0] as $newestRun
441
+ | ($newestRun.recorded | not)
442
+ and ([ $runs[] | select(sameVerdict($newestRun)) ] | length) > 1)
443
+ then ["ambiguous", "", "", ""]
292
444
  else
293
445
  $generation[0] as $run
294
446
  | (if ($run.binding | type) == "object" then $run.binding else {} end) as $proof
295
447
  | (($proof.mode // "") | tostring) as $mode
296
448
  | (($proof.executedCommands // []) | map(select(type == "string"))) as $executed
297
- | ($required - $executed) as $missing
449
+ | ($proof | has("notRequiredCommands")) as $hasReleases
450
+ | (if $hasReleases then $proof.notRequiredCommands else [] end) as $releases
451
+ | ($proof.verificationCommands // null) as $commands
452
+ | ($proof.impactStamp // null) as $stamp
453
+ | (if ($hasReleases | not) then true
454
+ else
455
+ ($proof.proofSchemaVersion == 4)
456
+ and ($releases | type) == "array"
457
+ and ($releases | length) > 0
458
+ and ($releases | all(.[];
459
+ type == "object"
460
+ and (.name | nonemptyString)
461
+ and (.impactTarget | nonemptyString)
462
+ and (.basis | nonemptyString)))
463
+ and ($releases | distinctNames)
464
+ and ($commands | type) == "array"
465
+ and ($commands | all(.[];
466
+ type == "object"
467
+ and (.name | nonemptyString)
468
+ and ((has("impactTarget") | not) or (.impactTarget | nonemptyString))))
469
+ and ($commands | distinctNames)
470
+ and ($stamp | type) == "object"
471
+ and ($stamp.stampVersion == ${TRUSTED_IMPACT_STAMP_VERSION})
472
+ and ($stamp.basis == "target-scoped")
473
+ and (($stamp.reasons | type) == "array")
474
+ and ($stamp.reasons | all(.[]; type == "string"))
475
+ and (($stamp.unsubscribedPaths | type) == "array")
476
+ and ($stamp.unsubscribedPaths | all(.[]; type == "string"))
477
+ and (($stamp.targets | type) == "array")
478
+ and ($stamp.targets | all(.[];
479
+ type == "object"
480
+ and (.name | nonemptyString)
481
+ and (.basis | nonemptyString)
482
+ and ((.impact == "affected") or (.impact == "not-affected"))
483
+ and ((.subscribedPaths | type) == "array")
484
+ and (.subscribedPaths | all(.[]; type == "string"))))
485
+ and ($stamp.targets | distinctNames)
486
+ and (([$releases[].name] - $executed | length) == ($releases | length))
487
+ and ($releases | all(.[]; releaseAuthorized(.; $commands; $stamp)))
488
+ end) as $releasesValid
489
+ | (if $releasesValid then [$releases[].name] else [] end) as $released
490
+ | ($required - $executed - $released) as $missing
298
491
  | (if $run.status != "completed" then "pending"
299
492
  elif $run.conclusion != "success" then "failed"
300
493
  elif (($run.binding | type) != "object")
@@ -304,10 +497,11 @@ def rankable:
304
497
  or ($proof.repository != $repository) then "unreadable"
305
498
  elif $proof.outcome != "passed" then "failed"
306
499
  elif ($required | length) == 0 then "incomplete"
500
+ elif ($releasesValid | not) then "incomplete"
307
501
  elif ($missing | length) != 0 then "incomplete"
308
502
  else "proven"
309
503
  end) as $reason
310
- | [$reason, $mode, ($missing | join(", "))]
504
+ | [$reason, $mode, ($missing | join(", ")), $run.url]
311
505
  end)
312
506
  | map(gsub("[\\r\\n\\t]"; " "))
313
507
  | join("\n")
@@ -359,31 +553,42 @@ reason=error
359
553
  detail=''
360
554
  mode=''
361
555
  missing=''
556
+ source_url=''
362
557
 
558
+ # One proof lookup at one commit. Sets lookup_reason / lookup_mode /
559
+ # lookup_missing / lookup_url, or lookup_detail when the read itself
560
+ # failed. Always returns 0: every caller must reach the single
561
+ # GITHUB_OUTPUT write below whatever this function meets.
562
+ #
363
563
  # filter=all with full pagination is load-bearing (ADR 0022). GitHub's
364
564
  # default "latest" filter is ordered by completion, so a newer generation
365
565
  # that is still running can be hidden behind an older completed one — the
366
566
  # 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
567
+ gate_lookup() {
568
+ lookup_reason=error
569
+ lookup_mode=''
570
+ lookup_missing=''
571
+ lookup_url=''
572
+ lookup_detail=''
573
+ if ! lookup_response=$(gh api --method GET --paginate \
574
+ "repos/$GITHUB_REPOSITORY/commits/$1/check-runs" \
575
+ -f "check_name=$CHECK_NAME" \
576
+ -f filter=all \
577
+ -f per_page=100 2>&1); then
578
+ lookup_detail="checks API unreadable: $lookup_response"
579
+ return 0
580
+ fi
581
+ if ! lookup_finding=$(printf '%s' "$lookup_response" | jq -r -s \
582
+ --arg name "$CHECK_NAME" \
583
+ --arg app "$FACTORY_APP_ID" \
584
+ --arg sha "$1" \
585
+ --arg repository "$GITHUB_REPOSITORY" \
586
+ --argjson required "$REQUIRED_COMMANDS" \
587
+ '${GATE_JQ}' 2>&1); then
588
+ lookup_detail="unreadable proof binding: $lookup_finding"
589
+ return 0
590
+ fi
591
+ # Four separate reads, not one IFS split: tab is IFS whitespace, so a
387
592
  # split would collapse the empty fields the vocabulary relies on.
388
593
  #
389
594
  # The trailing "|| :" on each read is load-bearing. "missing" is empty for
@@ -394,17 +599,32 @@ else
394
599
  # GITHUB_OUTPUT write below, which is exactly how this gate failed in
395
600
  # hosted CI on every decidable verdict while every test passed (#319).
396
601
  {
397
- IFS= read -r reason || :
398
- IFS= read -r mode || :
399
- IFS= read -r missing || :
400
- } <<< "$finding"
401
- case "$reason" in
602
+ IFS= read -r lookup_reason || :
603
+ IFS= read -r lookup_mode || :
604
+ IFS= read -r lookup_missing || :
605
+ IFS= read -r lookup_url || :
606
+ } <<< "$lookup_finding"
607
+ case "$lookup_reason" in
402
608
  proven | none | pending | failed | unreadable | incomplete | ambiguous) ;;
403
609
  *)
404
- detail="unexpected gate result: $reason"
405
- reason=error
610
+ lookup_detail="unexpected gate result: $lookup_reason"
611
+ lookup_reason=error
406
612
  ;;
407
613
  esac
614
+ return 0
615
+ }
616
+
617
+ if [ -z "${shellExpansion("HEAD_SHA:-")}" ]; then
618
+ detail='no verification head SHA'
619
+ elif [ -z "${shellExpansion("GITHUB_REPOSITORY:-")}" ]; then
620
+ detail='no repository name'
621
+ else
622
+ gate_lookup "$HEAD_SHA"
623
+ reason="$lookup_reason"
624
+ detail="$lookup_detail"
625
+ mode="$lookup_mode"
626
+ missing="$lookup_missing"
627
+ source_url="$lookup_url"
408
628
  fi
409
629
 
410
630
  # The binding is App-verified, but it still reaches markdown. Only a plain
@@ -423,6 +643,9 @@ fi
423
643
  # line so it cannot restructure the summary it is written into.
424
644
  detail=$(printf '%s' "$detail" | tr '\n\r\t' ' ' | cut -c1-240)
425
645
  missing=$(printf '%s' "$missing" | tr '\n\r\t' ' ' | cut -c1-240)
646
+ if ! [[ "$source_url" =~ ^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/runs/[0-9]+$ ]]; then
647
+ source_url=''
648
+ fi
426
649
 
427
650
  SUMMARY="${shellExpansion("GITHUB_STEP_SUMMARY:-/dev/null")}"
428
651
  say() { printf '%s\n' "$1" >> "$SUMMARY"; }
@@ -433,9 +656,13 @@ say ''
433
656
  case "$reason" in
434
657
  proven)
435
658
  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."
659
+ say "Skipped. The factory already verified this exact content, so this job did not run the $SURFACE suite a second time."
437
660
  say ''
438
- say "- Reused proof: the \`$CHECK_NAME\` check run published by the pinned factory GitHub App."
661
+ if [ -n "$source_url" ]; then
662
+ say "- Reused proof: [\`$CHECK_NAME\`]($source_url), published by the pinned factory GitHub App."
663
+ else
664
+ say "- Reused proof: the \`$CHECK_NAME\` check run published by the pinned factory GitHub App."
665
+ fi
439
666
  say "- Covers head: \`$HEAD_SHA\`"
440
667
  say "- Recorded mode: \`$mode\` (diagnostic only), outcome \`passed\`."
441
668
  ;;
@@ -470,14 +697,14 @@ case "$reason" in
470
697
  incomplete)
471
698
  say "Ran the full suite. The factory proof for this commit does not cover every command the $SURFACE surface requires."
472
699
  say ''
473
- say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` passed, but its \`executedCommands\` is missing: \`$missing\`"
700
+ say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` passed, but its executed commands plus stamp-authorized \`notRequiredCommands\` do not cover this surface. Missing: \`$missing\`"
474
701
  say ''
475
702
  say '${CORRECTIVE_LINE}'
476
703
  ;;
477
704
  ambiguous)
478
705
  say 'Ran the full suite. The newest factory proof for this commit is ambiguous.'
479
706
  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."
707
+ say "Two different \`$CHECK_NAME\` proofs at head \`$HEAD_SHA\` share the newest generation, the newest repeats an earlier run's verdict with no proof time to tell them apart, or a run's start time cannot be ranked, so there is no single newest generation to trust. The gate refuses rather than picking one."
481
708
  say ''
482
709
  say '${CORRECTIVE_LINE}'
483
710
  ;;
@@ -501,6 +728,7 @@ fi
501
728
  printf '${FACTORY_PROOF_GATE_OUTPUT}=%s\n' "$verdict"
502
729
  printf '${FACTORY_PROOF_GATE_REASON_OUTPUT}=%s\n' "$reason"
503
730
  printf '${FACTORY_PROOF_GATE_MODE_OUTPUT}=%s\n' "$mode"
731
+ printf '${FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT}=%s\n' "$source_url"
504
732
  } >> "${shellExpansion("GITHUB_OUTPUT:-/dev/null")}"
505
733
  `.trim();
506
734
 
@@ -552,9 +780,10 @@ export interface FactoryProofGateStep {
552
780
 
553
781
  /**
554
782
  * 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.
783
+ * gagen runtime dependency. It belongs first in the job it guards: a few API
784
+ * reads with the default `GITHUB_TOKEN`, no checkout, no install, so a proven
785
+ * head costs a runner nothing beyond job startup. The step runs on pull
786
+ * requests only, so it needs only `checks: read` (#873, #863).
558
787
  *
559
788
  * A **step, not a job**, and that is not a style preference. A separate gate
560
789
  * job that errored would leave the guarded job `skipped`, and a summary job
@@ -570,11 +799,16 @@ export const factoryProofGateStep = (
570
799
  continueOnError: true as const,
571
800
  env: Object.freeze({
572
801
  GH_TOKEN: githubExpression("secrets.GITHUB_TOKEN"),
573
- HEAD_SHA: githubExpression("github.event.pull_request.head.sha"),
802
+ // On a pull request the verified head is the PR branch tip. The step
803
+ // never runs on a push, so no reachable path reads the `github.sha`
804
+ // half.
805
+ HEAD_SHA: githubExpression(
806
+ "github.event.pull_request.head.sha || github.sha"
807
+ ),
574
808
  }),
575
809
  id: FACTORY_PROOF_GATE_STEP_ID,
576
810
  if: FACTORY_PROOF_GATE_IF,
577
- name: "Check for factory proof of this head",
811
+ name: FACTORY_PROOF_GATE_STEP_NAME,
578
812
  run: factoryProofGateScript(options),
579
813
  // Never omit: the runner's default `run:` shell supplies `-e`, which
580
814
  // voids the fail-open design. See FACTORY_PROOF_GATE_SHELL.
@@ -0,0 +1,131 @@
1
+ /** Generic timing and presentation steps around the proof-reuse gate (#652). */
2
+
3
+ import {
4
+ FACTORY_PROOF_GATE_MODE_OUTPUT,
5
+ FACTORY_PROOF_GATE_OUTPUT,
6
+ FACTORY_PROOF_GATE_REASON_OUTPUT,
7
+ FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT,
8
+ FACTORY_PROOF_GATE_STEP_ID,
9
+ } from "./proof-reuse-gate.ts";
10
+
11
+ const githubExpression = (expression: string): string =>
12
+ `\${{ ${expression} }}`;
13
+
14
+ const shellExpansion = (expression: string): string => `\${${expression}}`;
15
+
16
+ const safeLabel = (surface: string): string => {
17
+ const cleaned = (typeof surface === "string" ? surface : "")
18
+ .replaceAll(/[^\w -]/gu, "")
19
+ .trim()
20
+ .slice(0, 60);
21
+ return cleaned.length > 0 ? cleaned : "verification";
22
+ };
23
+
24
+ const FACTORY_PROOF_TIMING_STEP_ID = "ci-timing";
25
+ const FACTORY_PROOF_TIMING_START_STEP_NAME = "Start CI timing";
26
+ const FACTORY_PROOF_TIMING_SUMMARY_STEP_NAME = "Record proof-reuse timing";
27
+
28
+ export interface FactoryProofReusePresentationOptions {
29
+ /** Human-readable name of the guarded suite. */
30
+ readonly surface: string;
31
+ }
32
+
33
+ export interface FactoryProofTimingStartStep {
34
+ readonly continueOnError: true;
35
+ readonly id: typeof FACTORY_PROOF_TIMING_STEP_ID;
36
+ readonly name: typeof FACTORY_PROOF_TIMING_START_STEP_NAME;
37
+ readonly run: string;
38
+ }
39
+
40
+ export const factoryProofTimingStartStep = (): FactoryProofTimingStartStep =>
41
+ Object.freeze({
42
+ continueOnError: true as const,
43
+ id: FACTORY_PROOF_TIMING_STEP_ID,
44
+ name: FACTORY_PROOF_TIMING_START_STEP_NAME,
45
+ run: String.raw`started_ms="$(node -e 'process.stdout.write(String(Date.now()))')"
46
+ printf 'started_ms=%s\n' "$started_ms" >> "$GITHUB_OUTPUT"`,
47
+ });
48
+
49
+ const factoryProofReuseSummaryScript = ({
50
+ surface,
51
+ }: FactoryProofReusePresentationOptions): string => {
52
+ const label = safeLabel(surface);
53
+ return String.raw`now_ms="$(node -e 'process.stdout.write(String(Date.now()))')"
54
+ ci_started_ms="${shellExpansion("CI_STARTED_MS:-")}"
55
+
56
+ SUMMARY="${shellExpansion("GITHUB_STEP_SUMMARY:-/dev/null")}"
57
+ say() { printf '%s\n' "$1" >> "$SUMMARY"; }
58
+
59
+ say '## ${label} timing'
60
+ say ''
61
+
62
+ if [ "${shellExpansion("GITHUB_EVENT_NAME:-")}" = 'push' ] && [ -z "${shellExpansion("PROOF_REASON:-")}" ]; then
63
+ # A push run with no recorded reason is one where the gate step's condition
64
+ # kept it off entirely, so the full suite ran with no reuse decision. The
65
+ # gate runs on pull requests only (#863), so that is every push.
66
+ say '- Path: full execution, no proof consulted'
67
+ say '- Proof-reuse gate: did not run on this ref; the full suite ran.'
68
+ say "- Verified head: \`${shellExpansion("GITHUB_SHA:-unknown")}\`"
69
+ echo "::notice title=Factory proof reuse::The proof-reuse gate did not run on this ref; the full ${label} suite executed."
70
+ elif [ "${shellExpansion("PROOF_REUSED:-")}" = 'true' ]; then
71
+ say '- Path: trusted local proof reused'
72
+ if [ -n "${shellExpansion("PROOF_SOURCE_URL:-")}" ]; then
73
+ say "- Reused proof: [exact source check](${shellExpansion("PROOF_SOURCE_URL")})"
74
+ fi
75
+ say "- Bound head: \`${shellExpansion("PROOF_HEAD_SHA:-unknown")}\`"
76
+ say "- Factory verification mode: ${shellExpansion("PROOF_MODE:-unavailable")} (diagnostic only)"
77
+ echo "::notice title=Factory proof reuse::Reused trusted local proof for ${label} at ${shellExpansion("PROOF_HEAD_SHA:-unknown")}."
78
+ else
79
+ say "- Path: full GitHub CI fallback (${shellExpansion("PROOF_REASON:-error")})"
80
+ say "- Bound head: \`${shellExpansion("PROOF_HEAD_SHA:-unknown")}\`"
81
+ say "- Factory verification mode: ${shellExpansion("PROOF_MODE:-unavailable")} (diagnostic only)"
82
+ echo "::notice title=Factory proof reuse::No reusable proof for ${label}; the full hosted suite executed (${shellExpansion("PROOF_REASON:-error")})."
83
+ fi
84
+
85
+ if [[ "$ci_started_ms" =~ ^[0-9]+$ ]]; then
86
+ say "- GitHub workflow execution after the proof gate: $((now_ms - ci_started_ms)) ms"
87
+ else
88
+ say '- GitHub workflow execution after the proof gate: unavailable'
89
+ fi
90
+ say ''`;
91
+ };
92
+
93
+ export interface FactoryProofReuseSummaryStep {
94
+ readonly continueOnError: true;
95
+ readonly env: Readonly<Record<string, string>>;
96
+ readonly if: "always()";
97
+ readonly name: typeof FACTORY_PROOF_TIMING_SUMMARY_STEP_NAME;
98
+ readonly run: string;
99
+ }
100
+
101
+ export const factoryProofReuseSummaryStep = (
102
+ options: FactoryProofReusePresentationOptions
103
+ ): FactoryProofReuseSummaryStep =>
104
+ Object.freeze({
105
+ continueOnError: true as const,
106
+ env: Object.freeze({
107
+ CI_STARTED_MS: githubExpression(
108
+ `steps.${FACTORY_PROOF_TIMING_STEP_ID}.outputs.started_ms`
109
+ ),
110
+ // PR runs bind to the PR branch tip; push runs to the pushed head. No
111
+ // push run records a reason, and this value only labels the summary.
112
+ PROOF_HEAD_SHA: githubExpression(
113
+ "github.event.pull_request.head.sha || github.sha"
114
+ ),
115
+ PROOF_MODE: githubExpression(
116
+ `steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_MODE_OUTPUT}`
117
+ ),
118
+ PROOF_REASON: githubExpression(
119
+ `steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_REASON_OUTPUT}`
120
+ ),
121
+ PROOF_REUSED: githubExpression(
122
+ `steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_OUTPUT}`
123
+ ),
124
+ PROOF_SOURCE_URL: githubExpression(
125
+ `steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT}`
126
+ ),
127
+ }),
128
+ if: "always()" as const,
129
+ name: FACTORY_PROOF_TIMING_SUMMARY_STEP_NAME,
130
+ run: factoryProofReuseSummaryScript(options),
131
+ });