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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Skip CI stages a pregate attestation on the pull request head already proved
[._.]/ Adam Eivyca4ce2c8e95b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c218a398dc..299b5d4fd1 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -34,6 +34,12 @@ jobs:# Still live despite the removed push trigger: a called workflow inherits# the caller's event, and release.yml calls this one from a push.if: github.event_name != 'push' || !contains(github.event.head_commit.message, '[skip ci]')+ # `statuses: read` lets the planner read the head's `pregate` commit status+ # (docs/GITHUB_ACTIONS.md "Pregate attestation"). Read only: nothing in+ # this job may create a status, and a fork's token could not anyway.+ permissions:+ contents: read+ statuses: readoutputs:full: ${{ steps.plan.outputs.full }}reason: ${{ steps.plan.outputs.reason }}@@ -66,6 +72,11 @@ jobs:client_shards: ${{ steps.plan.outputs.client_shards }}windows_shards: ${{ steps.plan.outputs.windows_shards }}suite_reasons: ${{ steps.plan.outputs.suite_reasons }}+ # The pregate attestation honored for this head (JSON), and the stages it+ # let the plan skip. Informational: every leaf job already gates on the+ # mode/flag outputs above, which the planner cleared for attested stages.+ attestation: ${{ steps.plan.outputs.attestation }}+ attested_stages: ${{ steps.plan.outputs.attested_stages }}node_minimum: ${{ steps.node-minimum.outputs.run }}steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1@@ -106,6 +117,17 @@ jobs:# The planner turns a PR into `release` into a full plan: that PR is# the single gate a release ships behind, so it never runs scoped.CI_BASE_REF: ${{ github.base_ref }}+ # Pregate attestation inputs. The planner honors a `pregate` commit+ # status on the head only for a same-repository, non-bot pull request+ # whose status the repository owner created and whose attested tree+ # is the head's tree; everything else leaves the plan as computed.+ CI_EVENT_NAME: ${{ github.event_name }}+ CI_REPOSITORY: ${{ github.repository }}+ CI_REPOSITORY_OWNER: ${{ github.repository_owner }}+ CI_PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}+ CI_PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ CI_PR_AUTHOR: ${{ github.event.pull_request.user.login }}+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: node scripts/ci-test-plan.js# The Node-minimum job proves the lockfiles install and the runtime gate@@ -144,6 +166,7 @@ jobs:CLIENT_SHARDS: ${{ steps.plan.outputs.client_shards }}WINDOWS_SHARDS: ${{ steps.plan.outputs.windows_shards }}SUITE_REASONS: ${{ steps.plan.outputs.suite_reasons }}+ ATTESTATION: ${{ steps.plan.outputs.attestation }}run: |{echo "### CI impact plan"@@ -162,6 +185,7 @@ jobs:echo "- Node minimum compatibility: \`${NODE_MINIMUM_MODE}\`"echo "- Windows server tests: \`${WINDOWS_MODE}\` (\`${WINDOWS_TEST_MODE}\`, shards \`${WINDOWS_SHARDS}\`)"echo "- Suite selection reasons: \`${SUITE_REASONS}\`"+ echo "- Pregate attestation: \`${ATTESTATION}\`"} >> "$GITHUB_STEP_SUMMARY"prompt-history:diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex d1c2fd276b..417ba13e4d 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -55,9 +55,12 @@ jobs:# so this grants what ci.yml's gate jobs read (`actions: read`, to name a# failed step) and scopes full-ci DOWN from the workflow-level# `contents: write` the release job needs; ci.yml only ever checks out.+ # `statuses: read` is what the impact job declares to read a head's+ # pregate attestation; a called job cannot hold a scope the caller lacks.permissions:contents: readactions: read+ statuses: readuses: ./.github/workflows/ci.ymlwith:full: truediff --git a/scripts/ci-base-sha.test.js b/scripts/ci-base-sha.test.jsindex f83768dcb3..3dfb63f804 100644--- a/scripts/ci-base-sha.test.js+++ b/scripts/ci-base-sha.test.js@@ -76,6 +76,19 @@ describe('ci.yml checkout depth', () => {expect(body, id).not.toMatch(/CI_BASE_SHA:\s*\$\{\{/);}});++ it('gives the planner the head commit the attestation tree is read from', () => {+ // The pregate attestation compares the attested tree with `<head>^{tree}`.+ // At depth 2 the merge-ref checkout carries the head as HEAD^2, which is+ // the only reason the planner can resolve it without a wider fetch — so+ // the planner pins the event head to that parent, and the impact job must+ // keep passing the head and keep the depth that makes it present.+ const planner = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'ci-test-plan.js'), 'utf8');+ expect(planner).toContain("['rev-parse', '--verify', '--quiet', 'HEAD^2']");+ expect(jobs.impact).toContain('CI_PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}');+ expect(jobs.impact).toMatch(/fetch-depth:\s*2\b/);+ expect(jobs.impact).not.toMatch(/fetch-depth:\s*0\b/);+ });});describe('ci.yml required checks', () => {diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex fa7a1e4394..a17f6bbadb 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -9,6 +9,7 @@ import { isDirectlyInvoked } from './lib/directInvocation.js';import { writeStepOutput } from './lib/githubOutput.js';import { resolveDbTestFiles } from './lib/dbTestFiles.js';import { BROWSER_SUITES } from './lib/browserSuites.js';+import { ATTESTABLE_STAGES, selectAttestation } from './lib/pregateAttestation.js';import { declaresPromptHashes, isNumberedMigrationFile } from './migrations/shippedPromptHistory.js';const TEST_FILE_RE = /\.(?:test|spec)\.[cm]?[jt]sx?$/i;@@ -1381,6 +1382,10 @@ export function emitGitHubPlan(plan) {client_shards: JSON.stringify(plan.shards.client),windows_shards: JSON.stringify(plan.shards.windows),suite_reasons: JSON.stringify(plan.suiteReasons),+ // The pregate attestation this plan honored (see applyAttestation), or+ // why none was: `{"attested": false, "reason": …}` is still a decision.+ attestation: JSON.stringify(plan.attestation ?? { attested: false, reason: 'no attestation resolved' }),+ attested_stages: JSON.stringify(plan.attestedStages ?? []),};Object.entries(outputs).forEach(([name, value]) => {@@ -1588,6 +1593,148 @@ export function collectPlanInputs({ baseSha, forceFull = false, changedFiles, cwclientDependencies, dbDependencies, browserDependencies, dependencyChanges, promptHistoryInputs, linuxContainmentInputs };}+// ---------------------------------------------------------------------------+// Pregate attestation (docs/GITHUB_ACTIONS.md "Pregate attestation")+//+// 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.+//+// 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.+// ---------------------------------------------------------------------------++/** Stages a receipt may attest to, mapped to the plan fields they clear. */+const ATTESTATION_SKIPS = Object.freeze({+ lint: (plan) => ({ lint: { ...plan.lint, mode: 'skip' } }),+ client: (plan) => ({ client: { ...plan.client, mode: 'skip' } }),+ build: () => ({ build: false }),+ smoke: () => ({ smoke: false }),+ browser: () => ({ browserFiles: [] }),+ db: () => ({ db: false }),+ 'prompt-history': () => ({ promptHistory: false }),+});++/**+ * 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.+ *+ * @param {NodeJS.ProcessEnv} env+ * @returns {{eligible: boolean, reason: string, headSha?: string, repository?: string, owner?: string}}+ */+export function attestationEligibility(env) {+ const trim = (value) => (typeof value === 'string' ? value.trim() : '');+ const eventName = trim(env.CI_EVENT_NAME);+ const repository = trim(env.CI_REPOSITORY);+ const owner = trim(env.CI_REPOSITORY_OWNER);+ const headRepo = trim(env.CI_PR_HEAD_REPO);+ const headSha = trim(env.CI_PR_HEAD_SHA);+ const author = trim(env.CI_PR_AUTHOR);+ if (eventName !== 'pull_request') return { eligible: false, reason: `event ${eventName || '(none)'} is not a pull request` };+ if (env.CI_FORCE_FULL === 'true') return { eligible: false, reason: 'full CI requested' };+ if (trim(env.CI_BASE_REF) === 'release') return { eligible: false, reason: 'release gate: pull request into release' };+ if (!repository || !owner) return { eligible: false, reason: 'repository or owner unknown' };+ if (headRepo.toLowerCase() !== repository.toLowerCase()) return { eligible: false, reason: `head repository ${headRepo || '(unknown)'} is not ${repository}` };+ if (!author || /\[bot\]$/i.test(author)) return { eligible: false, reason: `pull request author ${author || '(unknown)'} is a bot or unknown` };+ if (!/^[0-9a-f]{40}$/.test(headSha)) return { eligible: false, reason: 'head sha unknown' };+ return { eligible: true, reason: 'same-repository pull request', headSha, repository, owner };+}++/**+ * 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.+ *+ * `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}}+ */+export function resolveCiAttestation({ env = process.env, exec = execFileSync, cwd = process.cwd(), log = console.warn } = {}) {+ const none = (reason) => {+ log(`⏭️ Pregate attestation not honored: ${reason}.`);+ return { attested: false, reason };+ };+ const eligibility = attestationEligibility(env);+ if (!eligibility.eligible) return none(eligibility.reason);+ const { headSha, repository, owner } = eligibility;+ const capture = (command, args) => {+ try {+ return exec(command, args, { cwd, encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'] }).trim();+ } catch (error) {+ return { error: error?.stderr?.toString().trim() || error?.message || 'command failed' };+ }+ };+ const mergeHead = capture('git', ['rev-parse', '--verify', '--quiet', 'HEAD^2']);+ if (typeof mergeHead !== 'string' || mergeHead !== headSha) {+ return none(`checkout is not the merge ref of head ${headSha.slice(0, 9)}`);+ }+ 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 { 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 };+}++/**+ * 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.+ *+ * @param {object} plan - a finished plan (buildCiTestPlan)+ * @param {{attested: boolean, reason: string, stages?: string[], sha?: string, tree?: string, creator?: string, createdAt?: string}} 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 smokeCovered = attested.has('smoke') || !plan.smoke;+ const skips = { ...ATTESTATION_SKIPS, server: smokeCovered ? (current) => ({ server: { ...current.server, mode: 'skip' } }) : null };+ let next = base;+ const skipped = [];+ for (const stage of ATTESTABLE_STAGES) {+ if (!attested.has(stage) || !skips[stage]) continue;+ 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 suiteReasons = { ...plan.suiteReasons, attestation: `${label}: skipping ${skipped.join(', ') || 'nothing'}` };+ for (const stage of skipped) suiteReasons[stage === 'prompt-history' ? 'promptHistory' : stage] = `skipped: ${label}`;+ 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 };+}+function main() {const forceFullReason = forceFullReasonFor({forceFull: process.env.CI_FORCE_FULL === 'true',@@ -1617,7 +1764,7 @@ function main() {forceFull,changedFiles: changedFilesOverride,});- emitGitHubPlan(buildCiTestPlan(changedFiles, {+ const plan = buildCiTestPlan(changedFiles, {trackedFiles,forceFull,forceFullReason,@@ -1629,7 +1776,9 @@ function main() {dependencyChanges,promptHistoryInputs,linuxContainmentInputs,- }));+ });+ // Last, over the finished plan: the attestation only ever removes work.+ emitGitHubPlan(applyAttestation(plan, resolveCiAttestation()));}if (isDirectlyInvoked(import.meta.url)) main();diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.jsindex 877bd9c1d1..d325f09e0f 100644--- a/scripts/ci-test-plan.test.js+++ b/scripts/ci-test-plan.test.js@@ -9,8 +9,12 @@ import { staticImportClosure } from '../server/lib/staticImportGraph.js';import { TRUSTED_REBUILDS } from './trusted-rebuilds.js';import { workflowJobs } from './lib/workflowJobs.js';+import { encodeAttestation } from './lib/pregateAttestation.js';+import {ALWAYS_RUN_TESTS,+ applyAttestation,+ attestationEligibility,BROWSER_SUITES,buildCiTestPlan,classifyDependencyChange,@@ -23,6 +27,7 @@ import {MAX_TARGETED_TEST_FILES,needsSlashdoSubmodule,PLATFORM_PACKAGE_RES,+ resolveCiAttestation,shardIndexes,SLASHDO_GITLINK_PATH,sourceReferencePattern,@@ -1950,3 +1955,190 @@ describe('path-gated single-purpose jobs', () => {expect(jobs.gate).toContain('CI_GATE_RESULT_LINUX_CONTAINMENT: ${{ needs.linux-containment.result }}');});});++describe('pregate attestation', () => {+ const repo = fileURLToPath(new URL('../', import.meta.url));+ const TREE = 'a'.repeat(40);+ const HEAD = 'c'.repeat(40);+ const REPOSITORY = 'acme/widget';+ 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,+ });+ /** 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 key = `${command} ${args.join(' ')}`;+ 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.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);+ }+ throw new Error(`unexpected ${key}`);+ };+ const quiet = () => {};+ 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', () => {+ expect(attestationEligibility(prEnv)).toMatchObject({ eligible: true, headSha: HEAD, owner: 'acme' });+ expect(attestationEligibility({ ...prEnv, CI_PR_HEAD_REPO: 'someone/widget' }).reason).toMatch(/head repository someone\/widget is not/);+ expect(attestationEligibility({ ...prEnv, CI_PR_AUTHOR: 'dependabot[bot]' }).reason).toMatch(/is a bot/);+ expect(attestationEligibility({ ...prEnv, CI_BASE_REF: 'release' }).reason).toMatch(/release gate/);+ expect(attestationEligibility({ ...prEnv, CI_FORCE_FULL: 'true' }).reason).toMatch(/full CI requested/);+ expect(attestationEligibility({ ...prEnv, CI_EVENT_NAME: 'schedule' }).reason).toMatch(/not a pull request/);+ expect(attestationEligibility({ ...prEnv, CI_PR_HEAD_SHA: 'abc' }).reason).toMatch(/head sha unknown/);+ 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' });+ 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 reasons = [];+ const log = (line) => reasons.push(line);+ const refused = (options, env = prEnv) => {+ const result = resolveCiAttestation({ env, exec: fakeExec(options), log });+ expect(result.attested).toBe(false);+ return result.reason;+ };+ expect(refused({ statuses: [status({ creator: { login: 'someone' } })] })).toMatch(/created by "someone"/);+ 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({}, { ...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);+ });++ 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 }));+ expect(attested).toMatchObject({+ full: false,+ server: { mode: 'skip' }, client: { mode: 'skip' }, lint: { mode: 'skip' },+ db: false, build: false, smoke: false, browserFiles: [], promptHistory: false,+ // Untouched: no local run exists for these.+ windows: plan.windows, windowsMode: plan.windowsMode, windowsFiles: plan.windowsFiles, linuxContainment: true,+ 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.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 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 attested = applyAttestation(plan, partial);+ expect(attested.server.mode).toBe(plan.server.mode);+ expect(attested.smoke).toBe(true);+ expect(attested.lint.mode).toBe('skip');+ expect(attested.attestedStages).toEqual(['lint']);+ expect(attested.suiteReasons.server).toMatch(/server job kept: the boot smoke was not attested$/);+ // With no smoke selected, the server stage alone is enough.+ const noSmoke = applyAttestation({ ...plan, smoke: false }, partial);+ expect(noSmoke.server.mode).toBe('skip');+ expect(noSmoke.attestedStages).toEqual(['lint', 'server']);+ });++ it('records why no attestation applied without touching the plan', () => {+ const plan = fullPlan();+ const untouched = applyAttestation(plan, { attested: false, reason: 'head repository someone/widget is not acme/widget' });+ expect(untouched).toMatchObject({ ...plan, attestedStages: [] });+ expect(untouched.full).toBe(true);+ expect(untouched.suiteReasons.attestation).toBe('not honored: head repository someone/widget is not acme/widget');+ });++ it('emits the attestation through the planner CLI and ci.yml gates the impact job on it', () => {+ // 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.+ 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));+ 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('server/lib/example.js', 'export const value = 1;\n');+ write('server/lib/example.test.js', 'import { value } from "./example.js";\n');+ git('add', '--all');+ git('commit', '-qm', 'base');+ git('checkout', '-qb', 'feature');+ write('server/lib/example.js', 'export const value = 2;\n');+ git('add', '--all');+ git('commit', '-qm', 'change');+ const head = git('rev-parse', 'HEAD');+ const headTree = git('rev-parse', 'HEAD^{tree}');+ git('checkout', '-q', '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 });+ writeFileSync(join(bin, 'gh.cmd'), `@"${process.execPath}" "%~dp0gh.js" %*\r\n`);+ const statuses = JSON.stringify([status({ description: encodeAttestation({ tree: headTree, stages: ['scan', 'lint', 'server', 'smoke', 'client', 'build'] }) })]);+ const plan = (env) => JSON.parse(execFileSync(process.execPath, [planner], {+ cwd: root, encoding: 'utf8',+ env: { ...process.env, PATH: `${bin}${process.platform === 'win32' ? ';' : ':'}${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.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/);++ const fork = plan({ CI_PR_HEAD_REPO: 'someone/widget' });+ expect(JSON.parse(fork.attestation)).toEqual({ attested: false, reason: `head repository someone/widget is not ${REPOSITORY}` });+ expect(fork.server_mode).not.toBe('skip');+ expect(JSON.parse(fork.attested_stages)).toEqual([]);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }++ const jobs = workflowJobs(readFileSync(join(repo, '.github/workflows/ci.yml'), 'utf8'));+ // Reading statuses needs the scope; nothing in the impact job may write one.+ expect(jobs.impact).toMatch(/\n permissions:\n contents: read\n statuses: read\n/);+ const planStep = jobs.impact.slice(jobs.impact.indexOf('id: plan'), jobs.impact.indexOf('run: node scripts/ci-test-plan.js'));+ for (const line of [+ "CI_EVENT_NAME: ${{ github.event_name }}",+ 'CI_REPOSITORY: ${{ github.repository }}',+ 'CI_REPOSITORY_OWNER: ${{ github.repository_owner }}',+ 'CI_PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}',+ 'CI_PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}',+ 'CI_PR_AUTHOR: ${{ github.event.pull_request.user.login }}',+ 'GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}',+ ]) 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.+ 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.+ expect(jobs['full-gate']).toMatch(/needs\.impact\.outputs\.full == 'true'/);+ });+});