feat(pregate): pre-push housekeeping guards (--stage guards, push runs them, gstack's guard list) (GST-1138)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
garrytanandcapy-ai[bot] committed 2026-11-03 04:16:13 +00:00
1 parent 4ec1722ecb
commit b5f64260ac
10 files changed
+194 -14

No files matched your search

+8 -3
View File
@@ -37,9 +37,14 @@ import { displayNamePattern, workflowCallers } from './workflows';
export const CHECKS: readonly CheckDef[] = [regenCheck, secretsCheck, straysCheck, literalsCheck, timingCheck, guardsCheck, lanesCheck];
export const CHECK_IDS = CHECKS.map(c => c.id);
export const PREGATE_OUT_REL = '.gstack/tmp/pregate.json';
/** Where `--stage guards` (the pre-push housekeeping guards) writes by default, so it never replaces the full run's file. */
export const PREGATE_GUARDS_OUT_REL = '.gstack/tmp/pregate-guards.json';
/** The checks `--stage guards` runs: generated-file freshness and the repo's guards, each only for the files the diff touched. */
export const PREPUSH_CHECK_IDS = ['regen', 'guards'] as const;
export const PREGATE_TIER2 = ['ratchets', 'lint', 'links', 'hermetic', 'patches', 'integrator'] as const;
export interface RunOptions { stage: Stage | 'all'; only?: string[]; run?: string }
/** `guards` selects PREPUSH_CHECK_IDS (preflight checks): the pre-push run, docs/pregate.md#prepush. */
export interface RunOptions { stage: Stage | 'guards' | 'all'; only?: string[]; run?: string }
/** Apply the repo's `warn` downgrades: never `secrets`. `lanes` applies its own (a touched file with no lane, after the selected tests ran), so nothing it fails is downgraded here. */
export function applyDowngrades(ctx: PregateContext, result: CheckResult, def: CheckDef): CheckResult {
@@ -82,7 +87,7 @@ const git = (cwd: string, args: string[]): string | null => {
};
export async function runPregate(ctx: PregateContext, o: RunOptions): Promise<PregateFile> {
const selected = CHECKS.filter(c => (o.stage === 'all' || c.stage === o.stage) && (!o.only || o.only.includes(c.id)));
const selected = o.stage === 'guards' ? CHECKS.filter(c => (PREPUSH_CHECK_IDS as readonly string[]).includes(c.id)) : CHECKS.filter(c => (o.stage === 'all' || c.stage === o.stage) && (!o.only || o.only.includes(c.id)));
if (selected.some(c => c.id === 'lanes')) { const line = autoCarry(ctx); if (line) ctx.progress(line); }
const checks: CheckResult[] = [];
const clocks: Record<Stage, number> = { preflight: 0, tests: 0 };
@@ -98,7 +103,7 @@ export async function runPregate(ctx: PregateContext, o: RunOptions): Promise<Pr
const file: PregateFile = {
schema_version: 1, tree: ctx.wtree, head: ctx.head, base: `${ctx.baseRef}@${ctx.baseSha.slice(0, 12)}`, generated_at: new Date().toISOString(),
policy: ctx.configLabel, ...(ctx.configDigest ? { policy_digest: ctx.configDigest } : {}), ...(ctx.absentUserPolicy ? { policy_user_path: ctx.absentUserPolicy } : {}), registry: ctx.registryLabel, run: o.run, scratch: ctx.scratch,
stage1_ms: o.stage === 'tests' ? undefined : clocks.preflight, stage2_ms: o.stage === 'preflight' ? undefined : clocks.tests,
stage1_ms: o.stage === 'tests' ? undefined : clocks.preflight, stage2_ms: o.stage === 'preflight' || o.stage === 'guards' ? undefined : clocks.tests,
checks: checks.map(c => { const { remote: _r, ...rest } = c; return rest; }),
requires_remote: remote,
};
+33 -1
View File
@@ -20,6 +20,7 @@ import { parseReceiptDocs, type ReceiptDocs } from './ship-receipt-docs';
import { resolveStateRoot } from './state-root';
import { bumpVersion, cmpVersion, fmtVersion, parseVersion, versionWidth, type Bump } from './version-source';
import { waitForRun } from './ci-carry';
import { PREPUSH_CHECK_IDS } from './pregate/index';
import { buildRunCheck } from './pregate/run-check';
import { bin, carryLane, carryNoneLine, evidenceExempt, firstLine, flagReader, fragmentPath, gh, git, hostedOrigin, laneLine, lanes, mappedLanes, releasePaths, Report, runLanes, sh, shipPolicy, short, stampedFiles } from './ship-bin-common';
@@ -38,7 +39,8 @@ export const RELEASE_HELP = `gstack-ship-release — /ship Steps 12 and 15-17 (s
A lane the base branch maps in .gstack/pregate.json ship_lanes_from is carried from a verified CI run at this exact
tree, else deferred (EVIDENCE: DEFERRED): the pregate then runs its preflight stage here and its tests stage in accept
push --branch <branch-name> [--gate-open <n>] [--gate-open-approved] [--early [--base <base>]]
Step 17 after its guard block: the saved-branch check, the open-gate check, the sealed guard, the idempotency check, git push -u;
Step 17 after its guard block: the saved-branch check, the open-gate check, the sealed guard, the pre-push housekeeping
guards (gstack-pregate --stage guards; a pass at HEAD's tree is reused), the idempotency check, git push -u;
--early (the Phase 2 push before review, so CI runs beside it) also runs pregate's secrets scan on the commits first
accept --base <base> --lane <label>=<command>... [--wait <s>]
after push: final-tree CI acceptance. Waits up to --wait seconds (default 170) for the CI run of each mapped profile at
@@ -467,6 +469,33 @@ export async function accept(argv: readonly string[], cwd: string): Promise<Repo
return r.next('Step 18: the receipt records ci_carried from the ledger');
}
/**
* The pre-push housekeeping guards (docs/pregate.md#prepush): `gstack-pregate --stage guards` before every push, early or
* final, so a stale golden, a size ratchet or a type error fails here instead of a CI round. A pass recorded at HEAD's
* exact tree by this step or by finish's preflight (both under .git, which no commit can carry) is reused, never rerun.
*/
function prepushGuards(cwd: string, base: string | undefined): { line: string; stop?: string } {
const gitPath = (name: string) => path.resolve(cwd, git(cwd, ['rev-parse', '--git-path', `gstack/${name}`]).stdout.trim() || `.git/gstack/${name}`);
const tree = git(cwd, ['rev-parse', 'HEAD^{tree}']).stdout.trim();
const out = gitPath('pregate-guards.json');
for (const file of [out, gitPath('pregate-finish-preflight.json')]) {
let rec: { tree?: string; checks?: { id: string; status: string; detail?: string }[] };
try { rec = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { continue; }
const rows = PREPUSH_CHECK_IDS.map(id => rec.checks?.find(c => c.id === id));
if (tree && rec.tree === tree && rows.every(row => row?.status === 'pass')) return { line: `GUARDS: pass (reused from ${path.basename(file)} at tree ${tree.slice(0, 12)}: ${rows.map(row => `${row!.id} ${row!.detail ?? 'pass'}`).join('; ')})` };
}
fs.rmSync(out, { force: true });
const pg = bin(cwd, 'gstack-pregate', ['--stage', 'guards', '--allow-repo-commands', '--out', out, ...(base ? ['--base', base] : [])], 3_600_000);
const text = pg.stdout + pg.stderr;
const verdict = /^PREGATE: (.+?) tree=/m.exec(text)?.[1] ?? `unreadable (exit ${pg.status})`;
let detail: string | undefined;
try { detail = (JSON.parse(fs.readFileSync(out, 'utf8')).checks as { id: string; detail?: string }[]).map(c => `${c.id} ${c.detail ?? ''}`.trim()).join('; '); } catch { /* no record: the verdict line says why */ }
const line = `GUARDS: ${verdict}${detail ? ` (${detail})` : ''}`;
if (pg.status === 0 && /^(pass|warn)/.test(verdict)) return { line };
const fix = /^gstack-pregate: (?:regen|guards): .*$/m.exec(pg.stderr)?.[0] ?? firstLine(pg.stderr || pg.stdout);
return { line, stop: `the pre-push guards did not pass (${fix}): fix it, commit, then rerun push` };
}
export function push(argv: readonly string[], cwd: string): Report {
const { flag, has } = flagReader(argv);
const r = new Report();
@@ -496,6 +525,9 @@ export function push(argv: readonly string[], cwd: string): Report {
r.add(`SECRETS: ${verdict} (early push)`);
if (scan.status !== 0 || !/^(pass|warn)/.test(verdict)) return r.stop(`the secrets scan did not pass before the early push (${firstLine(scan.stderr) || verdict}): remove the finding from the commits, then rerun push --early`);
}
const guards = prepushGuards(cwd, flag('--base'));
r.add(guards.line);
if (guards.stop) return r.stop(guards.stop);
const local = git(cwd, ['rev-parse', 'HEAD']).stdout.trim();
const remote = git(cwd, ['ls-remote', '--heads', 'origin', `refs/heads/${branch}`], 120_000);
if (remote.status !== 0) return r.stop(`cannot verify the remote branch (${firstLine(remote.stderr)}): restore access before pushing`);