Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Close the attestation gaps the security review found

[._.]/ Adam Eivy3aa49fbdc379
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 299b5d4fd1..698bc643b3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -106,6 +106,13 @@ jobs:
- name: Scan the diff for hidden content
run: node scripts/scan-diff-hidden-content.js
+ # Linux resolves `./Foo.js` only as spelled; macOS and Windows do not. A
+ # pregate attestation lets a macOS run stand in for the Linux test jobs,
+ # so the one Linux-only failure it cannot see is checked here, on every
+ # pull request, before any job is skipped on its strength.
+ - name: Check relative imports match the tracked path case
+ run: node scripts/check-import-case.js
+
- name: Select affected test surfaces
id: plan
env:
@@ -188,6 +195,32 @@ jobs:
echo "- Pregate attestation: \`${ATTESTATION}\`"
} >> "$GITHUB_STEP_SUMMARY"
+ # `autofixer/` is a real install target — its own package.json, its own
+ # tracked lockfile, its own .npmrc — installed by `npm run setup` and by
+ # scripts/ensure-deps.js on every `npm start`. Nothing else in CI resolves
+ # it, so a lockfile that no longer installs (a yanked version, a corrupted
+ # integrity hash, a manifest/lockfile mismatch) would ship green and only
+ # break on a user's machine at setup time. The parity assertions in
+ # server/dependency-overrides.test.js are static — they parse the JSON;
+ # only `npm ci` proves the tree still resolves.
+ #
+ # Here rather than on the server job because this job always runs: a
+ # pregate attestation can skip the server job, and this check must never
+ # go with it. Deliberately uncached and ungated: a cache hit that skipped
+ # the install would skip the very check this step exists for. 67
+ # packages, well under a second, on the runner's own Node (no setup-node
+ # in this job; the lockfile resolves the same on any supported major).
+ #
+ # No rebuild step follows. autofixer/.npmrc pins ignore-scripts=true and
+ # scripts/trusted-rebuilds.js deliberately lists no rebuilds for this
+ # workspace, because nothing it depends on ships a native addon.
+ - name: Install autofixer dependencies
+ run: npm ci --prefix autofixer
+
+ # Same reason: the entry-point syntax check must not ride a skippable job.
+ - name: Check server entry-point syntax
+ run: node --check server/index.js
+
prompt-history:
name: Shipped prompt history
needs: impact
@@ -341,33 +374,6 @@ jobs:
vitest-server-${{ runner.os }}-${{ hashFiles('server/package-lock.json') }}-
vitest-server-${{ runner.os }}-
- # `autofixer/` is a real install target — its own package.json, its own
- # tracked lockfile, its own .npmrc — installed by `npm run setup` and by
- # scripts/ensure-deps.js on every `npm start`. Nothing else in CI resolves
- # it, so a lockfile that no longer installs (a yanked version, a corrupted
- # integrity hash, a manifest/lockfile mismatch) would ship green and only
- # break on a user's machine at setup time. The parity assertions in
- # server/dependency-overrides.test.js are static — they parse the JSON;
- # only `npm ci` proves the tree still resolves.
- #
- # Deliberately uncached and deliberately ungated within the job: a cache
- # hit that skipped the install would skip the very check this step exists
- # for, and the job as a whole already gates on the planner's server_mode
- # (autofixer/ is one of the server runner's roots in ci-test-plan.js, so a
- # change here selects this job). Unlike the once-only steps that pin to
- # shard 1, it runs on every shard: autofixer/*.test.js is globbed by the
- # server runner, and which shard picks up a file that imports `express` is
- # not knowable from here. 67 packages, well under a second.
- #
- # No rebuild step follows. autofixer/.npmrc pins ignore-scripts=true and
- # scripts/trusted-rebuilds.js deliberately lists no rebuilds for this
- # workspace, because nothing it depends on ships a native addon.
- - name: Install autofixer dependencies
- run: npm ci --prefix autofixer
-
- - name: Check server entry-point syntax
- run: node --check server/index.js
-
# The submodule ships no source into this checkout by default (see
# AGENTS.md "Slashdo Commands"), so the planner's `slashdo` output is
# the only signal that the selected tests need it — an unrelated scoped
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md
index d46d6c60d9..30dcdf157c 100644
--- a/docs/CONTRIBUTING.md
+++ b/docs/CONTRIBUTING.md
@@ -120,16 +120,22 @@ that was validated — untracked and uncommitted files included, so a later
commit of that state yields the same `HEAD^{tree}`. A green summary never
claims a suite it skipped; required CI checks still apply.
-After the push, `node scripts/pregate-attest.js` posts that receipt as a
-`pregate` commit status on the pushed head, bound to the validated tree, and
-the pull request's impact planner skips the stages it attests to (only stages
-that ran and passed; never Windows, Linux containment or the Node-minimum
-check). It refuses — saying what to rerun — when the receipt did not pass,
-the tree changed after pregate, the commit is not on the upstream remote yet,
-or nothing attestable ran; a refusal just means CI runs everything as before.
-`--dry-run` prints the status without posting it. Only a repository writer
-can create the status and only the repository owner's counts, so fork and
-Dependabot pull requests are unaffected. Contract and inspection:
+After the push (and, when you open the pull request yourself, before
+`gh pr create`), `node scripts/pregate-attest.js` posts that receipt as a
+`pregate` commit status on the pushed head, bound to the validated tree and
+naming the platform and Node it ran on, and the pull request's impact planner
+skips the stages it attests to (only stages that ran and passed; never
+Windows, Linux containment or the Node-minimum check; and, per stage, never
+one that a change `main` gained since the branch forked could reach). It
+refuses — saying what to rerun — when the receipt did not pass, the tree
+changed after pregate, the commit is not on the upstream remote yet, or
+nothing attestable ran, and it attests no server, client or lint stage from
+a receipt planned with `--base` against something other than the default
+branch's merge base; a refusal just means CI runs everything as before.
+`--dry-run` prints the status without posting it; `--revoke "<reason>"`
+withdraws every earlier attestation on the commit. Only a repository writer
+can create the status and only the repository owner's newest one counts, so
+fork and Dependabot pull requests are unaffected. Contract and inspection:
[Pregate attestation](GITHUB_ACTIONS.md#pregate-attestation).
PRs run the browser suites' smoke profile; the `[fidelity]` cases run nightly
diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.md
index 9d00e60ef0..bed933f053 100644
--- a/docs/GITHUB_ACTIONS.md
+++ b/docs/GITHUB_ACTIONS.md
@@ -201,46 +201,87 @@ pushed head, and the impact planner skips what it attests to:
by a `--skip-*` flag, left to CI by a downgraded full plan, or missing a
prerequisite — is not attested, and a downgraded full plan never attests
its server or client stage (it ran the always-run guards, not CI's
- selection). The vocabulary is `ATTESTABLE_STAGES` in
- `scripts/lib/pregateAttestation.js`.
+ selection). A receipt planned with `--base` against anything other than the
+ default branch's merge base attests no server, client or lint stage either:
+ its diff-selected plan was narrower than CI's. The vocabulary is
+ `ATTESTABLE_STAGES` in `scripts/lib/pregateAttestation.js`.
- **The tree binding.** The status description is
- `tree=<40-hex> stages=<list>`: the receipt's `git write-tree` hash of the
- exact working tree pregate validated, untracked and uncommitted files
- included. `pregate-attest.js` refuses unless `<commit>^{tree}` equals it —
- anything changed after pregate means a rerun — and the planner compares it
- with the head commit's tree on the PR. A SHA is never compared, for the same
- reason `scripts/verify-ci-status.js` compares trees: the content is what was
- tested. The commit must already be on the upstream remote (the one
- `branch.<name>.remote` names); GitHub only accepts a status on a commit it
- has, which is why attesting is a step after `git push`, not a pregate flag.
+ `tree=<40-hex> os=<platform> node=<major> stages=<list>`: the receipt's
+ `git write-tree` hash of the exact working tree pregate validated, untracked
+ and uncommitted files included, plus the platform and Node major the stages
+ ran on. `pregate-attest.js` refuses unless `<commit>^{tree}` equals the
+ receipt's tree — anything changed after pregate means a rerun — and the
+ planner compares it with the head commit's tree on the PR. A SHA is never
+ compared, for the same reason `scripts/verify-ci-status.js` compares trees:
+ the content is what was tested. The commit must already be on the upstream
+ remote (the one `branch.<name>.remote` names); GitHub only accepts a status
+ on a commit it has, which is why attesting is a step after `git push`, not a
+ pregate flag.
+- **The merge ref is not the head tree.** The receipt vouches for the head
+ commit's tree; CI tests the merge ref, that tree plus whatever `main`
+ gained since the branch forked. The planner reads that base-side diff
+ (`git diff --name-only HEAD^2 HEAD`) and refuses the attestation **per
+ stage** when it contains a test file the plan selected for that runner, a
+ non-test source under the runner's roots (`server/`, `scripts/`, `lib/`,
+ `autofixer/` for the server stages; `client/src/` for the client ones), or a
+ runner config, setup, workflow or dependency-manifest file (which refuses
+ every stage). Docs-only movement, or movement in the other runner, keeps
+ the attestation. Each refusal names the path in `suite_reasons` and in the
+ `attestation` output's `driftRefused`. In practice the local workflow
+ re-syncs the branch onto `main` before pregate, so the drift is usually
+ empty.
- **Who can post one.** A commit status on this repository can only be created
by an actor with write access, and the planner honors only the newest
- successful `pregate` status whose `creator.login` is the repository owner.
- The `GITHUB_TOKEN` of a `pull_request` run from a fork is read-only and
- cannot create one; a Dependabot pull request is refused by author; a status
- by anyone else is ignored. The impact job holds `statuses: read` and nothing
- more (`release.yml` grants the same scope to the called workflow). CI is
- still the authority for every outsider.
+ `pregate` status — of any state — when it is a success whose
+ `creator.login` is the repository owner. The `GITHUB_TOKEN` of a
+ `pull_request` run from a fork is read-only and cannot create one; a
+ Dependabot pull request is refused by author; a status by anyone else is
+ ignored, and a newer one by anyone else blocks the owner's older success.
+ The impact job holds `statuses: read` and nothing more (`release.yml`
+ grants the same scope to the called workflow). CI is still the authority
+ for every outsider.
+- **Revocation.** `node scripts/pregate-attest.js --revoke "<reason>"` posts a
+ `failure` status on the commit; because the newest status decides, every
+ earlier attestation on that commit is withdrawn and the next run plans as
+ if none existed. Use it when a local result turns out to be wrong (a flaky
+ pass, a suite that was not really run).
+- **Platform.** A macOS pregate may attest the Linux jobs: per the project's
+ policy, other platforms are checked only when a change could plausibly
+ break them, and the Windows job is the one platform-specific proof CI keeps.
+ The one Linux-only failure a case-insensitive filesystem cannot see — a
+ relative import whose case differs from the tracked path — is closed by
+ `scripts/check-import-case.js`, which the impact job runs on every pull
+ request before any stage can be skipped (it resolves every relative
+ `import`, `import()` literal and `new URL(…, import.meta.url)` in the
+ changed modules against `git ls-files` with exact spelling). The platform
+ and Node major of the attesting run are in the status and in the plan
+ summary's `Pregate attestation` line.
- **When it applies.** Only a same-repository pull request into a non-`release`
base that was not forced full. The planner verifies the merge-ref checkout's
- second parent is the event's head (so the tree compared is the tree under
- test) and reads `repos/{repo}/commits/{head}/statuses`. Any failure — API
- error, unreadable description, tree mismatch, wrong creator — leaves the
- plan exactly as computed and records the reason.
-- **What CI still runs.** The impact job and its hidden-content scan, the
- Windows job, the Linux worker-containment job, the Node-minimum check and
- the `CI Gate` itself always run as planned. The server job stays when its
- boot smoke is selected but not attested, because the smoke runs on that job.
- An attested run reports `full: false`, so `Full CI Gate` is never published
- on the strength of a receipt. The planner reads the plan from the merge ref,
- so a test added on `main` after the local run can still be selected and
- then skipped under the attestation — the same class of gap the nightly
- full run on `main` exists to catch.
+ second parent is the event's head (so the attested tree is compared with
+ the right commit) and reads `repos/{repo}/commits/{head}/statuses`. A head
+ committed less than five minutes ago with no `pregate` status yet is re-read
+ for up to 90 seconds (10-second interval; the summary says how long it
+ waited), because the status is posted after the push that started the run.
+ When you open the pull request yourself, the order is push, attest, then
+ `gh pr create`, so the status precedes the `pull_request` event. Any
+ failure — API error, unreadable description, tree mismatch, wrong creator,
+ a non-success newest status — leaves the plan exactly as computed and
+ records the reason.
+- **What CI still runs.** The impact job — its hidden-content scan, the
+ import-case check, `npm ci --prefix autofixer` and the `node --check` of
+ the server entry point (both moved here from the server job so an attested
+ run cannot skip them) — the Windows job, the Linux worker-containment job,
+ the Node-minimum check and the `CI Gate` itself always run as planned. The
+ server job stays when its boot smoke is selected but not attested, because
+ the smoke runs on that job. An attested run reports `full: false`, so
+ `Full CI Gate` is never published on the strength of a receipt.
- **How to inspect it.** The impact job's summary prints a `Pregate
- attestation` line (`attested`, the head and tree, the stages, or the reason
- none applied) and `suite_reasons` names each skipped suite as attested.
+ attestation` line (`attested`, the head and tree, the platform and Node,
+ the stages, `driftRefused`, or the reason none applied) and `suite_reasons`
+ names each skipped suite as attested and each refused one with its path.
On the commit: `gh api repos/<owner>/<repo>/commits/<sha>/statuses` lists
- every `pregate` status with its creator, description and timestamp;
+ every `pregate` status with its creator, state, description and timestamp;
`node scripts/pregate-attest.js --dry-run` shows what would be posted for
the current receipt and HEAD without posting it.
@@ -542,13 +583,15 @@ The selected work is split across parallel jobs:
`PORTOS_SMOKE_BOOT=1` so no scheduler, agent recovery, or peer sync starts —
`npm run smoke` behaves the same on a clean checkout and on a live install. The install
and the native-addon rebuild are skipped when a `server/node_modules` cache is
- restored and its trusted-rebuild mark checks out. This job also runs
+ restored and its trusted-rebuild mark checks out. The impact job (which
+ always runs, even when a pregate attestation skips this one) runs
`npm ci --prefix autofixer` — uncached and never skipped, because resolving
- that workspace's tracked lockfile *is* the check. It is the only CI step that
- installs `autofixer/`, which `npm run setup` and `scripts/ensure-deps.js`
- install on every user's machine; without it a lockfile that stopped resolving
- shipped green and failed at setup time. (`browser/` gets no such step: zero
- dependencies, and its lockfile is deliberately gitignored.)
+ that workspace's tracked lockfile *is* the check — and `node --check
+ server/index.js`. It is the only CI step that installs `autofixer/`, which
+ `npm run setup` and `scripts/ensure-deps.js` install on every user's
+ machine; without it a lockfile that stopped resolving shipped green and
+ failed at setup time. (`browser/` gets no such step: zero dependencies, and
+ its lockfile is deliberately gitignored.)
- **Client tests and build** — affected client tests, plus the production build
whenever client source changed. Build and the Scalar-removal bundle pin run on
shard 1 only.
diff --git a/scripts/check-import-case.js b/scripts/check-import-case.js
new file mode 100644
index 0000000000..84cf8a132d
--- /dev/null
+++ b/scripts/check-import-case.js
@@ -0,0 +1,136 @@
+#!/usr/bin/env node
+
+/**
+ * Fail a pull request whose relative imports spell a path in a case that
+ * differs from the tracked file.
+ *
+ * macOS (APFS) and Windows (NTFS) resolve `./Foo.js` to a tracked `foo.js`;
+ * Linux does not. A pregate run on macOS therefore cannot see this one class
+ * of Linux-only failure, and the pregate attestation lets such a run stand in
+ * for the Linux test jobs — so the impact job, which always runs, checks it
+ * here instead (docs/GITHUB_ACTIONS.md "Pregate attestation").
+ *
+ * For every changed JavaScript module (or every tracked one, when no base is
+ * known), each relative specifier — static `import`/`export … from`, a literal
+ * dynamic `import('./x')`, and `new URL('./x', import.meta.url)` — is resolved
+ * against `git ls-files` with exact spelling, trying the usual extension and
+ * index completions. A specifier that matches a tracked path only
+ * case-insensitively is a mismatch; one that matches nothing at all is left
+ * to the module loader (an alias, a generated file, a package path).
+ *
+ * node scripts/check-import-case.js [--base <sha>] # default: $CI_BASE_SHA
+ *
+ * ZERO external dependencies — this runs before `npm ci` in the impact job.
+ */
+
+import { execFileSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { dirname, posix } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { staticImportSpecifiersFromSource } from '../server/lib/staticImportGraph.js';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
+
+const MODULE_RE = /\.(?:[cm]?jsx?|tsx?)$/i;
+const DYNAMIC_IMPORT_RE = /\bimport\(\s*['"]([^'"]+)['"]\s*\)/g;
+const NEW_URL_RE = /new URL\(\s*['"]([^'"]+)['"]\s*,\s*import\.meta\.url\s*\)/g;
+const COMPLETIONS = ['', '.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '/index.js', '/index.jsx', '/index.ts', '/index.tsx'];
+
+/** Every relative specifier in a module's source, in source order. */
+export function relativeSpecifiers(source) {
+ const code = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
+ const found = [...staticImportSpecifiersFromSource(code)];
+ for (const re of [DYNAMIC_IMPORT_RE, NEW_URL_RE]) {
+ re.lastIndex = 0;
+ let match;
+ while ((match = re.exec(code)) !== null) found.push(match[1]);
+ }
+ return found.filter((specifier) => specifier.startsWith('./') || specifier.startsWith('../'))
+ .map((specifier) => specifier.split(/[?#]/)[0]);
+}
+
+/**
+ * Case mismatches between a file's relative specifiers and the tracked tree.
+ *
+ * @param {string} file - repo-relative path of the importing module
+ * @param {string} source - its text
+ * @param {Set<string>} tracked - every `git ls-files` path, exact spelling
+ * @param {Map<string, string[]>} [folded] - lowercase path → tracked spellings
+ * @returns {Array<{file: string, specifier: string, resolved: string, tracked: string}>}
+ */
+export function importCaseMismatches(file, source, tracked, folded = foldTracked(tracked)) {
+ const mismatches = [];
+ for (const specifier of relativeSpecifiers(source)) {
+ const target = posix.normalize(posix.join(posix.dirname(file), specifier));
+ if (target.startsWith('../')) continue;
+ const candidates = COMPLETIONS.map((completion) => `${target}${completion}`);
+ if (candidates.some((candidate) => tracked.has(candidate))) continue;
+ const insensitive = candidates.flatMap((candidate) => folded.get(candidate.toLowerCase()) ?? []);
+ if (insensitive.length > 0) mismatches.push({ file, specifier, resolved: target, tracked: insensitive[0] });
+ }
+ return mismatches;
+}
+
+/** Lowercased path → the tracked spellings that fold to it. */
+export function foldTracked(tracked) {
+ const folded = new Map();
+ for (const path of tracked) {
+ const key = path.toLowerCase();
+ folded.set(key, [...(folded.get(key) ?? []), path]);
+ }
+ return folded;
+}
+
+const gitOutput = (args, cwd) => execFileSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
+const gitLines = (args, cwd) => gitOutput(args, cwd).split('\n').filter(Boolean);
+
+/**
+ * Check the changed modules (or every tracked module) of a checkout.
+ *
+ * @param {{cwd?: string, baseSha?: string|null}} [options]
+ * @returns {{checked: number, mismatches: Array<object>}}
+ */
+export function checkImportCase({ cwd = process.cwd(), baseSha = null } = {}) {
+ const tracked = new Set(gitOutput(['ls-files', '-z'], cwd).split('\0').filter(Boolean));
+ const folded = foldTracked(tracked);
+ const changed = baseSha
+ ? gitLines(['diff', '--name-only', '--diff-filter=ACMR', `${baseSha}...HEAD`], cwd).filter((path) => tracked.has(path))
+ : [...tracked];
+ const modules = changed.filter((path) => MODULE_RE.test(path) && !path.includes('/node_modules/'));
+ const mismatches = modules.flatMap((file) => {
+ let source;
+ try {
+ source = readFileSync(posix.join(cwd, file), 'utf8');
+ } catch {
+ return [];
+ }
+ return importCaseMismatches(file, source, tracked, folded);
+ });
+ return { checked: modules.length, mismatches };
+}
+
+function parseArgs(argv) {
+ const options = { baseSha: process.env.CI_BASE_SHA || null };
+ for (let index = 0; index < argv.length; index += 1) {
+ if (argv[index] === '--base') {
+ options.baseSha = argv[index + 1] || null;
+ index += 1;
+ } else {
+ throw new Error(`Unknown option: ${argv[index]}.`);
+ }
+ }
+ return options;
+}
+
+function main() {
+ const { baseSha } = parseArgs(process.argv.slice(2));
+ const { checked, mismatches } = checkImportCase({ cwd: dirname(dirname(fileURLToPath(import.meta.url))), baseSha });
+ if (mismatches.length > 0) {
+ console.error(`❌ ${mismatches.length} import path(s) differ from the tracked file only in case — Linux cannot resolve them:`);
+ for (const { file, specifier, tracked } of mismatches) console.error(` ${file}: '${specifier}' → tracked as ${tracked}`);
+ process.exitCode = 1;
+ return;
+ }
+ console.log(`✅ Import case check: ${checked} module(s) ${baseSha ? 'changed since the base' : 'tracked'}, every relative import matches the tracked spelling.`);
+}
+
+if (isDirectlyInvoked(import.meta.url)) main();
diff --git a/scripts/check-import-case.test.js b/scripts/check-import-case.test.js
new file mode 100644
index 0000000000..4edf89058b
--- /dev/null
+++ b/scripts/check-import-case.test.js
@@ -0,0 +1,91 @@
+/**
+ * The import-case guard is what lets a macOS pregate attestation stand in for
+ * the Linux jobs without hiding the one Linux-only module failure a
+ * case-insensitive filesystem cannot see. It must flag a specifier that
+ * matches a tracked path only by case, in every import shape, and leave alone
+ * both exact matches and paths git does not track at all.
+ */
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { checkImportCase, importCaseMismatches, relativeSpecifiers } from './check-import-case.js';
+
+const tracked = new Set(['src/Foo.js', 'src/lib/index.js', 'src/util/Helpers.jsx', 'src/data.json']);
+
+describe('relativeSpecifiers', () => {
+ it('collects static, dynamic-literal and import.meta.url specifiers, relative ones only, without query strings', () => {
+ const source = [
+ "import a from './Foo.js';",
+ "export { b } from '../lib';",
+ "import 'side-effect-package';",
+ "const c = await import('./util/Helpers.jsx?raw');",
+ "const d = new URL('./data.json', import.meta.url);",
+ "// import x from './Commented.js'",
+ "/* import y from './Blocked.js' */",
+ "import z from 'zod';",
+ ].join('\n');
+ expect(relativeSpecifiers(source)).toEqual(['./Foo.js', '../lib', './util/Helpers.jsx', './data.json']);
+ });
+});
+
+describe('importCaseMismatches', () => {
+ it('flags a case-only mismatch in each import shape and resolves extension and index completions', () => {
+ const source = "import a from './foo.js';\nconst b = import('./util/helpers');\nconst c = new URL('./DATA.json', import.meta.url);\nimport d from './lib';";
+ expect(importCaseMismatches('src/entry.js', source, tracked)).toEqual([
+ { file: 'src/entry.js', specifier: './foo.js', resolved: 'src/foo.js', tracked: 'src/Foo.js' },
+ { file: 'src/entry.js', specifier: './util/helpers', resolved: 'src/util/helpers', tracked: 'src/util/Helpers.jsx' },
+ { file: 'src/entry.js', specifier: './DATA.json', resolved: 'src/DATA.json', tracked: 'src/data.json' },
+ ]);
+ });
+
+ it('passes exact spellings and ignores specifiers git does not track at all', () => {
+ const source = "import a from './Foo.js';\nimport b from './lib';\nimport c from './util/Helpers';\nimport d from './generated/manifest.js';\nimport e from '../../outside.js';";
+ expect(importCaseMismatches('src/entry.js', source, tracked)).toEqual([]);
+ });
+});
+
+describe('checkImportCase against a repository', () => {
+ it('checks only the modules changed since the base, and every tracked module without one', () => {
+ const root = mkdtempSync(join(tmpdir(), 'portos-import-case-'));
+ const git = (...args) => execFileSync('git', ['-c', 'user.name=Example', '-c', '[email protected]', '-c', 'commit.gpgsign=false', ...args], { cwd: root, encoding: 'utf8' }).trim();
+ const write = (path, body) => {
+ mkdirSync(dirname(join(root, path)), { recursive: true });
+ writeFileSync(join(root, path), body);
+ };
+ try {
+ git('init', '-q', '-b', 'main');
+ git('config', 'core.hooksPath', join(root, 'empty-hooks'));
+ write('src/Foo.js', 'export const foo = 1;\n');
+ write('src/old.js', "import { foo } from './foo.js';\n");
+ git('add', '--all');
+ git('commit', '-qm', 'base with a latent mismatch');
+ const base = git('rev-parse', 'HEAD');
+ write('src/new.js', "import { foo } from './Foo.js';\nexport const bar = foo;\n");
+ git('add', '--all');
+ git('commit', '-qm', 'clean addition');
+ // Only the new module is examined against the base: the latent mismatch
+ // in an untouched file is not this pull request's to answer for.
+ expect(checkImportCase({ cwd: root, baseSha: base })).toEqual({ checked: 1, mismatches: [] });
+ // Without a base every tracked module is examined.
+ const whole = checkImportCase({ cwd: root });
+ expect(whole.checked).toBe(3);
+ expect(whole.mismatches).toEqual([{ file: 'src/old.js', specifier: './foo.js', resolved: 'src/foo.js', tracked: 'src/Foo.js' }]);
+ // A changed module with the mismatch fails the scoped check.
+ write('src/new.js', "import { foo } from './foo.js';\n");
+ git('commit', '-qam', 'regress');
+ expect(checkImportCase({ cwd: root, baseSha: base }).mismatches.map((m) => m.file)).toEqual(['src/new.js']);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it('is wired into the impact job before any job can be skipped on an attestation', () => {
+ const workflow = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', '.github', 'workflows', 'ci.yml'), 'utf8');
+ const impact = workflow.slice(workflow.indexOf('\n impact:\n'), workflow.indexOf('\n prompt-history:\n'));
+ expect(impact).toContain('run: node scripts/check-import-case.js');
+ expect(impact.indexOf('node scripts/check-import-case.js')).toBeLessThan(impact.indexOf('node scripts/ci-test-plan.js'));
+ });
+});
diff --git a/scripts/ci-base-sha.test.js b/scripts/ci-base-sha.test.js
index 3dfb63f804..1d58f819c2 100644
--- a/scripts/ci-base-sha.test.js
+++ b/scripts/ci-base-sha.test.js
@@ -252,24 +252,27 @@ describe('ci.yml autofixer workspace install', () => {
const installers = Object.entries(jobs)
.filter(([, body]) => body.includes('npm ci --prefix autofixer'));
- it('resolves the autofixer lockfile on the job that runs the server suite', () => {
+ it('resolves the autofixer lockfile and checks the server entry point on the job that always runs', () => {
// autofixer/ carries its own package.json, its own tracked lockfile, and
// its own .npmrc, and `npm run setup` / scripts/ensure-deps.js install it
// on every user's machine. When no CI job ran `npm ci` against it, a
// lockfile that stopped resolving shipped green and failed at setup time
// instead — the static parity checks in dependency-overrides.test.js only
- // parse the JSON. The server job is the one that already globs
- // autofixer/*.test.js, so it is where the tree belongs.
+ // parse the JSON. It lived on the server job until a pregate attestation
+ // could skip that job; the impact job is the one that always runs, so the
+ // install and the `node --check` of the entry point moved there.
// Named, so the loop below is never vacuously green on a deleted step.
- expect(jobs.server).toMatch(/- name: Install autofixer dependencies\n {8}run: npm ci --prefix autofixer/);
+ expect(jobs.impact).toMatch(/- name: Install autofixer dependencies\n {8}run: npm ci --prefix autofixer/);
+ expect(jobs.impact).toMatch(/- name: Check server entry-point syntax\n {8}run: node --check server\/index\.js/);
+ expect(jobs.server).not.toContain('npm ci --prefix autofixer');
+ expect(jobs.server).not.toContain('node --check server/index.js');
});
it('never lets a cache hit skip the resolution it exists to prove', () => {
// The server tree is cached and its `npm ci` is skipped on a hit, which is
// fine because that job's job is to run tests. This step's whole purpose is
// the install, so caching it (or gating it on a cache outcome) would put
- // the hole straight back. The job-level `server_mode != 'skip'` is what
- // keeps a docs-only plan from paying for it.
+ // the hole straight back. It is cheap enough to pay on every plan.
for (const [id, body] of installers) {
const step = body.match(
/- name: Install autofixer dependencies\n(?<between>(?: {8}.*\n)*?) {8}run: npm ci --prefix autofixer/,
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.js
index a17f6bbadb..47b2a8b5f8 100644
--- a/scripts/ci-test-plan.js
+++ b/scripts/ci-test-plan.js
@@ -1598,18 +1598,25 @@ export function collectPlanInputs({ baseSha, forceFull = false, changedFiles, cw
//
// A local `npm run pregate` that ran a stage to green, followed by
// `node scripts/pregate-attest.js` after the push, leaves a `pregate` commit
-// status on the head whose description names the validated TREE and the
-// stages that passed (scripts/lib/pregateAttestation.js). This section reads
-// that status back and lets the plan skip those stages — never Windows, the
-// Linux containment job, or the Node-minimum check, which have no local run.
+// status on the head whose description names the validated TREE, the platform
+// and Node major it ran on, and the stages that passed
+// (scripts/lib/pregateAttestation.js). This section reads that status back
+// and lets the plan skip those stages — never Windows, the Linux containment
+// job, or the Node-minimum check, which have no local run.
//
// Fail closed at every step: anything other than a same-repository pull
// request into a non-release base, with a head commit the owner attested
-// whose tree is exactly the head tree, leaves the plan untouched and the
-// reason in the outputs. The planner never has to be right about a fork or a
-// bot for this to be safe — a fork's token cannot create a status here and a
-// bot's login is not the owner's — but it refuses them explicitly so the
-// summary says why.
+// whose tree is exactly the head commit's tree, leaves the plan untouched and
+// the reason in the outputs. The planner never has to be right about a fork
+// or a bot for this to be safe — a fork's token cannot create a status here
+// and a bot's login is not the owner's — but it refuses them explicitly so
+// the summary says why.
+//
+// What the receipt vouches for is the HEAD COMMIT's tree; what CI tests is
+// the merge ref, that tree plus whatever the base branch gained since the
+// branch forked. `attestationDrift` closes that gap per stage: a base-side
+// change that could reach a stage's runner refuses the attestation for that
+// stage, and docs-only or other-runner movement keeps it.
// ---------------------------------------------------------------------------
/** Stages a receipt may attest to, mapped to the plan fields they clear. */
@@ -1623,6 +1630,11 @@ const ATTESTATION_SKIPS = Object.freeze({
'prompt-history': () => ({ promptHistory: false }),
});
+/** How long after the head commit a just-posted status may still be on its way. */
+const ATTESTATION_YOUNG_HEAD_SECONDS = 300;
+const ATTESTATION_POLL_TOTAL_MS = 90_000;
+const ATTESTATION_POLL_INTERVAL_MS = 10_000;
+
/**
* Whether this run may honor an attestation at all, and the head it would
* read it from. Reads only the `CI_*` inputs ci.yml passes to the plan step.
@@ -1648,21 +1660,77 @@ export function attestationEligibility(env) {
return { eligible: true, reason: 'same-repository pull request', headSha, repository, owner };
}
+const isRunnerConfig = (path) => FULL_TRIGGER_RULES.some((rule) => rule.re.test(path)) || WORKSPACE_CACHE_COMMON_INPUTS.has(path);
+const isSourceUnder = (path, prefixes) => isExecutable(path) && !isTestFile(path) && !isDocumentationOnly(path)
+ && prefixes.some((prefix) => path.startsWith(prefix));
+
+/**
+ * Per stage, whether a base-side path could change that stage's outcome:
+ * (a) a test file the plan selected for the runner, (b) a non-test source
+ * under the runner's roots, or (c) a runner config or setup file. Each entry
+ * is the first offending path, for the refusal reason.
+ */
+const STAGE_DRIFT_RULES = Object.freeze({
+ server: (plan, path) => plan.server.files.includes(path) || isSourceUnder(path, RUNNER_ROOTS.server) || WORKSPACE_CACHE_SERVER_INPUTS.has(path),
+ client: (plan, path) => plan.client.files.includes(path) || isSourceUnder(path, RUNNER_ROOTS.client) || WORKSPACE_CACHE_CLIENT_INPUTS.has(path),
+ lint: (plan, path) => isLintSurface(path),
+ build: (plan, path) => isSourceUnder(path, ['client/']) || WORKSPACE_CACHE_CLIENT_INPUTS.has(path),
+ smoke: (plan, path) => isSourceUnder(path, ['server/']) || path === 'scripts/smoke-boot.js' || WORKSPACE_CACHE_SERVER_INPUTS.has(path),
+ browser: (plan, path) => plan.browserFiles.includes(path) || BROWSER_SUITES.includes(path)
+ || isSourceUnder(path, ['server/', 'client/src/']) || WORKSPACE_CACHE_SERVER_INPUTS.has(path) || WORKSPACE_CACHE_CLIENT_INPUTS.has(path),
+ db: (plan, path) => resolveDbTestFiles([path]).length > 0 || isSourceUnder(path, ['server/']) || WORKSPACE_CACHE_SERVER_INPUTS.has(path),
+ 'prompt-history': (plan, path) => PROMPT_HISTORY_PATH_RE.test(path),
+});
+
+/**
+ * The stages a base-side diff refuses, each with the path that refuses it.
+ *
+ * `driftPaths` is `git diff --name-only HEAD^2 HEAD` on the merge ref: exactly
+ * what the base branch added since the branch forked. A runner config or
+ * workflow change refuses every stage; otherwise each stage answers for its
+ * own runner. Null (the diff could not be read) refuses everything.
+ *
+ * @param {object} plan - the finished plan
+ * @param {string[]|null} driftPaths
+ * @returns {Record<string, string>} stage → reason
+ */
+export function attestationDrift(plan, driftPaths) {
+ const refused = {};
+ if (!Array.isArray(driftPaths)) {
+ for (const stage of Object.keys(STAGE_DRIFT_RULES)) refused[stage] = 'base movement could not be read';
+ return refused;
+ }
+ const paths = uniqueSorted(driftPaths.filter((path) => typeof path === 'string' && path.length > 0));
+ const config = paths.find(isRunnerConfig);
+ for (const [stage, touches] of Object.entries(STAGE_DRIFT_RULES)) {
+ const hit = config ?? paths.find((path) => touches(plan, path));
+ if (hit) refused[stage] = `base branch moved: ${hit}`;
+ }
+ return refused;
+}
+
/**
* The attestation on the pull request's head, or null and why.
*
* The checkout is the merge ref at depth 2, which carries the head commit as
* `HEAD^2`: that is what makes `<head>^{tree}` resolvable without a wider
* fetch, and the first check — the event's head must BE that second parent,
- * or the tree compared would not be the tree being tested.
+ * or the attested tree would be compared with some other commit's. It is NOT
+ * the tree under test: the merge ref also carries the base branch's movement,
+ * which `attestationDrift` weighs per stage in applyAttestation from the
+ * `baseDrift` returned here.
+ *
+ * A status posted moments after the push can still be on its way when the
+ * run starts, so a head younger than five minutes with no `pregate` status
+ * is re-read for up to 90 seconds before "no attestation" is concluded.
*
* `log` defaults to stderr: the planner's stdout is the JSON plan pregate
* and the tests parse, so every human-readable line here stays off it.
*
- * @param {{env?: NodeJS.ProcessEnv, exec?: typeof execFileSync, cwd?: string, log?: (line: string) => void}} [options]
- * @returns {{attested: boolean, reason: string, sha?: string, tree?: string, stages?: string[], creator?: string, createdAt?: string}}
+ * @param {{env?: NodeJS.ProcessEnv, exec?: typeof execFileSync, cwd?: string, log?: (line: string) => void, now?: () => number, sleep?: (ms: number) => void}} [options]
+ * @returns {{attested: boolean, reason: string, sha?: string, tree?: string, os?: string, node?: number, stages?: string[], creator?: string, createdAt?: string, baseDrift?: string[]|null, waitedMs?: number}}
*/
-export function resolveCiAttestation({ env = process.env, exec = execFileSync, cwd = process.cwd(), log = console.warn } = {}) {
+export function resolveCiAttestation({ env = process.env, exec = execFileSync, cwd = process.cwd(), log = console.warn, now = Date.now, sleep = sleepMs } = {}) {
const none = (reason) => {
log(`⏭️ Pregate attestation not honored: ${reason}.`);
return { attested: false, reason };
@@ -1683,40 +1751,67 @@ export function resolveCiAttestation({ env = process.env, exec = execFileSync, c
}
const headTree = capture('git', ['rev-parse', '--verify', '--quiet', `${headSha}^{tree}`]);
if (typeof headTree !== 'string') return none(`cannot resolve the tree of head ${headSha.slice(0, 9)}`);
- const body = capture('gh', ['api', `repos/${repository}/commits/${headSha}/statuses?per_page=100`]);
- if (typeof body !== 'string') return none(`statuses API failed: ${body.error}`);
- let statuses;
- try {
- statuses = JSON.parse(body);
- } catch {
- return none('statuses API returned unreadable JSON');
+ const committed = capture('git', ['show', '-s', '--format=%ct', headSha]);
+ const headAgeSeconds = typeof committed === 'string' && /^\d+$/.test(committed) ? Math.floor(now() / 1000) - Number(committed) : null;
+
+ const readStatuses = () => {
+ const body = capture('gh', ['api', `repos/${repository}/commits/${headSha}/statuses?per_page=100`]);
+ if (typeof body !== 'string') return { error: `statuses API failed: ${body.error}` };
+ try {
+ return { statuses: JSON.parse(body) };
+ } catch {
+ return { error: 'statuses API returned unreadable JSON' };
+ }
+ };
+ const started = now();
+ let waitedMs = 0;
+ let selected;
+ for (;;) {
+ const read = readStatuses();
+ if (read.error) return none(read.error);
+ selected = selectAttestation(read.statuses, { owner, headTree });
+ const missing = !selected.attestation && selected.reason.startsWith('no "');
+ const young = headAgeSeconds !== null && headAgeSeconds >= 0 && headAgeSeconds < ATTESTATION_YOUNG_HEAD_SECONDS;
+ if (!missing || !young || now() - started >= ATTESTATION_POLL_TOTAL_MS) break;
+ sleep(ATTESTATION_POLL_INTERVAL_MS);
+ waitedMs = now() - started;
}
- const { attestation, reason } = selectAttestation(statuses, { owner, headTree });
- if (!attestation) return none(reason);
- log(`✅ Pregate attestation on ${headSha.slice(0, 9)} (tree ${attestation.tree.slice(0, 12)}): ${attestation.stages.join(', ')} — ${reason}.`);
- return { attested: true, reason, sha: headSha, ...attestation };
+ if (waitedMs > 0) log(`⏳ Waited ${Math.round(waitedMs / 1000)}s for a pregate status on the ${headAgeSeconds}s-old head ${headSha.slice(0, 9)}.`);
+ if (!selected.attestation) return none(selected.reason);
+ const drift = capture('git', ['diff', '--name-only', 'HEAD^2', 'HEAD']);
+ const baseDrift = typeof drift === 'string' ? drift.split('\n').filter(Boolean) : null;
+ const { attestation, reason } = selected;
+ log(`✅ Pregate attestation on ${headSha.slice(0, 9)} (tree ${attestation.tree.slice(0, 12)}): ${attestation.stages.join(', ')} — ${reason}; base moved by ${baseDrift ? `${baseDrift.length} file(s)` : 'an unreadable diff'}.`);
+ return { attested: true, reason, sha: headSha, ...attestation, baseDrift, waitedMs };
+}
+
+function sleepMs(ms) {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
/**
* The plan with every attested stage skipped and the decision recorded.
*
- * The server job owns the boot smoke (`smoke == 'true' && matrix.shard == 1`
- * on a job gated by `server_mode != 'skip'`), so `server` is skipped only when
- * the smoke is attested too or was never selected; otherwise skipping the job
- * would drop an unattested smoke on the floor. `full` is forced false so the
- * `Full CI Gate` is never published for a run that skipped anything on the
- * strength of a local receipt. Windows, Linux containment, the Node-minimum
- * check and the shard matrices are left as the plan computed them.
+ * Stages the base-side drift refuses (`attestationDrift`) stay as planned and
+ * say why. The server job owns the boot smoke (`smoke == 'true' &&
+ * matrix.shard == 1` on a job gated by `server_mode != 'skip'`), so `server`
+ * is skipped only when the smoke is attested too or was never selected;
+ * otherwise skipping the job would drop an unattested smoke on the floor.
+ * `full` is forced false so the `Full CI Gate` is never published for a run
+ * that skipped anything on the strength of a local receipt. Windows, Linux
+ * containment, the Node-minimum check and the shard matrices are left as the
+ * plan computed them.
*
* @param {object} plan - a finished plan (buildCiTestPlan)
- * @param {{attested: boolean, reason: string, stages?: string[], sha?: string, tree?: string, creator?: string, createdAt?: string}} attestation
+ * @param {{attested: boolean, reason: string, stages?: string[], sha?: string, tree?: string, os?: string, node?: number, creator?: string, createdAt?: string, baseDrift?: string[]|null}} attestation
*/
export function applyAttestation(plan, attestation) {
const base = { ...plan, attestation, attestedStages: [] };
if (!attestation?.attested) {
return { ...base, suiteReasons: { ...plan.suiteReasons, attestation: `not honored: ${attestation?.reason ?? 'unknown'}` } };
}
- const attested = new Set(attestation.stages ?? []);
+ const refused = attestationDrift(plan, attestation.baseDrift ?? null);
+ const attested = new Set((attestation.stages ?? []).filter((stage) => !refused[stage]));
const smokeCovered = attested.has('smoke') || !plan.smoke;
const skips = { ...ATTESTATION_SKIPS, server: smokeCovered ? (current) => ({ server: { ...current.server, mode: 'skip' } }) : null };
let next = base;
@@ -1726,13 +1821,18 @@ export function applyAttestation(plan, attestation) {
next = { ...next, ...skips[stage](next) };
skipped.push(stage);
}
- const label = `attested by pregate on ${String(attestation.sha ?? '').slice(0, 9)} (tree ${String(attestation.tree ?? '').slice(0, 12)})`;
+ const label = `attested by pregate on ${String(attestation.sha ?? '').slice(0, 9)} (tree ${String(attestation.tree ?? '').slice(0, 12)}, ${attestation.os ?? '?'}/node ${attestation.node ?? '?'})`;
+ const driftRefused = Object.fromEntries((attestation.stages ?? []).filter((stage) => refused[stage]).map((stage) => [stage, refused[stage]]));
const suiteReasons = { ...plan.suiteReasons, attestation: `${label}: skipping ${skipped.join(', ') || 'nothing'}` };
- for (const stage of skipped) suiteReasons[stage === 'prompt-history' ? 'promptHistory' : stage] = `skipped: ${label}`;
+ const reasonKey = (stage) => (stage === 'prompt-history' ? 'promptHistory' : stage);
+ for (const stage of skipped) suiteReasons[reasonKey(stage)] = `skipped: ${label}`;
+ for (const [stage, reason] of Object.entries(driftRefused)) {
+ if (stage !== 'scan') suiteReasons[reasonKey(stage)] = `${plan.suiteReasons[reasonKey(stage)] ?? 'planned'}; attestation refused: ${reason}`;
+ }
if (attested.has('server') && !smokeCovered) {
suiteReasons.server = `${plan.suiteReasons.server}; server job kept: the boot smoke was not attested`;
}
- return { ...next, full: false, attestedStages: skipped, suiteReasons };
+ return { ...next, full: false, attestedStages: skipped, attestation: { ...attestation, driftRefused }, suiteReasons };
}
function main() {
diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.js
index 5e9e83cf34..8709bb9f7c 100644
--- a/scripts/ci-test-plan.test.js
+++ b/scripts/ci-test-plan.test.js
@@ -14,6 +14,7 @@ import { encodeAttestation } from './lib/pregateAttestation.js';
import {
ALWAYS_RUN_TESTS,
applyAttestation,
+ attestationDrift,
attestationEligibility,
BROWSER_SUITES,
buildCiTestPlan,
@@ -1961,28 +1962,38 @@ describe('pregate attestation', () => {
const TREE = 'a'.repeat(40);
const HEAD = 'c'.repeat(40);
const REPOSITORY = 'acme/widget';
+ const ALL = ['scan', 'lint', 'server', 'smoke', 'client', 'build', 'db', 'browser', 'prompt-history'];
+ const encode = (stages, tree = TREE) => encodeAttestation({ tree, stages, os: 'darwin', node: 26 });
const prEnv = {
CI_EVENT_NAME: 'pull_request', CI_REPOSITORY: REPOSITORY, CI_REPOSITORY_OWNER: 'acme', CI_PR_HEAD_REPO: REPOSITORY,
CI_PR_HEAD_SHA: HEAD, CI_PR_AUTHOR: 'acme', CI_BASE_REF: 'main', CI_FORCE_FULL: 'false',
};
const status = (overrides = {}) => ({
- context: 'pregate', state: 'success', creator: { login: 'acme' }, created_at: '2026-10-18T10:00:00Z',
- description: encodeAttestation({ tree: TREE, stages: ['scan', 'lint', 'server', 'smoke', 'client', 'build', 'db', 'browser', 'prompt-history'] }),
- ...overrides,
+ context: 'pregate', state: 'success', creator: { login: 'acme' }, created_at: '2026-10-18T10:00:00Z', description: encode(ALL), ...overrides,
});
- /** An execFileSync double: git answers from `git`, gh from `statuses`; a thrown entry throws. */
- const fakeExec = ({ mergeHead = HEAD, headTree = TREE, statuses = [status()], apiError = null } = {}) => (command, args) => {
+ const NOW = 1_800_000_000_000;
+ /** An execFileSync double: git answers from the options, gh from `statuses`; a thrown entry throws. */
+ const fakeExec = ({ mergeHead = HEAD, headTree = TREE, statuses = [status()], apiError = null, drift = [], committedAt = Math.floor(NOW / 1000) - 3600, calls = [] } = {}) => (command, args) => {
const key = `${command} ${args.join(' ')}`;
+ calls.push(key);
if (key === 'git rev-parse --verify --quiet HEAD^2') return `${mergeHead}\n`;
if (key === `git rev-parse --verify --quiet ${HEAD}^{tree}`) return `${headTree}\n`;
+ if (key === `git show -s --format=%ct ${HEAD}`) return `${committedAt}\n`;
+ if (key === 'git diff --name-only HEAD^2 HEAD') {
+ if (drift === null) throw new Error('diff failed');
+ return `${drift.join('\n')}\n`;
+ }
if (key.startsWith('gh api ')) {
if (apiError) throw Object.assign(new Error('gh failed'), { stderr: apiError });
expect(key).toBe(`gh api repos/${REPOSITORY}/commits/${HEAD}/statuses?per_page=100`);
- return typeof statuses === 'string' ? statuses : JSON.stringify(statuses);
+ const page = typeof statuses === 'function' ? statuses() : statuses;
+ return typeof page === 'string' ? page : JSON.stringify(page);
}
throw new Error(`unexpected ${key}`);
};
const quiet = () => {};
+ const clock = () => { let t = NOW; return { now: () => t, sleep: (ms) => { t += ms; } }; };
+ const resolve = (options = {}, env = prEnv, extra = {}) => resolveCiAttestation({ env, exec: fakeExec(options), log: quiet, ...clock(), ...extra });
const fullPlan = () => buildCiTestPlan(['server/index.js'], { trackedFiles: TRACKED, forceFull: true, forceFullReason: 'full CI requested' });
it('is eligible only for a same-repository, non-bot pull request into a non-release base', () => {
@@ -1996,38 +2007,92 @@ describe('pregate attestation', () => {
expect(attestationEligibility({}).eligible).toBe(false);
});
- it('honors the owner\'s newest successful status whose tree is the head tree, and nothing else', () => {
- const honored = resolveCiAttestation({ env: prEnv, exec: fakeExec(), log: quiet });
- expect(honored).toMatchObject({ attested: true, sha: HEAD, tree: TREE, creator: 'acme' });
+ it('honors the owner\'s newest pregate status whose tree is the head tree, and nothing else', () => {
+ const honored = resolve();
+ expect(honored).toMatchObject({ attested: true, sha: HEAD, tree: TREE, creator: 'acme', os: 'darwin', node: 26, baseDrift: [], waitedMs: 0 });
expect(honored.stages).toContain('server');
- const older = status({ created_at: '2026-10-18T09:00:00Z', description: encodeAttestation({ tree: TREE, stages: ['lint'] }) });
- const newest = status({ created_at: '2026-10-18T11:00:00Z', description: encodeAttestation({ tree: TREE, stages: ['db'] }) });
- expect(resolveCiAttestation({ env: prEnv, exec: fakeExec({ statuses: [older, newest] }), log: quiet }).stages).toEqual(['db']);
+ const older = status({ created_at: '2026-10-18T09:00:00Z', description: encode(['lint']) });
+ const newest = status({ created_at: '2026-10-18T11:00:00Z', description: encode(['db']) });
+ expect(resolve({ statuses: [older, newest] }).stages).toEqual(['db']);
const reasons = [];
const log = (line) => reasons.push(line);
const refused = (options, env = prEnv) => {
- const result = resolveCiAttestation({ env, exec: fakeExec(options), log });
+ const result = resolveCiAttestation({ env, exec: fakeExec(options), log, ...clock() });
expect(result.attested).toBe(false);
return result.reason;
};
expect(refused({ statuses: [status({ creator: { login: 'someone' } })] })).toMatch(/created by "someone"/);
+ expect(refused({ statuses: [status(), status({ state: 'failure', description: 'revoked: flaky', created_at: '2026-10-18T12:00:00Z' })] })).toMatch(/newest pregate status is failure, not success \(revoked: flaky\)/);
expect(refused({ headTree: 'b'.repeat(40) })).toMatch(/is not the head tree/);
expect(refused({ mergeHead: 'd'.repeat(40) })).toMatch(/not the merge ref of head/);
expect(refused({ apiError: 'HTTP 403: Resource not accessible by integration' })).toMatch(/statuses API failed: HTTP 403/);
expect(refused({ statuses: '<html>captive portal</html>' })).toMatch(/unreadable JSON/);
- expect(refused({ statuses: [] })).toMatch(/no successful "pregate" status/);
+ expect(refused({ statuses: [] })).toMatch(/no "pregate" status/);
expect(refused({}, { ...prEnv, CI_PR_HEAD_REPO: 'someone/widget' })).toMatch(/head repository/);
// Every refusal is logged with its reason — the summary's only evidence.
expect(reasons.every((line) => line.startsWith('⏭️ Pregate attestation not honored: '))).toBe(true);
- expect(reasons).toHaveLength(7);
+ expect(reasons).toHaveLength(8);
+ });
+
+ it('waits up to 90 s for a status on a head younger than five minutes, and not on an older one', () => {
+ // The status is posted after the push that started this run, so a young
+ // head with no status yet is re-read at 10 s intervals.
+ let reads = 0;
+ const lateStatuses = () => { reads += 1; return reads < 4 ? [] : [status()]; };
+ const calls = [];
+ const young = resolveCiAttestation({ env: prEnv, exec: fakeExec({ statuses: lateStatuses, committedAt: Math.floor(NOW / 1000) - 60, calls }), log: quiet, ...clock() });
+ expect(young).toMatchObject({ attested: true, waitedMs: 30_000 });
+ expect(reads).toBe(4);
+
+ reads = 0;
+ const lines = [];
+ const never = resolveCiAttestation({ env: prEnv, exec: fakeExec({ statuses: () => { reads += 1; return []; }, committedAt: Math.floor(NOW / 1000) - 60 }), log: (line) => lines.push(line), ...clock() });
+ expect(never.attested).toBe(false);
+ expect(reads).toBe(10);
+ expect(lines.some((line) => /^⏳ Waited 90s for a pregate status on the 60s-old head/.test(line))).toBe(true);
+
+ reads = 0;
+ expect(resolve({ statuses: () => { reads += 1; return []; } }).attested).toBe(false);
+ expect(reads).toBe(1);
+ // A revocation or a mismatch is final: no waiting for it to change.
+ reads = 0;
+ expect(resolve({ statuses: () => { reads += 1; return [status({ state: 'failure' })]; }, committedAt: Math.floor(NOW / 1000) - 60 }).attested).toBe(false);
+ expect(reads).toBe(1);
+ });
+
+ it('refuses, per stage, the stages a base-side change could reach', () => {
+ const plan = { ...fullPlan(), server: { mode: 'files', files: ['server/lib/picked.test.js'], sources: [] }, client: { mode: 'files', files: ['client/src/picked.test.jsx'], sources: [] }, browserFiles: [BROWSER_SUITES[0]] };
+ const refusedBy = (drift) => Object.keys(attestationDrift(plan, drift)).sort();
+ expect(refusedBy([])).toEqual([]);
+ expect(refusedBy(['docs/GUIDE.md', 'README.md', 'client/public/logo.png'])).toEqual([]);
+ // (a) a test file the plan selected for that runner (every server or
+ // client module is also a lint surface: lint runs the whole tree)
+ expect(refusedBy(['server/lib/picked.test.js'])).toEqual(['lint', 'server']);
+ expect(refusedBy(['client/src/picked.test.jsx'])).toEqual(['client', 'lint']);
+ expect(refusedBy(['server/lib/unpicked.test.js'])).toEqual(['lint']);
+ expect(refusedBy([BROWSER_SUITES[0]])).toEqual(['browser', 'lint']);
+ expect(refusedBy(['server/services/backup.db.test.js'])).toEqual(['db', 'lint']);
+ // (b) a non-test source under the runner's roots
+ expect(refusedBy(['server/services/thing.js'])).toEqual(['browser', 'db', 'lint', 'server', 'smoke']);
+ expect(refusedBy(['client/src/components/Thing.jsx'])).toEqual(['browser', 'build', 'client', 'lint']);
+ expect(refusedBy(['scripts/tool.js'])).toEqual(['server']);
+ expect(refusedBy(['scripts/migrations/999-x.js'])).toEqual(['prompt-history', 'server']);
+ expect(refusedBy(['data.reference/prompts/stages/x.md'])).toEqual(['prompt-history']);
+ // (c) runner config and setup files refuse everything
+ for (const config of ['server/vitest.config.js', 'client/vitest.config.js', 'scripts/vitestCiPool.js', 'server/package-lock.json', '.github/workflows/ci.yml', 'scripts/run-ci-tests.js']) {
+ expect(refusedBy([config]), config).toEqual(['browser', 'build', 'client', 'db', 'lint', 'prompt-history', 'server', 'smoke']);
+ }
+ expect(attestationDrift(plan, ['server/services/thing.js']).server).toBe('base branch moved: server/services/thing.js');
+ // Unreadable drift refuses everything.
+ expect(refusedBy(null)).toHaveLength(8);
});
it('skips the attested stages, reports full=false, and leaves the CI-only jobs alone', () => {
const plan = fullPlan();
expect(plan).toMatchObject({ full: true, windows: true, linuxContainment: true, promptHistory: true, db: true, build: true, smoke: true });
- const attested = applyAttestation(plan, resolveCiAttestation({ env: prEnv, exec: fakeExec(), log: quiet }));
+ const attested = applyAttestation(plan, resolve());
expect(attested).toMatchObject({
full: false,
server: { mode: 'skip' }, client: { mode: 'skip' }, lint: { mode: 'skip' },
@@ -2037,16 +2102,35 @@ describe('pregate attestation', () => {
shards: plan.shards,
});
expect(attested.attestedStages).toEqual(['prompt-history', 'lint', 'server', 'client', 'build', 'smoke', 'browser', 'db']);
- expect(attested.suiteReasons.server).toBe(`skipped: attested by pregate on ${HEAD.slice(0, 9)} (tree ${TREE.slice(0, 12)})`);
+ expect(attested.attestation.driftRefused).toEqual({});
+ expect(attested.suiteReasons.server).toBe(`skipped: attested by pregate on ${HEAD.slice(0, 9)} (tree ${TREE.slice(0, 12)}, darwin/node 26)`);
expect(attested.suiteReasons.promptHistory).toMatch(/^skipped: attested by pregate/);
expect(attested.suiteReasons.windows).toBe(plan.suiteReasons.windows);
expect(attested.suiteReasons.attestation).toMatch(/^attested by pregate .*: skipping prompt-history, lint, server/);
expect(attested.changedFiles).toEqual(plan.changedFiles);
});
+ it('keeps every stage the base movement refuses, with the path, and skips the rest', () => {
+ const plan = fullPlan();
+ const moved = resolve({ drift: ['server/services/thing.js', 'docs/x.md'] });
+ const attested = applyAttestation(plan, moved);
+ expect(attested.attestedStages).toEqual(['prompt-history', 'client', 'build']);
+ expect(attested).toMatchObject({ full: false, server: { mode: plan.server.mode }, lint: { mode: plan.lint.mode }, smoke: true, db: true, client: { mode: 'skip' }, build: false, promptHistory: false });
+ expect(attested.browserFiles).toEqual(plan.browserFiles);
+ expect(attested.attestation.driftRefused).toEqual({
+ server: 'base branch moved: server/services/thing.js', lint: 'base branch moved: server/services/thing.js', smoke: 'base branch moved: server/services/thing.js',
+ browser: 'base branch moved: server/services/thing.js', db: 'base branch moved: server/services/thing.js',
+ });
+ expect(attested.suiteReasons.server).toBe(`${plan.suiteReasons.server}; attestation refused: base branch moved: server/services/thing.js`);
+ // The probe: a merge tree that differs from the head tree in runner source attests nothing for that runner.
+ const unreadable = applyAttestation(plan, resolve({ drift: null }));
+ expect(unreadable.attestedStages).toEqual([]);
+ expect(unreadable.server.mode).toBe(plan.server.mode);
+ });
+
it('keeps the server job when the boot smoke it owns was not attested', () => {
const plan = fullPlan();
- const partial = { attested: true, reason: 'r', sha: HEAD, tree: TREE, stages: ['scan', 'server', 'lint'] };
+ const partial = { attested: true, reason: 'r', sha: HEAD, tree: TREE, os: 'linux', node: 24, stages: ['scan', 'server', 'lint'], baseDrift: [] };
const attested = applyAttestation(plan, partial);
expect(attested.server.mode).toBe(plan.server.mode);
expect(attested.smoke).toBe(true);
@@ -2073,8 +2157,8 @@ describe('pregate attestation', () => {
// the decision logic on every platform; this one proves the CLI wiring.
it.skipIf(process.platform === 'win32')('emits the attestation through the planner CLI', () => {
// A merge-ref checkout (HEAD^2 is the pull request head) with a fake `gh`
- // on PATH, so the whole wiring — env in, statuses API, plan outputs — runs
- // exactly as the impact job does.
+ // on PATH, so the whole wiring — env in, statuses API, base drift, plan
+ // outputs — runs exactly as the impact job does.
const root = mkdtempSync(join(tmpdir(), 'portos-ci-attest-'));
const bin = join(root, 'bin');
const planner = fileURLToPath(new URL('./ci-test-plan.js', import.meta.url));
@@ -2097,20 +2181,24 @@ describe('pregate attestation', () => {
const head = git('rev-parse', 'HEAD');
const headTree = git('rev-parse', 'HEAD^{tree}');
git('checkout', '-q', 'main');
+ // The base moves by a docs file only: the attestation survives it.
+ write('docs/note.md', 'base moved\n');
+ git('add', '--all');
+ git('commit', '-qm', 'docs on main');
git('merge', '-q', '--no-ff', '--no-edit', 'feature');
const base = git('rev-parse', 'HEAD^1');
mkdirSync(bin, { recursive: true });
writeFileSync(join(bin, 'gh.js'), 'process.stdout.write(process.env.FAKE_GH_STATUSES);\n');
writeFileSync(join(bin, 'gh'), `#!/bin/sh\nexec "${process.execPath}" "$(dirname "$0")/gh.js" "$@"\n`, { mode: 0o755 });
- const statuses = JSON.stringify([status({ description: encodeAttestation({ tree: headTree, stages: ['scan', 'lint', 'server', 'smoke', 'client', 'build'] }) })]);
+ const statuses = JSON.stringify([status({ description: encode(['scan', 'lint', 'server', 'smoke', 'client', 'build'], headTree) })]);
const plan = (env) => JSON.parse(execFileSync(process.execPath, [planner], {
cwd: root, encoding: 'utf8',
env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, FAKE_GH_STATUSES: statuses, CI_BASE_SHA: base, GITHUB_OUTPUT: '', GITHUB_STEP_SUMMARY: '', ...prEnv, CI_PR_HEAD_SHA: head, ...env },
}));
const honored = plan({});
- expect(JSON.parse(honored.attestation)).toMatchObject({ attested: true, sha: head, tree: headTree, creator: 'acme' });
+ expect(JSON.parse(honored.attestation)).toMatchObject({ attested: true, sha: head, tree: headTree, creator: 'acme', os: 'darwin', node: 26, baseDrift: ['docs/note.md'], driftRefused: {} });
expect(JSON.parse(honored.attested_stages)).toEqual(['lint', 'server', 'client', 'build', 'smoke']);
expect(honored).toMatchObject({ full: false, server_mode: 'skip', client_mode: 'skip', lint_mode: 'skip', build: false, smoke: false });
expect(JSON.parse(honored.suite_reasons).attestation).toMatch(/^attested by pregate/);
@@ -2140,7 +2228,8 @@ describe('pregate attestation', () => {
]) expect(planStep).toContain(line);
expect(jobs.impact).toContain('attestation: ${{ steps.plan.outputs.attestation }}');
expect(jobs.impact).toContain('attested_stages: ${{ steps.plan.outputs.attested_stages }}');
- // The summary is where a reader learns a stage was skipped on a receipt.
+ // The summary is where a reader learns a stage was skipped on a receipt,
+ // and the attestation JSON carries the platform and Node it ran on.
expect(jobs.impact).toContain('ATTESTATION: ${{ steps.plan.outputs.attestation }}');
expect(jobs.impact).toMatch(/echo "- Pregate attestation: \\`\$\{ATTESTATION\}\\`"/);
// The full gate must stay withheld: `full` is reported false on an attested run.
diff --git a/scripts/lib/pregateAttestation.js b/scripts/lib/pregateAttestation.js
index 2a13f0c485..676e884a0e 100644
--- a/scripts/lib/pregateAttestation.js
+++ b/scripts/lib/pregateAttestation.js
@@ -6,8 +6,10 @@
* The status is bound to a TREE hash, not a commit: the receipt hashes the
* exact working tree pregate validated, and the planner compares it with
* `<head>^{tree}` — the same "content, not SHA" reasoning as
- * `scripts/verify-ci-status.js`. A description is at most 140 characters
- * (GitHub's limit), which fits every stage name with room to spare.
+ * `scripts/verify-ci-status.js`. The description also names the platform and
+ * Node major the stages ran on, so the plan summary can show what vouched for
+ * a Linux job. A description is at most 140 characters (GitHub's limit),
+ * which fits every stage name plus those two fields.
*
* Builtins only: the planner loads this before any dependency install.
*/
@@ -54,19 +56,27 @@ export function attestedStagesFromReceipt(report) {
});
}
+/** `process.version` → its major, e.g. `v26.10.0` → 26. */
+export const nodeMajor = (version) => {
+ const match = /^v?(\d+)/.exec(String(version ?? ''));
+ return match ? Number(match[1]) : null;
+};
+
/**
- * The status description for a tree and its attested stages.
+ * The status description for a tree, the platform it ran on, and its stages.
*
- * @param {{tree: string, stages: string[]}} attestation
+ * @param {{tree: string, stages: string[], os: string, node: number}} attestation
* @returns {string}
*/
-export function encodeAttestation({ tree, stages }) {
+export function encodeAttestation({ tree, stages, os, node }) {
if (!TREE_RE.test(tree ?? '')) throw new Error('attestation needs a 40-hex tree hash');
+ if (!/^[a-z0-9]+$/.test(os ?? '')) throw new Error('attestation needs a platform name (process.platform)');
+ if (!Number.isInteger(node) || node <= 0) throw new Error('attestation needs a Node major version');
const ordered = ATTESTABLE_STAGES.filter((stage) => stages.includes(stage));
const unknown = stages.filter((stage) => !ATTESTABLE.has(stage));
if (unknown.length > 0) throw new Error(`unknown attestation stage(s): ${unknown.join(', ')}`);
if (ordered.length === 0) throw new Error('attestation needs at least one stage');
- const description = `tree=${tree} stages=${ordered.join(',')}`;
+ const description = `tree=${tree} os=${os} node=${node} stages=${ordered.join(',')}`;
if (description.length > STATUS_DESCRIPTION_MAX_LENGTH) {
throw new Error(`attestation description exceeds ${STATUS_DESCRIPTION_MAX_LENGTH} characters`);
}
@@ -74,66 +84,93 @@ export function encodeAttestation({ tree, stages }) {
}
/**
- * The tree and stages a status description claims, or null when it is not an
- * attestation this module wrote: any unknown stage name, a malformed tree, or
- * extra fields make the whole description unreadable rather than partially
- * trusted.
+ * The tree, platform, Node major and stages a status description claims, or
+ * null when it is not an attestation this module wrote: any unknown stage
+ * name, a malformed tree, or extra fields make the whole description
+ * unreadable rather than partially trusted.
*
* @param {string} description
- * @returns {{tree: string, stages: string[]}|null}
+ * @returns {{tree: string, stages: string[], os: string, node: number}|null}
*/
export function parseAttestation(description) {
- const match = /^tree=([0-9a-f]{40}) stages=([a-z,-]+)$/.exec(String(description ?? '').trim());
+ const match = /^tree=([0-9a-f]{40}) os=([a-z0-9]+) node=(\d{1,3}) stages=([a-z,-]+)$/.exec(String(description ?? '').trim());
if (!match) return null;
- const stages = match[2].split(',');
+ const stages = match[4].split(',');
if (stages.length === 0 || stages.some((stage) => !ATTESTABLE.has(stage))) return null;
if (new Set(stages).size !== stages.length) return null;
- return { tree: match[1], stages: ATTESTABLE_STAGES.filter((stage) => stages.includes(stage)) };
+ return { tree: match[1], os: match[2], node: Number(match[3]), stages: ATTESTABLE_STAGES.filter((stage) => stages.includes(stage)) };
+}
+
+/**
+ * The description a revocation posts: a `failure` state whose text says why,
+ * so the planner's refusal names it and a reader of the commit's statuses
+ * sees the operator's reason.
+ */
+export function encodeRevocation(reason) {
+ const text = `revoked: ${String(reason ?? '').trim() || 'pregate result withdrawn'}`.replace(/[\r\n]+/g, ' ');
+ return text.length > STATUS_DESCRIPTION_MAX_LENGTH ? `${text.slice(0, STATUS_DESCRIPTION_MAX_LENGTH - 1)}…` : text;
}
+/**
+ * GitHub's SSH endpoint hosts answer for github.com. Same rule as
+ * `server/lib/gitRemote.js`: the host is what the API is addressed to.
+ */
+const API_HOST_ALIASES = { 'ssh.github.com': 'github.com' };
+
/**
* Parse an `owner/repo` out of a git remote URL — the SSH and HTTPS shapes
* `server/lib/gitRemote.js#parseGitRemoteUrl` accepts, without that module's
- * ssh-alias resolution (the API host is always github.com here) or its
- * import closure. Null for anything that is not exactly two path segments.
+ * ssh-config alias resolution or its import closure. `ssh.github.com` is
+ * folded to `github.com`. A personal ssh alias (`git@github-acme:…`, no dot in
+ * the host) parses but `hostIsResolvable` is false for it: the caller then
+ * learns the real host from `gh repo view`. Null for anything that is not
+ * exactly two path segments.
*
* @param {string} url
- * @returns {{host: string, owner: string, repo: string}|null}
+ * @returns {{host: string, owner: string, repo: string, hostIsResolvable: boolean}|null}
*/
export function parseRemoteRepository(url) {
if (typeof url !== 'string' || !url.trim()) return null;
const trimmed = url.trim().replace(/\/$/, '');
const stripGit = (value) => value.replace(/\.git$/i, '');
- const stripPort = (host) => host.replace(/:\d+$/, '');
+ const normalizeHost = (host) => {
+ const bare = host.replace(/:\d+$/, '').toLowerCase();
+ return API_HOST_ALIASES[bare] ?? bare;
+ };
+ const shape = (host, owner, repo) => ({ host, owner, repo: stripGit(repo), hostIsResolvable: host.includes('.') });
const scp = /^[a-zA-Z0-9._-]+@([^:]+):(?:\d+\/)?([^/]+)\/([^/]+)$/.exec(trimmed);
- if (scp) return { host: stripPort(scp[1]), owner: scp[2], repo: stripGit(scp[3]) };
+ if (scp) return shape(normalizeHost(scp[1]), scp[2], scp[3]);
const urlStyle = /^[a-zA-Z]+:\/\/(?:[^@/]+@)?([^/]+)\/([^/]+)\/([^/]+)$/.exec(trimmed);
- if (urlStyle) return { host: stripPort(urlStyle[1]), owner: urlStyle[2], repo: stripGit(urlStyle[3]) };
+ if (urlStyle) return shape(normalizeHost(urlStyle[1]), urlStyle[2], urlStyle[3]);
return null;
}
/**
- * The newest usable attestation among a commit's statuses, or null with the
- * reason none qualifies.
+ * The newest `pregate` status decides, whatever its state: a later `failure`
+ * (a revocation, `pregate-attest.js --revoke`) or `pending`/`error` withdraws
+ * an earlier success on the same commit, and a later success by someone else
+ * blocks it too — the newest word on the commit is not the owner's.
*
* Trust rests on three facts, each checked here: only a repository writer can
* create a status on this repository (a fork's `pull_request` token is
* read-only); the status was created by the repository owner; and the tree it
- * names is the tree of the head being tested. "Newest" is by `created_at`, so
- * a re-run of pregate-attest after a fix supersedes an older attestation on
- * the same commit.
+ * names is the tree of the head commit.
*
* @param {Array<object>} statuses - `/repos/{repo}/commits/{sha}/statuses` rows
* @param {{owner: string, headTree: string}} expected
- * @returns {{attestation: {tree: string, stages: string[], creator: string, createdAt: string}|null, reason: string}}
+ * @returns {{attestation: {tree: string, stages: string[], os: string, node: number, creator: string, createdAt: string}|null, reason: string}}
*/
export function selectAttestation(statuses, { owner, headTree }) {
if (!Array.isArray(statuses)) return { attestation: null, reason: 'statuses unreadable' };
const candidates = statuses
- .filter((status) => status?.context === PREGATE_STATUS_CONTEXT && status?.state === 'success')
+ .filter((status) => status?.context === PREGATE_STATUS_CONTEXT)
.sort((a, b) => String(b?.created_at ?? '').localeCompare(String(a?.created_at ?? '')));
- if (candidates.length === 0) return { attestation: null, reason: `no successful "${PREGATE_STATUS_CONTEXT}" status on the head` };
+ if (candidates.length === 0) return { attestation: null, reason: `no "${PREGATE_STATUS_CONTEXT}" status on the head` };
const newest = candidates[0];
+ if (newest?.state !== 'success') {
+ const detail = typeof newest?.description === 'string' && newest.description ? ` (${newest.description.slice(0, 80)})` : '';
+ return { attestation: null, reason: `newest pregate status is ${newest?.state ?? 'unknown'}, not success${detail}` };
+ }
const creator = newest?.creator?.login;
if (!owner || creator !== owner) {
return { attestation: null, reason: `newest pregate status was created by ${creator ? `"${creator}"` : 'an unknown actor'}, not the repository owner` };
@@ -143,5 +180,5 @@ export function selectAttestation(statuses, { owner, headTree }) {
if (!TREE_RE.test(headTree ?? '') || parsed.tree !== headTree) {
return { attestation: null, reason: `attested tree ${parsed.tree.slice(0, 12)} is not the head tree ${String(headTree ?? '').slice(0, 12) || '(unknown)'}` };
}
- return { attestation: { ...parsed, creator, createdAt: String(newest.created_at ?? '') }, reason: `attested by ${creator} at ${newest.created_at}` };
+ return { attestation: { ...parsed, creator, createdAt: String(newest.created_at ?? '') }, reason: `attested by ${creator} at ${newest.created_at} on ${parsed.os}/node ${parsed.node}` };
}
diff --git a/scripts/pre-install-entrypoints.test.js b/scripts/pre-install-entrypoints.test.js
index b98cb9505f..9576290a97 100644
--- a/scripts/pre-install-entrypoints.test.js
+++ b/scripts/pre-install-entrypoints.test.js
@@ -29,6 +29,7 @@ const PRE_INSTALL_ENTRYPOINTS = [
'scripts/ci-dependabot-admission.js',
'scripts/ci-base-sha.js',
'scripts/ci-test-plan.js',
+ 'scripts/check-import-case.js',
'scripts/scan-diff-hidden-content.js',
];
diff --git a/scripts/pregate-attest.js b/scripts/pregate-attest.js
index e01ebde615..a6c9e1cd05 100644
--- a/scripts/pregate-attest.js
+++ b/scripts/pregate-attest.js
@@ -6,23 +6,31 @@
* `npm run pregate` leaves a receipt (`.cache/pregate/report.json`) that names
* the stages it ran and the hash of the exact working tree it validated. This
* script turns a green receipt into a commit status — context `pregate`, state
- * `success`, description `tree=<hash> stages=<…>` — on the commit that carries
- * that same tree, so the pull request's impact planner can skip the attested
- * stages (`applyAttestation` in scripts/ci-test-plan.js). It runs AFTER the
- * push: GitHub only accepts a status on a commit it has.
+ * `success`, description `tree=<hash> os=<platform> node=<major> stages=<…>` —
+ * on the commit that carries that same tree, so the pull request's impact
+ * planner can skip the attested stages (`applyAttestation` in
+ * scripts/ci-test-plan.js). It runs AFTER the push: GitHub only accepts a
+ * status on a commit it has. When you open the pull request yourself, attest
+ * before `gh pr create`, so the status exists when the `pull_request` event
+ * starts the run.
*
* node scripts/pregate-attest.js [--sha <40-hex>] [--dry-run] [--target-url <url>]
+ * node scripts/pregate-attest.js --revoke [<reason>] [--sha <40-hex>]
*
* Refuses, with the command to rerun, when the receipt did not pass or the
* tree changed while pregate ran, when the commit's tree is not the receipt's
* tree (something changed after pregate: rerun it on this exact state), when
* the commit is not on the upstream remote yet, or when no stage qualifies.
* Only stages that ran and passed are attested; a skipped or uncovered suite
- * is CI's to prove, exactly as the pregate summary said.
+ * is CI's to prove, exactly as the pregate summary said. A receipt planned
+ * against a `--base` other than the default branch's merge base attests no
+ * server, client or lint stage: its selection was narrower than CI's.
*
- * Authentication is the operator's own `gh` login; nothing here reads or asks
- * for the PortOS instance password. Builtins only, like the other pregate
- * scripts, so it runs from any checkout without an install.
+ * `--revoke` posts a `failure` status with the reason, which withdraws every
+ * earlier attestation on that commit (the planner honors only the newest
+ * `pregate` status). Authentication is the operator's own `gh` login; nothing
+ * here reads or asks for the PortOS instance password. Builtins only, like
+ * the other pregate scripts, so it runs from any checkout without an install.
*/
import { spawnSync } from 'node:child_process';
@@ -31,26 +39,31 @@ import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { isDirectlyInvoked } from './lib/directInvocation.js';
import {
- attestedStagesFromReceipt, encodeAttestation, parseRemoteRepository, PREGATE_STATUS_CONTEXT,
+ attestedStagesFromReceipt, encodeAttestation, encodeRevocation, nodeMajor, parseRemoteRepository, PREGATE_STATUS_CONTEXT,
} from './lib/pregateAttestation.js';
import { PREGATE_REPORT_PATH } from './lib/pregateReport.js';
const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const SHA_RE = /^[0-9a-f]{40}$/;
const RERUN = 'rerun `npm run pregate` on this exact tree, then push and attest again';
+/** Stages whose selection depends on the diff base; a narrowed base under-selects them. */
+const BASE_DEPENDENT_STAGES = new Set(['server', 'client', 'lint']);
export const USAGE = `Usage: node scripts/pregate-attest.js [--sha <40-hex>] [--dry-run] [--target-url <url>]
+ node scripts/pregate-attest.js --revoke [<reason>] [--sha <40-hex>] [--dry-run]
--sha <40-hex> attest this commit instead of HEAD (must carry the receipt's tree)
--dry-run print the status payload without posting it
--target-url <url> optional link to show beside the status
+ --revoke [reason] post a failure status that withdraws earlier attestations on the commit
-h, --help display this usage
-Run it AFTER \`git push\`: a commit status can only be created on a pushed commit.`;
+Run it AFTER \`git push\` (and, for a new pull request, BEFORE \`gh pr create\`):
+a commit status can only be created on a pushed commit.`;
/** Parse argv before any Git inspection. */
export function parseArgs(argv) {
- const options = { sha: null, dryRun: false, targetUrl: null, help: false };
+ const options = { sha: null, dryRun: false, targetUrl: null, help: false, revoke: null };
for (let index = 0; index < argv.length; index += 1) {
const flag = argv[index];
switch (flag) {
@@ -68,6 +81,12 @@ export function parseArgs(argv) {
index += 1;
break;
}
+ case '--revoke': {
+ const value = argv[index + 1];
+ options.revoke = value && !value.startsWith('-') ? value : '';
+ if (options.revoke) index += 1;
+ break;
+ }
case '--dry-run': options.dryRun = true; break;
case '--help':
case '-h': options.help = true; break;
@@ -82,14 +101,14 @@ const refusal = (message) => Object.assign(new Error(message), { refusal: true }
/**
* What to attest, given the receipt and the commit's own facts. Pure: the
- * caller supplies the tree lookup and the push check so this is testable
- * without a repository.
+ * caller supplies the tree lookup, the push check and the default merge base
+ * so this is testable without a repository.
*
* @param {object} report - the parsed receipt
- * @param {{sha: string, treeOf: (sha: string) => string|null, isPushed: (sha: string) => boolean, remote: string}} commit
- * @returns {{sha: string, tree: string, stages: string[], description: string}}
+ * @param {{sha: string, treeOf: (sha: string) => string|null, isPushed: (sha: string) => boolean, remote: string, defaultMergeBase?: string|null, os?: string, node?: number}} commit
+ * @returns {{sha: string, tree: string, stages: string[], description: string, notes: string[]}}
*/
-export function planAttestation(report, { sha, treeOf, isPushed, remote }) {
+export function planAttestation(report, { sha, treeOf, isPushed, remote, defaultMergeBase = null, os = process.platform, node = nodeMajor(process.version) }) {
if (!report || typeof report !== 'object') throw refusal(`no receipt at ${PREGATE_REPORT_PATH}; ${RERUN}`);
if (typeof report.plan?.downgraded !== 'boolean') {
throw refusal(`receipt at ${PREGATE_REPORT_PATH} predates attestation (no plan.downgraded); ${RERUN}`);
@@ -106,29 +125,58 @@ export function planAttestation(report, { sha, treeOf, isPushed, remote }) {
if (!isPushed(sha)) {
throw refusal(`commit ${sha.slice(0, 9)} is not on ${remote} yet: push it first (\`git push\`), then attest. A status can only be posted on a pushed commit.`);
}
- const stages = attestedStagesFromReceipt(report);
- if (stages.length === 0) throw refusal(`the receipt attests no stage: nothing ran and passed beyond what CI must prove itself; ${RERUN}`);
- return { sha, tree, stages, description: encodeAttestation({ tree, stages }) };
+ let stages = attestedStagesFromReceipt(report);
+ const notes = [];
+ // The receipt's plan was computed against its recorded base. CI plans
+ // against the default branch's merge base; a `--base` nearer the head (or an
+ // unknown one) selected fewer tests, so the diff-selected stages are not
+ // CI's stages and cannot be attested. The resource suites run whole.
+ const receiptBase = typeof report.base?.sha === 'string' ? report.base.sha : null;
+ if (!receiptBase || !defaultMergeBase || receiptBase !== defaultMergeBase) {
+ const dropped = stages.filter((stage) => BASE_DEPENDENT_STAGES.has(stage));
+ stages = stages.filter((stage) => !BASE_DEPENDENT_STAGES.has(stage));
+ if (dropped.length > 0) {
+ notes.push(`not attesting ${dropped.join(', ')}: the receipt was planned against base ${receiptBase ? receiptBase.slice(0, 9) : '(unknown)'} (${report.base?.ref ?? report.options?.base ?? '--base'}), not the default branch's merge base ${defaultMergeBase ? defaultMergeBase.slice(0, 9) : '(unresolved)'}; rerun pregate without --base to attest them`);
+ }
+ }
+ if (stages.length === 0) throw refusal(`the receipt attests no stage: nothing ran and passed beyond what CI must prove itself${notes.length ? ` (${notes.join('; ')})` : ''}; ${RERUN}`);
+ return { sha, tree, stages, description: encodeAttestation({ tree, stages, os, node }), notes };
}
-/** The `gh api` invocation that creates the status; exported so tests can pin it. */
-export function statusRequest({ owner, repo, host }, { sha, description, targetUrl }) {
+/** The `gh api` invocation that creates a status; exported so tests can pin it. */
+export function statusRequest({ owner, repo, host }, { sha, description, targetUrl, state = 'success' }) {
const args = [
'api', '--method', 'POST', `repos/${owner}/${repo}/statuses/${sha}`,
- '-f', 'state=success', '-f', `context=${PREGATE_STATUS_CONTEXT}`, '-f', `description=${description}`,
+ '-f', `state=${state}`, '-f', `context=${PREGATE_STATUS_CONTEXT}`, '-f', `description=${description}`,
];
if (targetUrl) args.push('-f', `target_url=${targetUrl}`);
if (host && host !== 'github.com') args.push('--hostname', host);
return { command: 'gh', args };
}
+/**
+ * The repository the status goes to. The upstream remote's URL is the first
+ * word; when its host is an ssh alias (`git@github-acme:…`) or unparseable,
+ * `gh repo view` from the checkout — which resolves the alias through the
+ * same ssh config git does — names the real host and owner/repo.
+ */
+export function resolveRepository(remoteUrl, { ghRepoView }) {
+ const parsed = parseRemoteRepository(remoteUrl ?? '');
+ if (parsed?.hostIsResolvable) return parsed;
+ const viewed = ghRepoView();
+ const url = viewed?.url ? parseRemoteRepository(viewed.url) : null;
+ const [owner, repo] = typeof viewed?.nameWithOwner === 'string' ? viewed.nameWithOwner.split('/') : [];
+ if (url?.hostIsResolvable && owner && repo) return { host: url.host, owner, repo, hostIsResolvable: true };
+ return parsed?.hostIsResolvable ? parsed : null;
+}
+
/**
* Run the attestation. `exec` is `spawnSync`-shaped and injectable so the
* tests drive git and gh without a repository or a network.
*
* @returns {number} the process exit code
*/
-export function runAttest({ argv = [], cwd = REPO_ROOT, exec = spawnSync, log = console.log, error = console.error, readReceipt = defaultReadReceipt } = {}) {
+export function runAttest({ argv = [], cwd = REPO_ROOT, exec = spawnSync, log = console.log, error = console.error, readReceipt = defaultReadReceipt, platform = process.platform, nodeVersion = process.version } = {}) {
let options;
try {
options = parseArgs(argv);
@@ -158,9 +206,18 @@ export function runAttest({ argv = [], cwd = REPO_ROOT, exec = spawnSync, log =
if (!remote) {
throw refusal(`branch ${branch ?? '(detached HEAD)'} has no upstream remote; push it with \`git push -u <remote> ${branch ?? '<branch>'}\` first.`);
}
- const remoteUrl = git(['remote', 'get-url', remote]);
- const repository = parseRemoteRepository(remoteUrl ?? '');
- if (!repository) throw refusal(`remote ${remote} has no owner/repo URL this script can read.`);
+ const ghRepoView = () => {
+ const viewed = run('gh', ['repo', 'view', '--json', 'nameWithOwner,url']);
+ if (!viewed.ok) return null;
+ try {
+ return JSON.parse(viewed.stdout);
+ } catch {
+ return null;
+ }
+ };
+ const repository = resolveRepository(git(['remote', 'get-url', remote]), { ghRepoView });
+ if (!repository) throw refusal(`remote ${remote} has no owner/repo URL this script can read, and \`gh repo view\` could not name the repository.`);
+ const target = `${repository.owner}/${repository.repo}`;
const treeOf = (commit) => git(['rev-parse', '--verify', '--quiet', `${commit}^{tree}`]);
// Remote-tracking refs are current right after a push; a commit nothing
@@ -169,9 +226,28 @@ export function runAttest({ argv = [], cwd = REPO_ROOT, exec = spawnSync, log =
const branches = git(['branch', '-r', '--contains', commit, '--format=%(refname:short)']);
return branches !== null && branches.split('\n').some((name) => name.startsWith(`${remote}/`));
};
- const attestation = planAttestation(readReceipt(cwd), { sha, treeOf, isPushed, remote });
+
+ if (options.revoke !== null) {
+ if (!isPushed(sha)) throw refusal(`commit ${sha.slice(0, 9)} is not on ${remote}: there is no status to revoke.`);
+ const description = encodeRevocation(options.revoke);
+ const request = statusRequest(repository, { sha, description, state: 'failure' });
+ if (options.dryRun) {
+ log(JSON.stringify({ repository: target, sha, context: PREGATE_STATUS_CONTEXT, state: 'failure', description, command: [request.command, ...request.args] }, null, 2));
+ return 0;
+ }
+ const posted = run(request.command, request.args);
+ if (!posted.ok) throw refusal(`gh could not create the revocation on ${target}: ${posted.stderr || posted.stdout || 'gh api failed'}`);
+ log(`⛔ Revoked the pregate attestation on ${sha} — status "${PREGATE_STATUS_CONTEXT}" is now failure (${description}); the pull request's CI runs every stage.`);
+ return 0;
+ }
+
+ // The default branch of the upstream remote, as `git clone` records it;
+ // `<remote>/main` when the symbolic ref was never set.
+ const defaultBranch = git(['symbolic-ref', '--short', '-q', `refs/remotes/${remote}/HEAD`]) || `${remote}/main`;
+ const defaultMergeBase = git(['merge-base', defaultBranch, sha]);
+ const attestation = planAttestation(readReceipt(cwd), { sha, treeOf, isPushed, remote, defaultMergeBase, os: platform, node: nodeMajor(nodeVersion) });
+ attestation.notes.forEach((note) => log(`⚠️ ${note}.`));
const request = statusRequest(repository, { ...attestation, targetUrl: options.targetUrl });
- const target = `${repository.owner}/${repository.repo}`;
if (options.dryRun) {
log(JSON.stringify({ repository: target, sha, context: PREGATE_STATUS_CONTEXT, state: 'success', description: attestation.description, target_url: options.targetUrl, command: [request.command, ...request.args] }, null, 2));
diff --git a/scripts/pregate-attest.test.js b/scripts/pregate-attest.test.js
index 49871e30c2..3a78a6e6b8 100644
--- a/scripts/pregate-attest.test.js
+++ b/scripts/pregate-attest.test.js
@@ -1,48 +1,61 @@
/**
* The attestation posted after a push must never vouch for more than pregate
* proved: a failed or unstable receipt, a tree other than the one validated,
- * a commit the remote does not have, or a stage that was skipped is each a
- * refusal — exercised here through `runAttest` with an injected exec, so the
- * only thing left to a live run is `gh`'s own authentication.
+ * a commit the remote does not have, a plan computed against a narrowed base,
+ * or a stage that was skipped is each a refusal — exercised here through
+ * `runAttest` with an injected exec, so the only thing left to a live run is
+ * `gh`'s own authentication.
*/
import { describe, expect, it } from 'vitest';
-import { parseArgs, planAttestation, runAttest, statusRequest, USAGE } from './pregate-attest.js';
+import { parseArgs, planAttestation, resolveRepository, runAttest, statusRequest, USAGE } from './pregate-attest.js';
import {
- ATTESTABLE_STAGES, attestedStagesFromReceipt, encodeAttestation, parseAttestation, parseRemoteRepository,
- PREGATE_STATUS_CONTEXT, selectAttestation, STATUS_DESCRIPTION_MAX_LENGTH,
+ ATTESTABLE_STAGES, attestedStagesFromReceipt, encodeAttestation, encodeRevocation, nodeMajor, parseAttestation,
+ parseRemoteRepository, PREGATE_STATUS_CONTEXT, selectAttestation, STATUS_DESCRIPTION_MAX_LENGTH,
} from './lib/pregateAttestation.js';
import { buildPregateReport } from './lib/pregateReport.js';
const TREE = 'a'.repeat(40);
const OTHER_TREE = 'b'.repeat(40);
const SHA = 'c'.repeat(40);
+const BASE = 'e'.repeat(40);
+const OS = 'darwin';
+const NODE = 26;
+const encode = (stages, tree = TREE) => encodeAttestation({ tree, stages, os: OS, node: NODE });
const stage = (suite, status = 'passed', name = suite) => ({ name, suite, command: `node scripts/${suite}.js`, status, durationMs: 1, exitCode: status === 'passed' ? 0 : 1 });
const plan = { full: false, reason: 'scoped', server: { mode: 'files', files: [], sources: [] }, client: { mode: 'skip', files: [], sources: [] }, lint: { mode: 'full', files: [] }, browser: { files: [] }, db: false, build: false, smoke: false, windows: false, promptHistory: false, linuxContainment: false, suiteReasons: {} };
/** A receipt as pregate writes it, with the given stage outcomes. */
-const receipt = ({ stages, tree = TREE, treeAfterRun = tree, downgraded = false, skipped = [] }) => buildPregateReport({
- plan, options: {}, base: { ref: 'origin/main', sha: 'base' }, head: { sha: SHA }, tree, treeAfterRun, stages, skipped,
+const receipt = ({ stages, tree = TREE, treeAfterRun = tree, downgraded = false, skipped = [], base = { ref: 'origin/main', sha: BASE } }) => buildPregateReport({
+ plan, options: { base: base.ref }, base, head: { sha: SHA }, tree, treeAfterRun, stages, skipped,
runtime: {}, startedAt: 's', finishedAt: 'f', downgraded,
});
describe('attestation encoding', () => {
- it('round-trips every stage and stays within the status description limit', () => {
- const description = encodeAttestation({ tree: TREE, stages: [...ATTESTABLE_STAGES].reverse() });
- expect(description.length).toBeLessThanOrEqual(STATUS_DESCRIPTION_MAX_LENGTH);
- expect(description).toBe(`tree=${TREE} stages=${ATTESTABLE_STAGES.join(',')}`);
- expect(parseAttestation(description)).toEqual({ tree: TREE, stages: [...ATTESTABLE_STAGES] });
- expect(parseAttestation(encodeAttestation({ tree: TREE, stages: ['db', 'lint'] }))).toEqual({ tree: TREE, stages: ['lint', 'db'] });
- });
-
- it('rejects what it did not write: unknown stages, a short tree, duplicates, extra fields', () => {
- expect(() => encodeAttestation({ tree: TREE, stages: ['windows'] })).toThrow(/unknown attestation stage/);
- expect(() => encodeAttestation({ tree: TREE.slice(1), stages: ['lint'] })).toThrow(/40-hex/);
- expect(() => encodeAttestation({ tree: TREE, stages: [] })).toThrow(/at least one stage/);
- expect(parseAttestation(`tree=${TREE} stages=lint,windows`)).toBeNull();
- expect(parseAttestation(`tree=${TREE} stages=lint,lint`)).toBeNull();
- expect(parseAttestation(`tree=${TREE} stages=lint extra=1`)).toBeNull();
- expect(parseAttestation(`tree=${TREE.slice(2)} stages=lint`)).toBeNull();
+ it('round-trips every stage plus platform and Node major within the status description limit', () => {
+ for (const os of ['darwin', 'linux', 'win32']) {
+ const description = encodeAttestation({ tree: TREE, stages: [...ATTESTABLE_STAGES].reverse(), os, node: 999 });
+ expect(description.length).toBeLessThanOrEqual(STATUS_DESCRIPTION_MAX_LENGTH);
+ expect(parseAttestation(description)).toEqual({ tree: TREE, os, node: 999, stages: [...ATTESTABLE_STAGES] });
+ }
+ expect(encode(['db', 'lint'])).toBe(`tree=${TREE} os=darwin node=26 stages=lint,db`);
+ expect(parseAttestation(encode(['db', 'lint']))).toEqual({ tree: TREE, os: OS, node: NODE, stages: ['lint', 'db'] });
+ expect(nodeMajor('v26.10.0')).toBe(26);
+ expect(nodeMajor('garbage')).toBeNull();
+ });
+
+ it('rejects what it did not write: unknown stages, a short tree, duplicates, extra or missing fields', () => {
+ expect(() => encode(['windows'])).toThrow(/unknown attestation stage/);
+ expect(() => encode(['lint'], TREE.slice(1))).toThrow(/40-hex/);
+ expect(() => encode([])).toThrow(/at least one stage/);
+ expect(() => encodeAttestation({ tree: TREE, stages: ['lint'], os: 'Mac OS', node: NODE })).toThrow(/platform/);
+ expect(() => encodeAttestation({ tree: TREE, stages: ['lint'], os: OS, node: NaN })).toThrow(/Node major/);
+ expect(parseAttestation(`tree=${TREE} os=darwin node=26 stages=lint,windows`)).toBeNull();
+ expect(parseAttestation(`tree=${TREE} os=darwin node=26 stages=lint,lint`)).toBeNull();
+ expect(parseAttestation(`tree=${TREE} os=darwin node=26 stages=lint extra=1`)).toBeNull();
+ expect(parseAttestation(`tree=${TREE} stages=lint`)).toBeNull();
+ expect(parseAttestation(`tree=${TREE.toUpperCase()} os=darwin node=26 stages=lint`)).toBeNull();
+ expect(parseAttestation(`tree=${TREE} os=darwin node=26 stages=`)).toBeNull();
expect(parseAttestation(undefined)).toBeNull();
});
@@ -52,51 +65,86 @@ describe('attestation encoding', () => {
expect(attestedStagesFromReceipt(receipt({ stages, downgraded: true }))).toEqual(['scan', 'lint']);
expect(attestedStagesFromReceipt({})).toEqual([]);
});
+
+ it('encodes a revocation as a bounded failure description', () => {
+ expect(encodeRevocation('tests were flaky')).toBe('revoked: tests were flaky');
+ expect(encodeRevocation('')).toBe('revoked: pregate result withdrawn');
+ expect(encodeRevocation('x'.repeat(200)).length).toBe(STATUS_DESCRIPTION_MAX_LENGTH);
+ expect(encodeRevocation('a\nb')).toBe('revoked: a b');
+ });
});
describe('selectAttestation', () => {
- const status = (overrides) => ({ context: PREGATE_STATUS_CONTEXT, state: 'success', creator: { login: 'owner' }, description: encodeAttestation({ tree: TREE, stages: ['lint'] }), created_at: '2026-10-18T10:00:00Z', ...overrides });
+ const status = (overrides) => ({ context: PREGATE_STATUS_CONTEXT, state: 'success', creator: { login: 'owner' }, description: encode(['lint']), created_at: '2026-10-18T10:00:00Z', ...overrides });
- it('takes the newest successful pregate status by the owner whose tree is the head tree', () => {
- const older = status({ description: encodeAttestation({ tree: TREE, stages: ['lint', 'server'] }), created_at: '2026-10-18T09:00:00Z' });
+ it('takes the newest pregate status by the owner whose tree is the head tree', () => {
+ const older = status({ description: encode(['lint', 'server']), created_at: '2026-10-18T09:00:00Z' });
const newer = status({ created_at: '2026-10-18T11:00:00Z' });
- const result = selectAttestation([older, newer, status({ context: 'ci/other' })], { owner: 'owner', headTree: TREE });
- expect(result.attestation).toMatchObject({ tree: TREE, stages: ['lint'], creator: 'owner' });
+ const result = selectAttestation([older, newer, status({ context: 'ci/other', created_at: '2026-10-18T12:00:00Z' })], { owner: 'owner', headTree: TREE });
+ expect(result.attestation).toMatchObject({ tree: TREE, stages: ['lint'], creator: 'owner', os: OS, node: NODE });
expect(result.reason).toContain('attested by owner');
+ expect(result.reason).toContain('darwin/node 26');
});
- it('refuses the wrong creator, a mismatched tree, an unreadable description and a failed state', () => {
+ it('lets the newest status of ANY state decide: a later failure, pending or error revokes an earlier success', () => {
+ const success = status({ created_at: '2026-10-18T09:00:00Z' });
+ for (const state of ['failure', 'pending', 'error']) {
+ const later = status({ state, description: 'revoked: flaky run', created_at: '2026-10-18T10:00:00Z' });
+ const result = selectAttestation([success, later], { owner: 'owner', headTree: TREE });
+ expect(result.attestation).toBeNull();
+ expect(result.reason).toBe(`newest pregate status is ${state}, not success (revoked: flaky run)`);
+ }
+ // And a newer success by someone else blocks the owner's older one.
+ const foreign = status({ creator: { login: 'someone' }, created_at: '2026-10-18T12:00:00Z' });
+ expect(selectAttestation([success, foreign], { owner: 'owner', headTree: TREE }).reason).toMatch(/created by "someone"/);
+ });
+
+ it('refuses the wrong creator, a mismatched tree, an unreadable description and no status at all', () => {
expect(selectAttestation([status({ creator: { login: 'someone' } })], { owner: 'owner', headTree: TREE }).reason).toMatch(/created by "someone"/);
expect(selectAttestation([status()], { owner: 'owner', headTree: OTHER_TREE }).reason).toMatch(/is not the head tree/);
expect(selectAttestation([status({ description: 'pregate passed' })], { owner: 'owner', headTree: TREE }).reason).toMatch(/unreadable description/);
- expect(selectAttestation([status({ state: 'failure' })], { owner: 'owner', headTree: TREE }).reason).toMatch(/no successful/);
+ expect(selectAttestation([status({ context: 'ci/other' })], { owner: 'owner', headTree: TREE }).reason).toMatch(/^no "pregate" status/);
expect(selectAttestation('not an array', { owner: 'owner', headTree: TREE }).reason).toMatch(/unreadable/);
- // A newer status by someone else outranks and so blocks an older owner one:
- // the newest word on the commit wins, and it is not the owner's.
- const owned = status({ created_at: '2026-10-18T09:00:00Z' });
- const foreign = status({ creator: { login: 'someone' }, created_at: '2026-10-18T12:00:00Z' });
- expect(selectAttestation([owned, foreign], { owner: 'owner', headTree: TREE }).attestation).toBeNull();
});
});
-describe('parseRemoteRepository', () => {
- it('reads owner/repo from the SSH and HTTPS remote shapes and rejects extra segments', () => {
- expect(parseRemoteRepository('[email protected]:acme/widget.git')).toEqual({ host: 'github.com', owner: 'acme', repo: 'widget' });
- expect(parseRemoteRepository('[email protected]:443/acme/widget.git')).toEqual({ host: 'ssh.github.com', owner: 'acme', repo: 'widget' });
- expect(parseRemoteRepository('https://github.com/acme/widget')).toEqual({ host: 'github.com', owner: 'acme', repo: 'widget' });
- expect(parseRemoteRepository('ssh://[email protected]:443/acme/widget.git')).toEqual({ host: 'github.com', owner: 'acme', repo: 'widget' });
+describe('repository resolution', () => {
+ it('reads owner/repo from the SSH and HTTPS remote shapes, folds ssh.github.com, and flags an alias host', () => {
+ expect(parseRemoteRepository('[email protected]:acme/widget.git')).toEqual({ host: 'github.com', owner: 'acme', repo: 'widget', hostIsResolvable: true });
+ expect(parseRemoteRepository('[email protected]:443/acme/widget.git')).toMatchObject({ host: 'github.com', owner: 'acme', repo: 'widget' });
+ expect(parseRemoteRepository('ssh://[email protected]:443/acme/widget.git')).toMatchObject({ host: 'github.com' });
+ expect(parseRemoteRepository('https://github.com/acme/widget')).toMatchObject({ host: 'github.com', owner: 'acme', repo: 'widget' });
+ expect(parseRemoteRepository('[email protected]:org/repo.git')).toMatchObject({ host: 'ghe.example.com', owner: 'org', repo: 'repo', hostIsResolvable: true });
+ expect(parseRemoteRepository('git@github-acme:acme/widget.git')).toMatchObject({ host: 'github-acme', hostIsResolvable: false });
expect(parseRemoteRepository('[email protected]:acme/widget/extra')).toBeNull();
expect(parseRemoteRepository('')).toBeNull();
});
+
+ it('asks gh repo view for the real host behind an ssh alias, and only then', () => {
+ let asked = 0;
+ const ghRepoView = () => { asked += 1; return { nameWithOwner: 'acme/widget', url: 'https://github.com/acme/widget' }; };
+ expect(resolveRepository('[email protected]:acme/widget.git', { ghRepoView })).toMatchObject({ host: 'github.com', owner: 'acme', repo: 'widget' });
+ expect(asked).toBe(0);
+ expect(resolveRepository('git@github-acme:acme/widget.git', { ghRepoView })).toEqual({ host: 'github.com', owner: 'acme', repo: 'widget', hostIsResolvable: true });
+ expect(asked).toBe(1);
+ expect(resolveRepository('git@github-acme:acme/widget.git', { ghRepoView: () => null })).toBeNull();
+ expect(resolveRepository('not a url', { ghRepoView: () => ({ nameWithOwner: 'o/r', url: 'https://ghe.example.com/o/r' }) })).toMatchObject({ host: 'ghe.example.com', owner: 'o', repo: 'r' });
+ });
+
+ it('targets a non-github.com host explicitly and github.com implicitly', () => {
+ expect(statusRequest({ owner: 'o', repo: 'r', host: 'github.com' }, { sha: SHA, description: 'd' }).args).not.toContain('--hostname');
+ expect(statusRequest({ owner: 'o', repo: 'r', host: 'ghe.example.com' }, { sha: SHA, description: 'd' }).args).toEqual(expect.arrayContaining(['--hostname', 'ghe.example.com']));
+ expect(statusRequest({ owner: 'o', repo: 'r', host: 'github.com' }, { sha: SHA, description: 'revoked: x', state: 'failure' }).args).toContain('state=failure');
+ });
});
describe('planAttestation', () => {
- const commit = { sha: SHA, treeOf: () => TREE, isPushed: () => true, remote: 'origin' };
+ const commit = { sha: SHA, treeOf: () => TREE, isPushed: () => true, remote: 'origin', defaultMergeBase: BASE, os: OS, node: NODE };
const green = receipt({ stages: [stage('scan'), stage('lint'), stage('server'), stage('smoke')] });
it('attests exactly the passed stages of a green, stable receipt on a pushed commit with that tree', () => {
expect(planAttestation(green, commit)).toEqual({
- sha: SHA, tree: TREE, stages: ['scan', 'lint', 'server', 'smoke'], description: `tree=${TREE} stages=scan,lint,server,smoke`,
+ sha: SHA, tree: TREE, stages: ['scan', 'lint', 'server', 'smoke'], description: `tree=${TREE} os=darwin node=26 stages=scan,lint,server,smoke`, notes: [],
});
});
@@ -116,6 +164,20 @@ describe('planAttestation', () => {
expect(() => planAttestation(green, { ...commit, isPushed: () => false })).toThrow(/not on origin yet: push it first/);
});
+ it('drops the diff-selected stages when the receipt was planned against a narrowed or unknown base', () => {
+ const narrowed = receipt({ stages: [stage('scan'), stage('lint'), stage('server'), stage('client'), stage('smoke'), stage('db')], base: { ref: 'HEAD~1', sha: 'f'.repeat(40) } });
+ const result = planAttestation(narrowed, commit);
+ expect(result.stages).toEqual(['scan', 'smoke', 'db']);
+ expect(result.notes[0]).toMatch(/not attesting lint, server, client: the receipt was planned against base fffffffff \(HEAD~1\), not the default branch's merge base eeeeeeeee/);
+ // The probe shape: no base sha recorded at all.
+ const probe = { passed: true, treeStable: true, tree: TREE, options: { base: 'HEAD~1' }, base: { ref: 'HEAD~1' }, plan: { downgraded: false }, stages: [stage('scan'), stage('server')] };
+ expect(planAttestation(probe, commit).stages).toEqual(['scan']);
+ // An unresolved default merge base fails the same way.
+ expect(planAttestation(green, { ...commit, defaultMergeBase: null }).stages).toEqual(['scan', 'smoke']);
+ // Nothing left after the drop is a refusal that says why.
+ expect(() => planAttestation(receipt({ stages: [stage('server')], base: { ref: 'HEAD~1', sha: 'f'.repeat(40) } }), commit)).toThrow(/attests no stage.*not attesting server/);
+ });
+
it('refuses when nothing attestable passed', () => {
const guardsOnly = receipt({ stages: [stage('server')], downgraded: true });
expect(() => planAttestation(guardsOnly, commit)).toThrow(/attests no stage/);
@@ -140,25 +202,29 @@ describe('runAttest', () => {
[/^git remote get-url upstream$/, '[email protected]:acme/widget.git'],
[/^git rev-parse --verify --quiet .*\^\{tree\}$/, TREE],
[/^git branch -r --contains .* --format=/, 'upstream/feature\nfork/feature'],
+ [/^git symbolic-ref --short -q refs\/remotes\/upstream\/HEAD$/, 'upstream/main'],
+ [/^git merge-base upstream\/main /, BASE],
];
const green = receipt({ stages: [stage('scan'), stage('lint'), stage('db', 'passed', 'provision'), stage('db', 'passed', 'suite')] });
const io = () => { const out = []; const err = []; return { out, err, log: (line) => out.push(line), error: (line) => err.push(line) }; };
+ const run = (options) => runAttest({ platform: OS, nodeVersion: 'v26.10.0', ...options });
it('posts the status through gh on the upstream remote with the receipt-derived description', () => {
const calls = [];
const { out, err, log, error } = io();
const exec = fakeExec([...gitTable(), [/^gh api --method POST /, '{}']], calls);
- const code = runAttest({ argv: [], exec, log, error, readReceipt: () => green });
+ const code = run({ argv: [], exec, log, error, readReceipt: () => green });
expect(err).toEqual([]);
expect(code).toBe(0);
- expect(calls.at(-1)).toBe(`gh api --method POST repos/acme/widget/statuses/${SHA} -f state=success -f context=pregate -f description=tree=${TREE} stages=scan,lint,db`);
+ expect(calls.at(-1)).toBe(`gh api --method POST repos/acme/widget/statuses/${SHA} -f state=success -f context=pregate -f description=tree=${TREE} os=darwin node=26 stages=scan,lint,db`);
expect(out.at(-1)).toContain(`Attested ${SHA} tree=${TREE} stages=scan,lint,db`);
+ expect(calls.some((call) => call.startsWith('gh repo view'))).toBe(false);
});
it('posts nothing on --dry-run and prints the payload it would send', () => {
const calls = [];
const { out, log, error } = io();
- const code = runAttest({ argv: ['--dry-run', '--target-url', 'https://example.com/run/1'], exec: fakeExec(gitTable(), calls), log, error, readReceipt: () => green });
+ const code = run({ argv: ['--dry-run', '--target-url', 'https://example.com/run/1'], exec: fakeExec(gitTable(), calls), log, error, readReceipt: () => green });
expect(code).toBe(0);
expect(calls.some((call) => call.startsWith('gh '))).toBe(false);
const payload = JSON.parse(out[0]);
@@ -175,7 +241,7 @@ describe('runAttest', () => {
]) {
const calls = [];
const { err, log, error } = io();
- const code = runAttest({ argv: [], exec: fakeExec(table, calls), log, error, readReceipt: () => report });
+ const code = run({ argv: [], exec: fakeExec(table, calls), log, error, readReceipt: () => report });
expect(code).toBe(1);
expect(err[0]).toMatch(/^⛔ Not attested: /);
expect(err[0]).toMatch(message);
@@ -183,39 +249,79 @@ describe('runAttest', () => {
}
});
+ it('narrows the attestation when the receipt base is not the default branch merge base, and says so', () => {
+ const { out, log, error } = io();
+ const calls = [];
+ const exec = fakeExec([[/^git merge-base upstream\/main /, 'f'.repeat(40)], ...gitTable(), [/^gh api --method POST /, '{}']], calls);
+ expect(run({ argv: [], exec, log, error, readReceipt: () => green })).toBe(0);
+ expect(out.some((line) => /⚠️ not attesting lint: the receipt was planned against base/.test(line))).toBe(true);
+ expect(calls.at(-1)).toContain('stages=scan,db');
+ });
+
it('attests --sha instead of HEAD and refuses a branch with no upstream remote', () => {
const other = 'd'.repeat(40);
const calls = [];
const { log, error } = io();
- const code = runAttest({ argv: ['--sha', other], exec: fakeExec([...gitTable(), [/^gh api/, '{}']], calls), log, error, readReceipt: () => green });
+ const code = run({ argv: ['--sha', other], exec: fakeExec([...gitTable(), [/^gh api/, '{}']], calls), log, error, readReceipt: () => green });
expect(code).toBe(0);
expect(calls.some((call) => call === 'git rev-parse HEAD')).toBe(false);
expect(calls.at(-1)).toContain(`statuses/${other}`);
const { err: noUpstreamErr, log: log2, error: error2 } = io();
const detached = fakeExec([[/^git rev-parse HEAD$/, SHA], [/^git config --get/, { status: 1, stdout: '', stderr: '' }], ...gitTable()]);
- expect(runAttest({ argv: [], exec: detached, log: log2, error: error2, readReceipt: () => green })).toBe(1);
+ expect(run({ argv: [], exec: detached, log: log2, error: error2, readReceipt: () => green })).toBe(1);
expect(noUpstreamErr[0]).toMatch(/no upstream remote; push it with `git push -u <remote> feature`/);
});
+ it('resolves an ssh-alias remote through gh repo view before posting', () => {
+ const calls = [];
+ const { log, error } = io();
+ const exec = fakeExec([
+ [/^git remote get-url upstream$/, 'git@github-acme:acme/widget.git'],
+ [/^gh repo view --json nameWithOwner,url$/, JSON.stringify({ nameWithOwner: 'acme/widget', url: 'https://github.com/acme/widget' })],
+ ...gitTable(), [/^gh api --method POST /, '{}'],
+ ], calls);
+ expect(run({ argv: [], exec, log, error, readReceipt: () => green })).toBe(0);
+ expect(calls.at(-1)).toMatch(/^gh api --method POST repos\/acme\/widget\/statuses\//);
+ expect(calls.at(-1)).not.toContain('--hostname');
+
+ const { err, log: log2, error: error2 } = io();
+ const unresolved = fakeExec([[/^git remote get-url upstream$/, 'git@github-acme:acme/widget.git'], [/^gh repo view/, { status: 1, stdout: '', stderr: 'no' }], ...gitTable()]);
+ expect(run({ argv: [], exec: unresolved, log: log2, error: error2, readReceipt: () => green })).toBe(1);
+ expect(err[0]).toMatch(/gh repo view` could not name the repository/);
+ });
+
+ it('revokes with a failure status carrying the reason, without reading a receipt', () => {
+ const calls = [];
+ const { out, log, error } = io();
+ const exec = fakeExec([...gitTable(), [/^gh api --method POST /, '{}']], calls);
+ expect(run({ argv: ['--revoke', 'flaky DB run'], exec, log, error, readReceipt: () => { throw new Error('must not read'); } })).toBe(0);
+ expect(calls.at(-1)).toBe(`gh api --method POST repos/acme/widget/statuses/${SHA} -f state=failure -f context=pregate -f description=revoked: flaky DB run`);
+ expect(out.at(-1)).toMatch(/^⛔ Revoked the pregate attestation/);
+ // Dry-run revocation posts nothing; an unpushed commit has nothing to revoke.
+ const dry = [];
+ expect(run({ argv: ['--revoke', '--dry-run'], exec: fakeExec(gitTable(), dry), ...io(), readReceipt: () => null })).toBe(0);
+ expect(dry.some((call) => call.startsWith('gh api'))).toBe(false);
+ const { err, log: log3, error: error3 } = io();
+ expect(run({ argv: ['--revoke'], exec: fakeExec(gitTable([[/^git branch -r --contains/, 'fork/feature']])), log: log3, error: error3 })).toBe(1);
+ expect(err[0]).toMatch(/no status to revoke/);
+ });
+
it('reports a gh failure as a refusal, naming the repository', () => {
const { err, log, error } = io();
const exec = fakeExec([...gitTable(), [/^gh api/, { status: 1, stdout: '', stderr: 'HTTP 403: Resource not accessible' }]]);
- expect(runAttest({ argv: [], exec, log, error, readReceipt: () => green })).toBe(1);
+ expect(run({ argv: [], exec, log, error, readReceipt: () => green })).toBe(1);
expect(err[0]).toMatch(/gh could not create the status on acme\/widget: HTTP 403/);
});
it('parses its flags and rejects the rest with usage', () => {
- expect(parseArgs(['--sha', SHA, '--dry-run'])).toEqual({ sha: SHA, dryRun: true, targetUrl: null, help: false });
+ expect(parseArgs(['--sha', SHA, '--dry-run'])).toEqual({ sha: SHA, dryRun: true, targetUrl: null, help: false, revoke: null });
+ expect(parseArgs(['--revoke'])).toMatchObject({ revoke: '' });
+ expect(parseArgs(['--revoke', 'why', '--dry-run'])).toMatchObject({ revoke: 'why', dryRun: true });
expect(() => parseArgs(['--sha', 'abc'])).toThrow(/40-character/);
expect(() => parseArgs(['--nope'])).toThrow(/Unknown option/);
const { err, log, error } = io();
- expect(runAttest({ argv: ['--nope'], exec: fakeExec([]), log, error })).toBe(2);
+ expect(run({ argv: ['--nope'], exec: fakeExec([]), log, error })).toBe(2);
expect(err[0]).toContain(USAGE);
});
-
- it('targets a non-github.com host explicitly and github.com implicitly', () => {
- expect(statusRequest({ owner: 'o', repo: 'r', host: 'github.com' }, { sha: SHA, description: 'd' }).args).not.toContain('--hostname');
- expect(statusRequest({ owner: 'o', repo: 'r', host: 'ghe.example.com' }, { sha: SHA, description: 'd' }).args).toEqual(expect.arrayContaining(['--hostname', 'ghe.example.com']));
- });
});
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index b7d6bc3c70..37b75013ae 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -288,7 +288,7 @@ ${DISPATCH_HINT_FANOUT_GUIDANCE}
**Verify the ${pr} body's issue trailer after create AND after every edit.** The ${pr}-body flow is create-then-edit — the file is written once, then re-read minutes later during the review loop — which is a wide window for a stale or foreign body to land. Belt to the namespacing's braces: immediately after \`create\` and after each body \`edit\`, re-read the published body with \`${bodyCmd}\` — **note it takes no number: both CLIs resolve the ${pr} from your checked-out \`claim/issue-<num>\` branch, and passing an ISSUE number where a ${pr} number belongs is how you end up reading (and then "correcting") someone else's ${pr}** — and confirm the body carries this agent's own trailer. A full-scope ship MUST carry \`Closes #<num>\` for this issue; \`Refs #<num>\` is permitted ONLY for a deliberate partial ship that also records the required \`Done ✓ / Remaining ▢\` reconciliation comment. If it does not, rewrite the body from this agent's own scratch file and re-verify. **Cap this at 2 rewrites:** if the trailer still doesn't match, the scratch file itself is suspect — re-derive the body from your own branch's commits/diff for one final attempt, and if that also fails, STOP, leave the ${pr} open, and say so in the result you hand back. Never loop on it: Phase C waits for every agent to finish, so one agent stuck re-publishing blocks the whole batch's merges. And never assume a zero exit code means the right body was published.
## Phase C — Serialize only the merge instant (orchestrator, after all agents finish)
-Bring every ready ${pr} to a CI-verified head CONCURRENTLY, without merge admission: re-sync each onto the latest default branch, run pregate, push, run \`node scripts/pregate-attest.js\` (on GitHub it posts the pregate receipt as a commit status so CI skips the attested stages; a refusal is reported in the summary, never retried), and gate on **required** CI on that exact head (one re-run on a flaky required check, then proceed; a real failure or an irreconcilable conflict leaves that ${pr} OPEN and recorded — move to the next). Then merge them ONE AT A TIME: for each green ${pr}, the parent orchestrator acquires the repository merge admission described in the Claim Workflow Handoff, re-reads the ${pr}, merges with \`${mergeCmd} ${mergePin}\` when the forge still reports it mergeable, and releases its own lease immediately (outcome merged). A ${pr} the forge no longer reports mergeable releases with outcome resync and goes back through the concurrent sync/pregate/CI step outside the lease; a base that moved while the ${pr} stays mergeable needs no resync. After all merges, run Phase 7 cleanup once per merged worktree.
+Bring every ready ${pr} to a CI-verified head CONCURRENTLY, without merge admission: re-sync each onto the latest default branch, run pregate, push, run \`node scripts/pregate-attest.js\` when the repository ships it (on GitHub it posts the pregate receipt as a commit status so CI skips the attested stages; a refusal is reported in the summary, never retried), and gate on **required** CI on that exact head (one re-run on a flaky required check, then proceed; a real failure or an irreconcilable conflict leaves that ${pr} OPEN and recorded — move to the next). Then merge them ONE AT A TIME: for each green ${pr}, the parent orchestrator acquires the repository merge admission described in the Claim Workflow Handoff, re-reads the ${pr}, merges with \`${mergeCmd} ${mergePin}\` when the forge still reports it mergeable, and releases its own lease immediately (outcome merged). A ${pr} the forge no longer reports mergeable releases with outcome resync and goes back through the concurrent sync/pregate/CI step outside the lease; a base that moved while the ${pr} stays mergeable needs no resync. After all merges, run Phase 7 cleanup once per merged worktree.
${forgeKey === 'gh' ? MANAGED_WORKTREE_CLEANUP_CONTRACT : ''}
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
index a02041a4f5..af5d6b231b 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
@@ -26,7 +26,7 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a
2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
-**Pregate attestation (GitHub, right after the push, before waiting for CI):** from the checkout you pushed, run `node scripts/pregate-attest.js`. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work.
+**Pregate attestation (GitHub, right after the push, before waiting for CI):** if this repository has `scripts/pregate-attest.js` (PortOS does), run `node scripts/pregate-attest.js` from the checkout you pushed. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). When you open the pull request yourself rather than through `/do:pr`, the order is push, attest, then `gh pr create`, so the status exists when the `pull_request` event starts the run. If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work. A repository without that script has nothing to attest; move on.
4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.
5. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.
6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
index 47506ff384..fa30e7a2e2 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
@@ -31,7 +31,7 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a
2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.
3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
-**Pregate attestation (GitHub, right after the push, before waiting for CI):** from the checkout you pushed, run `node scripts/pregate-attest.js`. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work.
+**Pregate attestation (GitHub, right after the push, before waiting for CI):** if this repository has `scripts/pregate-attest.js` (PortOS does), run `node scripts/pregate-attest.js` from the checkout you pushed. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). When you open the pull request yourself rather than through `/do:pr`, the order is push, attest, then `gh pr create`, so the status exists when the `pull_request` event starts the run. If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work. A repository without that script has nothing to attest; move on.
4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.
5. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.
6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
index 3186ca85e4..3d55fe9e3d 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
@@ -13,7 +13,7 @@ A previous agent finished task **task-example** and opened **PR https://github.c
2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
-**Pregate attestation (GitHub, right after the push, before waiting for CI):** from the checkout you pushed, run `node scripts/pregate-attest.js`. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work.
+**Pregate attestation (GitHub, right after the push, before waiting for CI):** if this repository has `scripts/pregate-attest.js` (PortOS does), run `node scripts/pregate-attest.js` from the checkout you pushed. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). When you open the pull request yourself rather than through `/do:pr`, the order is push, attest, then `gh pr create`, so the status exists when the `pull_request` event starts the run. If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work. A repository without that script has nothing to attest; move on.
4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.
5. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, repeat the configured review loop for `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.
6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
index 8e2ce74b76..0fa59f0c7d 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
@@ -36,7 +36,7 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a
**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published, so leave it open and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Report the pending review in your run summary — do NOT post a PR/MR comment saying the review was unavailable or inconclusive. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.
**Code-changing CI fix gate:** If a CI fix changes code, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any reviewer fixes before pushing or merging.
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
-**Pregate attestation (GitHub, right after the push, before waiting for CI):** from the checkout you pushed, run `node scripts/pregate-attest.js`. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work.
+**Pregate attestation (GitHub, right after the push, before waiting for CI):** if this repository has `scripts/pregate-attest.js` (PortOS does), run `node scripts/pregate-attest.js` from the checkout you pushed. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). When you open the pull request yourself rather than through `/do:pr`, the order is push, attest, then `gh pr create`, so the status exists when the `pull_request` event starts the run. If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work. A repository without that script has nothing to attest; move on.
4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.
5. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, after that rebase, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any fixes before pushing or merging; repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.
6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
index 2bb09a4236..f14322ce54 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
@@ -41,7 +41,7 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a
**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published, so leave it open and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Report the pending review in your run summary — do NOT post a PR/MR comment saying the review was unavailable or inconclusive. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.
**Code-changing CI fix gate:** If a CI fix changes code, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any reviewer fixes before pushing or merging.
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
-**Pregate attestation (GitHub, right after the push, before waiting for CI):** from the checkout you pushed, run `node scripts/pregate-attest.js`. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work.
+**Pregate attestation (GitHub, right after the push, before waiting for CI):** if this repository has `scripts/pregate-attest.js` (PortOS does), run `node scripts/pregate-attest.js` from the checkout you pushed. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). When you open the pull request yourself rather than through `/do:pr`, the order is push, attest, then `gh pr create`, so the status exists when the `pull_request` event starts the run. If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work. A repository without that script has nothing to attest; move on.
4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.
5. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, after that rebase, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any fixes before pushing or merging; repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.
6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
index 0ef7b14e74..e7496a059b 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
@@ -2,7 +2,7 @@
A previous agent finished the work for source task **task-example** and opened **PR https://github.com/example-org/example-repo/pull/42** on `feature/example`. **No code review was requested for this task, so nothing else will merge this PR Your job is to land it once CI is green.**
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
-**Pregate attestation (GitHub, right after the push, before waiting for CI):** from the checkout you pushed, run `node scripts/pregate-attest.js`. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work.
+**Pregate attestation (GitHub, right after the push, before waiting for CI):** if this repository has `scripts/pregate-attest.js` (PortOS does), run `node scripts/pregate-attest.js` from the checkout you pushed. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). When you open the pull request yourself rather than through `/do:pr`, the order is push, attest, then `gh pr create`, so the status exists when the `pull_request` event starts the run. If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work. A repository without that script has nothing to attest; move on.
1. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.
2. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, re-run the tests, `git push --force-with-lease`, and re-check.
3. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged (a saved `/do:pr` default can merge it for you), skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
index 925a505383..194920cdbc 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
@@ -2,7 +2,7 @@
This runs as **step 4 of the Completion Workflow above**, against the PR you just opened on `feature/example` (`https://github.com/example-org/example-repo/pull/42` / `42` are the shell variables you captured there). **No code review was requested for this task, so nothing else will merge this PR Land it yourself once CI is green.**
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
-**Pregate attestation (GitHub, right after the push, before waiting for CI):** from the checkout you pushed, run `node scripts/pregate-attest.js`. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work.
+**Pregate attestation (GitHub, right after the push, before waiting for CI):** if this repository has `scripts/pregate-attest.js` (PortOS does), run `node scripts/pregate-attest.js` from the checkout you pushed. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request's CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). When you open the pull request yourself rather than through `/do:pr`, the order is push, attest, then `gh pr create`, so the status exists when the `pull_request` event starts the run. If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work. A repository without that script has nothing to attest; move on.
1. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.
2. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, re-run the tests, `git push --force-with-lease`, and re-check.
3. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index 57e6eb3c27..53a9a175d3 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -638,7 +638,7 @@ export function buildMergeAdmissionSection(agentId) {
` printf '%s' "$ADMISSION_RESPONSE" | node -e 'const fs = require("node:fs"); const response = JSON.parse(fs.readFileSync(0,"utf8")); process.exit(response.admitted === true ? 0 : 1);'`,
'}',
'```',
- '- Otherwise (head changed, a required check is not green, or the PR is `DIRTY`/conflicting, `BEHIND` where branch rules require an up-to-date head, `BLOCKED`, or still `UNKNOWN` after a few re-reads): release with outcome resync. Then, OUTSIDE the lease, sync onto the latest default branch, rerun pregate and the affected required reviews, push, run `node scripts/pregate-attest.js` (a refusal is reported, not retried), wait for required CI on the new head, and acquire again. After three resync rounds without a merge, record leave-open instead.',
+ '- Otherwise (head changed, a required check is not green, or the PR is `DIRTY`/conflicting, `BEHIND` where branch rules require an up-to-date head, `BLOCKED`, or still `UNKNOWN` after a few re-reads): release with outcome resync. Then, OUTSIDE the lease, sync onto the latest default branch, rerun pregate and the affected required reviews, push, run `node scripts/pregate-attest.js` if the repository ships it (a refusal is reported, not retried), wait for required CI on the new head, and acquire again. After three resync rounds without a merge, record leave-open instead.',
'Verify the remote state is exactly MERGED, then release with outcome merged before worktree cleanup. On a recorded failure or leave-open handoff, release with outcome leave-open. Require released:true; report a failed release without deleting or overwriting ownership state:',
'```bash', command('release', { token: 'TOKEN', outcome: 'merged' }), '```',
'The server voids an agent lease 5 minutes after acquisition and lets another run reclaim it. A check refused with lease-expired or lease-owner-mismatch means stop: do not merge on that token; acquire again and repeat the re-read. Never bypass CI, infer success from absent checks, merge without the head pin, or treat auto-merge/queued as MERGED. Admission coordinates participating runs on this install only; manual merges and other installs can still move the base, which the forge’s merge state already reflects.',
diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.js
index 0aa26dd4cf..0906b8b1e1 100644
--- a/server/services/promptSections/reviewLifecycle.js
+++ b/server/services/promptSections/reviewLifecycle.js
@@ -1090,7 +1090,7 @@ export const LEAVE_PR_OPEN_STEP = (step, jiraTracked = false) => `${step}. **Lea
* numbers hold; it belongs between the push and the CI wait because the
* status must exist before the impact job plans the run.
*/
-const PREGATE_ATTESTATION_STEP = '**Pregate attestation (GitHub, right after the push, before waiting for CI):** from the checkout you pushed, run `node scripts/pregate-attest.js`. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request\'s CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work.';
+const PREGATE_ATTESTATION_STEP = '**Pregate attestation (GitHub, right after the push, before waiting for CI):** if this repository has `scripts/pregate-attest.js` (PortOS does), run `node scripts/pregate-attest.js` from the checkout you pushed. It posts a `pregate` commit status bound to the exact tree your green `npm run pregate` validated, and the pull request\'s CI then skips the stages that receipt attests to (docs/GITHUB_ACTIONS.md "Pregate attestation"). When you open the pull request yourself rather than through `/do:pr`, the order is push, attest, then `gh pr create`, so the status exists when the `pull_request` event starts the run. If it refuses — no receipt, a receipt that did not pass, a tree that changed after pregate, an unpushed commit — do not rerun pregate just to attest and do not retry the post: say why it refused in your completion summary and wait for full CI as before. A refusal is never a failure of the work. A repository without that script has nothing to attest; move on.';
export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github', alreadyMergedHint = ' (a saved `/do:pr` default can merge it for you)', localReviewers = [], localReviewRequired = false, reviewRecheckReviewers = [], mergeEquivalentLine = null, deleteBranch = true }) {
const gh = forge !== 'gitlab';