@patronage/factory-ci 1.0.0-alpha.40 → 1.0.0-alpha.42

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.
package/README.md CHANGED
@@ -407,7 +407,7 @@ The **proof-reuse gate** decides whether a hosted job may reuse the local verifi
407
407
 
408
408
  There is no mode to choose. The emitted condition is a trust predicate, so the package owns it: the merge-target opt-out and its push-event merge fallback (#611) are deleted, and no consumer option can reuse proof outside a pull request.
409
409
 
410
- A proof is reusable only when the complete Checks API result (`filter=all`, every page) establishes one unambiguous newest generation by greatest `started_at`, produced by the pinned App for the exact repository and head, completed successfully with `outcome: passed`, and covering every command identity the guarded surface requires. Coverage is the union of `executedCommands` and commands released by `notRequiredCommands` only after the gate validates each release against that same proof binding's command-to-target map and identity-bound impact stamp. Missing, malformed, duplicated, affected, unknown, or differently bound release data refuses reuse and runs the hosted surface. `mode` is reported as diagnostic metadata, never authorized on: a reduced-mode proof whose executed and stamp-authorized released commands cover a surface is reusable.
410
+ A proof is reusable only when the complete Checks API result (`filter=all`, every page) establishes one unambiguous newest generation, produced by the pinned App for the exact repository and head, completed successfully with `outcome: passed`, whose verification started after every other run at that head was posted, and covering every command identity the guarded surface requires. A pass is ordered at its typed proof's start, never later than its own `started_at`, and every other run at its `started_at`; the doc comment above `GATE_JQ` in `src/proof-reuse-gate.ts` states the full rule (#1490, #1506). Coverage is the union of `executedCommands` and commands released by `notRequiredCommands` only after the gate validates each release against that same proof binding's command-to-target map and identity-bound impact stamp. Missing, malformed, duplicated, affected, unknown, or differently bound release data refuses reuse and runs the hosted surface. `mode` is reported as diagnostic metadata, never authorized on: a reduced-mode proof whose executed and stamp-authorized released commands cover a surface is reusable.
411
411
 
412
412
  The only thing a consumer chooses is **what its surface requires**, expressed as the plain profile command objects that surface selects — a repository with distinct core and docs jobs selects distinct sets and gets distinct required coverage. `proofReuseRequiredCommands()` is the single derivation both the gate and the assertion go through. Identities are baked into the emitted script, so they are held to a plain `[A-Za-z0-9_][\w.:@/-]*` allow-list and shell-quoted at the interpolation site; a selection carrying anything else is unusable and degrades to a gate that always refuses.
413
413
 
@@ -504,7 +504,7 @@ const token = await mintInstallationToken(
504
504
 
505
505
  The factory publishes its check runs, and paitronage its proof comments, under the same GitHub App identity — two projects that had each written the same three steps: sign an RS256 app JWT, look the installation up when it is not already known, exchange the JWT for an installation access token.
506
506
 
507
- `mintInstallationToken({ credentials, owner, repo }, options?)` is that mechanism and nothing more. `credentials` is `{ appId, installationId?, privateKeyPath }`: the app id GitHub issued, the installation when a consumer has recorded one, and the path to the private key. The key is a _path_, not key material, so no caller has to hold a secret in memory to make this call — and **where that path comes from stays the consumer's**. Operator config, a secret manager, an environment variable: this package neither reads a config file nor knows a key-path convention. `githubAppJwt(credentials, options?)` is the signing step alone, for a caller that needs the app JWT rather than an installation token.
507
+ `mintInstallationToken({ credentials, owner, repo }, options?)` is that mechanism and nothing more. `credentials` is `{ appId, installationId?, privateKeyPath }`: the app id GitHub issued, the installation when a consumer has recorded one, and the path to the private key. Without `installationId`, the mint discovers the installation from `owner`/`repo`. With one, it makes one installation lookup (`GET /app/installations/{id}`) and refuses to mint unless that installation's account is `owner`, compared case-insensitively; the error names both owners (#1428). The key is a _path_, not key material, so no caller has to hold a secret in memory to make this call — and **where that path comes from stays the consumer's**. Operator config, a secret manager, an environment variable: this package neither reads a config file nor knows a key-path convention. `githubAppJwt(credentials, options?)` is the signing step alone, for a caller that needs the app JWT rather than an installation token.
508
508
 
509
509
  Nothing is cached. The token is returned to the caller, which owns its lifetime — this module keeps no copy of the token or the key, and never writes either to any output. Mint requests send `Connection: close` and retry transport failures — fetch rejection, timeout, a body that dies mid-read, or 408/429/5xx — with doubling backoff for three attempts by default. Exhaustion throws `GitHubAppTokenTransportError` with the attempt count and a bounded credential-free reason. Any other 4xx is GitHub's verdict and throws `GitHubApiError` on the first response without retrying. The budget is the caller's: `transportAttempts` sets the total attempts, and a caller whose mint is best-effort and already has a fallback passes `1` so the fallback stays prompt. The backoff is fixed and does not scale with `timeoutMs`.
510
510
 
@@ -752,7 +752,7 @@ const graph = await evaluateStack({
752
752
 
753
753
  `evaluateStack` runs a stack program at one stage and returns the graph Alchemy would plan, with no state store and no network. It wraps Alchemy's `Plan.make`: the program registers its resources under a `Stack` service, then the plan builds under `inMemoryState()` at the requested `Stage`. Every provider answers its `read` and `list` probes with "absent", so the cold-adoption probe `Plan.make` makes for a resource with resolved props and no prior state never leaves the process. A stage the program returns from early (paitronage's `placeholder` stage) evaluates to an empty graph.
754
754
 
755
- `program` is the effect the consumer hands `Alchemy.Stack`, not the `Alchemy.Stack(...)` value. The value captures the consumer's real `providers` and `state` layers, and at Alchemy 2.0.0-beta.77 `Cloudflare.providers()` resolves credentials when its layer builds (`Credentials.fromAuthProvider` inside `CloudflareApiLive`), so evaluating the value cannot stay credential-free. Export the program next to the stack:
755
+ `program` is the effect the consumer hands `Alchemy.Stack`, not the `Alchemy.Stack(...)` value. The value captures the consumer's real `providers` and `state` layers, and at Alchemy 2.0.0-beta.81 building `Cloudflare.providers()` is not inert (`ProfileStoreLive` inside `CloudflareApiLive` writes `~/.alchemy/profiles/default`, and the layer needs the `AuthProviders` service), so evaluating the value cannot stay free of side effects. Export the program next to the stack:
756
756
 
757
757
  ```ts
758
758
  export const program = Effect.gen(function* () {
@@ -763,7 +763,7 @@ export default Alchemy.Stack("hq", { providers, state }, program);
763
763
 
764
764
  Pass `providers` when the program depends on hand-written provider layers. Every provider that layer registers keeps its identity (`stables`, `aliases`, `diff`) and loses its probes; an unregistered resource type still evaluates. Each graph resource carries the `LogicalId`, `Type`, and raw `Props` of its plan node, so a prop may hold an unresolved Alchemy output. `upstreamByProp` names, per top-level prop, the logical ids that prop's value references, which is the only way to read a cross-resource reference out of raw props: an output is a function, so the prop that holds it says nothing on its own. A prop that references nothing carries no key. The references are kept per prop and never pooled into one list, so a caller asking which resources one prop names is never answered with an id a different prop mentioned. Each binding row comes from Alchemy's Worker binding channel: `worker` is the host's logical id, `name` and `type` are the strings Alchemy emits (`d1`, `kv_namespace`, `secrets_store_secret`, and so on), and `target` is the logical id of the resource the row references, when it references one.
765
765
 
766
- The caller's `providers` layer is **built** before its probes are stubbed: `evaluateStack` wraps that layer, and Alchemy's own lookup resolves each provider out of it before `read` and `list` are replaced. So any side effect a layer performs at construction — a credential read, a network call, a file write — is the caller's, and happens. This is why `Cloudflare.providers()` must not be passed: at beta.77 it resolves credentials when its layer builds (`Credentials.fromAuthProvider` inside `CloudflareApiLive`), before there is anything to stub. The no-network guarantee covers evaluation, not layer construction: pass only layers whose construction is inert.
766
+ The caller's `providers` layer is **built** before its probes are stubbed: `evaluateStack` wraps that layer, and Alchemy's own lookup resolves each provider out of it before `read` and `list` are replaced. So any side effect a layer performs at construction — a credential read, a network call, a file write — is the caller's, and happens. This is why `Cloudflare.providers()` must not be passed: at beta.81 its `CloudflareApiLive` still creates `~/.alchemy/profiles/default` and requires `AuthProviders` when it builds, before there is anything to stub. Beta.77 also resolved credentials there (`Credentials.fromAuthProvider`); beta.81 defers that to first use. The no-network guarantee covers evaluation, not layer construction: pass only layers whose construction is inert.
767
767
 
768
768
  The helper decides nothing about the graph. Invariants over it are separate exports; `assertUrlImpliesAuth` below is the first.
769
769
 
@@ -799,7 +799,7 @@ The factory's own security review prompt carries the same rule in prose, so a re
799
799
  import { ALCHEMY_BASELINE, assertAlchemyBaseline } from "@patronage/factory-ci";
800
800
  ```
801
801
 
802
- `ALCHEMY_BASELINE` is the exact `alchemy` and `effect` pair the fleet moves together on: `{ alchemy: "2.0.0-beta.77", effect: "4.0.0-rc.112" }`. It is a plain constant on the root entry — it imports neither package — so any consumer can read it without installing the `./alchemy` subpath's peers.
802
+ `ALCHEMY_BASELINE` is the exact `alchemy` and `effect` pair the fleet moves together on: `{ alchemy: "2.0.0-beta.81", effect: "4.0.1" }`. It is a plain constant on the root entry — it imports neither package — so any consumer can read it without installing the `./alchemy` subpath's peers.
803
803
 
804
804
  `assertAlchemyBaseline({ packageJson })` is a consumer contract helper: it fails when the consumer's own `dependencies` or `devDependencies` pin `alchemy` or `effect` to anything other than the baseline, and it fails when only one of the pair is present. Alchemy peers on Effect, so an unpinned auto-installed Effect can drift outside the baseline while a lone `alchemy` pin would otherwise pass. Both packages remaining absent is not drift — they are optional peers of the subpath, so a consumer that never imports it, such as this package's own CLI, carries neither and passes. The pin is exact, not a range: the fleet is pre-1.0 and moves together, so a range would let one project drift silently ahead of or behind the rest. `assertAlchemyBaseline` reads only the object it is handed; it never walks the filesystem or reads a lockfile. Call it from a consumer's own contract test, passing that consumer's parsed `package.json`.
805
805
 
@@ -1,3 +1,3 @@
1
1
  {
2
- "fingerprint": "89c0b72f65fa82d2e6d93588accde1f05676b0512c27e5b959c4cf83993d3873"
2
+ "fingerprint": "5fb898a6c12742fa0bce46740c73196710cd687d4cc29e4874f91067083ef1e3"
3
3
  }
@@ -744,7 +744,7 @@ declare const isAlchemyLifecycleError: (error: unknown) => error is AlchemyLifec
744
744
  * The renderer logs every line through Effect's pretty console logger, so a
745
745
  * line arrives as `[HH:MM:SS.mmm] INFO (#1): <line>`, and coloured when the
746
746
  * child inherits `FORCE_COLOR`. Both wrappers are stripped before a line is
747
- * read. The captured output under `tests/fixtures/plan-output/beta-77/` is
747
+ * read. The captured output under `tests/fixtures/plan-output/beta-81/` is
748
748
  * the evidence for every shape this file reads.
749
749
  *
750
750
  * The adapter fails on anything it does not recognise: no summary, two
@@ -1,4 +1,4 @@
1
- import { i as isLocalPreviewStage, n as executeAlchemyEntry, r as resolveAlchemyChildCwd, s as ALCHEMY_BASELINE } from "../execute-alchemy-entry-CZ7Knz4q.js";
1
+ import { i as isLocalPreviewStage, n as executeAlchemyEntry, r as resolveAlchemyChildCwd, s as ALCHEMY_BASELINE } from "../execute-alchemy-entry-B0lBN-YZ.js";
2
2
  import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
  import { createHash } from "node:crypto";
@@ -585,7 +585,7 @@ const assertDestroyLeftNothing = async ({ stack, stage, stateReader }) => {
585
585
  * The renderer logs every line through Effect's pretty console logger, so a
586
586
  * line arrives as `[HH:MM:SS.mmm] INFO (#1): <line>`, and coloured when the
587
587
  * child inherits `FORCE_COLOR`. Both wrappers are stripped before a line is
588
- * read. The captured output under `tests/fixtures/plan-output/beta-77/` is
588
+ * read. The captured output under `tests/fixtures/plan-output/beta-81/` is
589
589
  * the evidence for every shape this file reads.
590
590
  *
591
591
  * The adapter fails on anything it does not recognise: no summary, two
@@ -12,8 +12,8 @@ import { spawnSync } from "node:child_process";
12
12
  * `effect`, so it ships from the root entry, not the `./alchemy` subpath.
13
13
  */
14
14
  const ALCHEMY_BASELINE = {
15
- alchemy: "2.0.0-beta.77",
16
- effect: "4.0.0-rc.112"
15
+ alchemy: "2.0.0-beta.81",
16
+ effect: "4.0.1"
17
17
  };
18
18
  const BASELINE_PACKAGE_NAMES = Object.keys(ALCHEMY_BASELINE);
19
19
  /**
package/dist/index.d.ts CHANGED
@@ -12,8 +12,8 @@ import { StdioOptions } from "node:child_process";
12
12
  * `effect`, so it ships from the root entry, not the `./alchemy` subpath.
13
13
  */
14
14
  declare const ALCHEMY_BASELINE: {
15
- readonly alchemy: "2.0.0-beta.77";
16
- readonly effect: "4.0.0-rc.112";
15
+ readonly alchemy: "2.0.0-beta.81";
16
+ readonly effect: "4.0.1";
17
17
  };
18
18
  /**
19
19
  * The slice of a consumer's `package.json` that carries the pins this
@@ -551,9 +551,10 @@ declare class GitHubAppTokenTransportError extends Error {
551
551
  * — when it has been recorded — which installation to mint against.
552
552
  *
553
553
  * `installationId` is optional because the installation is discoverable from
554
- * the repository. `privateKeyPath` is a path rather than key material so no
555
- * consumer has to hold a secret in memory to call this, and so the key-path
556
- * convention stays the consumer's.
554
+ * the repository. When it is set, the mint still looks it up to confirm its
555
+ * account owns the repository. `privateKeyPath` is a path rather than key
556
+ * material so no consumer has to hold a secret in memory to call this, and so
557
+ * the key-path convention stays the consumer's.
557
558
  */
558
559
  interface GithubAppCredentials {
559
560
  appId: number | string;
@@ -610,8 +611,12 @@ declare const githubAppJwt: (credentials: GithubAppCredentials, options?: Pick<G
610
611
  *
611
612
  * When the credentials omit `installationId`, the installation is discovered
612
613
  * from the repository first — the same call every consumer had written for
613
- * itself. Nothing is cached: the token is returned to the caller and this
614
- * module keeps no copy.
614
+ * itself. A pinned `installationId` is looked up instead, and the mint is
615
+ * refused unless that installation's account is the repository owner (GitHub
616
+ * logins compare case-insensitively): a `repositories` restriction names
617
+ * repositories without an owner, so a pin for one account must not mint for
618
+ * a same-named repository under another (#1428). Nothing is cached: the token
619
+ * is returned to the caller and this module keeps no copy.
615
620
  */
616
621
  declare const mintInstallationToken: (input: {
617
622
  credentials: GithubAppCredentials;
@@ -743,7 +748,11 @@ declare const FACTORY_PROOF_GATE_IF = "github.event_name == 'pull_request'";
743
748
  * - `unreadable` it passed but carries no binding for this repository and head
744
749
  * - `incomplete` its executed plus stamp-authorized released commands do not
745
750
  * cover every required command
746
- * - `ambiguous` two newest generations share the greatest start time
751
+ * - `ambiguous` two different generations share the newest instant, the
752
+ * newest repeats another run's verdict with no proof time to
753
+ * tell them apart, a run's start time cannot be ranked, or the
754
+ * newest pass started before another run at this head was
755
+ * posted
747
756
  * - `error` the gate could not reach a decision (fail open)
748
757
  *
749
758
  * There is no `reduced`: mode stopped being an authorization condition in
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as bundleAlchemyEntry } from "./bundle-alchemy-entry-CT5hCphA.js";
2
- import { a as localPreviewStage, c as assertAlchemyBaseline, i as isLocalPreviewStage, n as executeAlchemyEntry, o as parseLocalPreviewStage, s as ALCHEMY_BASELINE, t as EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER } from "./execute-alchemy-entry-CZ7Knz4q.js";
2
+ import { a as localPreviewStage, c as assertAlchemyBaseline, i as isLocalPreviewStage, n as executeAlchemyEntry, o as parseLocalPreviewStage, s as ALCHEMY_BASELINE, t as EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER } from "./execute-alchemy-entry-B0lBN-YZ.js";
3
3
  import { createRequire } from "node:module";
4
4
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
5
5
  import path from "node:path";
@@ -353,13 +353,23 @@ const githubAppJson = (request, url, jwt, method, budget) => githubJson$1({
353
353
  refusal: (status, statusText) => new GitHubApiError(status, statusText),
354
354
  transport: (failure, attempts) => new GitHubAppTokenTransportError(failure.reason, attempts, failure.status)
355
355
  });
356
+ const installationAccountLogin = (installation) => {
357
+ const { account } = installation;
358
+ if (typeof account !== "object" || account === null) return;
359
+ const { login } = account;
360
+ return typeof login === "string" ? login : void 0;
361
+ };
356
362
  /**
357
363
  * Mint an installation access token for one repository.
358
364
  *
359
365
  * When the credentials omit `installationId`, the installation is discovered
360
366
  * from the repository first — the same call every consumer had written for
361
- * itself. Nothing is cached: the token is returned to the caller and this
362
- * module keeps no copy.
367
+ * itself. A pinned `installationId` is looked up instead, and the mint is
368
+ * refused unless that installation's account is the repository owner (GitHub
369
+ * logins compare case-insensitively): a `repositories` restriction names
370
+ * repositories without an owner, so a pin for one account must not mint for
371
+ * a same-named repository under another (#1428). Nothing is cached: the token
372
+ * is returned to the caller and this module keeps no copy.
363
373
  */
364
374
  const mintInstallationToken = async (input, options = {}) => {
365
375
  const { credentials } = input;
@@ -374,6 +384,10 @@ const mintInstallationToken = async (input, options = {}) => {
374
384
  const installation = await githubAppJson(request, `https://api.github.com/repos/${input.owner}/${input.repo}/installation`, jwt, "GET", budget);
375
385
  if (typeof installation.id !== "number") throw new TypeError("GitHub App installation response omitted id");
376
386
  installationId = installation.id;
387
+ } else {
388
+ const accountLogin = installationAccountLogin(await githubAppJson(request, `https://api.github.com/app/installations/${installationId}`, jwt, "GET", budget));
389
+ if (accountLogin === void 0) throw new TypeError("GitHub App installation response omitted account login");
390
+ if (accountLogin.toLowerCase() !== input.owner.toLowerCase()) throw new Error(`GitHub App installation ${installationId} belongs to ${accountLogin}, not ${input.owner}; refusing to mint a token for ${input.owner}/${input.repo}`);
377
391
  }
378
392
  const restriction = input.permissions === void 0 && input.repositories === void 0 ? void 0 : JSON.stringify({
379
393
  ...input.permissions === void 0 ? {} : { permissions: input.permissions },
@@ -518,7 +532,11 @@ const FACTORY_PROOF_GATE_IF = "github.event_name == 'pull_request'";
518
532
  * - `unreadable` it passed but carries no binding for this repository and head
519
533
  * - `incomplete` its executed plus stamp-authorized released commands do not
520
534
  * cover every required command
521
- * - `ambiguous` two newest generations share the greatest start time
535
+ * - `ambiguous` two different generations share the newest instant, the
536
+ * newest repeats another run's verdict with no proof time to
537
+ * tell them apart, a run's start time cannot be ranked, or the
538
+ * newest pass started before another run at this head was
539
+ * posted
522
540
  * - `error` the gate could not reach a decision (fail open)
523
541
  *
524
542
  * There is no `reduced`: mode stopped being an authorization condition in
@@ -558,6 +576,24 @@ const COMMAND_IDENTITY_MAX_LENGTH = 120;
558
576
  * lockstep with the proof/check-payload producer.
559
577
  */
560
578
  const TRUSTED_IMPACT_STAMP_VERSION = 4;
579
+ /**
580
+ * The verify modes the CLI reads a payload under (`isResolvedPrVerifyMode` in
581
+ * `software-factory/src/pr-verify-mode.ts`). factory-ci cannot import it, so
582
+ * the list is repeated here, and the software-factory differential suite pins
583
+ * the two lists together (#1510).
584
+ */
585
+ const RESOLVED_VERIFY_MODES = [
586
+ "docs-only",
587
+ "trivial",
588
+ "full"
589
+ ];
590
+ /**
591
+ * The check-text size over which the CLI drops a transported typed proof
592
+ * (`readTransportedVerifyProof` in
593
+ * `software-factory/src/pr-verify-check-payload.ts`), in UTF-8 bytes of the
594
+ * raw text it parsed, fence included (#1510).
595
+ */
596
+ const TRANSPORT_CAP_BYTES = 6e4;
561
597
  const isProofReuseCommand = (value) => {
562
598
  if (!(value && typeof value === "object")) return false;
563
599
  const entry = value;
@@ -642,46 +678,229 @@ const resolveProofReuseCommands = (catalog, names, selectionLabel) => names.map(
642
678
  * document. Anything unparseable degrades to `null`, and therefore to a
643
679
  * refusal.
644
680
  *
645
- * This is the *second* parser of that payload: `parsePrVerifyCheckPayload`
681
+ * This is the *second* parser of that payload, and it does not reimplement
682
+ * the first: `parsePrVerifyCheckPayload`
646
683
  * (`software-factory/src/pr-verify-check-payload.ts`) regex-extracts the fenced
647
- * block, while this one strips fence lines and `fromjson`s what remains. The
648
- * one input that separates them is prose around the fence, which parses there
649
- * and refuses here. Both halves of that are asserted in the test suite rather
650
- * than asserted here in prose — the exact shape the renderer emits is proven,
651
- * and the divergent shape is proven to fail safe. Two parsers of one payload
652
- * can drift; what must not drift silently is which direction they drift in.
684
+ * block up to the next line that starts with a fence and `JSON.parse`s it,
685
+ * while this one strips every such line and `fromjson`s what remains. The
686
+ * writer renders JSON, whose strings hold no raw line feed, between one
687
+ * opening and one closing fence line, so on its text the two read the same
688
+ * JSON, three backticks inside a string included. On other text they can
689
+ * differ in either direction. Prose around the fence parses there and refuses
690
+ * here; the test suite asserts that the exact shape the renderer emits is
691
+ * proven here and that the prose-wrapped shape refuses. Text that parses here
692
+ * and not there is part of the trust boundary below.
693
+ *
694
+ * Once parsed, a payload is read by the CLI's readability rules (#1510).
695
+ * `bound` requires the binding's
696
+ * `kind`, `schemaVersion` 1, this head, this repository and a resolved verify
697
+ * mode (`resolvedMode`, the CLI's `isResolvedPrVerifyMode`), and the verdict
698
+ * stage refuses a run that is not `bound` as `unreadable`; an `outcome` other
699
+ * than `passed` is never a pass. `binding` drops a transported typed proof
700
+ * (`verificationProof`) when the text it parsed, fence included, is over
701
+ * 60,000 UTF-8 bytes, as `readTransportedVerifyProof` does, so the run is a
702
+ * pass with no typed proof to both readers. On text the writer never emits,
703
+ * this reader can still read a payload differently; see the trust boundary
704
+ * below.
705
+ *
706
+ * A passing generation is ordered by when its verification started, never
707
+ * later than when its run reached GitHub and never by when its verification
708
+ * ended (#1409, #1490). Every other run is ordered by when it reached GitHub
709
+ * (#1506). It is the rule `fetchPrVerifyProofBinding` applies
710
+ * (`software-factory/src/github-check-runs.ts`), mirrored here because this
711
+ * reader is jq in generated CI and cannot import it:
712
+ *
713
+ * - A passing run (`passing`) is completed with conclusion `success`, and its
714
+ * binding is bound to this head and repository with outcome `passed`. When it
715
+ * transports a typed proof (`verificationProof`) whose start is computable
716
+ * (`proofStart`: its `endedAt` minus its `durationMs`), it is ordered at that
717
+ * start, or at its own `started_at` when that is earlier. Such runs with the
718
+ * same binding, status and conclusion are one generation posted more than
719
+ * once (`pr:verify` posts, `pr:publish` re-posts), ordered at the earliest of
720
+ * its members' instants, whatever order GitHub serves them in. A re-post does
721
+ * not move the proof's start, so a re-post of an older pass never outranks a
722
+ * newer failure, and a post plus its re-post is no tie.
723
+ * - Any other run is its own generation at its `started_at`: one still
724
+ * running, a failure or cancellation whether or not it carries a proof, an
725
+ * unbound one, or a pass with no usable typed proof (over the text cap,
726
+ * written before proofs travelled, or with no computable start). A run is
727
+ * created no earlier than its verification began, so `started_at` is an
728
+ * upper bound on that start. Ranking there can only make such a run newer
729
+ * than it is, so it vetoes more, never less.
730
+ * - Neither `endedAt` nor a passing run's `started_at` is its start. The
731
+ * factory posts a `pr-verify` run only once verification has finished, so
732
+ * both say when it ended, and an older pass ordered there would hide a run
733
+ * that started after the pass began: still running, or failed (#1490). A
734
+ * pass's `started_at` only caps its proof's start. A failure's `started_at`
735
+ * is when it was posted, not when it started, and that is deliberate: a
736
+ * veto's instant only has to be no earlier than its start.
737
+ * - Only a pass is ordered by its proof because this reader cannot run the
738
+ * proof schema (#1506). The CLI drops a payload whose proof fails that
739
+ * schema and orders the run at its `started_at`; ordered by its proof's
740
+ * claimed start, a failure carrying a malformed proof ranked under an older
741
+ * pass here, and the gate returned `proven` where the CLI refused. For an
742
+ * honest proof, `started_at` is no earlier than `endedAt`, which is no
743
+ * earlier than the start, so the cap changes nothing for a valid pass.
744
+ * - A pass is reused only when its verification started strictly after every
745
+ * other run at this head was posted (#1506). Its start is its instant: its
746
+ * proof's start, capped as above, or its `started_at` when it is ordered
747
+ * there. Every other run's post is its `started_at`, rounded down to the
748
+ * whole second. Only the pass's own generation is left out: its re-post
749
+ * group, or, for a pass with no typed proof, that run alone
750
+ * (`ownGeneration`). At most one generation can satisfy this, and that one
751
+ * is the newest, so the gate selects the newest generation and, when it is
752
+ * a pass (`passing`), refuses it as `ambiguous` unless every other run was
753
+ * posted before its instant. When the newest generation is not a pass, the
754
+ * verdict is a refusal anyway, so its reason (`failed`, `pending`, ...)
755
+ * stands and the check does not run.
756
+ * - The check exists because any other run may be ordered earlier than its
757
+ * post by a proof this reader cannot validate: a pass that only claims
758
+ * `passed` looks to jq exactly like one the CLI validates. Without it, a
759
+ * successful run whose malformed proof claimed an early start ranked under
760
+ * an older pass, whether that pass was ordered by its proof or at its
761
+ * `started_at`, and the gate reused the older pass where the CLI, which
762
+ * drops that payload and ranks the run at its `started_at`, refused. With
763
+ * it, whether a pass may be reused never consults another run's proof
764
+ * fields, only when each other run was posted, which GitHub records. Those
765
+ * fields can only cause a refusal; they never hide a veto. The pass's own
766
+ * clock is capped at its post, so it can only count against that pass.
767
+ * - Two changes on valid input follow, and both only add refusals, each
768
+ * costing one hosted run in a rare case. A failure carrying a proof is
769
+ * ordered when it was posted instead of when it started, so an older failure
770
+ * that finished after a newer pass began now refuses reuse. Two pass
771
+ * generations whose verifications overlapped now refuse, as does an older
772
+ * pass re-posted after a newer pass started. Passes that ran one after the
773
+ * other, and a pass with its own re-posts, are reused as before.
774
+ * - The hosted gate's trust boundary is a class. This reader does not
775
+ * reimplement the CLI's payload parser. On payloads the factory's writer
776
+ * emits, both readers select the same pass or both refuse: the differential
777
+ * suite, `software-factory/src/pr-verify-reuse-differential.test.ts`,
778
+ * asserts it over 9,653 generated run sets. On App-signed text the writer
779
+ * never emits, the two can differ in either direction. The known instances
780
+ * where this gate reuses and the CLI refuses are: (a) a reused run whose
781
+ * typed proof fails `validatePrVerifyProof`; (b) a newest pass that repeats
782
+ * another run's verdict only once the CLI normalizes that run's payload, say
783
+ * by dropping a key, since the CLI compares normalized payloads and this
784
+ * reader raw ones; (c) a payload in `output.summary` beside a text payload
785
+ * the CLI cannot read, which the CLI reads from the summary and this reader
786
+ * from the text; (d) text that this reader's strip-and-`fromjson` reads and
787
+ * the CLI's fence match or `JSON.parse` refuses, such as a closing fence
788
+ * with no opening one, a doubled opening fence, a fence line inside the
789
+ * JSON, a payload split across two fenced blocks, or a number literal such
790
+ * as `NaN` where the jq in use accepts it (jq 1.8 does). Mirroring any of it
791
+ * would turn this reader into a parser. Only the factory App can post the
792
+ * run, and that identity bounds the whole class (#1511).
793
+ * - A run not ordered by a typed proof carries no generation identity, so it
794
+ * is never grouped. Two separate executions with the same command names and
795
+ * verdict post the same compact binding, and so does a re-post. When the
796
+ * newest generation is one of these and repeats another run's verdict
797
+ * (binding, status and conclusion), it could be a re-post of an older
798
+ * verdict or a new one, so it is `ambiguous`. Proofs that size are rare;
799
+ * refusing costs a hosted run.
800
+ *
801
+ * Two different generations that share the newest instant are `ambiguous`
802
+ * rather than arbitrarily resolved: the gate cannot tell which one describes
803
+ * the tree, and silently picking either is exactly the kind of coin-flip
804
+ * authorization this whole mechanism exists to remove.
653
805
  *
654
- * Ordering is by `started_at` alone, normalized to whole seconds. Two
655
- * generations that share the greatest start time are `ambiguous` rather than
656
- * arbitrarily resolved: the gate cannot tell which one describes the tree, and
657
- * silently picking either is exactly the kind of coin-flip authorization this
658
- * whole mechanism exists to remove. Sub-second precision is dropped so
659
- * `…:00Z` and `…:00.000Z` compare equal; two genuine verification generations
660
- * starting within the same second at the same head is not a real state, and
661
- * collapsing them errs toward refusing.
806
+ * Every instant is a whole epoch second, rounded down. A `started_at` keeps
807
+ * its whole second, so `…:00Z` and `…:00.500Z` compare equal. A proof's start
808
+ * is `floor((endedAt - durationMs) / 1000)` with `endedAt` in epoch
809
+ * milliseconds, its fraction read to the millisecond the way `Date.parse`
810
+ * reads it. Rounding down is monotonic, so it can merge two instants into a
811
+ * tie, which is `ambiguous`, but never invert them. It also fails closed: a
812
+ * proof's start never moves later, so it never outranks an unbound run in the
813
+ * same second. The TypeScript reader rounds the same way, so the two agree on
814
+ * every canonical instant. Two genuine verification generations within the
815
+ * same second at the same head is not a real state.
662
816
  *
663
- * The comparison is lexical, which is correct only for fixed-width UTC. A
664
- * `+HH:MM` offset would sort by its literal text rather than by its instant,
665
- * and an absent `started_at` would sort to the bottom. The Checks API returns
666
- * neither today, so this is guarded rather than merely noted: every candidate
667
- * must carry a canonical UTC timestamp, and one that does not makes the newest
668
- * generation unestablishable, which is `ambiguous`. Refusing costs a hosted
669
- * run; ranking an unorderable set could authorize the wrong one.
817
+ * `fromdateiso8601` reads only canonical UTC, and the gate never asks it to
818
+ * read anything else. Every candidate must carry a canonical UTC
819
+ * `started_at`, and one that does not makes the newest generation
820
+ * unestablishable, which is `ambiguous`. A typed proof whose `endedAt` is not
821
+ * canonical UTC, or whose `durationMs` is missing or not a finite non-negative
822
+ * number, records no start, and its run falls back to `started_at` like any
823
+ * other run without a typed proof. Refusing costs a hosted run; ranking an
824
+ * unorderable set could authorize the wrong one.
670
825
  */
671
826
  const GATE_JQ = String.raw`
672
827
  def binding:
673
828
  [ .output.text, .output.summary ]
674
829
  | map(select(type == "string"))
675
- | map(split("\n") | map(select(startswith("${"```"}") | not)) | join("\n"))
676
- | map(. as $body | try ($body | fromjson) catch null)
677
- | map(select(type == "object"))
830
+ | map(. as $text
831
+ | (split("\n") | map(select(startswith("${"```"}") | not)) | join("\n")
832
+ | try fromjson catch null)
833
+ | select(type == "object")
834
+ | if ($text | utf8bytelength) > ${TRANSPORT_CAP_BYTES}
835
+ then del(.verificationProof)
836
+ else .
837
+ end)
678
838
  | .[0];
679
839
 
840
+ def resolvedMode:
841
+ IN(${RESOLVED_VERIFY_MODES.map((mode) => JSON.stringify(mode)).join(", ")});
842
+
680
843
  def startedAt: (.started_at // "") | tostring;
681
844
 
682
845
  def rankable:
683
846
  test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z$");
684
847
 
848
+ def wholeSecond: sub("\\.[0-9]+Z$"; "Z");
849
+
850
+ def epochSecond:
851
+ if type == "string" and rankable
852
+ then (try (wholeSecond | fromdateiso8601) catch null)
853
+ else null
854
+ end;
855
+
856
+ def millisecondPart:
857
+ ((capture("\\.(?<digits>[0-9]+)Z$") | .digits) // "") + "000"
858
+ | .[0:3]
859
+ | tonumber;
860
+
861
+ def bound:
862
+ (.binding | type) == "object"
863
+ and .binding.kind == "pr-verify-proof-binding"
864
+ and .binding.schemaVersion == 1
865
+ and .binding.headSha == $sha
866
+ and .binding.repository == $repository
867
+ and (.binding.mode | resolvedMode);
868
+
869
+ def passing:
870
+ .status == "completed"
871
+ and .conclusion == "success"
872
+ and bound
873
+ and .binding.outcome == "passed";
874
+
875
+ def proofStart:
876
+ if bound and (.binding.verificationProof | type) == "object" then
877
+ .binding.verificationProof as $proof
878
+ | ($proof.endedAt | epochSecond) as $ended
879
+ | $proof.durationMs as $duration
880
+ | if $ended != null
881
+ and ($duration | type) == "number"
882
+ and ($duration | isinfinite | not)
883
+ and $duration >= 0
884
+ then ($ended * 1000 + ($proof.endedAt | millisecondPart) - $duration)
885
+ / 1000
886
+ | floor
887
+ else null
888
+ end
889
+ else null
890
+ end;
891
+
892
+ def sameVerdict($other):
893
+ bound
894
+ and .status == $other.status
895
+ and .conclusion == $other.conclusion
896
+ and .binding == $other.binding;
897
+
898
+ def ownGeneration($generation):
899
+ if $generation.recorded
900
+ then .recorded and sameVerdict($generation)
901
+ else .index == $generation.index
902
+ end;
903
+
685
904
  def nonemptyString:
686
905
  type == "string" and length > 0;
687
906
 
@@ -706,12 +925,33 @@ def releaseAuthorized($release; $commands; $stamp):
706
925
  url: ((.html_url // "") | tostring),
707
926
  binding: binding }
708
927
  ] as $runs
709
- | ($runs | map(.started | rankable) | all) as $orderable
710
- | ($runs | map(.started | sub("\\.[0-9]+Z$"; "Z")) | max) as $newest
711
- | [ $runs[] | select((.started | sub("\\.[0-9]+Z$"; "Z")) == $newest) ] as $generation
928
+ | ($runs | map(.started | epochSecond != null) | all) as $orderable
929
+ | [ range(0; $runs | length) as $index
930
+ | $runs[$index]
931
+ | (.started | epochSecond) as $posted
932
+ | (if passing then proofStart else null end) as $start
933
+ | . + { at: ([$start, $posted] | map(select(. != null)) | min),
934
+ index: $index,
935
+ recorded: ($start != null) }
936
+ ] as $observed
937
+ | ( [ $observed[] | select(.recorded | not) ]
938
+ + ( [ $observed[] | select(.recorded) ]
939
+ | group_by([.status, .conclusion, .binding])
940
+ | map(.[0] + { at: (map(.at) | min) }) ) ) as $generations
941
+ | ($generations | map(.at) | max) as $newest
942
+ | [ $generations[] | select(.at == $newest) ] as $generation
712
943
  | (if ($runs | length) == 0 then ["none", "", "", ""]
713
944
  elif ($orderable | not) then ["ambiguous", "", "", ""]
714
945
  elif ($generation | length) != 1 then ["ambiguous", "", "", ""]
946
+ elif ($generation[0] as $newestRun
947
+ | ($newestRun.recorded | not)
948
+ and ([ $runs[] | select(sameVerdict($newestRun)) ] | length) > 1)
949
+ then ["ambiguous", "", "", ""]
950
+ elif ($generation[0] as $newestRun
951
+ | ($newestRun | passing)
952
+ and any($observed[] | select(ownGeneration($newestRun) | not);
953
+ (.started | epochSecond) >= $newestRun.at))
954
+ then ["ambiguous", "", "", ""]
715
955
  else
716
956
  $generation[0] as $run
717
957
  | (if ($run.binding | type) == "object" then $run.binding else {} end) as $proof
@@ -761,11 +1001,7 @@ def releaseAuthorized($release; $commands; $stamp):
761
1001
  | ($required - $executed - $released) as $missing
762
1002
  | (if $run.status != "completed" then "pending"
763
1003
  elif $run.conclusion != "success" then "failed"
764
- elif (($run.binding | type) != "object")
765
- or ($proof.kind != "pr-verify-proof-binding")
766
- or ($proof.schemaVersion != 1)
767
- or ($proof.headSha != $sha)
768
- or ($proof.repository != $repository) then "unreadable"
1004
+ elif ($run | bound | not) then "unreadable"
769
1005
  elif $proof.outcome != "passed" then "failed"
770
1006
  elif ($required | length) == 0 then "incomplete"
771
1007
  elif ($releasesValid | not) then "incomplete"
@@ -966,7 +1202,7 @@ case "$reason" in
966
1202
  ambiguous)
967
1203
  say 'Ran the full suite. The newest factory proof for this commit is ambiguous.'
968
1204
  say ''
969
- 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."
1205
+ 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, a run's start time cannot be ranked, or the newest pass started before another run at this head was posted, so there is no single newest generation to trust. The gate refuses rather than picking one."
970
1206
  say ''
971
1207
  say '${CORRECTIVE_LINE}'
972
1208
  ;;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@patronage/factory-ci",
3
- "version": "1.0.0-alpha.40",
3
+ "version": "1.0.0-alpha.42",
4
4
  "description": "Deep CI and deploy building blocks for Patronage factory projects: workflow source artifacts, hosted diff classification, Alchemy entry execution, and disposable-stage semantics",
5
5
  "keywords": [
6
6
  "alchemy",
@@ -40,8 +40,8 @@
40
40
  "devDependencies": {
41
41
  "@types/node": "24.13.3",
42
42
  "@vitest/coverage-v8": "4.1.10",
43
- "alchemy": "2.0.0-beta.77",
44
- "effect": "4.0.0-rc.112",
43
+ "alchemy": "2.0.0-beta.81",
44
+ "effect": "4.0.1",
45
45
  "knip": "6.27.0",
46
46
  "oxfmt": "0.59.0",
47
47
  "oxlint": "1.76.0",
@@ -15,7 +15,7 @@
15
15
  * The renderer logs every line through Effect's pretty console logger, so a
16
16
  * line arrives as `[HH:MM:SS.mmm] INFO (#1): <line>`, and coloured when the
17
17
  * child inherits `FORCE_COLOR`. Both wrappers are stripped before a line is
18
- * read. The captured output under `tests/fixtures/plan-output/beta-77/` is
18
+ * read. The captured output under `tests/fixtures/plan-output/beta-81/` is
19
19
  * the evidence for every shape this file reads.
20
20
  *
21
21
  * The adapter fails on anything it does not recognise: no summary, two
@@ -8,8 +8,8 @@
8
8
  * `effect`, so it ships from the root entry, not the `./alchemy` subpath.
9
9
  */
10
10
  export const ALCHEMY_BASELINE = {
11
- alchemy: "2.0.0-beta.77",
12
- effect: "4.0.0-rc.112",
11
+ alchemy: "2.0.0-beta.81",
12
+ effect: "4.0.1",
13
13
  } as const;
14
14
 
15
15
  /**
@@ -36,9 +36,10 @@ const JWT_LIFETIME_SECONDS = 600;
36
36
  * — when it has been recorded — which installation to mint against.
37
37
  *
38
38
  * `installationId` is optional because the installation is discoverable from
39
- * the repository. `privateKeyPath` is a path rather than key material so no
40
- * consumer has to hold a secret in memory to call this, and so the key-path
41
- * convention stays the consumer's.
39
+ * the repository. When it is set, the mint still looks it up to confirm its
40
+ * account owns the repository. `privateKeyPath` is a path rather than key
41
+ * material so no consumer has to hold a secret in memory to call this, and so
42
+ * the key-path convention stays the consumer's.
42
43
  */
43
44
  export interface GithubAppCredentials {
44
45
  appId: number | string;
@@ -160,13 +161,28 @@ export const setGithubAppTokenTransportWaitForTests = (
160
161
  setGithubTransportWaitForTests(next);
161
162
  };
162
163
 
164
+ const installationAccountLogin = (
165
+ installation: Record<string, unknown>
166
+ ): string | undefined => {
167
+ const { account } = installation;
168
+ if (typeof account !== "object" || account === null) {
169
+ return undefined;
170
+ }
171
+ const { login } = account as { login?: unknown };
172
+ return typeof login === "string" ? login : undefined;
173
+ };
174
+
163
175
  /**
164
176
  * Mint an installation access token for one repository.
165
177
  *
166
178
  * When the credentials omit `installationId`, the installation is discovered
167
179
  * from the repository first — the same call every consumer had written for
168
- * itself. Nothing is cached: the token is returned to the caller and this
169
- * module keeps no copy.
180
+ * itself. A pinned `installationId` is looked up instead, and the mint is
181
+ * refused unless that installation's account is the repository owner (GitHub
182
+ * logins compare case-insensitively): a `repositories` restriction names
183
+ * repositories without an owner, so a pin for one account must not mint for
184
+ * a same-named repository under another (#1428). Nothing is cached: the token
185
+ * is returned to the caller and this module keeps no copy.
170
186
  */
171
187
  export const mintInstallationToken = async (
172
188
  input: {
@@ -209,6 +225,25 @@ export const mintInstallationToken = async (
209
225
  throw new TypeError("GitHub App installation response omitted id");
210
226
  }
211
227
  installationId = installation.id;
228
+ } else {
229
+ const pinned = await githubAppJson(
230
+ request,
231
+ `https://api.github.com/app/installations/${installationId}`,
232
+ jwt,
233
+ "GET",
234
+ budget
235
+ );
236
+ const accountLogin = installationAccountLogin(pinned);
237
+ if (accountLogin === undefined) {
238
+ throw new TypeError(
239
+ "GitHub App installation response omitted account login"
240
+ );
241
+ }
242
+ if (accountLogin.toLowerCase() !== input.owner.toLowerCase()) {
243
+ throw new Error(
244
+ `GitHub App installation ${installationId} belongs to ${accountLogin}, not ${input.owner}; refusing to mint a token for ${input.owner}/${input.repo}`
245
+ );
246
+ }
212
247
  }
213
248
 
214
249
  const restriction =
@@ -146,7 +146,11 @@ export const FACTORY_PROOF_GATE_IF = "github.event_name == 'pull_request'";
146
146
  * - `unreadable` it passed but carries no binding for this repository and head
147
147
  * - `incomplete` its executed plus stamp-authorized released commands do not
148
148
  * cover every required command
149
- * - `ambiguous` two newest generations share the greatest start time
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, a run's start time cannot be ranked, or the
152
+ * newest pass started before another run at this head was
153
+ * posted
150
154
  * - `error` the gate could not reach a decision (fail open)
151
155
  *
152
156
  * There is no `reduced`: mode stopped being an authorization condition in
@@ -203,6 +207,22 @@ const COMMAND_IDENTITY_MAX_LENGTH = 120;
203
207
  */
204
208
  const TRUSTED_IMPACT_STAMP_VERSION = 4;
205
209
 
210
+ /**
211
+ * The verify modes the CLI reads a payload under (`isResolvedPrVerifyMode` in
212
+ * `software-factory/src/pr-verify-mode.ts`). factory-ci cannot import it, so
213
+ * the list is repeated here, and the software-factory differential suite pins
214
+ * the two lists together (#1510).
215
+ */
216
+ const RESOLVED_VERIFY_MODES = ["docs-only", "trivial", "full"] as const;
217
+
218
+ /**
219
+ * The check-text size over which the CLI drops a transported typed proof
220
+ * (`readTransportedVerifyProof` in
221
+ * `software-factory/src/pr-verify-check-payload.ts`), in UTF-8 bytes of the
222
+ * raw text it parsed, fence included (#1510).
223
+ */
224
+ const TRANSPORT_CAP_BYTES = 60_000;
225
+
206
226
  const isProofReuseCommand = (value: unknown): value is ProofReuseCommand => {
207
227
  if (!(value && typeof value === "object")) {
208
228
  return false;
@@ -312,46 +332,229 @@ export const resolveProofReuseCommands = (
312
332
  * document. Anything unparseable degrades to `null`, and therefore to a
313
333
  * refusal.
314
334
  *
315
- * This is the *second* parser of that payload: `parsePrVerifyCheckPayload`
335
+ * This is the *second* parser of that payload, and it does not reimplement
336
+ * the first: `parsePrVerifyCheckPayload`
316
337
  * (`software-factory/src/pr-verify-check-payload.ts`) regex-extracts the fenced
317
- * block, while this one strips fence lines and `fromjson`s what remains. The
318
- * one input that separates them is prose around the fence, which parses there
319
- * and refuses here. Both halves of that are asserted in the test suite rather
320
- * than asserted here in prose — the exact shape the renderer emits is proven,
321
- * and the divergent shape is proven to fail safe. Two parsers of one payload
322
- * can drift; what must not drift silently is which direction they drift in.
338
+ * block up to the next line that starts with a fence and `JSON.parse`s it,
339
+ * while this one strips every such line and `fromjson`s what remains. The
340
+ * writer renders JSON, whose strings hold no raw line feed, between one
341
+ * opening and one closing fence line, so on its text the two read the same
342
+ * JSON, three backticks inside a string included. On other text they can
343
+ * differ in either direction. Prose around the fence parses there and refuses
344
+ * here; the test suite asserts that the exact shape the renderer emits is
345
+ * proven here and that the prose-wrapped shape refuses. Text that parses here
346
+ * and not there is part of the trust boundary below.
347
+ *
348
+ * Once parsed, a payload is read by the CLI's readability rules (#1510).
349
+ * `bound` requires the binding's
350
+ * `kind`, `schemaVersion` 1, this head, this repository and a resolved verify
351
+ * mode (`resolvedMode`, the CLI's `isResolvedPrVerifyMode`), and the verdict
352
+ * stage refuses a run that is not `bound` as `unreadable`; an `outcome` other
353
+ * than `passed` is never a pass. `binding` drops a transported typed proof
354
+ * (`verificationProof`) when the text it parsed, fence included, is over
355
+ * 60,000 UTF-8 bytes, as `readTransportedVerifyProof` does, so the run is a
356
+ * pass with no typed proof to both readers. On text the writer never emits,
357
+ * this reader can still read a payload differently; see the trust boundary
358
+ * below.
359
+ *
360
+ * A passing generation is ordered by when its verification started, never
361
+ * later than when its run reached GitHub and never by when its verification
362
+ * ended (#1409, #1490). Every other run is ordered by when it reached GitHub
363
+ * (#1506). It is the rule `fetchPrVerifyProofBinding` applies
364
+ * (`software-factory/src/github-check-runs.ts`), mirrored here because this
365
+ * reader is jq in generated CI and cannot import it:
366
+ *
367
+ * - A passing run (`passing`) is completed with conclusion `success`, and its
368
+ * binding is bound to this head and repository with outcome `passed`. When it
369
+ * transports a typed proof (`verificationProof`) whose start is computable
370
+ * (`proofStart`: its `endedAt` minus its `durationMs`), it is ordered at that
371
+ * start, or at its own `started_at` when that is earlier. Such runs with the
372
+ * same binding, status and conclusion are one generation posted more than
373
+ * once (`pr:verify` posts, `pr:publish` re-posts), ordered at the earliest of
374
+ * its members' instants, whatever order GitHub serves them in. A re-post does
375
+ * not move the proof's start, so a re-post of an older pass never outranks a
376
+ * newer failure, and a post plus its re-post is no tie.
377
+ * - Any other run is its own generation at its `started_at`: one still
378
+ * running, a failure or cancellation whether or not it carries a proof, an
379
+ * unbound one, or a pass with no usable typed proof (over the text cap,
380
+ * written before proofs travelled, or with no computable start). A run is
381
+ * created no earlier than its verification began, so `started_at` is an
382
+ * upper bound on that start. Ranking there can only make such a run newer
383
+ * than it is, so it vetoes more, never less.
384
+ * - Neither `endedAt` nor a passing run's `started_at` is its start. The
385
+ * factory posts a `pr-verify` run only once verification has finished, so
386
+ * both say when it ended, and an older pass ordered there would hide a run
387
+ * that started after the pass began: still running, or failed (#1490). A
388
+ * pass's `started_at` only caps its proof's start. A failure's `started_at`
389
+ * is when it was posted, not when it started, and that is deliberate: a
390
+ * veto's instant only has to be no earlier than its start.
391
+ * - Only a pass is ordered by its proof because this reader cannot run the
392
+ * proof schema (#1506). The CLI drops a payload whose proof fails that
393
+ * schema and orders the run at its `started_at`; ordered by its proof's
394
+ * claimed start, a failure carrying a malformed proof ranked under an older
395
+ * pass here, and the gate returned `proven` where the CLI refused. For an
396
+ * honest proof, `started_at` is no earlier than `endedAt`, which is no
397
+ * earlier than the start, so the cap changes nothing for a valid pass.
398
+ * - A pass is reused only when its verification started strictly after every
399
+ * other run at this head was posted (#1506). Its start is its instant: its
400
+ * proof's start, capped as above, or its `started_at` when it is ordered
401
+ * there. Every other run's post is its `started_at`, rounded down to the
402
+ * whole second. Only the pass's own generation is left out: its re-post
403
+ * group, or, for a pass with no typed proof, that run alone
404
+ * (`ownGeneration`). At most one generation can satisfy this, and that one
405
+ * is the newest, so the gate selects the newest generation and, when it is
406
+ * a pass (`passing`), refuses it as `ambiguous` unless every other run was
407
+ * posted before its instant. When the newest generation is not a pass, the
408
+ * verdict is a refusal anyway, so its reason (`failed`, `pending`, ...)
409
+ * stands and the check does not run.
410
+ * - The check exists because any other run may be ordered earlier than its
411
+ * post by a proof this reader cannot validate: a pass that only claims
412
+ * `passed` looks to jq exactly like one the CLI validates. Without it, a
413
+ * successful run whose malformed proof claimed an early start ranked under
414
+ * an older pass, whether that pass was ordered by its proof or at its
415
+ * `started_at`, and the gate reused the older pass where the CLI, which
416
+ * drops that payload and ranks the run at its `started_at`, refused. With
417
+ * it, whether a pass may be reused never consults another run's proof
418
+ * fields, only when each other run was posted, which GitHub records. Those
419
+ * fields can only cause a refusal; they never hide a veto. The pass's own
420
+ * clock is capped at its post, so it can only count against that pass.
421
+ * - Two changes on valid input follow, and both only add refusals, each
422
+ * costing one hosted run in a rare case. A failure carrying a proof is
423
+ * ordered when it was posted instead of when it started, so an older failure
424
+ * that finished after a newer pass began now refuses reuse. Two pass
425
+ * generations whose verifications overlapped now refuse, as does an older
426
+ * pass re-posted after a newer pass started. Passes that ran one after the
427
+ * other, and a pass with its own re-posts, are reused as before.
428
+ * - The hosted gate's trust boundary is a class. This reader does not
429
+ * reimplement the CLI's payload parser. On payloads the factory's writer
430
+ * emits, both readers select the same pass or both refuse: the differential
431
+ * suite, `software-factory/src/pr-verify-reuse-differential.test.ts`,
432
+ * asserts it over 9,653 generated run sets. On App-signed text the writer
433
+ * never emits, the two can differ in either direction. The known instances
434
+ * where this gate reuses and the CLI refuses are: (a) a reused run whose
435
+ * typed proof fails `validatePrVerifyProof`; (b) a newest pass that repeats
436
+ * another run's verdict only once the CLI normalizes that run's payload, say
437
+ * by dropping a key, since the CLI compares normalized payloads and this
438
+ * reader raw ones; (c) a payload in `output.summary` beside a text payload
439
+ * the CLI cannot read, which the CLI reads from the summary and this reader
440
+ * from the text; (d) text that this reader's strip-and-`fromjson` reads and
441
+ * the CLI's fence match or `JSON.parse` refuses, such as a closing fence
442
+ * with no opening one, a doubled opening fence, a fence line inside the
443
+ * JSON, a payload split across two fenced blocks, or a number literal such
444
+ * as `NaN` where the jq in use accepts it (jq 1.8 does). Mirroring any of it
445
+ * would turn this reader into a parser. Only the factory App can post the
446
+ * run, and that identity bounds the whole class (#1511).
447
+ * - A run not ordered by a typed proof carries no generation identity, so it
448
+ * is never grouped. Two separate executions with the same command names and
449
+ * verdict post the same compact binding, and so does a re-post. When the
450
+ * newest generation is one of these and repeats another run's verdict
451
+ * (binding, status and conclusion), it could be a re-post of an older
452
+ * verdict or a new one, so it is `ambiguous`. Proofs that size are rare;
453
+ * refusing costs a hosted run.
454
+ *
455
+ * Two different generations that share the newest instant are `ambiguous`
456
+ * rather than arbitrarily resolved: the gate cannot tell which one describes
457
+ * the tree, and silently picking either is exactly the kind of coin-flip
458
+ * authorization this whole mechanism exists to remove.
323
459
  *
324
- * Ordering is by `started_at` alone, normalized to whole seconds. Two
325
- * generations that share the greatest start time are `ambiguous` rather than
326
- * arbitrarily resolved: the gate cannot tell which one describes the tree, and
327
- * silently picking either is exactly the kind of coin-flip authorization this
328
- * whole mechanism exists to remove. Sub-second precision is dropped so
329
- * `…:00Z` and `…:00.000Z` compare equal; two genuine verification generations
330
- * starting within the same second at the same head is not a real state, and
331
- * collapsing them errs toward refusing.
460
+ * Every instant is a whole epoch second, rounded down. A `started_at` keeps
461
+ * its whole second, so `…:00Z` and `…:00.500Z` compare equal. A proof's start
462
+ * is `floor((endedAt - durationMs) / 1000)` with `endedAt` in epoch
463
+ * milliseconds, its fraction read to the millisecond the way `Date.parse`
464
+ * reads it. Rounding down is monotonic, so it can merge two instants into a
465
+ * tie, which is `ambiguous`, but never invert them. It also fails closed: a
466
+ * proof's start never moves later, so it never outranks an unbound run in the
467
+ * same second. The TypeScript reader rounds the same way, so the two agree on
468
+ * every canonical instant. Two genuine verification generations within the
469
+ * same second at the same head is not a real state.
332
470
  *
333
- * The comparison is lexical, which is correct only for fixed-width UTC. A
334
- * `+HH:MM` offset would sort by its literal text rather than by its instant,
335
- * and an absent `started_at` would sort to the bottom. The Checks API returns
336
- * neither today, so this is guarded rather than merely noted: every candidate
337
- * must carry a canonical UTC timestamp, and one that does not makes the newest
338
- * generation unestablishable, which is `ambiguous`. Refusing costs a hosted
339
- * run; ranking an unorderable set could authorize the wrong one.
471
+ * `fromdateiso8601` reads only canonical UTC, and the gate never asks it to
472
+ * read anything else. Every candidate must carry a canonical UTC
473
+ * `started_at`, and one that does not makes the newest generation
474
+ * unestablishable, which is `ambiguous`. A typed proof whose `endedAt` is not
475
+ * canonical UTC, or whose `durationMs` is missing or not a finite non-negative
476
+ * number, records no start, and its run falls back to `started_at` like any
477
+ * other run without a typed proof. Refusing costs a hosted run; ranking an
478
+ * unorderable set could authorize the wrong one.
340
479
  */
341
480
  const GATE_JQ = String.raw`
342
481
  def binding:
343
482
  [ .output.text, .output.summary ]
344
483
  | map(select(type == "string"))
345
- | map(split("\n") | map(select(startswith("${"```"}") | not)) | join("\n"))
346
- | map(. as $body | try ($body | fromjson) catch null)
347
- | map(select(type == "object"))
484
+ | map(. as $text
485
+ | (split("\n") | map(select(startswith("${"```"}") | not)) | join("\n")
486
+ | try fromjson catch null)
487
+ | select(type == "object")
488
+ | if ($text | utf8bytelength) > ${TRANSPORT_CAP_BYTES}
489
+ then del(.verificationProof)
490
+ else .
491
+ end)
348
492
  | .[0];
349
493
 
494
+ def resolvedMode:
495
+ IN(${RESOLVED_VERIFY_MODES.map((mode) => JSON.stringify(mode)).join(", ")});
496
+
350
497
  def startedAt: (.started_at // "") | tostring;
351
498
 
352
499
  def rankable:
353
500
  test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z$");
354
501
 
502
+ def wholeSecond: sub("\\.[0-9]+Z$"; "Z");
503
+
504
+ def epochSecond:
505
+ if type == "string" and rankable
506
+ then (try (wholeSecond | fromdateiso8601) catch null)
507
+ else null
508
+ end;
509
+
510
+ def millisecondPart:
511
+ ((capture("\\.(?<digits>[0-9]+)Z$") | .digits) // "") + "000"
512
+ | .[0:3]
513
+ | tonumber;
514
+
515
+ def bound:
516
+ (.binding | type) == "object"
517
+ and .binding.kind == "pr-verify-proof-binding"
518
+ and .binding.schemaVersion == 1
519
+ and .binding.headSha == $sha
520
+ and .binding.repository == $repository
521
+ and (.binding.mode | resolvedMode);
522
+
523
+ def passing:
524
+ .status == "completed"
525
+ and .conclusion == "success"
526
+ and bound
527
+ and .binding.outcome == "passed";
528
+
529
+ def proofStart:
530
+ if bound and (.binding.verificationProof | type) == "object" then
531
+ .binding.verificationProof as $proof
532
+ | ($proof.endedAt | epochSecond) as $ended
533
+ | $proof.durationMs as $duration
534
+ | if $ended != null
535
+ and ($duration | type) == "number"
536
+ and ($duration | isinfinite | not)
537
+ and $duration >= 0
538
+ then ($ended * 1000 + ($proof.endedAt | millisecondPart) - $duration)
539
+ / 1000
540
+ | floor
541
+ else null
542
+ end
543
+ else null
544
+ end;
545
+
546
+ def sameVerdict($other):
547
+ bound
548
+ and .status == $other.status
549
+ and .conclusion == $other.conclusion
550
+ and .binding == $other.binding;
551
+
552
+ def ownGeneration($generation):
553
+ if $generation.recorded
554
+ then .recorded and sameVerdict($generation)
555
+ else .index == $generation.index
556
+ end;
557
+
355
558
  def nonemptyString:
356
559
  type == "string" and length > 0;
357
560
 
@@ -376,12 +579,33 @@ def releaseAuthorized($release; $commands; $stamp):
376
579
  url: ((.html_url // "") | tostring),
377
580
  binding: binding }
378
581
  ] as $runs
379
- | ($runs | map(.started | rankable) | all) as $orderable
380
- | ($runs | map(.started | sub("\\.[0-9]+Z$"; "Z")) | max) as $newest
381
- | [ $runs[] | select((.started | sub("\\.[0-9]+Z$"; "Z")) == $newest) ] as $generation
582
+ | ($runs | map(.started | epochSecond != null) | all) as $orderable
583
+ | [ range(0; $runs | length) as $index
584
+ | $runs[$index]
585
+ | (.started | epochSecond) as $posted
586
+ | (if passing then proofStart else null end) as $start
587
+ | . + { at: ([$start, $posted] | map(select(. != null)) | min),
588
+ index: $index,
589
+ recorded: ($start != null) }
590
+ ] as $observed
591
+ | ( [ $observed[] | select(.recorded | not) ]
592
+ + ( [ $observed[] | select(.recorded) ]
593
+ | group_by([.status, .conclusion, .binding])
594
+ | map(.[0] + { at: (map(.at) | min) }) ) ) as $generations
595
+ | ($generations | map(.at) | max) as $newest
596
+ | [ $generations[] | select(.at == $newest) ] as $generation
382
597
  | (if ($runs | length) == 0 then ["none", "", "", ""]
383
598
  elif ($orderable | not) then ["ambiguous", "", "", ""]
384
599
  elif ($generation | length) != 1 then ["ambiguous", "", "", ""]
600
+ elif ($generation[0] as $newestRun
601
+ | ($newestRun.recorded | not)
602
+ and ([ $runs[] | select(sameVerdict($newestRun)) ] | length) > 1)
603
+ then ["ambiguous", "", "", ""]
604
+ elif ($generation[0] as $newestRun
605
+ | ($newestRun | passing)
606
+ and any($observed[] | select(ownGeneration($newestRun) | not);
607
+ (.started | epochSecond) >= $newestRun.at))
608
+ then ["ambiguous", "", "", ""]
385
609
  else
386
610
  $generation[0] as $run
387
611
  | (if ($run.binding | type) == "object" then $run.binding else {} end) as $proof
@@ -431,11 +655,7 @@ def releaseAuthorized($release; $commands; $stamp):
431
655
  | ($required - $executed - $released) as $missing
432
656
  | (if $run.status != "completed" then "pending"
433
657
  elif $run.conclusion != "success" then "failed"
434
- elif (($run.binding | type) != "object")
435
- or ($proof.kind != "pr-verify-proof-binding")
436
- or ($proof.schemaVersion != 1)
437
- or ($proof.headSha != $sha)
438
- or ($proof.repository != $repository) then "unreadable"
658
+ elif ($run | bound | not) then "unreadable"
439
659
  elif $proof.outcome != "passed" then "failed"
440
660
  elif ($required | length) == 0 then "incomplete"
441
661
  elif ($releasesValid | not) then "incomplete"
@@ -645,7 +865,7 @@ case "$reason" in
645
865
  ambiguous)
646
866
  say 'Ran the full suite. The newest factory proof for this commit is ambiguous.'
647
867
  say ''
648
- 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."
868
+ 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, a run's start time cannot be ranked, or the newest pass started before another run at this head was posted, so there is no single newest generation to trust. The gate refuses rather than picking one."
649
869
  say ''
650
870
  say '${CORRECTIVE_LINE}'
651
871
  ;;