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

Post a green pregate receipt as a tree-bound commit status after the push

[._.]/ Adam Eivy6c0df92bd35c
diff --git a/scripts/lib/pregateAttestation.js b/scripts/lib/pregateAttestation.js
new file mode 100644
index 0000000000..2a13f0c485
--- /dev/null
+++ b/scripts/lib/pregateAttestation.js
@@ -0,0 +1,147 @@
+/**
+ * The wire contract between `scripts/pregate-attest.js` (which posts a commit
+ * status after a complete local pregate) and `scripts/ci-test-plan.js` (which
+ * reads it back on the pull request and skips the stages it attests to).
+ *
+ * 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.
+ *
+ * Builtins only: the planner loads this before any dependency install.
+ */
+
+/** The commit-status `context` the attestation is posted under. */
+export const PREGATE_STATUS_CONTEXT = 'pregate';
+
+/** GitHub truncates a status description past this many characters. */
+export const STATUS_DESCRIPTION_MAX_LENGTH = 140;
+
+/**
+ * Receipt `suite` names a status may attest to, in the order they are
+ * encoded. `scan` is informational (the hidden-content scan runs inside the
+ * impact job and is never skipped); every other name maps to a CI job or step
+ * the planner can leave out — see `applyAttestation` in scripts/ci-test-plan.js.
+ */
+export const ATTESTABLE_STAGES = Object.freeze([
+ 'scan', 'prompt-history', 'lint', 'server', 'client', 'build', 'smoke', 'browser', 'db',
+]);
+
+const TREE_RE = /^[0-9a-f]{40}$/;
+const ATTESTABLE = new Set(ATTESTABLE_STAGES);
+
+/**
+ * The stages a receipt vouches for: every receipt stage of that suite ran and
+ * passed, and the suite ran CI's selection for it.
+ *
+ * A downgraded full plan ran only the always-run guards in the server and
+ * client stages (`downgradeFullPlan` in scripts/pregate.js), so those two
+ * suites are never attested from such a receipt even though their stages
+ * passed; lint runs whole either way. Stages that were skipped, not run,
+ * or absent from the receipt are simply not attested — CI keeps running them.
+ *
+ * @param {object} report - a `.cache/pregate/report.json` receipt
+ * @returns {string[]} in ATTESTABLE_STAGES order
+ */
+export function attestedStagesFromReceipt(report) {
+ const stages = Array.isArray(report?.stages) ? report.stages : [];
+ const reduced = report?.plan?.downgraded === true ? new Set(['server', 'client']) : new Set();
+ return ATTESTABLE_STAGES.filter((suite) => {
+ if (reduced.has(suite)) return false;
+ const records = stages.filter((stage) => stage?.suite === suite);
+ return records.length > 0 && records.every((stage) => stage.status === 'passed');
+ });
+}
+
+/**
+ * The status description for a tree and its attested stages.
+ *
+ * @param {{tree: string, stages: string[]}} attestation
+ * @returns {string}
+ */
+export function encodeAttestation({ tree, stages }) {
+ if (!TREE_RE.test(tree ?? '')) throw new Error('attestation needs a 40-hex tree hash');
+ 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(',')}`;
+ if (description.length > STATUS_DESCRIPTION_MAX_LENGTH) {
+ throw new Error(`attestation description exceeds ${STATUS_DESCRIPTION_MAX_LENGTH} characters`);
+ }
+ return description;
+}
+
+/**
+ * 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.
+ *
+ * @param {string} description
+ * @returns {{tree: string, stages: string[]}|null}
+ */
+export function parseAttestation(description) {
+ const match = /^tree=([0-9a-f]{40}) stages=([a-z,-]+)$/.exec(String(description ?? '').trim());
+ if (!match) return null;
+ const stages = match[2].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)) };
+}
+
+/**
+ * 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.
+ *
+ * @param {string} url
+ * @returns {{host: string, owner: string, repo: string}|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 scp = /^[a-zA-Z0-9._-]+@([^:]+):(?:\d+\/)?([^/]+)\/([^/]+)$/.exec(trimmed);
+ if (scp) return { host: stripPort(scp[1]), owner: scp[2], repo: stripGit(scp[3]) };
+ const urlStyle = /^[a-zA-Z]+:\/\/(?:[^@/]+@)?([^/]+)\/([^/]+)\/([^/]+)$/.exec(trimmed);
+ if (urlStyle) return { host: stripPort(urlStyle[1]), owner: urlStyle[2], repo: stripGit(urlStyle[3]) };
+ return null;
+}
+
+/**
+ * The newest usable attestation among a commit's statuses, or null with the
+ * reason none qualifies.
+ *
+ * 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.
+ *
+ * @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}}
+ */
+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')
+ .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` };
+ const newest = candidates[0];
+ 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` };
+ }
+ const parsed = parseAttestation(newest.description);
+ if (!parsed) return { attestation: null, reason: 'newest pregate status has an unreadable description' };
+ 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}` };
+}
diff --git a/scripts/lib/pregateReport.js b/scripts/lib/pregateReport.js
index 5f8c67ed82..e01ec73af9 100644
--- a/scripts/lib/pregateReport.js
+++ b/scripts/lib/pregateReport.js
@@ -19,7 +19,12 @@ import { dirname, join, resolve } from 'node:path';
/** Repo-relative location of the receipt; gitignored under `/.cache/`. */
export const PREGATE_REPORT_PATH = '.cache/pregate/report.json';
-export const PREGATE_REPORT_VERSION = 1;
+/**
+ * Version 2 added `plan.downgraded`: whether a full plan was replaced by the
+ * always-run guards. `scripts/pregate-attest.js` refuses a receipt without it,
+ * because a downgraded server stage passing is not CI's server selection passing.
+ */
+export const PREGATE_REPORT_VERSION = 2;
/**
* Hash the exact working tree as it stands: tracked, modified, deleted and
@@ -66,6 +71,7 @@ export function buildPregateReport({
runtime,
startedAt,
finishedAt,
+ downgraded = false,
}) {
const stageRecords = stages.map(({ name, suite, command, status, durationMs, exitCode = null, signal = null }) => ({
name, suite, command, status, durationMs, exitCode, signal,
@@ -85,6 +91,9 @@ export function buildPregateReport({
options,
plan: {
full: plan.full,
+ // True when a full plan ran only the always-run guards (no `--full`):
+ // the server and client stages below then prove less than CI's selection.
+ downgraded: Boolean(downgraded),
reason: plan.reason,
server: { mode: plan.server.mode, files: plan.server.files, sources: plan.server.sources },
client: { mode: plan.client.mode, files: plan.client.files, sources: plan.client.sources },
diff --git a/scripts/pregate-attest.js b/scripts/pregate-attest.js
new file mode 100644
index 0000000000..e01ebde615
--- /dev/null
+++ b/scripts/pregate-attest.js
@@ -0,0 +1,213 @@
+#!/usr/bin/env node
+
+/**
+ * Post the pregate attestation for a pushed commit.
+ *
+ * `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.
+ *
+ * node scripts/pregate-attest.js [--sha <40-hex>] [--dry-run] [--target-url <url>]
+ *
+ * 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.
+ *
+ * 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';
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
+import {
+ attestedStagesFromReceipt, encodeAttestation, 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';
+
+export const USAGE = `Usage: node scripts/pregate-attest.js [--sha <40-hex>] [--dry-run] [--target-url <url>]
+
+ --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
+ -h, --help display this usage
+
+Run it AFTER \`git push\`: 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 };
+ for (let index = 0; index < argv.length; index += 1) {
+ const flag = argv[index];
+ switch (flag) {
+ case '--sha': {
+ const value = argv[index + 1];
+ if (!value || !SHA_RE.test(value)) throw new Error('--sha requires a full 40-character hex commit id.');
+ options.sha = value;
+ index += 1;
+ break;
+ }
+ case '--target-url': {
+ const value = argv[index + 1];
+ if (!value || value.startsWith('-')) throw new Error('--target-url requires a value.');
+ options.targetUrl = value;
+ index += 1;
+ break;
+ }
+ case '--dry-run': options.dryRun = true; break;
+ case '--help':
+ case '-h': options.help = true; break;
+ default: throw new Error(`Unknown option: ${flag}.`);
+ }
+ }
+ return options;
+}
+
+/** A refusal the operator can act on; `runAttest` prints it and returns 1. */
+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.
+ *
+ * @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}}
+ */
+export function planAttestation(report, { sha, treeOf, isPushed, remote }) {
+ 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}`);
+ }
+ if (report.passed !== true) throw refusal(`receipt at ${PREGATE_REPORT_PATH} did not pass; fix the failure and ${RERUN}`);
+ if (report.treeStable !== true) {
+ throw refusal(`the working tree changed while pregate ran (${String(report.tree).slice(0, 12)} → ${String(report.treeAfterRun).slice(0, 12)}); ${RERUN}`);
+ }
+ const tree = treeOf(sha);
+ if (!tree) throw refusal(`cannot resolve ${sha}^{tree}: is ${sha.slice(0, 9)} a commit in this checkout?`);
+ if (tree !== report.tree) {
+ throw refusal(`commit ${sha.slice(0, 9)} has tree ${tree.slice(0, 12)} but the receipt validated tree ${String(report.tree).slice(0, 12)} — something changed after pregate; ${RERUN}`);
+ }
+ 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 }) };
+}
+
+/** The `gh api` invocation that creates the status; exported so tests can pin it. */
+export function statusRequest({ owner, repo, host }, { sha, description, targetUrl }) {
+ const args = [
+ 'api', '--method', 'POST', `repos/${owner}/${repo}/statuses/${sha}`,
+ '-f', 'state=success', '-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 };
+}
+
+/**
+ * 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 } = {}) {
+ let options;
+ try {
+ options = parseArgs(argv);
+ } catch (parseError) {
+ error(`❌ ${parseError.message}\n\n${USAGE}`);
+ return 2;
+ }
+ if (options.help) {
+ log(USAGE);
+ return 0;
+ }
+
+ const run = (command, args) => {
+ const result = exec(command, args, { cwd, encoding: 'utf8' });
+ return { ok: !result.error && result.status === 0, stdout: String(result.stdout ?? '').trim(), stderr: String(result.stderr ?? result.error?.message ?? '').trim() };
+ };
+ const git = (args) => {
+ const result = run('git', args);
+ return result.ok ? result.stdout : null;
+ };
+
+ try {
+ const sha = options.sha ?? git(['rev-parse', 'HEAD']);
+ if (!sha || !SHA_RE.test(sha)) throw refusal('cannot resolve HEAD; pass --sha <40-hex>.');
+ const branch = git(['symbolic-ref', '--short', '-q', 'HEAD']);
+ const remote = branch ? git(['config', '--get', `branch.${branch}.remote`]) : null;
+ 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 treeOf = (commit) => git(['rev-parse', '--verify', '--quiet', `${commit}^{tree}`]);
+ // Remote-tracking refs are current right after a push; a commit nothing
+ // under `<remote>/` contains has not been pushed (or not fetched back).
+ const isPushed = (commit) => {
+ 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 });
+ 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));
+ log(`ℹ️ Dry run: no status posted for ${sha.slice(0, 9)} (tree ${attestation.tree.slice(0, 12)}, stages ${attestation.stages.join(',')}).`);
+ return 0;
+ }
+
+ const posted = run(request.command, request.args);
+ if (!posted.ok) {
+ throw refusal(`gh could not create the status on ${target}: ${posted.stderr || posted.stdout || 'gh api failed'} (is \`gh auth status\` logged in with write access?)`);
+ }
+ log(`✅ Attested ${sha} tree=${attestation.tree} stages=${attestation.stages.join(',')} — status "${PREGATE_STATUS_CONTEXT}" on ${target}; the pull request's CI skips those stages.`);
+ return 0;
+ } catch (failure) {
+ if (failure?.refusal === true) {
+ error(`⛔ Not attested: ${failure.message}`);
+ return 1;
+ }
+ throw failure;
+ }
+}
+
+function defaultReadReceipt(root) {
+ let raw;
+ try {
+ raw = readFileSync(join(root, PREGATE_REPORT_PATH), 'utf8');
+ } catch {
+ return null;
+ }
+ try {
+ return JSON.parse(raw);
+ } catch {
+ throw refusal(`receipt at ${PREGATE_REPORT_PATH} is not JSON; ${RERUN}`);
+ }
+}
+
+if (isDirectlyInvoked(import.meta.url)) {
+ process.exitCode = runAttest({ argv: process.argv.slice(2) });
+}
diff --git a/scripts/pregate-attest.test.js b/scripts/pregate-attest.test.js
new file mode 100644
index 0000000000..49871e30c2
--- /dev/null
+++ b/scripts/pregate-attest.test.js
@@ -0,0 +1,221 @@
+/**
+ * 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.
+ */
+import { describe, expect, it } from 'vitest';
+import { parseArgs, planAttestation, runAttest, statusRequest, USAGE } from './pregate-attest.js';
+import {
+ ATTESTABLE_STAGES, attestedStagesFromReceipt, encodeAttestation, 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 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,
+ 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();
+ expect(parseAttestation(undefined)).toBeNull();
+ });
+
+ it('attests only suites whose every stage passed, and never a downgraded server/client run', () => {
+ const stages = [stage('scan'), stage('lint'), stage('server'), stage('build', 'passed', 'client build'), stage('build', 'failed', 'bundle pin'), stage('db', 'not-run')];
+ expect(attestedStagesFromReceipt(receipt({ stages }))).toEqual(['scan', 'lint', 'server']);
+ expect(attestedStagesFromReceipt(receipt({ stages, downgraded: true }))).toEqual(['scan', 'lint']);
+ expect(attestedStagesFromReceipt({})).toEqual([]);
+ });
+});
+
+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 });
+
+ 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' });
+ 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' });
+ expect(result.reason).toContain('attested by owner');
+ });
+
+ it('refuses the wrong creator, a mismatched tree, an unreadable description and a failed state', () => {
+ 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('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' });
+ expect(parseRemoteRepository('[email protected]:acme/widget/extra')).toBeNull();
+ expect(parseRemoteRepository('')).toBeNull();
+ });
+});
+
+describe('planAttestation', () => {
+ const commit = { sha: SHA, treeOf: () => TREE, isPushed: () => true, remote: 'origin' };
+ 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`,
+ });
+ });
+
+ it('refuses a failed receipt, an unstable tree, a legacy receipt and a missing one', () => {
+ const failed = receipt({ stages: [stage('scan'), stage('lint', 'failed')] });
+ expect(() => planAttestation(failed, commit)).toThrow(/did not pass/);
+ expect(() => planAttestation(receipt({ stages: [stage('scan')], treeAfterRun: OTHER_TREE }), commit)).toThrow(/changed while pregate ran/);
+ const legacy = { ...green, plan: { ...green.plan } };
+ delete legacy.plan.downgraded;
+ expect(() => planAttestation(legacy, commit)).toThrow(/predates attestation/);
+ expect(() => planAttestation(null, commit)).toThrow(/no receipt/);
+ });
+
+ it('refuses a commit whose tree is not the validated tree, and an unpushed one', () => {
+ expect(() => planAttestation(green, { ...commit, treeOf: () => OTHER_TREE })).toThrow(/something changed after pregate; rerun/);
+ expect(() => planAttestation(green, { ...commit, treeOf: () => null })).toThrow(/cannot resolve/);
+ expect(() => planAttestation(green, { ...commit, isPushed: () => false })).toThrow(/not on origin yet: push it first/);
+ });
+
+ it('refuses when nothing attestable passed', () => {
+ const guardsOnly = receipt({ stages: [stage('server')], downgraded: true });
+ expect(() => planAttestation(guardsOnly, commit)).toThrow(/attests no stage/);
+ });
+});
+
+describe('runAttest', () => {
+ /** A spawnSync double keyed by `command args…`; unknown invocations fail loudly. */
+ const fakeExec = (table, calls = []) => (command, args) => {
+ const key = `${command} ${args.join(' ')}`;
+ calls.push(key);
+ for (const [pattern, result] of table) {
+ if (pattern.test(key)) return typeof result === 'string' ? { status: 0, stdout: `${result}\n`, stderr: '' } : result;
+ }
+ return { status: 1, stdout: '', stderr: `unexpected: ${key}` };
+ };
+ const gitTable = (overrides = []) => [
+ ...overrides,
+ [/^git rev-parse HEAD$/, SHA],
+ [/^git symbolic-ref --short -q HEAD$/, 'feature'],
+ [/^git config --get branch\.feature\.remote$/, 'upstream'],
+ [/^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'],
+ ];
+ 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) }; };
+
+ 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 });
+ 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(out.at(-1)).toContain(`Attested ${SHA} tree=${TREE} stages=scan,lint,db`);
+ });
+
+ 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 });
+ expect(code).toBe(0);
+ expect(calls.some((call) => call.startsWith('gh '))).toBe(false);
+ const payload = JSON.parse(out[0]);
+ expect(payload).toMatchObject({ repository: 'acme/widget', sha: SHA, context: 'pregate', state: 'success', target_url: 'https://example.com/run/1' });
+ expect(payload.command).toContain('target_url=https://example.com/run/1');
+ });
+
+ it('refuses an unpushed commit, a tree mismatch and a failed receipt without calling gh', () => {
+ for (const [table, report, message] of [
+ [gitTable([[/^git branch -r --contains/, 'fork/feature']]), green, /not on upstream yet/],
+ [gitTable([[/^git rev-parse --verify --quiet .*\^\{tree\}$/, OTHER_TREE]]), green, /something changed after pregate/],
+ [gitTable(), receipt({ stages: [stage('lint', 'failed')] }), /did not pass/],
+ [gitTable(), null, /no receipt/],
+ ]) {
+ const calls = [];
+ const { err, log, error } = io();
+ const code = runAttest({ argv: [], exec: fakeExec(table, calls), log, error, readReceipt: () => report });
+ expect(code).toBe(1);
+ expect(err[0]).toMatch(/^⛔ Not attested: /);
+ expect(err[0]).toMatch(message);
+ expect(calls.some((call) => call.startsWith('gh '))).toBe(false);
+ }
+ });
+
+ 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 });
+ 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(noUpstreamErr[0]).toMatch(/no upstream remote; push it with `git push -u <remote> feature`/);
+ });
+
+ 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(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', '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(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/scripts/pregate.js b/scripts/pregate.js
index 3a1b859b0b..f6b55a87d9 100644
--- a/scripts/pregate.js
+++ b/scripts/pregate.js
@@ -42,7 +42,10 @@
* records the plan, each stage's outcome and duration, the skipped suites, the
* base and HEAD commits, and the hash of the exact working tree validated —
* untracked and uncommitted files included — so a later attestation can match
- * it to the commit that ships.
+ * it to the commit that ships. Attesting is deliberately NOT a flag here:
+ * pregate runs before the commit and the push, and a commit status can only
+ * be posted on a pushed commit, so `node scripts/pregate-attest.js` is its
+ * own step after `git push` (docs/GITHUB_ACTIONS.md "Pregate attestation").
*/
import { spawn, spawnSync } from 'child_process';
@@ -662,6 +665,7 @@ async function main() {
treeAfterRun,
stages: results,
skipped: uncovered,
+ downgraded,
runtime: { node: process.version, platform: process.platform, arch: process.arch, maxWorkers: pregateWorkerEnv(process.env).PORTOS_PREGATE_MAX_WORKERS },
startedAt,
finishedAt: new Date().toISOString(),
diff --git a/scripts/pregate.test.js b/scripts/pregate.test.js
index 4a0ccd8cfc..6de4ccc429 100644
--- a/scripts/pregate.test.js
+++ b/scripts/pregate.test.js
@@ -153,7 +153,7 @@ describe('pregate hidden-content invocation', () => {
'scripts/pregate.js', 'scripts/checkNodeVersion.js', 'scripts/scan-diff-hidden-content.js',
'scripts/ci-test-plan.js', 'scripts/ci-base-sha.js', 'server/lib/staticImportGraph.js',
'scripts/lib/directInvocation.js', 'scripts/lib/browserFidelity.js', 'scripts/lib/browserTestProfiles.js', 'scripts/lib/githubOutput.js', 'scripts/lib/dbTestFiles.js',
- 'scripts/lib/browserSuites.js', 'scripts/lib/workspaceDependencies.js', 'scripts/lib/pregateReport.js',
+ 'scripts/lib/browserSuites.js', 'scripts/lib/workspaceDependencies.js', 'scripts/lib/pregateReport.js', 'scripts/lib/pregateAttestation.js',
'scripts/migrations/shippedPromptHistory.js', 'server/lib/aiToolkit/internal/windowsSafeSpawn.js',
'server/lib/diffHiddenContentScan.js', 'server/lib/modelAbuseGuard.js',
'server/lib/textUtils.js',
@@ -684,7 +684,7 @@ describe('the gate end to end', () => {
'scripts/pregate.js', 'scripts/checkNodeVersion.js', 'scripts/scan-diff-hidden-content.js',
'scripts/ci-test-plan.js', 'scripts/ci-base-sha.js', 'server/lib/staticImportGraph.js',
'scripts/lib/directInvocation.js', 'scripts/lib/browserFidelity.js', 'scripts/lib/browserTestProfiles.js', 'scripts/lib/githubOutput.js', 'scripts/lib/dbTestFiles.js',
- 'scripts/lib/browserSuites.js', 'scripts/lib/workspaceDependencies.js', 'scripts/lib/pregateReport.js',
+ 'scripts/lib/browserSuites.js', 'scripts/lib/workspaceDependencies.js', 'scripts/lib/pregateReport.js', 'scripts/lib/pregateAttestation.js',
'scripts/migrations/shippedPromptHistory.js', 'server/lib/aiToolkit/internal/windowsSafeSpawn.js',
'server/lib/diffHiddenContentScan.js', 'server/lib/modelAbuseGuard.js',
'server/lib/textUtils.js',
@@ -940,7 +940,8 @@ describe('buildPregateReport', () => {
startedAt: 's',
finishedAt: 'f',
});
- expect(report.version).toBe(1);
+ expect(report.version).toBe(2);
+ expect(report.plan.downgraded).toBe(false);
expect(report.passed).toBe(false);
expect(report.treeStable).toBe(false);
expect(report.stages).toEqual([
@@ -961,6 +962,9 @@ describe('buildPregateReport', () => {
});
expect(report.passed).toBe(false);
expect(report.treeStable).toBe(true);
+ expect(buildPregateReport({
+ plan: planWith(), options: {}, base: {}, head: {}, tree: 't', stages: [], skipped: [], runtime: {}, startedAt: 's', finishedAt: 'f', downgraded: true,
+ }).plan.downgraded).toBe(true);
});
});