A green CI run now counts for your branch when only main moved under it (GST-3567) (#4728)

/ship's final CI check (`gstack-ship-release accept`) now accepts a
green pull request run that tested your branch merged onto a newer main,
when main changed none of your lines.

Why: before, it refused that run and you had to merge main and rerun CI,
which never settles on a busy repo (harness-evals #576, gstack #4722).

Nothing to do. Repos with a land step still re-check the merged tree;
repos with `land: null` get no merged-tree check.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/specialist-batched#1 reader=testing
Review-Finding: lib/pregate/run-check.ts:70:functional-contract reader=qa
Review-Finding: p2/outside-voice#1 reader=outside-voice
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-23 03:51:23 +00:00
1 parent 8751b382dd
commit 261f380002
13 files changed
+344 -27

No files matched your search

+7 -3
View File
@@ -12,7 +12,9 @@
* the lookup, so admitted dirty or untracked work never carries;
* each run passes verifyRun (same-repository head, the profile's workflow,
* event and jobs, the newest attempt, no newer red or running run on HEAD,
* max age, the run's own tree.json naming HEAD's tree);
* max age, the run's own tree.json naming HEAD's tree, or a pull_request
* run's merge of HEAD onto a newer base commit with the pull request's own
* lines byte-identical: only the base moved, onlyBaseMoved, GST-3567);
* every run executed tests;
* with an inventory command, the runs' tree.json files cover every file it
* prints (a lane carries only what CI provably ran); with named jobs instead
@@ -79,13 +81,15 @@ function newestVerified(src: RunSource, name: string, profile: RunProfile, heads
const twins = heads.slice(1).map(h => h.slice(0, 12));
if (!listed.length) return no('no_run', `no ${profile.workflow} run (${profile.events.join(', ')}) on ${heads[0]!.slice(0, 12)}${twins.length ? ` or on ${twins.join(', ')}, which git reads as the same tree` : ''} yet`);
const refusals: string[] = [];
const notMoved: string[] = [];
const docsOnly = src.docsOnly && ((sha: string) => src.docsOnly!(sha) && (sha === heads[0] || src.docsOnly!(heads[0]!)));
for (const run of listed) {
const v = verifyRun(src.deps, { repo: src.repo, runRef: String(run.id), profileName: name, profile, vetoHeads: heads, now: src.now, unchanged: src.unchanged, docsOnly, dispatchable: src.dispatchable?.(profile) });
const v = verifyRun(src.deps, { repo: src.repo, runRef: String(run.id), profileName: name, profile, vetoHeads: heads, now: src.now, unchanged: src.unchanged, docsOnly, dispatchable: src.dispatchable?.(profile), onlyBaseMoved: src.onlyBaseMoved });
if (v.ok) return v;
refusals.push(`run ${run.id}: ${v.reason}${v.reason === 'rerun_malformed' || v.reason === 'tree_log_unbound' || (v.reason === 'artifact_missing' && profile.tree_log_step) ? ` (${v.detail})` : ''}${v.fix ? ` (the pull request's base moved after the run; fix: ${v.fix})` : ''}`);
if (v.notMoved) notMoved.push(`run ${run.id} tested a merge onto a newer base, but it does not count for the head: ${v.notMoved} (docs/pregate.md#base-moved-carry)`);
}
return no('no_verified_run', `${name}: ${refusals.join('; ')}`);
return { ...no('no_verified_run', `${name}: ${refusals.join('; ')}`), ...(notMoved.length ? { diagnosis: notMoved } : {}) };
}
/**
+3 -3
View File
@@ -32,7 +32,7 @@ import { baseBranchOf, baseMismatchFix, describeSubstitution, substituteStampOnl
import { EXCEPTION_RECEIPT, exceptionProblem, exceptionSummary, flakyDecision, flakyRuns, parseCases, redRunChanged, type FailureDeps, type FlakyInput } from './flaky-exception';
import { buildRunCheck } from './run-check';
import { resolveBaseBranch } from '../ship-policy';
import { parseRunReceipt, parseRunRef, runChanged, runReceiptFields, uncoveredFiles, verifyRun, type ApiJob, type ApiRun, type RemoteGateRuns, type RunDeps, type RunEvidence, type RunProfile } from '../run-evidence';
import { parseRunReceipt, parseRunRef, runChanged, runReceiptFields, uncoveredFiles, verifyRun, type ApiJob, type ApiRun, type BaseMove, type RemoteGateRuns, type RunDeps, type RunEvidence, type RunProfile } from '../run-evidence';
import type { CheckDef, CheckResult, PregateContext, Stage } from './types';
import { displayNamePattern, workflowCallers } from './workflows';
@@ -285,7 +285,7 @@ function userPolicyChange(file: PregateFile): string | null {
export interface ClearInput { runUrl?: string; bundleLane?: string; receiptPath?: string; runs?: string[]; evidence?: RunCheck; flaky?: FlakyInput; allowRepoCommands?: boolean; /** The branch whose run profiles `evidence` holds (gstack-pregate clear: the record's own); absent, origin/HEAD's. */ base?: string }
/** What a run clear needs: the base branch's run profiles, the verifier's dependencies, the clock, and the remote gate's inventory. */
export interface RunCheck { repo: string; deps: RunDeps; profiles: Record<string, RunProfile>; gateRuns: RemoteGateRuns | null; now: Date; unchanged?: (p: RunProfile) => string | null; docsOnly?: (head: string) => boolean; dispatchable?: (p: RunProfile) => boolean; inventory: (command: string, tree: string, selected?: string[]) => string[] | { error: string }; failures?: FailureDeps }
export interface RunCheck { repo: string; deps: RunDeps; profiles: Record<string, RunProfile>; gateRuns: RemoteGateRuns | null; now: Date; unchanged?: (p: RunProfile) => string | null; docsOnly?: (head: string) => boolean; dispatchable?: (p: RunProfile) => boolean; onlyBaseMoved?: (merge: string, head: string) => BaseMove; inventory: (command: string, tree: string, selected?: string[]) => string[] | { error: string }; failures?: FailureDeps }
export type ClearDecision = { receipt: string; attested: boolean; substitution?: PregateReceiptSubstitution; exception?: PregateException } | { refused: 'usage' | 'PREGATE_RECEIPT_INVALID'; message: string; fix?: string };
/**
@@ -430,7 +430,7 @@ function clearByRuns(file: PregateFile, lane: string, refs: string[], check: Run
const verdicts = new Map<string, ReturnType<typeof verifyRun>>();
const verdict = (name: string, ref: string) => {
const key = `${name}\0${ref}`;
if (!verdicts.has(key)) verdicts.set(key, verifyRun(check.deps, { repo: check.repo, runRef: ref, profileName: name, profile: check.profiles[name]!, vetoHeads: file.head ? [file.head] : [], now: check.now }));
if (!verdicts.has(key)) verdicts.set(key, verifyRun(check.deps, { repo: check.repo, runRef: ref, profileName: name, profile: check.profiles[name]!, vetoHeads: file.head ? [file.head] : [], now: check.now, onlyBaseMoved: check.onlyBaseMoved }));
return verdicts.get(key)!;
};
const missingProfile = names.find(name => !check.profiles[name]);
+31 -1
View File
@@ -11,7 +11,8 @@ import { spawnSync } from '../spawn-sync';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { ghArtifactDeps, ghRunDeps, runInventory, type RunProfile } from '../run-evidence';
import { ghArtifactDeps, ghRunDeps, runInventory, type BaseMove, type RunProfile } from '../run-evidence';
import { ownLinesSame } from '../review-round-grant';
import { classifyDocsOnly } from '../docs-only';
import { wtreeFingerprint } from '../script-invocation';
import { resolveBaseBranch } from '../ship-policy';
@@ -58,6 +59,34 @@ export function gateInputsChanged(root: string, base: string, p: RunProfile): st
return null;
}
const SHA = /^[0-9a-f]{40}$/;
const refreshedBases = new Set<string>();
/**
* Whether pull_request merge commit `merge` is `head` merged onto a newer commit of the base with only the base moved (GST-3567):
* its parents are a commit on `baseRef` and then `head`, and the pull request's own added and removed lines in the merge are
* byte-identical to the head's own, at the same places (ownLinesSame, the rule a base-only merge of a reviewed head meets). So
* the run that tested the merge tested exactly the pull request's changes, on a newer base. GitHub merges onto the base as it was
* when the run started, often newer than this checkout's `origin/<base>`, so a base parent missing from it fetches that branch
* once per process before refusing.
*/
export function onlyBaseMoved(root: string, o: { merge: string; head: string; baseRef: string }): BaseMove {
const git = (args: string[], timeout = 30_000) => spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout });
const listed = git(['rev-list', '--parents', '-n', '1', o.merge]);
const parents = listed.status === 0 ? (listed.stdout ?? '').trim().split(' ').slice(1) : [];
if (parents.length !== 2 || parents[1] !== o.head || !SHA.test(parents[0]!)) return { ok: false, why: `merge commit ${o.merge.slice(0, 12)} is not a base commit merged with the head ${o.head.slice(0, 12)} (its parents: ${parents.map(p => p.slice(0, 12)).join(', ') || 'none'})` };
const base = parents[0]!;
const onBase = () => git(['merge-base', '--is-ancestor', base, o.baseRef]).status === 0;
const branch = o.baseRef.startsWith('origin/') ? o.baseRef.slice('origin/'.length) : null;
if (!onBase() && branch && !refreshedBases.has(`${root}\0${branch}`)) {
refreshedBases.add(`${root}\0${branch}`);
git(['fetch', '--quiet', '--no-tags', 'origin', `+refs/heads/${branch}:refs/remotes/origin/${branch}`], 120_000);
}
if (!onBase()) return { ok: false, why: `its base parent ${base.slice(0, 12)} is not on ${o.baseRef}${branch ? ', even after fetching it' : ''}` };
if (!ownLinesSame(root, o.baseRef, o.head, o.merge)) return { ok: false, why: `the pull request's own added and removed lines in the tested merge are not byte-identical to the head's at the same places (the base edited a line the pull request changes, or one next to it), so more than the base moved` };
return { ok: true, base };
}
/**
* `profiled` says whether `lane` may have a run profile: an unreadable base counts as profiled, so a lane is
* recorded unverified only once the base shows it has none. `policy: 'head'` reads the branch's profiles instead, only
@@ -74,6 +103,7 @@ export function buildRunCheck(root: string, lane: string | null, allowRepoComman
repo, deps: ghRunDeps(repo, root), failures: ghArtifactDeps(repo), profiles: loaded.config.run_profiles, gateRuns: loaded.config.remote_gate_runs, now: new Date(),
unchanged: p => gateInputsChanged(root, base, p),
dispatchable: p => canDispatch(root, policy === 'head' ? 'HEAD' : `origin/${base}`, p),
onlyBaseMoved: (merge, head) => onlyBaseMoved(root, { merge, head, baseRef: `origin/${base}` }),
docsOnly: head => {
const mb = spawnSync('git', ['merge-base', `origin/${base}`, head], { cwd: root, encoding: 'utf8', timeout: 30_000 });
try { return mb.status === 0 && classifyDocsOnly({ root, base: mb.stdout.trim(), head, policyRef: `origin/${base}` }).docsOnly; } catch { return false; }
+24 -12
View File
@@ -27,7 +27,12 @@
* (run_changed otherwise). A pull_request run tested GitHub's merge commit,
* not its head, so it counts only when its tree.json names that head and a
* merge commit (sha) whose tree git computes equal to the head's tree: the
* head already contained its base, so the merge tested the head tree.
* head already contained its base, so the merge tested the head tree. A lane
* carry (the caller passes onlyBaseMoved, GST-3567) also counts it when the
* merge commit is the head merged onto a commit of the base branch and the
* pull request's own added and removed lines in it are byte-identical to the
* head's own (lib/pregate/run-check.ts onlyBaseMoved):
* only the base moved. Land's merged-tree CI never passes it.
*
* Profiles are the base branch's `.gstack/pregate.json` `run_profiles`, so a
* pull request can tighten them but never relax them. The workflow a run
@@ -95,9 +100,12 @@ export type RunRefusal = 'run_ref_invalid' | 'other_repository' | 'fork_run' | '
/** `docs_only`: a pull_request run whose gate skipped every skippable job on a change lib/docs-only.ts calls human docs only; it ran and recorded no tests (R81). */
/** `tree_source`: `job-log` when tree.json came from the job log because the run held no artifact (HARN-118); absent for an artifact. */
/** `rerun`: the files whose newest result came from a re-run attempt (tree.json `rerun_files`, gbrain#9690), with the run's `attempts`; set only when a file passed on a re-run (GST-3054). */
export interface RunEvidence { run_id: number; run_attempt: number; head_sha: string; tree: string; profile: string; event: string; finished_at: string; files: string[]; tests: number | null; skipped?: string[]; skipped_jobs?: string[]; docs_only?: true; rerun?: string[]; attempts?: number[]; tree_source?: 'job-log' }
/** `fix`: the one command that clears a refusal the caller can repair, such as a pull_request run that tested a merge with an older base. */
export type RunVerdict = { ok: true; evidence: RunEvidence } | { ok: false; reason: RunRefusal; detail: string; fix?: string };
/** `base_moved`: the pull_request run tested its head merged onto `base`, a newer base commit, with the pull request's own lines byte-identical (lib/pregate/run-check.ts onlyBaseMoved, GST-3567); `tree` is then the head's tree it counts for and `tested_tree` the merge's. */
export interface RunEvidence { run_id: number; run_attempt: number; head_sha: string; tree: string; profile: string; event: string; finished_at: string; files: string[]; tests: number | null; skipped?: string[]; skipped_jobs?: string[]; docs_only?: true; rerun?: string[]; attempts?: number[]; tree_source?: 'job-log'; base_moved?: { merge: string; base: string; tested_tree: string } }
/** `fix`: the one command that clears a refusal the caller can repair, such as a pull_request run that tested a merge with an older base. `notMoved`: why onlyBaseMoved did not count that run for its head. */
export type RunVerdict = { ok: true; evidence: RunEvidence } | { ok: false; reason: RunRefusal; detail: string; fix?: string; notMoved?: string };
/** What lib/pregate/run-check.ts onlyBaseMoved decides about a pull_request run's merge commit (GST-3567): the base it merged onto, or why it does not count for the head. */
export type BaseMove = { ok: true; base: string } | { ok: false; why: string };
const SHA = /^[0-9a-f]{40}$/;
const RUN_EVENTS = ['push', 'workflow_dispatch', 'pull_request'];
@@ -184,7 +192,7 @@ export const normalPath = (f: string): string => f.replace(/^(\.\/)+/, '');
* The verdict for run `runRef` under `profile`. `vetoHeads` are further heads
* whose newer runs of the same workflow can veto (the consumer's own head).
*/
export function verifyRun(deps: RunDeps, o: { repo: string; runRef: string; profileName: string; profile: RunProfile; vetoHeads?: string[]; ignoreRun?: number; now: Date; unchanged?: (p: RunProfile) => string | null; docsOnly?: (head: string) => boolean; dispatchable?: boolean }): RunVerdict {
export function verifyRun(deps: RunDeps, o: { repo: string; runRef: string; profileName: string; profile: RunProfile; vetoHeads?: string[]; ignoreRun?: number; now: Date; unchanged?: (p: RunProfile) => string | null; docsOnly?: (head: string) => boolean; dispatchable?: boolean; onlyBaseMoved?: (merge: string, head: string) => BaseMove }): RunVerdict {
const id = parseRunRef(o.runRef, o.repo);
if (id === null) return fail('run_ref_invalid', `${JSON.stringify(o.runRef)} is not a run id or a run URL on ${o.repo}`);
const p = o.profile;
@@ -258,12 +266,15 @@ export function verifyRun(deps: RunDeps, o: { repo: string; runRef: string; prof
const baseMoved = o.dispatchable === false
? `push a merge of the base to ${run.head_branch || '<branch>'}, or ask the pull request's author to (${p.workflow} cannot be dispatched for this run profile), then gstack-ci-carry wait`
: `gh workflow run ${p.workflow} --ref ${run.head_branch || '<branch>'}, then gstack-ci-carry wait`;
let moved: RunEvidence['base_moved'];
if (rec.tree !== headTree) {
const testedMerge = pr && typeof rec.sha === 'string' && SHA.test(rec.sha) && deps.commitTree(rec.sha) === rec.tree;
if (testedMerge) return fail('tree_mismatch', `${at} tested merge commit ${(rec.sha as string).slice(0, 12)} (tree ${String(rec.tree)}), not its head ${run.head_sha.slice(0, 12)}'s tree ${headTree}: the pull request was behind its base (the base moved after the run, or the branch lacks its tip)`, baseMoved);
return fail('tree_mismatch', `${at} recorded tree ${String(rec.tree)}, but its head ${run.head_sha.slice(0, 12)} has tree ${headTree}`);
if (!testedMerge) return fail('tree_mismatch', `${at} recorded tree ${String(rec.tree)}, but its head ${run.head_sha.slice(0, 12)} has tree ${headTree}`);
const m = o.onlyBaseMoved?.(rec.sha as string, run.head_sha);
if (!m?.ok) return { ...fail('tree_mismatch', `${at} tested merge commit ${(rec.sha as string).slice(0, 12)} (tree ${String(rec.tree)}), not its head ${run.head_sha.slice(0, 12)}'s tree ${headTree}: the pull request was behind its base (the base moved after the run, or the branch lacks its tip)${m ? `; it does not count for the head because ${m.why}` : ''}`, baseMoved), ...(m ? { notMoved: m.why } : {}) };
moved = { merge: rec.sha as string, base: m.base, tested_tree: rec.tree as string };
}
if (pr) {
if (pr && !moved) {
if (typeof rec.sha !== 'string' || !SHA.test(rec.sha)) return fail('artifact_mismatch', `${at}'s ${p.artifact} names no merge commit (sha) for its pull_request run`);
const mergeTree = deps.commitTree(rec.sha);
if (!mergeTree) return fail('api_error', `git cannot read the tree of merge commit ${rec.sha}`);
@@ -283,7 +294,7 @@ export function verifyRun(deps: RunDeps, o: { repo: string; runRef: string; prof
const skipped = rec.skipped_files === undefined ? {} : { skipped: (rec.skipped_files as string[]).map(normalPath) };
const rerun = ((rec.rerun_files ?? []) as string[]).map(normalPath);
const reran = rerun.length ? { rerun, attempts: [...new Set((rec.attempts ?? []) as number[])].sort((a, b) => a - b) } : {};
return { ok: true, evidence: { run_id: id, run_attempt: run.run_attempt, head_sha: run.head_sha, tree: headTree, profile: o.profileName, event: run.event, finished_at: finishedAt!, files, tests, ...skipped, ...(skippedJobs.length ? { skipped_jobs: skippedJobs } : {}), ...reran, ...(fromLog ? { tree_source: 'job-log' as const } : {}) } };
return { ok: true, evidence: { run_id: id, run_attempt: run.run_attempt, head_sha: run.head_sha, tree: headTree, profile: o.profileName, event: run.event, finished_at: finishedAt!, files, tests, ...skipped, ...(skippedJobs.length ? { skipped_jobs: skippedJobs } : {}), ...reran, ...(fromLog ? { tree_source: 'job-log' as const } : {}), ...(moved ? { base_moved: moved } : {}) } };
} catch (e: any) {
return fail('api_error', `reading run ${id} failed: ${String(e?.message ?? e).slice(0, 300)}`);
}
@@ -383,7 +394,8 @@ export function uncoveredFiles(inventory: string[], evidence: RunEvidence[], ski
/** What a run check reads: the repository, the verifier's dependencies, the base branch's profiles and the clock. */
/** `unchanged` (findCarry only): null when a profile's workflow and gate inputs match the base, else which file differs. */
export interface RunSource { repo: string; deps: RunDeps; profiles: Record<string, RunProfile>; now: Date; unchanged?: (p: RunProfile) => string | null; docsOnly?: (head: string) => boolean; dispatchable?: (p: RunProfile) => boolean }
/** `onlyBaseMoved`: onlyBaseMoved bound to the checkout and its base branch, so a lane carry counts a run whose base moved (GST-3567). */
export interface RunSource { repo: string; deps: RunDeps; profiles: Record<string, RunProfile>; now: Date; unchanged?: (p: RunProfile) => string | null; docsOnly?: (head: string) => boolean; dispatchable?: (p: RunProfile) => boolean; onlyBaseMoved?: (merge: string, head: string) => BaseMove }
export type FromRunVerdict = { ok: true; evidence: RunEvidence; receipt: string } | { ok: false; reason: string; detail: string };
/**
@@ -395,7 +407,7 @@ export function verifyFromRun(src: RunSource, ref: string, names: string[], tree
if (!names.length) return { ok: false, reason: 'no_profile', detail: 'the base branch declares no run_profiles entry for this machine\'s OS whose workflow holds a lane this machine runs (gstack\'s ci-reuse/free-tests, for example)' };
const refusals: Array<{ reason: string; detail: string }> = [];
for (const name of names) {
const v = verifyRun(src.deps, { repo: src.repo, runRef: ref, profileName: name, profile: src.profiles[name]!, vetoHeads: SHA.test(head) ? [head] : [], now: src.now });
const v = verifyRun(src.deps, { repo: src.repo, runRef: ref, profileName: name, profile: src.profiles[name]!, vetoHeads: SHA.test(head) ? [head] : [], now: src.now, onlyBaseMoved: src.onlyBaseMoved });
if (!v.ok) { refusals.push({ reason: v.reason, detail: `${name}: ${v.detail}` }); continue; }
const e = v.evidence;
if (e.tree !== tree) return { ok: false, reason: 'tree_mismatch', detail: `run ${e.run_id} tested tree ${e.tree.slice(0, 12)}, not this tree ${tree.slice(0, 12)}` };
@@ -410,7 +422,7 @@ export function verifyFromRun(src: RunSource, ref: string, names: string[], tree
* whose files passed only on a re-run adds `rerun=<files> attempts=<list>` (GST-3054): allowed, but never shown as a clean pass.
*/
export function runReceiptFields(evidence: RunEvidence[], now: Date): string {
return `runs=${evidence.map(e => `${e.run_id}/${e.run_attempt}`).join(',')} profiles=${evidence.map(e => e.profile).join(',')} heads=${[...new Set(evidence.map(e => e.head_sha.slice(0, 12)))].join(',')}${rerunMarker([...rerunByRun(evidence).values()])}${evidence.some(e => e.tree_source === 'job-log') ? ' tree_source=job-log' : ''} verified=${now.toISOString()}`;
return `runs=${evidence.map(e => `${e.run_id}/${e.run_attempt}`).join(',')} profiles=${evidence.map(e => e.profile).join(',')} heads=${[...new Set(evidence.map(e => e.head_sha.slice(0, 12)))].join(',')}${rerunMarker([...rerunByRun(evidence).values()])}${evidence.some(e => e.tree_source === 'job-log') ? ' tree_source=job-log' : ''}${evidence.some(e => e.base_moved) ? ` base_moved=${[...new Set(evidence.flatMap(e => (e.base_moved ? [e.base_moved.base.slice(0, 12)] : [])))].join(',')}` : ''} verified=${now.toISOString()}`;
}
/** The re-run record per carried run (`<id>/<attempt>`): the distinct re-run files and attempts across every profile that read that run, so two profiles on one run count each file once. */