@patronage/factory-ci 1.0.0-alpha.40 → 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.
package/README.md CHANGED
@@ -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": "3b1f520867e761216243d4a3f5577bd738a5931601b0e3ecc60e2e54147316d1"
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,9 @@ 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, or a run's start time cannot be ranked
747
754
  * - `error` the gate could not reach a decision (fail open)
748
755
  *
749
756
  * 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,9 @@ 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, or a run's start time cannot be ranked
522
538
  * - `error` the gate could not reach a decision (fail open)
523
539
  *
524
540
  * There is no `reduced`: mode stopped being an authorization condition in
@@ -651,22 +667,45 @@ const resolveProofReuseCommands = (catalog, names, selectionLabel) => names.map(
651
667
  * and the divergent shape is proven to fail safe. Two parsers of one payload
652
668
  * can drift; what must not drift silently is which direction they drift in.
653
669
  *
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.
670
+ * Ordering is by the proof's own generation, never by when a run reached
671
+ * GitHub (#1409). It is the rule `fetchPrVerifyProofBinding` applies
672
+ * (`software-factory/src/github-check-runs.ts`), mirrored here because this
673
+ * reader is jq in generated CI and cannot import it:
674
+ *
675
+ * - A run whose binding is bound to this head and repository and transports a
676
+ * typed proof (`verificationProof`) is ordered at the `endedAt` that proof
677
+ * records. Such runs with the same binding, status and conclusion are one
678
+ * generation posted more than once (`pr:verify` posts, `pr:publish`
679
+ * re-posts). So a re-post of an older pass never outranks a newer failure,
680
+ * and a post plus its re-post is no tie.
681
+ * - Any other run is its own generation at its `started_at`: an unbound one,
682
+ * or a bound one with no typed proof (over the text cap, or written before
683
+ * proofs travelled). The factory records a proof before it posts it, so
684
+ * that is the latest its proof could have been recorded.
685
+ * - Such a run carries no generation identity, so it is never grouped. Two
686
+ * separate executions with the same command names and verdict post the same
687
+ * compact binding, and so does a re-post. When the newest generation is one
688
+ * of these and repeats another run's verdict (binding, status and
689
+ * conclusion), it could be a re-post of an older verdict or a new one, so it
690
+ * is `ambiguous`. Proofs that size are rare; refusing costs a hosted run.
691
+ *
692
+ * Two different generations that share the newest instant are `ambiguous`
693
+ * rather than arbitrarily resolved: the gate cannot tell which one describes
694
+ * the tree, and silently picking either is exactly the kind of coin-flip
695
+ * authorization this whole mechanism exists to remove. Instants are
696
+ * normalized to whole seconds so `…:00Z` and `…:00.000Z` compare equal; two
697
+ * genuine verification generations within the same second at the same head
698
+ * is not a real state, and collapsing them errs toward refusing.
662
699
  *
663
700
  * The comparison is lexical, which is correct only for fixed-width UTC. A
664
701
  * `+HH:MM` offset would sort by its literal text rather than by its instant,
665
702
  * and an absent `started_at` would sort to the bottom. The Checks API returns
666
703
  * 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.
704
+ * must carry a canonical UTC `started_at`, and one that does not makes the
705
+ * newest generation unestablishable, which is `ambiguous`. A proof `endedAt`
706
+ * that is not canonical UTC is not a clock, and its run falls back to
707
+ * `started_at`. Refusing costs a hosted run; ranking an unorderable set could
708
+ * authorize the wrong one.
670
709
  */
671
710
  const GATE_JQ = String.raw`
672
711
  def binding:
@@ -682,6 +721,28 @@ def startedAt: (.started_at // "") | tostring;
682
721
  def rankable:
683
722
  test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z$");
684
723
 
724
+ def wholeSecond: sub("\\.[0-9]+Z$"; "Z");
725
+
726
+ def bound:
727
+ (.binding | type) == "object"
728
+ and .binding.kind == "pr-verify-proof-binding"
729
+ and .binding.schemaVersion == 1
730
+ and .binding.headSha == $sha
731
+ and .binding.repository == $repository;
732
+
733
+ def recordedAt:
734
+ if bound then
735
+ (.binding.verificationProof | if type == "object" then .endedAt else null end)
736
+ | if type == "string" and rankable then . else null end
737
+ else null
738
+ end;
739
+
740
+ def sameVerdict($other):
741
+ bound
742
+ and .status == $other.status
743
+ and .conclusion == $other.conclusion
744
+ and .binding == $other.binding;
745
+
685
746
  def nonemptyString:
686
747
  type == "string" and length > 0;
687
748
 
@@ -707,11 +768,23 @@ def releaseAuthorized($release; $commands; $stamp):
707
768
  binding: binding }
708
769
  ] as $runs
709
770
  | ($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
771
+ | [ $runs[]
772
+ | recordedAt as $recorded
773
+ | . + { at: (($recorded // .started) | wholeSecond), recorded: ($recorded != null) }
774
+ ] as $observed
775
+ | ( [ $observed[] | select(.recorded | not) ]
776
+ + ( [ $observed[] | select(.recorded) ]
777
+ | group_by([.status, .conclusion, .binding])
778
+ | map(.[0]) ) ) as $generations
779
+ | ($generations | map(.at) | max) as $newest
780
+ | [ $generations[] | select(.at == $newest) ] as $generation
712
781
  | (if ($runs | length) == 0 then ["none", "", "", ""]
713
782
  elif ($orderable | not) then ["ambiguous", "", "", ""]
714
783
  elif ($generation | length) != 1 then ["ambiguous", "", "", ""]
784
+ elif ($generation[0] as $newestRun
785
+ | ($newestRun.recorded | not)
786
+ and ([ $runs[] | select(sameVerdict($newestRun)) ] | length) > 1)
787
+ then ["ambiguous", "", "", ""]
715
788
  else
716
789
  $generation[0] as $run
717
790
  | (if ($run.binding | type) == "object" then $run.binding else {} end) as $proof
@@ -966,7 +1039,7 @@ case "$reason" in
966
1039
  ambiguous)
967
1040
  say 'Ran the full suite. The newest factory proof for this commit is ambiguous.'
968
1041
  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."
1042
+ 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."
970
1043
  say ''
971
1044
  say '${CORRECTIVE_LINE}'
972
1045
  ;;
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.41",
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,9 @@ 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, or a run's start time cannot be ranked
150
152
  * - `error` the gate could not reach a decision (fail open)
151
153
  *
152
154
  * There is no `reduced`: mode stopped being an authorization condition in
@@ -321,22 +323,45 @@ export const resolveProofReuseCommands = (
321
323
  * and the divergent shape is proven to fail safe. Two parsers of one payload
322
324
  * can drift; what must not drift silently is which direction they drift in.
323
325
  *
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.
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.
332
355
  *
333
356
  * The comparison is lexical, which is correct only for fixed-width UTC. A
334
357
  * `+HH:MM` offset would sort by its literal text rather than by its instant,
335
358
  * and an absent `started_at` would sort to the bottom. The Checks API returns
336
359
  * 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.
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.
340
365
  */
341
366
  const GATE_JQ = String.raw`
342
367
  def binding:
@@ -352,6 +377,28 @@ def startedAt: (.started_at // "") | tostring;
352
377
  def rankable:
353
378
  test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z$");
354
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
+
355
402
  def nonemptyString:
356
403
  type == "string" and length > 0;
357
404
 
@@ -377,11 +424,23 @@ def releaseAuthorized($release; $commands; $stamp):
377
424
  binding: binding }
378
425
  ] as $runs
379
426
  | ($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
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
382
437
  | (if ($runs | length) == 0 then ["none", "", "", ""]
383
438
  elif ($orderable | not) then ["ambiguous", "", "", ""]
384
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", "", "", ""]
385
444
  else
386
445
  $generation[0] as $run
387
446
  | (if ($run.binding | type) == "object" then $run.binding else {} end) as $proof
@@ -645,7 +704,7 @@ case "$reason" in
645
704
  ambiguous)
646
705
  say 'Ran the full suite. The newest factory proof for this commit is ambiguous.'
647
706
  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."
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."
649
708
  say ''
650
709
  say '${CORRECTIVE_LINE}'
651
710
  ;;