mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-26 18:04:31 +01:00
Merge remote-tracking branch 'origin/main' into gsta258-l5-no-stop
This commit is contained in:
commit
ca43af4284
144 files changed
+5442
-373
No files matched your search
@@ -867,6 +867,51 @@ describe.skipIf(!HERMETIC)('aside-render: renderWithBrowse — daemon CLI contra
|
||||
expect(r.evals[0]).toBe('Fake Title');
|
||||
});
|
||||
|
||||
// Value: protects=a lazy Capy install (Chromium skipped until first use) renders on the first call: Playwright's missing-browser launch
|
||||
// error runs the checkout's gstack-browser-ensure once and retries newtab; fails_when=the render stops on "browse newtab failed: [browse]
|
||||
// Starting server..." with the cause hidden; why_new=GST-1204 (gbrain-evals#317: gstack-pr-shots on a Capy machine); seam=bin/gstack-browser-ensure
|
||||
const MISSING = "echo '[browse] Starting server...' >&2; echo '\u2554\u2550 Looks like Playwright was just installed or updated. \u2557' >&2; echo \"launch: Executable doesn't exist at /x/chrome-headless-shell\" >&2; exit 1";
|
||||
const lazyCheckout = (ensureBody: string, installedNewtab = ''): { browse: string; ensureLog: string; marker: string } => {
|
||||
const root = fs.mkdtempSync(path.join(tmp, 'lazy-'));
|
||||
const dist = path.join(root, 'browse', 'dist');
|
||||
fs.mkdirSync(dist, { recursive: true });
|
||||
fs.mkdirSync(path.join(root, 'bin'));
|
||||
const ensureLog = path.join(root, 'ensure.log');
|
||||
const marker = path.join(root, 'chromium');
|
||||
writeExecutable(path.join(root, 'bin', 'gstack-browser-ensure'), 'printf "%s\\n" "$*" >> ' + JSON.stringify(ensureLog) + '\n' + ensureBody.replace('MARKER', JSON.stringify(marker)) + '\n');
|
||||
fs.rmSync(log, { force: true });
|
||||
const browse = writeFakeBrowse(dist, log, { newtab: 'if [ ! -f ' + JSON.stringify(marker) + ' ]; then ' + MISSING + '; fi; ' + installedNewtab + ' echo \'{"tabId":7}\'' });
|
||||
return { browse, ensureLog, marker };
|
||||
};
|
||||
|
||||
test('a missing Playwright Chromium runs gstack-browser-ensure once, then the render proceeds', async () => {
|
||||
const { browse, ensureLog } = lazyCheckout(": > MARKER; echo 'BROWSER_OK playwright 140.0'");
|
||||
const r = await renderWithBrowse({ file: doc, steps: [{ kind: 'eval', expression: 'document.title' }] }, browse);
|
||||
expectOk(r);
|
||||
expect(readLines(ensureLog)).toEqual(['--quiet']);
|
||||
expect(readLines(log).filter((l) => l === 'newtab --json').length).toBe(2);
|
||||
expect(r.stdout).toContain('newtab: Chromium is not installed');
|
||||
});
|
||||
|
||||
// Value: protects=a Chromium download longer than the render budget leaves the retried newtab its own time; fails_when=the retry runs on
|
||||
// the 1 s floor and the first render on a fresh machine times out; why_new=GST-1204 review (outside voice + adversarial P2); seam=deadline
|
||||
test('the install time does not count against the render deadline', async () => {
|
||||
const { browse, ensureLog } = lazyCheckout("sleep 3; : > MARKER", 'sleep 1.5;');
|
||||
const r = await renderWithBrowse({ file: doc, timeoutMs: 2_500, steps: [{ kind: 'eval', expression: 'document.title' }] }, browse);
|
||||
expectOk(r);
|
||||
expect(readLines(ensureLog)).toEqual(['--quiet']);
|
||||
}, 20_000);
|
||||
|
||||
test('when gstack-browser-ensure cannot install Chromium, the error names the launch failure, not the daemon banner', async () => {
|
||||
const { browse, ensureLog } = lazyCheckout("echo 'BROWSER_UNAVAILABLE offline'; exit 1");
|
||||
const r = await renderWithBrowse({ file: doc, steps: [] }, browse);
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.error).toContain("browse newtab failed: launch: Executable doesn't exist");
|
||||
expect(r.error).toContain('BROWSER_UNAVAILABLE offline');
|
||||
expect(readLines(ensureLog).length).toBe(1);
|
||||
expect(readLines(log).filter((l) => l === 'newtab --json').length).toBe(1);
|
||||
});
|
||||
|
||||
test('any other newtab failure is not retried', async () => {
|
||||
const r = await renderWithBrowse({ file: doc, steps: [] }, fake({ newtab: `echo 'browser launch failed: no display' >&2; exit 1` }));
|
||||
expect(r.ok).toBe(false);
|
||||
|
||||
@@ -16,6 +16,7 @@ import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { ROOT, SMALL_PLAN, autoplan, env, journal, readRun } from './helpers/autoplan-run-fixture';
|
||||
import { capyRunner } from './helpers/autoplan-capy';
|
||||
import { captureDraft } from '../lib/autoplan-lean';
|
||||
|
||||
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'ap-lean-'));
|
||||
afterAll(() => fs.rmSync(TMP, { recursive: true, force: true }));
|
||||
@@ -488,3 +489,42 @@ describe('draft capture edges', () => {
|
||||
expect(prompt.indexOf('IGNORE THE PLAN')).toBeLessThan(prompt.indexOf(`\n${open[1]}\n`, open.index + 1));
|
||||
});
|
||||
});
|
||||
describe('draft capture base on a PR-branch clone (GST-1241)', () => {
|
||||
/** A clone of `feature`, its draft committed and pushed, whose origin/HEAD names `head` while origin's own HEAD stays main: a Capy machine started on a PR branch names that branch. */
|
||||
const clone = (name: string, head: string) => {
|
||||
const src = repo(name, false);
|
||||
fs.writeFileSync(path.join(src, 'lib', 'worker.ts'), 'export const retry = (n: number) => Math.min(30_000, 500 * 2 ** n);\n');
|
||||
git(src, 'commit', '-q', '-am', 'draft backoff');
|
||||
const bare = path.join(TMP, name, 'origin.git');
|
||||
git(TMP, 'clone', '-q', '--bare', src, bare);
|
||||
git(bare, 'symbolic-ref', 'HEAD', 'refs/heads/main');
|
||||
const cwd = path.join(TMP, name, 'clone');
|
||||
git(TMP, 'clone', '-q', '-b', 'feature', bare, cwd);
|
||||
git(cwd, 'remote', 'set-head', 'origin', head);
|
||||
expect(git(cwd, 'rev-parse', '--abbrev-ref', 'origin/HEAD').trim()).toBe(`origin/${head}`);
|
||||
return cwd;
|
||||
};
|
||||
const capture = (name: string, cwd: string) => {
|
||||
const dir = path.join(TMP, name, 'snap');
|
||||
const out = path.join(TMP, name, 'run');
|
||||
fs.mkdirSync(dir);
|
||||
fs.mkdirSync(out);
|
||||
const draft = captureDraft(cwd, dir, out);
|
||||
return { draft, diff: draft.sha256 ? fs.readFileSync(path.join(dir, 'draft.diff'), 'utf8') : '' };
|
||||
};
|
||||
|
||||
test('origin/HEAD naming the PR branch still captures the committed draft against main', () => {
|
||||
const { draft, diff } = capture('pr-head', clone('pr-head', 'feature'));
|
||||
expect(draft.none).toBeUndefined();
|
||||
expect(draft.base).toBe('origin/main');
|
||||
expect(draft.files).toEqual(['lib/worker.ts']);
|
||||
expect(diff).toContain('+export const retry = (n: number) => Math.min(30_000, 500 * 2 ** n);');
|
||||
});
|
||||
|
||||
test('control: origin/HEAD naming main captures the same draft', () => {
|
||||
const main = capture('main-head', clone('main-head', 'main'));
|
||||
expect(main.draft.base).toBe('origin/main');
|
||||
expect(main.draft.files).toEqual(['lib/worker.ts']);
|
||||
expect(main.diff).toContain('+export const retry = (n: number) => Math.min(30_000, 500 * 2 ** n);');
|
||||
});
|
||||
});
|
||||
@@ -138,4 +138,33 @@ describe('one Bun resolution contract, two twins', () => {
|
||||
expect(viaLaunch.dir).toBe(launch);
|
||||
expect(viaLaunch.env.PATH?.split(path.delimiter)[0]).toBe(launch);
|
||||
});
|
||||
|
||||
// GST-1233: a docs child's install replaced the shared verdict and republished the shared launch
|
||||
// directory with its own Bun; the finish pregate admits from ship's own record and launches ship's Bun.
|
||||
test("launchRuntime admits /ship from its own record when another workflow's install replaced the shared verdict, and never launches that install's Bun", () => {
|
||||
const l = layout({ storeVersions: ['1.4.4'] });
|
||||
const { installVerdictPath } = require('../lib/install-verdict') as typeof import('../lib/install-verdict');
|
||||
const checkout = fs.realpathSync(ROOT);
|
||||
const file = installVerdictPath(checkout, l.state, null);
|
||||
const head = spawnSync('git', ['-C', ROOT, 'rev-parse', 'HEAD'], { encoding: 'utf8', timeout: 10_000 }).stdout.trim();
|
||||
const childBun = path.join(bunStore(l.state), '1.4.4/bun');
|
||||
const launch = file.replace(/\.json$/, '.launch');
|
||||
fs.mkdirSync(launch, { recursive: true });
|
||||
fs.symlinkSync(childBun, path.join(launch, 'bun'));
|
||||
const record = { schema_version: 2, checkout, project: '', head, pins_planning_only: false, ok: true, min_revision: '', launch_path: launch, time: '' };
|
||||
fs.writeFileSync(file, JSON.stringify({ ...record, for: 'document-release', required: ['claude'], trailer: 'gstack: ok for=document-release', bun_path: fs.realpathSync(childBun), bun_version: '1.4.4' }));
|
||||
const refused = launchRuntime(ROOT, l.env);
|
||||
expect(refused.refusal).toMatchObject({ code: 'INSTALL_UNVERIFIED' });
|
||||
expect(refused.refusal?.detail).toContain('certified for=document-release');
|
||||
const own = file.replace(/\.json$/, '.for/ship.json');
|
||||
fs.mkdirSync(path.dirname(own), { recursive: true });
|
||||
fs.writeFileSync(own, JSON.stringify({ ...record, for: 'ship', required: ['claude', 'codex', 'patch'], trailer: 'gstack: ok for=ship', bun_path: REAL_BUN, bun_version: Bun.version }));
|
||||
const r = launchRuntime(ROOT, l.env);
|
||||
expect(r.refusal).toBeNull();
|
||||
expect(r.verdict).toBe('ok');
|
||||
expect(r.label).toBe(`bun ${Bun.version} at ${REAL_BUN} (recorded by the install verdict)`);
|
||||
expect(r.dir).toBe(path.dirname(REAL_BUN));
|
||||
fs.writeFileSync(file, JSON.stringify({ ...JSON.parse(fs.readFileSync(file, 'utf8')), ok: false, trailer: 'gstack: fail setup — ./setup failed' }));
|
||||
expect(launchRuntime(ROOT, l.env).refusal?.detail).toBe('install verdict: the install verdict says: gstack: fail setup — ./setup failed');
|
||||
});
|
||||
});
|
||||
@@ -53,14 +53,18 @@ const UPGRADE_DEPS = [
|
||||
'bin/gstack-upgrade', 'bin/gstack-bun-version.sh', 'bin/gstack-paths', 'bin/gstack-state-root.sh',
|
||||
'bin/gstack-egress-lib.sh', 'bin/gstack-egress-receipt', 'lib/egress-receipt.ts', 'lib/state-root.ts',
|
||||
'bin/gstack-lease', 'bin/gstack-harness-pid.sh',
|
||||
// Sourced by gstack-upgrade: without gstack-config in the fixture it resolves main unless GSTACK_UPDATE_CHANNEL says stable.
|
||||
'bin/gstack-update-channel.sh',
|
||||
];
|
||||
|
||||
/**
|
||||
* cloneAt 'A' (default): the clone sits at A (1.0.0), below B's minimum 1.0.1.
|
||||
* cloneAt 'B': the clone sits at B, AT the minimum, and the remote moves on to
|
||||
* C (1.0.2, minimum unchanged): behind origin but not below the floor.
|
||||
* next: the remote moves on to C for a clone at A too. stable: origin's stable
|
||||
* branch (the release, docs/releases.md) at that commit.
|
||||
*/
|
||||
function fixture(opts: { minWrapper?: number; cloneAt?: 'A' | 'B' } = {}) {
|
||||
function fixture(opts: { minWrapper?: number; cloneAt?: 'A' | 'B'; next?: boolean; stable?: 'A' | 'B' | 'C' } = {}) {
|
||||
const host = capyHost({ systemBun: '1.4.2' });
|
||||
hosts.push(host);
|
||||
const git = (args: string[], cwd: string) => {
|
||||
@@ -94,13 +98,14 @@ function fixture(opts: { minWrapper?: number; cloneAt?: 'A' | 'B' } = {}) {
|
||||
const b = git(['rev-parse', 'HEAD'], seed);
|
||||
git(['push', '-q', bare, 'main'], seed);
|
||||
let c = '';
|
||||
if (opts.cloneAt === 'B') {
|
||||
git(['clone', '-q', '--single-branch', '--depth', '1', `file://${bare}`, root], host.base);
|
||||
if (opts.cloneAt === 'B' || opts.next) {
|
||||
if (opts.cloneAt === 'B') git(['clone', '-q', '--single-branch', '--depth', '1', `file://${bare}`, root], host.base);
|
||||
write(path.join(seed, 'VERSION'), '1.0.2\n');
|
||||
git(['commit', '-qam', 'C'], seed);
|
||||
c = git(['rev-parse', 'HEAD'], seed);
|
||||
git(['push', '-q', bare, 'main'], seed);
|
||||
}
|
||||
if (opts.stable) git(['push', '-q', bare, `${{ A: a, B: b, C: c }[opts.stable]}:refs/heads/stable`], seed);
|
||||
const env = { ...host.env, GSTACK_CAPY_ROOT: root, GSTACK_CAPY_REPO: `file://${bare}`, WRAP_LOG: log, WRAP_FAIL_ONCE: path.join(host.base, 'fail-once') };
|
||||
const run = (args: string[] = [], extra: Record<string, string> = {}) => {
|
||||
const r = spawnSync('bash', [BOOT, ...args], { cwd: host.home, encoding: 'utf8', env: { ...env, ...extra }, timeout: 120_000 });
|
||||
@@ -140,13 +145,13 @@ describe('capy skill bootstrapper (capy/skill/gstack/scripts/install.sh)', () =>
|
||||
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.b);
|
||||
expect(f.git(['rev-parse', '--is-shallow-repository'])).toBe('true');
|
||||
expect(install.last).toBe('gstack: ok 1.0.1 for=autoplan');
|
||||
expect(f.calls()).toEqual([`installer --root ${f.root} --for autoplan lock=1 rev=3 min=1.0.1 from=1.0.0`]);
|
||||
expect(f.calls()).toEqual([`installer --root ${f.root} --for autoplan lock=1 rev=4 min=1.0.1 from=1.0.0`]);
|
||||
|
||||
const next = f.run(['--check', '--for', 'autoplan']);
|
||||
expect(next.status, next.stdout + next.stderr).toBe(0);
|
||||
expect(next.stdout).not.toContain('upgraded');
|
||||
expect(next.last).toBe('gstack: ok 1.0.1 for=autoplan');
|
||||
expect(f.calls().at(-1)).toBe(`installer --check --root ${f.root} --for autoplan lock= rev=3 min=1.0.1 from=`);
|
||||
expect(f.calls().at(-1)).toBe(`installer --check --root ${f.root} --for autoplan lock= rev=4 min=1.0.1 from=`);
|
||||
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.b);
|
||||
});
|
||||
|
||||
@@ -263,7 +268,7 @@ describe('capy skill: always current when online (the minimum is the floor, not
|
||||
expect(r.stdout).toMatch(/^SELF_UPGRADE: done 1\.0\.1 -> 1\.0\.2$/m);
|
||||
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.c);
|
||||
expect(r.last).toBe('gstack: ok 1.0.2 for=autoplan');
|
||||
expect(f.calls()).toEqual([`installer --root ${f.root} --for autoplan lock=1 rev=3 min=1.0.1 from=1.0.1`]);
|
||||
expect(f.calls()).toEqual([`installer --root ${f.root} --for autoplan lock=1 rev=4 min=1.0.1 from=1.0.1`]);
|
||||
expect(fs.existsSync(path.join(f.root, '.git/gstack-upgrade.pending'))).toBe(false);
|
||||
|
||||
const next = f.run(['--for', 'autoplan']);
|
||||
@@ -271,7 +276,7 @@ describe('capy skill: always current when online (the minimum is the floor, not
|
||||
expect(next.stdout).toMatch(/^SELF_UPGRADE: none \(current\)$/m);
|
||||
expect(next.stdout).not.toContain('SELF_UPGRADE: done');
|
||||
expect(next.last).toBe('gstack: ok 1.0.2 for=autoplan');
|
||||
expect(f.calls().at(-1)).toBe(`installer --root ${f.root} --for autoplan lock=1 rev=3 min=1.0.1 from=`);
|
||||
expect(f.calls().at(-1)).toBe(`installer --root ${f.root} --for autoplan lock=1 rev=4 min=1.0.1 from=`);
|
||||
});
|
||||
|
||||
test('--check mode never moves a behind checkout: it names the gap and the fast-forwarding command, then certifies the installed revision', () => {
|
||||
@@ -282,7 +287,7 @@ describe('capy skill: always current when online (the minimum is the floor, not
|
||||
expect(r.stdout).not.toContain('SELF_UPGRADE');
|
||||
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.b);
|
||||
expect(r.last).toBe('gstack: ok 1.0.1 for=autoplan');
|
||||
expect(f.calls()).toEqual([`installer --check --root ${f.root} --for autoplan lock= rev=3 min=1.0.1 from=`]);
|
||||
expect(f.calls()).toEqual([`installer --check --root ${f.root} --for autoplan lock= rev=4 min=1.0.1 from=`]);
|
||||
});
|
||||
|
||||
test('a dirty behind checkout is skipped with gstack-upgrade\'s reason and still ends ok: above the floor, the trailer is the doctor\'s', () => {
|
||||
@@ -295,7 +300,7 @@ describe('capy skill: always current when online (the minimum is the floor, not
|
||||
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.b);
|
||||
expect(fs.readFileSync(path.join(f.root, 'README.md'), 'utf8')).toBe('local edit\n');
|
||||
expect(r.last).toBe('gstack: ok 1.0.1 for=autoplan');
|
||||
expect(f.calls()).toEqual([`installer --root ${f.root} --for autoplan lock=1 rev=3 min=1.0.1 from=`]);
|
||||
expect(f.calls()).toEqual([`installer --root ${f.root} --for autoplan lock=1 rev=4 min=1.0.1 from=`]);
|
||||
});
|
||||
|
||||
test('GSTACK_CAPY_SELF_UPGRADE=off and GSTACK_CAPY_AUTO_UPGRADE=0 each disable the fast-forward by name and leave HEAD where it is', () => {
|
||||
@@ -315,6 +320,53 @@ describe('capy skill: always current when online (the minimum is the floor, not
|
||||
// Plan A9: the `latest:` trailer note comes only from origin's VERSION the
|
||||
// bootstrapper read in this run; a FETCH_HEAD left by an earlier run never
|
||||
// reaches the installer.
|
||||
describe('capy skill bootstrapper: the update channel (wrapper 4, docs/releases.md#channels)', () => {
|
||||
// Value: protects=an install that follows stable (GSTACK_UPDATE_CHANNEL=stable, or team mode through bin/gstack-update-channel.sh) is cloned at
|
||||
// origin's stable branch, not main, and stays there through the checkout half's self-upgrade; GSTACK_UPDATE_CHANNEL=main and a remote with no stable
|
||||
// branch (before the first release) clone main; fails_when=a fresh team install lands on unreleased main, the override cannot pick main, or a missing
|
||||
// stable branch fails the install; why_new=the clone test covers the default branch only; seam=GSTACK_UPDATE_CHANNEL instead of gstack-config's
|
||||
// team_mode; no_claim=GitHub's real stable branch
|
||||
test('a fresh clone follows stable when origin has it; GSTACK_UPDATE_CHANNEL=main and a missing stable branch clone main', () => {
|
||||
const f = fixture({ cloneAt: 'B', stable: 'B' });
|
||||
fs.rmSync(f.root, { recursive: true, force: true });
|
||||
const stable = f.run(['--for', 'autoplan'], { GSTACK_UPDATE_CHANNEL: 'stable' });
|
||||
expect(stable.status, stable.stdout + stable.stderr).toBe(0);
|
||||
expect(stable.stdout).toContain('gstack-capy-skill: channel stable 1.0.1 (GSTACK_UPDATE_CHANNEL=main follows every merge)');
|
||||
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.b);
|
||||
expect(stable.last).toBe('gstack: ok 1.0.1 for=autoplan');
|
||||
|
||||
fs.rmSync(f.root, { recursive: true, force: true });
|
||||
const main = f.run(['--for', 'autoplan'], { GSTACK_UPDATE_CHANNEL: 'main' });
|
||||
expect(main.status, main.stdout + main.stderr).toBe(0);
|
||||
expect(main.stdout).not.toContain('channel stable');
|
||||
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.c);
|
||||
|
||||
spawnSync('git', ['--git-dir', f.bare, 'update-ref', '-d', 'refs/heads/stable'], { env: f.host.env, timeout: 30_000 });
|
||||
fs.rmSync(f.root, { recursive: true, force: true });
|
||||
const bootstrap = f.run(['--for', 'autoplan'], { GSTACK_UPDATE_CHANNEL: 'stable' });
|
||||
expect(bootstrap.status, bootstrap.stdout + bootstrap.stderr).toBe(0);
|
||||
expect(bootstrap.stdout).toContain('channel stable, but origin has no stable branch yet (or the fetch failed); following main');
|
||||
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.c);
|
||||
});
|
||||
|
||||
// Value: protects=the bootstrapper's floor fast-forward of a checkout below the supported minimum goes to stable on the stable channel when stable
|
||||
// meets the minimum, and to main when stable is itself below it; fails_when=a stable install is pushed past the release to main, or left below the
|
||||
// floor because stable is too old; why_new=the floor tests cover main only; seam=GSTACK_UPDATE_CHANNEL; no_claim=GitHub's real stable branch
|
||||
test('below the floor: the fast-forward goes to stable when stable meets the minimum, else to main', () => {
|
||||
const atRelease = fixture({ next: true, stable: 'B' });
|
||||
const r = atRelease.run(['--for', 'autoplan'], { GSTACK_UPDATE_CHANNEL: 'stable' });
|
||||
expect(r.status, r.stdout + r.stderr).toBe(0);
|
||||
expect(r.stdout).toContain('gstack-capy-skill: upgraded 1.0.0 -> 1.0.1');
|
||||
expect(atRelease.git(['rev-parse', 'HEAD'])).toBe(atRelease.b);
|
||||
|
||||
const old = fixture({ next: true, stable: 'A' });
|
||||
const o = old.run(['--for', 'autoplan'], { GSTACK_UPDATE_CHANNEL: 'stable' });
|
||||
expect(o.status, o.stdout + o.stderr).toBe(0);
|
||||
expect(o.stdout).toContain('gstack-capy-skill: channel stable is at 1.0.0, below the supported minimum 1.0.1; following main');
|
||||
expect(old.git(['rev-parse', 'HEAD'])).toBe(old.c);
|
||||
});
|
||||
});
|
||||
|
||||
describe('capy skill bootstrapper: GSTACK_CAPY_REMOTE_VERSION', () => {
|
||||
test('a fresh fetch exports origin\'s VERSION; a failed fetch exports nothing even with a stale FETCH_HEAD', () => {
|
||||
const f = fixture({ cloneAt: 'B' });
|
||||
@@ -587,9 +639,11 @@ describe('capy skill: factory.md, the auto-loaded "how we work" page', () => {
|
||||
return [...new Set(problems)];
|
||||
}
|
||||
|
||||
test('it fits the 3,300-byte budget, and every citation, heading and skill it names resolves', () => {
|
||||
test('it fits the 3,450-byte budget, and every citation, heading and skill it names resolves', () => {
|
||||
const text = fs.readFileSync(FACTORY, 'utf8');
|
||||
expect(Buffer.byteLength(text)).toBeLessThanOrEqual(3300);
|
||||
// 3,300 since #3634; raised to 3,450 (the page's new size, rounded up to the next 25 bytes) for point 12's
|
||||
// R68 clause (Garry, 2026-11-03: crew threads ask their Captain for new threads). Raise it only by what a rule needs.
|
||||
expect(Buffer.byteLength(text)).toBeLessThanOrEqual(3450);
|
||||
expect(text).toMatch(/^# How we work/);
|
||||
expect(citationProblems(text)).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { afterAll, describe, expect, test } from 'bun:test';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { bunIsolationArgs } from '../lib/bun-isolation';
|
||||
|
||||
const SCRIPT = path.resolve(import.meta.dir, '..', 'scripts/check-conflict-markers.ts');
|
||||
const OPEN = '<'.repeat(7), MID = '='.repeat(7), CLOSE = '>'.repeat(7);
|
||||
const dirs: string[] = [];
|
||||
afterAll(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
|
||||
|
||||
function repo(base: Record<string, string> = { 'README.md': 'base\n' }) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-markers-'));
|
||||
dirs.push(root);
|
||||
const git = (...args: string[]) => {
|
||||
const r = spawnSync('git', ['-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', '-c', 'user.email=test@example.com', '-c', 'user.name=test', ...args], { cwd: root, encoding: 'utf8', timeout: 30_000 });
|
||||
if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);
|
||||
return r.stdout;
|
||||
};
|
||||
git('init', '-q');
|
||||
git('symbolic-ref', 'HEAD', 'refs/heads/main');
|
||||
const write = (files: Record<string, string>) => { for (const [p, c] of Object.entries(files)) { fs.mkdirSync(path.dirname(path.join(root, p)), { recursive: true }); fs.writeFileSync(path.join(root, p), c); } };
|
||||
write(base);
|
||||
git('add', '-A');
|
||||
git('commit', '-q', '-m', 'base');
|
||||
git('checkout', '-q', '-b', 'feat');
|
||||
const change = (files: Record<string, string>) => { write(files); git('add', '-A'); git('commit', '-q', '-m', 'change'); };
|
||||
const run = (env: Record<string, string> = {}) => spawnSync('bun', [...bunIsolationArgs(), SCRIPT, '--base', 'main'], { cwd: root, encoding: 'utf8', timeout: 60_000, env: { ...process.env, ...env } });
|
||||
return { root, git, change, write, run };
|
||||
}
|
||||
|
||||
describe('check-conflict-markers (GST-1190: #3927 kept markers inside a template literal and its tests passed)', () => {
|
||||
// Value: protects=a merge that leaves conflict markers in a changed file is refused before the push, even where the
|
||||
// markers sit inside a string the parser accepts; fails_when=a marker line in a template literal passes, a markdown
|
||||
// code block that shows a marker is refused, or a git display setting hides a file; why_new=GSTA-234 #3927;
|
||||
// seam=a real git repository and the script
|
||||
test('a marker inside a template literal is refused', () => {
|
||||
const r = repo();
|
||||
r.change({ 'lib/prompt.ts': `export const PROMPT = \`\n${OPEN} HEAD\nkeep this\n${MID}\nor this\n${CLOSE} origin/main\n\`;\n` });
|
||||
const out = r.run();
|
||||
expect(out.status).toBe(1);
|
||||
expect(out.stdout).toContain(`CONFLICT_MARKER: lib/prompt.ts:2 ${OPEN}\n`);
|
||||
expect(out.stdout).toContain(`CONFLICT_MARKER: lib/prompt.ts:4 ${MID}\n`);
|
||||
expect(out.stdout).toContain(`CONFLICT_MARKER: lib/prompt.ts:6 ${CLOSE}\n`);
|
||||
});
|
||||
|
||||
test('a markdown code block that shows a marker is not refused; the same lines outside a fence, or in a bash fence, are', () => {
|
||||
const r = repo();
|
||||
const block = `${OPEN} HEAD\nours\n${MID}\ntheirs\n${CLOSE} main\n`;
|
||||
r.change({ 'docs/merging.md': `# Merging\n\nGit writes this:\n\n\`\`\`\n${block}\`\`\`\n\nA heading\n${MID}\n` });
|
||||
const fenced = r.run();
|
||||
expect([fenced.status, fenced.stdout]).toEqual([0, expect.stringContaining('CONFLICT_MARKERS: none')]);
|
||||
r.change({ 'docs/merging.md': `# Merging\n\n${block}` });
|
||||
const bare = r.run();
|
||||
expect(bare.status).toBe(1);
|
||||
expect(bare.stdout).toContain(`CONFLICT_MARKER: docs/merging.md:3 ${OPEN}`);
|
||||
expect(bare.stdout).toContain(`CONFLICT_MARKER: docs/merging.md:5 ${MID}`);
|
||||
r.change({ 'skill/sections/x.md': `# X\n\n\`\`\`bash\n${OPEN} HEAD\necho a\n${MID}\necho b\n${CLOSE} feat\n\`\`\`\n` });
|
||||
expect(r.run().stdout).toContain(`CONFLICT_MARKER: skill/sections/x.md:4 ${OPEN}`);
|
||||
});
|
||||
|
||||
test('only changed lines count; a fixture declares itself on a line of its own, a mention elsewhere does not exempt a file', () => {
|
||||
const r = repo({ 'old.txt': `${OPEN} kept on main\n` });
|
||||
r.change({ 'old.txt': `${OPEN} kept on main\nnew line\n`, 'test/fixtures/merge.txt': `# gstack-conflict-markers: fixture\n${OPEN} HEAD\n${CLOSE} main\n` });
|
||||
expect(r.run()).toMatchObject({ status: 0 });
|
||||
r.change({ 'cfg.json': `{"fix": "declare gstack-conflict-markers: fixture"}\n${OPEN} HEAD\n` });
|
||||
expect(r.run().stdout).toContain(`CONFLICT_MARKER: cfg.json:2 ${OPEN}`);
|
||||
});
|
||||
|
||||
test('the pushed commit is read, not only the working tree; untracked files are not; git display settings change nothing', () => {
|
||||
const r = repo();
|
||||
r.change({ 'src/a b/ünï.ts': `const s = \`\n${CLOSE} theirs\n\`;\n` });
|
||||
for (const env of <Record<string, string>[]>[{}, { GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'diff.noprefix', GIT_CONFIG_VALUE_0: 'true' }, { GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'diff.mnemonicPrefix', GIT_CONFIG_VALUE_0: 'true' }]) {
|
||||
expect(r.run(env).stdout, JSON.stringify(env)).toContain(`CONFLICT_MARKER: src/a b/ünï.ts:2 ${CLOSE}`);
|
||||
}
|
||||
r.write({ 'src/a b/ünï.ts': 'const s = 1;\n', 'merge.ts.orig': `${OPEN} HEAD\n` });
|
||||
const repaired = r.run();
|
||||
expect([repaired.status, repaired.stdout]).toEqual([1, expect.stringContaining(`CONFLICT_MARKER: src/a b/ünï.ts:2 ${CLOSE}`)]);
|
||||
expect(repaired.stdout).not.toContain('merge.ts.orig');
|
||||
r.write({ 'README.md': `base\n${MID}\n` });
|
||||
r.git('add', '-A'); r.git('commit', '-q', '-m', 'repair');
|
||||
r.write({ 'lib/wip.ts': `${CLOSE} uncommitted\n` }); r.git('add', 'lib/wip.ts'); r.git('commit', '-q', '-m', 'wip'); r.write({ 'lib/wip.ts': `ok\n${OPEN} x\n` });
|
||||
expect(r.run().stdout).toContain(`CONFLICT_MARKER: lib/wip.ts:2 ${OPEN} (working tree)`);
|
||||
});
|
||||
});
|
||||
Vendored
+1
-1
@@ -67,7 +67,7 @@
|
||||
"spec": 9136,
|
||||
"sync-gbrain": 9749,
|
||||
"test-audit": 4622,
|
||||
"ubicloud": 3594,
|
||||
"ubicloud": 3971,
|
||||
"unfreeze": 409,
|
||||
"verify": 2896,
|
||||
"write-skill": 2264
|
||||
|
||||
+2
-2
@@ -325,8 +325,8 @@ repository-landing asks, including on Apple repos.
|
||||
|
||||
## Step 1: Pre-flight
|
||||
|
||||
Run `~/.gemini/antigravity-cli/skills/gstack/bin/gstack-ship-preflight --base <base>`: Steps 1–3's mechanics in one call;
|
||||
act on every `STOP:` and `NEXT:` line.
|
||||
Run `~/.gemini/antigravity-cli/skills/gstack/bin/gstack-ship-preflight --base <base> --run <SESSION_ID>`: Steps 1–3 at once;
|
||||
act on each `STOP:` and `NEXT:` line.
|
||||
|
||||
1. It saves the current branch as `<branch-name>`. If on the base branch or the repo's default branch, **abort**: "You're on the base branch. Ship from a feature branch."
|
||||
2. Uncommitted changes are always included; do not ask (`STATUS:`).
|
||||
|
||||
+2
-2
@@ -324,8 +324,8 @@ repository-landing asks, including on Apple repos.
|
||||
|
||||
## Step 1: Pre-flight
|
||||
|
||||
Run `~/.claude/skills/gstack/bin/gstack-ship-preflight --base <base>`: Steps 1–3's mechanics in one call;
|
||||
act on every `STOP:` and `NEXT:` line.
|
||||
Run `~/.claude/skills/gstack/bin/gstack-ship-preflight --base <base> --run <SESSION_ID>`: Steps 1–3 at once;
|
||||
act on each `STOP:` and `NEXT:` line.
|
||||
|
||||
1. It saves the current branch as `<branch-name>`. If on the base branch or the repo's default branch, **abort**: "You're on the base branch. Ship from a feature branch."
|
||||
2. Uncommitted changes are always included; do not ask (`STATUS:`).
|
||||
|
||||
+2
-2
@@ -323,8 +323,8 @@ repository-landing asks, including on Apple repos.
|
||||
|
||||
## Step 1: Pre-flight
|
||||
|
||||
Run `$GSTACK_ROOT/bin/gstack-ship-preflight --base <base>`: Steps 1–3's mechanics in one call;
|
||||
act on every `STOP:` and `NEXT:` line.
|
||||
Run `$GSTACK_ROOT/bin/gstack-ship-preflight --base <base> --run <SESSION_ID>`: Steps 1–3 at once;
|
||||
act on each `STOP:` and `NEXT:` line.
|
||||
|
||||
1. It saves the current branch as `<branch-name>`. If on the base branch or the repo's default branch, **abort**: "You're on the base branch. Ship from a feature branch."
|
||||
2. Uncommitted changes are always included; do not ask (`STATUS:`).
|
||||
|
||||
+2
-2
@@ -325,8 +325,8 @@ repository-landing asks, including on Apple repos.
|
||||
|
||||
## Step 1: Pre-flight
|
||||
|
||||
Run `$GSTACK_ROOT/bin/gstack-ship-preflight --base <base>`: Steps 1–3's mechanics in one call;
|
||||
act on every `STOP:` and `NEXT:` line.
|
||||
Run `$GSTACK_ROOT/bin/gstack-ship-preflight --base <base> --run <SESSION_ID>`: Steps 1–3 at once;
|
||||
act on each `STOP:` and `NEXT:` line.
|
||||
|
||||
1. It saves the current branch as `<branch-name>`. If on the base branch or the repo's default branch, **abort**: "You're on the base branch. Ship from a feature branch."
|
||||
2. Uncommitted changes are always included; do not ask (`STATUS:`).
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# Codex reply shapes from #3925
|
||||
|
||||
Issue #3925 reports two Codex consult replies that the outside-review helper
|
||||
summarised as `VERDICT: clean / FINDINGS: none`. The issue describes them but
|
||||
does not include them, so these files are synthesized from what it quotes:
|
||||
|
||||
- `cant-verify.txt`: a reply whose last line is `Verdict: Can't verify (...)`.
|
||||
The reviewer says it could not finish, so it is not `clean`.
|
||||
- `nonblocking-numbered.txt`: one numbered finding labeled `Nonblocking`, no
|
||||
P0-P3 tag, then `Verdict: ready` and `END OF REPORT: 1 findings (0 blocking)`.
|
||||
The verdict is `clean`, but `FINDINGS:` must not say `none`.
|
||||
- `ready-clean.txt`: the negative control, a real clean reply with
|
||||
`Verdict: ready` and no findings.
|
||||
|
||||
`test/outside-review-unparsed-severity.test.ts` holds the expected verdicts.
|
||||
@@ -0,0 +1,5 @@
|
||||
I read the diff for the files I could open. `lib/sync.ts` was excluded from
|
||||
the review scope, and the four required suites could not start in the sandbox,
|
||||
so I could not run them.
|
||||
|
||||
Verdict: Can't verify (one changed file excluded and four required suites blocked)
|
||||
@@ -0,0 +1,6 @@
|
||||
I read the diff and ran `bun test test/retry.test.ts`.
|
||||
|
||||
1. **Nonblocking — The retry log line repeats the attempt count.** `lib/retry.ts:41`
|
||||
|
||||
Verdict: ready
|
||||
END OF REPORT: 1 findings (0 blocking)
|
||||
@@ -0,0 +1,5 @@
|
||||
I read the diff, ran `bun test test/retry.test.ts`, and checked every caller of
|
||||
`retry()`. The cap is enforced and the tests cover the boundary.
|
||||
|
||||
Verdict: ready
|
||||
END OF REPORT: 0 findings (0 blocking)
|
||||
Vendored
+5
-5
@@ -22,10 +22,10 @@ const row=(type,content,stop)=>JSON.stringify({type,sessionId:sid,cwd,message:{r
|
||||
const text=s=>[{type:'text',text:s}];
|
||||
const append=(type,content,stop)=>fs.appendFileSync(file,row(type,content,stop));
|
||||
const rule='─'.repeat(120);
|
||||
const frame=(s,history='',top=rule,bottom=rule)=>{
|
||||
const frame=(s,history='',top=rule,bottom=rule,tail='')=>{
|
||||
const inputRows=1+(s.match(/\r\n/g)||[]).length;
|
||||
const topRow=(process.stdout.rows||40)-inputRows-2;
|
||||
process.stdout.write('\x1b[2J\x1b[H'+history+'\x1b['+topRow+';1H'+top+'\r\n❯ '+s+'\r\n'+bottom+'\r\npaste again to expand');
|
||||
process.stdout.write('\x1b[2J\x1b[H'+history+'\x1b['+topRow+';1H'+top+'\r\n❯ '+s+'\r\n'+bottom+'\r\npaste again to expand'+tail);
|
||||
};
|
||||
let input='',seed='',submitted=false;
|
||||
process.stdin.setRawMode(true);process.stdin.resume();
|
||||
@@ -40,12 +40,12 @@ else if(scenario==='startup-ci-placeholder')frame(process.env.CI==='true'&&proce
|
||||
else if(scenario==='startup-ci-typed-hint')frame(hint);
|
||||
else if(scenario==='startup-placeholder-cursor')frame('\x1b[7mT\x1b[27m\x1b[2m'+hint.slice(1)+'\x1b[22m');
|
||||
else if(scenario==='startup-placeholder-unicode')frame('\x1b[2mTry "refactor src/設定.ts"\x1b[22m');
|
||||
else if(['startup-placeholder','startup-prior-conversation','startup-missing-styles','startup-waiting','startup-prose-question','startup-permission','startup-fresh-waiting'].includes(scenario))frame('\x1b[2m'+hint+'\x1b[22m');
|
||||
else if(['startup-placeholder','startup-prior-conversation','startup-missing-styles','startup-waiting','startup-prose-question','startup-permission','startup-fresh-waiting'].includes(scenario))frame('\x1b[2m'+hint+'\x1b[22m','',rule,rule,
|
||||
scenario==='startup-prose-question'?'Which option do you prefer?\r\nA) Full review (recommended)\r\nB) Skip review\r\n'
|
||||
:scenario==='startup-permission'?'Bash command run checks requires permission\r\n':'');
|
||||
else if(scenario==='startup-typed-hint')frame(hint);
|
||||
else if(scenario==='startup-partial-dim')frame('\x1b[2mTry \x1b[22m"refactor <filepath>"');
|
||||
else frame('');
|
||||
if(scenario==='startup-prose-question')process.stdout.write('Which option do you prefer?\r\nA) Full review (recommended)\r\nB) Skip review\r\n');
|
||||
if(scenario==='startup-permission')process.stdout.write('Bash command run checks requires permission\r\n');
|
||||
process.stdin.on('data',chunk=>{
|
||||
input+=chunk.toString();
|
||||
if(input.startsWith('\x1b[200~')&&input.endsWith('\x1b[201~')){
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"sha":"fb21c0b80e98685ca8c5192aeaa217cfffe9fbdaa8890455c97e01be1b044a53","replay":"GSTA-258-C+GST-940"}
|
||||
{"sha":"6688963750c14f03cdbb249dcaa27ebd9e9c2c62170f4e142ec8ded28af010a1","replay":"GSTA-258-L7"}
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"sha":"e2a4d2aabe02e28140b3b8f3d5288bf0eac1872b5cb375eb011e4f0cde2ad67a","replay":"GSTA-258-C+GST-942"}
|
||||
{"sha":"1d03d5cd8f0cae5f01af85502004849c9fa2545009957f2c4c44a1359d9d0fc0","replay":"GSTA-258-L7"}
|
||||
@@ -0,0 +1 @@
|
||||
{"replay":"GSTA-258-L7","justification":"GSTA-258 L7 planner no-loss check (GST-1177, Addenda 1 and 7): the change only adds triggers (executables stay code; seal, sealed, custody and egress path tokens; redaction calls (camelCase or snake_case), redaction or outside-voice imports (from, side-effect, require, dynamic and Python forms) and SECRET or CREDENTIAL constants set to a regex literal, a regex list or new RegExp are security; the docs credential check reads every docs path whatever its class; a deleted file is never an executable, and an executable or symlink is code with its lines read whatever its docs, data or config name) and removes none; over the last 200 first-parent main commits to bf2cab34c5, planReview and collectCommit from origin/main and from this branch give the same depth, class, risk classes, next step and dispatches on 194, and the other 6 only raise: ed5c948eb6 (#3921, the GST-1164 secret-egress fix) and c197a139b7 (#3918, approval text in public PR bodies) and 514daebf5f (#3569, lib/sealed-guard.ts) go light to full on security, while 90a170c941, 71acd83aa6 and 216493fb32 gain security at unchanged full depth and reviewers; no commit's depth drops ; reruns after the pass 1 and Step 11 fixes give the same rows, and after the second-exception fixes 216493fb32 also gains security at unchanged depth and readers (GStack Minder drive handoffs/GSTA-258/L7-planner-noloss/, l7-200-v2.tsv, l7-200-v3.tsv, l7-200-v4.tsv)"}
|
||||
@@ -406,6 +406,44 @@ describe('gstack-capy-install', () => {
|
||||
expect(admits('ship')?.detail).toBe('the install verdict certified for=document-release, which does not cover codex that ship needs');
|
||||
});
|
||||
|
||||
// GST-1233 (TRUT-26): the union above needs the same Bun and an ok run, so a child whose shell
|
||||
// resolves another Bun, or whose install fails, still replaced the shared verdict and /ship's
|
||||
// finish pregate reported INSTALL_UNVERIFIED. Each workflow keeps its own verdict as well.
|
||||
test('--for ship then --for document-release with another Bun or a failed run: ship stays admitted; another HEAD invalidates both', () => {
|
||||
const f = fixture();
|
||||
const env = { HOME: f.home, GSTACK_HOME: path.join(f.home, '.gstack-state') };
|
||||
const admits = (skill: string) => verdictProblem(skill, f.root, env, '', '1.4.2', f.home);
|
||||
const ship = run(f, ['--for', 'ship'], { STUB_REQUIRED: 'claude codex patch runtime pins' });
|
||||
expect(ship.status, ship.stdout + ship.stderr).toBe(0);
|
||||
const file = ship.stdout.match(/GSTACK_INSTALL_VERDICT=(\S+)/)![1]!;
|
||||
const childBin = path.join(f.base, 'child-bin');
|
||||
script(path.join(childBin, 'bun'), ['[ "$1" = --version ] && { echo 1.4.2; exit 0; }', 'exit 0']);
|
||||
const docs = run(f, ['--for', 'document-release'], { STUB_REQUIRED: 'claude runtime', PATH: `${childBin}${path.delimiter}${f.env.PATH}` });
|
||||
expect(docs.status, docs.stdout + docs.stderr).toBe(0);
|
||||
expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toMatchObject({ for: 'document-release', bun_path: path.join(childBin, 'bun') });
|
||||
expect(admits('ship')).toBeNull();
|
||||
expect(admits('document-release')).toBeNull();
|
||||
const shipBun = JSON.parse(fs.readFileSync(file.replace(/\.json$/, '.for/ship.json'), 'utf8')).bun_path;
|
||||
expect(shipBun).not.toBe(path.join(childBin, 'bun'));
|
||||
const check = run(f, ['--check', '--for', 'ship'], { STUB_REQUIRED: 'claude codex patch runtime pins' });
|
||||
expect(check.status, check.stdout + check.stderr).toBe(0);
|
||||
expect(JSON.parse(fs.readFileSync(file.replace(/\.json$/, '.for/ship.json'), 'utf8')).bun_path).toBe(shipBun);
|
||||
expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toMatchObject({ for: 'ship', bun_path: shipBun });
|
||||
expect(admits('ship')).toBeNull();
|
||||
expect(admits('document-release')).toBeNull();
|
||||
const failed = run(f, ['--for', 'document-release'], { STUB_REQUIRED: 'claude runtime', STUB_DOCTOR_FAIL: '1' });
|
||||
expect(failed.status).not.toBe(0);
|
||||
expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toMatchObject({ for: 'document-release', ok: false });
|
||||
expect(admits('ship')).toBeNull();
|
||||
expect(admits('document-release')?.detail).toContain('the install verdict says: gstack: fail');
|
||||
sh('git -c user.email=t@t -c user.name=t commit -q --allow-empty -m next', f.root);
|
||||
expect(admits('ship')?.detail).toMatch(/^the install verdict says: gstack: fail/);
|
||||
const moved = run(f, ['--for', 'document-release'], { STUB_REQUIRED: 'claude runtime' });
|
||||
expect(moved.status, moved.stdout + moved.stderr).toBe(0);
|
||||
expect(admits('document-release')).toBeNull();
|
||||
expect(admits('ship')?.detail).toBe('the install verdict certified for=document-release, which does not cover codex that ship needs');
|
||||
});
|
||||
|
||||
test('--root clones when the directory is absent and refuses a non-gstack directory', () => {
|
||||
const f = fixture();
|
||||
const clone = path.join(f.base, 'clone');
|
||||
|
||||
@@ -92,6 +92,33 @@ describe('gstack-docs-candidate', () => {
|
||||
expect(fs.existsSync(path.join(dir, 'inside.json'))).toBe(false);
|
||||
});
|
||||
|
||||
// Value: protects=--docs takes a comma-separated list as well as repeated flags, a path that exists is taken whole even with a space or a comma in it, and a space-separated list is refused instead of recorded as one missing path; fails_when=--docs "a, b" records one path "a, b" (gstack-evals#191 /ship), a single path or an existing spaced path stops working, or "a b" is silently recorded;
|
||||
// why_new=each --docs value was one path; seam=gstack-docs-candidate snapshot; no_claim=--select, which still takes one path per flag
|
||||
test('--docs splits a comma-separated list; an existing path is taken whole; a space-separated list is refused', () => {
|
||||
const { dir, root, record } = repo();
|
||||
fs.writeFileSync(path.join(dir, 'my notes.md'), 'n\n');
|
||||
fs.writeFileSync(path.join(dir, 'a,b.md'), 'c\n');
|
||||
const docs = (...values: string[]) => {
|
||||
const r = run(dir, 'snapshot', '--out', record, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', ...values.flatMap(v => ['--docs', v]));
|
||||
expect(r.status, r.stderr).toBe(0);
|
||||
return JSON.parse(fs.readFileSync(record, 'utf8')).docs;
|
||||
};
|
||||
expect(docs('handbook')).toEqual(['handbook/guide.md']);
|
||||
expect(docs('handbook, app.ts')).toEqual(['app.ts', 'handbook/guide.md']);
|
||||
expect(docs('handbook,app.ts,', 'my notes.md')).toEqual(['app.ts', 'handbook/guide.md', 'my notes.md']);
|
||||
expect(docs('a,b.md')).toEqual(['a,b.md']);
|
||||
fs.rmSync(record);
|
||||
const spaced = run(dir, 'snapshot', '--out', record, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'handbook app.ts');
|
||||
expect([spaced.status, spaced.stderr.trim()]).toEqual([1, 'gstack-docs-candidate: --docs "handbook app.ts" names no file or directory and holds whitespace: repeat --docs for each path, or separate paths with commas']);
|
||||
expect(fs.existsSync(record)).toBe(false);
|
||||
for (const empty of ['', ' ', ',']) {
|
||||
const r = run(dir, 'snapshot', '--out', record, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', empty);
|
||||
expect([r.status, r.stderr.trim()]).toEqual([1, `gstack-docs-candidate: --docs ${JSON.stringify(empty)} names no path: give a file or directory, repeat --docs for each path, or separate paths with commas`]);
|
||||
expect(fs.existsSync(record)).toBe(false);
|
||||
}
|
||||
expect(fs.readdirSync(root)).toEqual(['repo']);
|
||||
});
|
||||
|
||||
test('--help prints the usage it names in its errors', () => {
|
||||
const { dir } = repo();
|
||||
const help = run(dir, '--help');
|
||||
|
||||
@@ -768,6 +768,38 @@ describe('gstack-lease', () => {
|
||||
expect(fs.readFileSync(file, 'utf8')).not.toContain('-1-old');
|
||||
});
|
||||
|
||||
// GST-1204: gstack-ship-preflight asks whether one /ship run is still open; open answers with the same released, aged-out, dead and stale rules live uses.
|
||||
test('open --run [--pid | --from]: 0 while that run is open on a live holder; 1 once released, aged out, dead, reused or never recorded; usage is 2', () => {
|
||||
const { dir, leases } = checkout();
|
||||
const open = (pid: number | string, id: string) => run(['open', '--root', dir, '--pid', String(pid), '--run', id]).status;
|
||||
const p = sleeper();
|
||||
expect(run(['touch', '--root', dir, '--pid', String(p), '--run', `${p}-1-a`]).status).toBe(0);
|
||||
expect(run(['touch', '--root', dir, '--pid', String(p), '--run', `${p}-2-b`]).status).toBe(0);
|
||||
expect(open(p, `${p}-1-a`)).toBe(0);
|
||||
expect(run(['open', '--root', dir, '--run', `${p}-1-a`]).status).toBe(0);
|
||||
expect(run(['open', '--root', dir, '--run', `${p}-1-a`, '--from', String(process.pid)]).status).toBe(1);
|
||||
expect(run(['touch', '--root', dir, '--pid', String(process.pid), '--run', 'own-1']).status).toBe(0);
|
||||
expect(run(['open', '--root', dir, '--run', 'own-1', '--from', String(process.pid)]).status).toBe(0);
|
||||
expect(open(p, `${p}-9-z`)).toBe(1);
|
||||
expect(run(['release', '--root', dir, '--pid', String(p), '--run', `${p}-1-a`]).status).toBe(0);
|
||||
expect(open(p, `${p}-1-a`)).toBe(1);
|
||||
expect(open(p, `${p}-2-b`)).toBe(0);
|
||||
const file = path.join(leases, String(p));
|
||||
const body = fs.readFileSync(file, 'utf8');
|
||||
fs.writeFileSync(file, body.replace(/^run (\S+) \d+$/m, `run $1 ${Math.floor(Date.now() / 1000) - 121 * 60}`));
|
||||
expect(open(p, `${p}-2-b`)).toBe(1);
|
||||
fs.writeFileSync(file, body.replace(/^.*$/m, otherStart(body.split('\n')[0]!)));
|
||||
expect(open(p, `${p}-2-b`)).toBe(1);
|
||||
const dead = deadPid();
|
||||
fs.writeFileSync(path.join(leases, String(dead)), `linux 00000000-0000-0000-0000-000000000000 1\nrun ${dead}-1-a ${Math.floor(Date.now() / 1000)}\n`);
|
||||
expect(open(dead, `${dead}-1-a`)).toBe(1);
|
||||
expect(run(['open', '--root', dir, '--run', `${dead}-1-a`]).status).toBe(1);
|
||||
expect(open(424243, '424243-1-a')).toBe(1);
|
||||
expect(open('x', 'y')).toBe(2);
|
||||
expect(run(['open', '--root', dir, '--pid', String(p)]).status).toBe(2);
|
||||
expect(run(['open', '--root', dir]).status).toBe(2);
|
||||
});
|
||||
|
||||
test('gstack-skill-start reports a lease the held lock kept from being written, and still starts', () => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-lease-home-'));
|
||||
const state = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-lease-state-'));
|
||||
|
||||
+114
-17
@@ -267,6 +267,28 @@ describe("gstack-post owns the redaction scan", () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Value: protects=the run list a CI carry or run clear prints (`runs=<id>/<attempt>,<id>/<attempt>`, lib/run-evidence.ts runReceiptFields) and a bare
|
||||
// `actions/runs/<id>` path post without a pii.phone.e164 confirmation, while a phone number in prose next to them still needs one (GST-1227);
|
||||
// fails_when=every run id after the first in a `runs=` list, or an `actions/runs/` path with no leading slash, needs --confirm, or the exemption
|
||||
// swallows +1 415 555 0123 on the same line; why_new=the run-word test covers only the id right after the word; seam=fake run; no_claim=real gh
|
||||
test("run ids in a runs= list or an actions/runs/ path are not phone numbers; a phone number beside them still is", () => {
|
||||
const clean = [
|
||||
"CI_CARRY: cleared pregate.json/remote_gate run tree=704992822996 tests=412 runs=41629861819/1,41629861820/2 profiles=free-tests,windows-smoke heads=2f9d11a0c3e4 verified=2026-11-03T18:00:00.000Z",
|
||||
"carried run=41629861819/1,416298618201/3",
|
||||
"logs at garrytan/gstack actions/runs/41629861819/attempts/2",
|
||||
];
|
||||
for (const body of clean) {
|
||||
const f = fakeEnv({ files: { "/b": body + "\n" }, visibility: "public" });
|
||||
expect([body, run(["pr-comment", "12", "--body-file", "/b"], f)]).toEqual([body, EXIT.posted]);
|
||||
}
|
||||
for (const body of ["call +1 415 555 0123 about runs=41629861819/1,41629861820/2", "runs=+14155550123/1", "runs=1/4155550123", "runs=4155550123", "runs=4155550123/1", "sales-actions/runs/4155550123"]) {
|
||||
const f = fakeEnv({ files: { "/b": body + "\n" }, visibility: "public" });
|
||||
expect([body, run(["pr-comment", "12", "--body-file", "/b"], f)]).toEqual([body, EXIT.confirm]);
|
||||
expect(f.stdout()).toContain("RULE: pii.phone.e164 LINE: 1 PART: body");
|
||||
expect(f.posts()).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test("the title is scanned too, and the pusher's own email is not a finding", () => {
|
||||
const f = fakeEnv({ files: { "/t": "v1 fix for jane.roe@acme-corp.io", "/b": "body" } });
|
||||
expect(run(["pr-create", "--base", "main", "--title-file", "/t", "--body-file", "/b"], f)).toBe(EXIT.confirm);
|
||||
@@ -446,16 +468,18 @@ describe("gstack-post pr-body merges the PR body by section", () => {
|
||||
expect(after.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt, Why; kept unclosed receipt fence; added none\n");
|
||||
});
|
||||
|
||||
// Value: protects=a full post (a receipt above its first heading, as /ship composes it) owns the text above the first heading (GST-412): stale lead text and stale text between the receipt and the
|
||||
// first heading are dropped and named on stderr with their first line, the file's own preamble takes their place, a receipt-only or text-only file
|
||||
// keeps the older merge, a repost is byte-identical and an attribution callout is never doubled; fails_when=pr-body keeps a stale intro above the
|
||||
// receipt or a stale note under it after /ship reposts the sections; why_new=lead text was kept unless the file brought its own; seam=fake run;
|
||||
// Value: protects=a full post (a receipt above its first heading, as /ship composes it) owns the text between the receipt and the first heading
|
||||
// (GST-412): a stale note there is dropped and named on stderr with its first line, the file's own text under its receipt takes its place, the
|
||||
// opening text above the receipt is kept unless the file brings its own (GST-1227), a receipt-only or text-only file keeps the older merge, a repost
|
||||
// is byte-identical and an attribution callout is never doubled; fails_when=pr-body keeps a stale note under the receipt after /ship reposts the
|
||||
// sections, or drops the opening text the file does not rewrite; why_new=lead text was kept unless the file brought its own; seam=fake run;
|
||||
// no_claim=real gh
|
||||
test("a full post replaces every text section above the current first heading and names each dropped piece", () => {
|
||||
const stale = withBody("Draft intro from gh pr create, long enough to need truncation in the summary line\nsecond line\n\n" + CURRENT, { "/b": RECEIPT("bbbb") + "\n## What changed\n\n- new\n" });
|
||||
test("a full post replaces the text under the receipt, keeps the opening text it does not rewrite, and names each dropped piece", () => {
|
||||
const intro = "Draft intro from gh pr create, long enough to need truncation in the summary line\nsecond line\n\n";
|
||||
const stale = withBody(intro + CURRENT, { "/b": RECEIPT("bbbb") + "\n## What changed\n\n- new\n" });
|
||||
expect(run(["pr-body", "5", "--body-file", "/b"], stale)).toBe(EXIT.posted);
|
||||
expect(sent(stale).input).toBe(RECEIPT("bbbb") + "\n## What changed\n\n- new\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: do it\n");
|
||||
expect(stale.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt, What changed; kept Why, Approvals; added none; dropped leading text (\"Draft intro from gh pr create, long enough to need truncati…\")\n");
|
||||
expect(sent(stale).input).toBe(intro + RECEIPT("bbbb") + "\n## What changed\n\n- new\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: do it\n");
|
||||
expect(stale.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt, What changed; kept leading text, Why, Approvals; added none\n");
|
||||
|
||||
const between = withBody(RECEIPT("aaaa") + "Old note under the receipt\n\n## What changed\n\n- old\n", { "/b": RECEIPT("bbbb") + "## What changed\n\n- new\n" });
|
||||
expect(run(["pr-body", "5", "--body-file", "/b"], between)).toBe(EXIT.posted);
|
||||
@@ -469,6 +493,79 @@ describe("gstack-post pr-body merges the PR body by section", () => {
|
||||
expect(own.stderr()).toBe("gstack-post: pr-body merged by section: replaced leading text, ship receipt, trailing text, Why; kept none; added none\n");
|
||||
});
|
||||
|
||||
// Value: protects=a full post keeps the PR's opening text (a Capy badge block and a paragraph above the first heading) byte for byte, lands a new
|
||||
// receipt right after it, and keeps a badge block that ends the body after the section above it is rewritten, on the first post and on a repost
|
||||
// (GST-1227); fails_when=pr-body drops the opening paragraph and the badge (truther#1174), a new receipt lands above them so the next post drops them
|
||||
// as a note under the receipt, or the trailing badge leaves with the section it follows; why_new=the GST-412 tests read every opening line as a
|
||||
// stale intro; seam=fake run; no_claim=real gh
|
||||
test("a full post keeps the opening text and a badge block above the first heading or at the end of the body byte for byte", () => {
|
||||
const BADGE = "<!-- capy-badge:start -->\n[](https://capy.ai)\n<!-- capy-badge:end -->\n";
|
||||
const PREAMBLE = BADGE + "\nThis PR stops the login retry from looping.\n\n";
|
||||
const first = withBody(PREAMBLE + "## What changed\n\n- the old summary\n\n## Why\n\nBecause.\n", { "/b": RECEIPT("bbbb") + "\n## What changed\n\n- new\n" });
|
||||
expect(run(["pr-body", "5", "--body-file", "/b"], first)).toBe(EXIT.posted);
|
||||
expect(sent(first).input).toBe(PREAMBLE + RECEIPT("bbbb") + "\n## What changed\n\n- new\n\n## Why\n\nBecause.\n");
|
||||
expect(first.stderr()).toBe("gstack-post: pr-body merged by section: replaced What changed; kept leading text, Why; added ship receipt\n");
|
||||
|
||||
const again = withBody(sent(first).input!, { "/b": RECEIPT("cccc") + "\n## What changed\n\n- newer\n" });
|
||||
expect(run(["pr-body", "5", "--body-file", "/b"], again)).toBe(EXIT.posted);
|
||||
expect(sent(again).input).toBe(PREAMBLE + RECEIPT("cccc") + "\n## What changed\n\n- newer\n\n## Why\n\nBecause.\n");
|
||||
expect(again.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt, What changed; kept leading text, Why; added none\n");
|
||||
|
||||
const trailing = withBody(CURRENT + "\n" + BADGE, { "/b": RECEIPT("bbbb") + "\n## Approvals\n\n- owner: ship it\n\n## Tests\n\n- one\n" });
|
||||
expect(run(["pr-body", "5", "--body-file", "/b"], trailing)).toBe(EXIT.posted);
|
||||
expect(sent(trailing).input).toBe(RECEIPT("bbbb") + "\n## What changed\n\n- the old summary\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: ship it\n\n## Tests\n\n- one\n\n" + BADGE);
|
||||
expect(trailing.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt, Approvals; kept What changed, Why, capy-badge block; added Tests\n");
|
||||
});
|
||||
|
||||
const BADGE = "<!-- capy-badge:start -->\n[](https://capy.ai)\n<!-- capy-badge:end -->\n";
|
||||
const SHOTS = (alt: string) => "<!-- shots:start -->\n\n<!-- shots:end -->\n";
|
||||
|
||||
// Value: protects=a marker block other than a Capy badge that ends the body stays inside its section exactly as before GST-1227, so a rewrite
|
||||
// replaces it with the section, a new section lands after it, text after a badge in mid-section never pairs with the note under a receipt,
|
||||
// and the file's own block stays in its section; fails_when=the old block and the stale lines after it survive a rewrite, a shots block is
|
||||
// split from its section, "Fixes #12" is dropped, or the file's block moves above the first heading; why_new=GST-1227 review P1; seam=none
|
||||
// (mergeBodySections); no_claim=the gh round trip
|
||||
test("a marker block that is not a trailing Capy badge stays inside its section", () => {
|
||||
const mid = mergeBodySections(RECEIPT("aaaa") + "\n## What changed\n\n- old\n" + SHOTS("a") + "stale line\n\n## Why\n\nBecause.\n", RECEIPT("bbbb") + "\n## What changed\n\n- new\n");
|
||||
expect([mid.body, mid.kept]).toEqual([RECEIPT("bbbb") + "\n## What changed\n\n- new\n\n## Why\n\nBecause.\n", ["Why"]]);
|
||||
const last = mergeBodySections(CURRENT + SHOTS("a"), RECEIPT("bbbb") + "\n## Tests\n\n- one\n");
|
||||
expect(last.body).toBe(RECEIPT("bbbb") + "\n## What changed\n\n- the old summary\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: do it\n" + SHOTS("a") + "\n## Tests\n\n- one\n");
|
||||
const collide = mergeBodySections("Intro\n\n## What changed\n\n- x\n" + BADGE + "Fixes #12\n", RECEIPT("bbbb") + "Review-loop exception: foo\n");
|
||||
expect(collide.body).toBe("Intro\n\n" + RECEIPT("bbbb") + "\nReview-loop exception: foo\n\n## What changed\n\n- x\n" + BADGE + "Fixes #12\n");
|
||||
const own = mergeBodySections(CURRENT, RECEIPT("bbbb") + "\n## What changed\n\n" + SHOTS("n") + "after the shots\n");
|
||||
expect(own.body).toBe(RECEIPT("bbbb") + "\n## What changed\n\n" + SHOTS("n") + "after the shots\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: do it\n");
|
||||
});
|
||||
|
||||
// Value: protects=a trailing badge the file brings into a body without one lands at the end once and a repost is byte-identical; fails_when=each
|
||||
// identical post adds another badge or moves it above the sections; why_new=GST-1227 review P2; seam=none (mergeBodySections); no_claim=the gh round trip
|
||||
test("a trailing badge the file brings lands at the end once and reposts byte for byte", () => {
|
||||
const file = RECEIPT("bbbb") + "\n## Tests\n\n- one\n\n" + BADGE;
|
||||
const once = mergeBodySections(CURRENT, file).body;
|
||||
expect(once).toBe(RECEIPT("bbbb") + "\n## What changed\n\n- the old summary\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: do it\n\n## Tests\n\n- one\n\n" + BADGE);
|
||||
const twice = mergeBodySections(once, file).body;
|
||||
expect(twice).toBe(once);
|
||||
expect(mergeBodySections(twice, file).body).toBe(once);
|
||||
});
|
||||
|
||||
// Value: protects=fences inside a marker block keep their meaning (a fenced `## x` opens no section), a badge inside a fence is text, and an
|
||||
// unclosed badge marker swallows nothing; fails_when=the fenced `## x` ends the block and opens a section, or the unclosed marker keeps the
|
||||
// rest of the old section after a rewrite; why_new=GST-1227 review P2; seam=none (mergeBodySections); no_claim=the gh round trip
|
||||
test("a fenced heading inside a marker block and an unclosed badge marker change nothing about the sections", () => {
|
||||
const fenced = mergeBodySections("## What changed\n\n<!-- shots:start -->\n```md\n## x\n```\n<!-- shots:end -->\n\n## Why\n\nold\n", "## Why\n\nnew\n");
|
||||
expect([fenced.body, fenced.replaced, fenced.kept]).toEqual(["## What changed\n\n<!-- shots:start -->\n```md\n## x\n```\n<!-- shots:end -->\n\n## Why\n\nnew\n", ["Why"], ["What changed"]]);
|
||||
const example = mergeBodySections("## Docs\n\n```md\n" + BADGE + "```\n", "## Docs\n\nnew\n");
|
||||
expect([example.body, example.kept]).toEqual(["## Docs\n\nnew\n", []]);
|
||||
const unclosed = mergeBodySections(RECEIPT("aaaa") + "\n## Why\n\nBecause.\n\n## Approvals\n\n- x\n<!-- capy-badge:start -->\nmore approvals\n", RECEIPT("bbbb") + "\n## Approvals\n\n- y\n");
|
||||
expect([unclosed.body, unclosed.kept]).toEqual([RECEIPT("bbbb") + "\n## Why\n\nBecause.\n\n## Approvals\n\n- y\n", ["Why"]]);
|
||||
});
|
||||
|
||||
// Value: protects=two marker blocks with one name merge by their sections; fails_when=the merge refuses them as a duplicated section;
|
||||
// why_new=GST-1227 review; seam=none (mergeBodySections); no_claim=the gh round trip
|
||||
test("two marker blocks with the same name merge by their sections", () => {
|
||||
const two = mergeBodySections("## A\n\n" + SHOTS("a") + "\n## B\n\n" + SHOTS("b"), "## A\n\n" + SHOTS("a2"));
|
||||
expect([two.body, two.replaced, two.kept]).toEqual(["## A\n\n" + SHOTS("a2") + "\n## B\n\n" + SHOTS("b"), ["A"], ["B"]]);
|
||||
});
|
||||
|
||||
// Value: protects=a partial post (no receipt above its first `## ` heading, even with a caption of its own or a receipt further down) keeps
|
||||
// the human intro and the note under the receipt; fails_when=a lane posting only `## Screenshots`
|
||||
// deletes the intro or a Review-loop exception line; why_new=GST-412 made any file with a section own the preamble (GstackMinder,
|
||||
@@ -489,10 +586,10 @@ describe("gstack-post pr-body merges the PR body by section", () => {
|
||||
// Value: protects=the dropped-piece excerpt on stderr never repeats a secret the merge removed from the body (the scan only reads the merged bytes);
|
||||
// fails_when=a stale intro holding a credential is echoed to stderr while it leaves the PR; why_new=the excerpt is new in GST-412; seam=fake run; no_claim=real gh
|
||||
test("a dropped piece whose first line the redaction scan flags is named without its text", () => {
|
||||
const leak = withBody(`Deploy key ${AWS} for the demo\n\n` + CURRENT, { "/b": RECEIPT("bbbb") + "\n## What changed\n\n- new\n" });
|
||||
const leak = withBody(RECEIPT("aaaa") + `Deploy key ${AWS} for the demo\n\n## What changed\n\n- old\n`, { "/b": RECEIPT("bbbb") + "\n## What changed\n\n- new\n" });
|
||||
expect(run(["pr-body", "5", "--body-file", "/b"], leak)).toBe(EXIT.posted);
|
||||
expect(leak.stderr()).not.toContain(AWS);
|
||||
expect(leak.stderr()).toContain("dropped leading text (first line withheld: the redaction scan flagged it)");
|
||||
expect(leak.stderr()).toContain("dropped trailing text (first line withheld: the redaction scan flagged it)");
|
||||
});
|
||||
|
||||
test("receipt-only and text-only files keep the older merge; a repost is byte-identical; a callout in the preamble is never doubled", () => {
|
||||
@@ -521,11 +618,11 @@ describe("gstack-post pr-body merges the PR body by section", () => {
|
||||
});
|
||||
|
||||
// Value: protects=--replace keeps the plain overwrite for a caller that composed the whole body, a current body with no H2 headings is kept as the leading
|
||||
// section by a file without sections and dropped (and named) by a full post (GST-412), an empty current body posts the new body byte for byte,
|
||||
// section, above a new receipt, by a file without sections and by a full post (GST-1227), an empty current body posts the new body byte for byte,
|
||||
// the scan runs on the merged bytes, and an unreadable current body is exit 3 with the --replace hint rather than an overwrite; fails_when=--replace
|
||||
// merges, headingless text is dropped by a receipt-only post or kept under new sections, the merge changes a lone new body, a secret in a kept section
|
||||
// passes the scan, or a failed read overwrites; why_new=first pr-body merge tests; seam=fake run; no_claim=real gh
|
||||
test("--replace overwrites; a body without H2 headings is kept by a file without a receipt and dropped by a full post; the merged bytes are what is scanned; a failed read refuses", () => {
|
||||
test("--replace overwrites; a body without H2 headings is kept above a new receipt by any file; the merged bytes are what is scanned; a failed read refuses", () => {
|
||||
const replaced = withBody(CURRENT, { "/b": "## What changed\n\nonly this\n" });
|
||||
expect(run(["pr-body", "5", "--replace", "--body-file", "/b"], replaced)).toBe(EXIT.posted);
|
||||
expect(sent(replaced).input).toBe("## What changed\n\nonly this\n");
|
||||
@@ -534,11 +631,11 @@ describe("gstack-post pr-body merges the PR body by section", () => {
|
||||
|
||||
const plain = withBody("Just a paragraph.\nAnother line.", { "/b": RECEIPT("bbbb") + "\n## Tests\n\n- one\n" });
|
||||
expect(run(["pr-body", "5", "--body-file", "/b"], plain)).toBe(EXIT.posted);
|
||||
expect(sent(plain).input).toBe(RECEIPT("bbbb") + "\n## Tests\n\n- one\n");
|
||||
expect(plain.stderr()).toBe("gstack-post: pr-body merged by section: replaced none; kept none; added ship receipt, Tests; dropped leading text (\"Just a paragraph.\")\n");
|
||||
expect(sent(plain).input).toBe("Just a paragraph.\nAnother line.\n\n" + RECEIPT("bbbb") + "\n## Tests\n\n- one\n");
|
||||
expect(plain.stderr()).toBe("gstack-post: pr-body merged by section: replaced none; kept leading text; added ship receipt, Tests\n");
|
||||
const plainText = withBody("Just a paragraph.\nAnother line.", { "/b": RECEIPT("bbbb") });
|
||||
expect(run(["pr-body", "5", "--body-file", "/b"], plainText)).toBe(EXIT.posted);
|
||||
expect(sent(plainText).input).toBe(RECEIPT("bbbb") + "\nJust a paragraph.\nAnother line.");
|
||||
expect(sent(plainText).input).toBe("Just a paragraph.\nAnother line.\n\n" + RECEIPT("bbbb"));
|
||||
expect(plainText.stderr()).toBe("gstack-post: pr-body merged by section: replaced none; kept leading text; added ship receipt\n");
|
||||
|
||||
const empty = withBody("", { "/b": "new body" });
|
||||
@@ -672,8 +769,8 @@ describe("gstack-post pr-body merges the PR body by section", () => {
|
||||
expect(fresh.added).toEqual(["leading text"]);
|
||||
const receipt = "```gstack-ship-receipt\n{\n \"head\": \"a\"\n}\n```\n";
|
||||
const afterReceipt = mergeBodySections("Intro line\n\n## Summary\n\nold\n", receipt + "note\n\n## Summary\n\nnew\n");
|
||||
expect(afterReceipt.body).toBe(receipt + "\nnote\n\n## Summary\n\nnew\n");
|
||||
expect(afterReceipt.body).toBe("Intro line\n\n" + receipt + "\nnote\n\n## Summary\n\nnew\n");
|
||||
expect(afterReceipt.replaced).toEqual(["Summary"]);
|
||||
expect(afterReceipt.dropped).toEqual(['leading text ("Intro line")']);
|
||||
expect(afterReceipt.dropped).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -25,7 +25,7 @@ const { parseDocsCompletion } = await import(path.join(root, 'test/helpers/docsy
|
||||
const { docsActorSeeded, DOCS_SEEDED_AUDIT_ID } = await import(path.join(root, 'test/helpers/docsync-fault-actor.ts'));
|
||||
const CALLBACK_TEST_MS = ${CALLBACK_TEST_MS};
|
||||
const callbacks = new Map();
|
||||
let fixture, control = '', launches = 0, recorded, legacyReaudit = false;
|
||||
let fixture, control = '', launches = 0, recorded, legacyReaudit = false, bodyStartedAt = 0;
|
||||
let returnedResult: SkillTestResult | undefined;
|
||||
let consumers: string[] = [];
|
||||
function expectResult(result: SkillTestResult) {
|
||||
@@ -47,7 +47,7 @@ mock.module(observerModule, () => ({ ...observers,
|
||||
mock.module(path.join(root, 'test/helpers/e2e-gate.ts'), () => ({ describeE2ETier: () => (_name, body) => body() }));
|
||||
mock.module(path.join(root, 'test/helpers/e2e-helpers.ts'), () => ({
|
||||
runId: 'free-docsync-faults', describeIfSelected: (_name, _names, body) => body(),
|
||||
testConcurrentIfSelected: (name, body, budget) => callbacks.set(name, { body, budget }),
|
||||
testConcurrentIfSelected: (name, body, budget) => callbacks.set(name, { body: () => { bodyStartedAt = Date.now(); return body(); }, budget }),
|
||||
createEvalCollector: () => ({}), finalizeEvalCollector() {},
|
||||
logCost(_name, result) {
|
||||
expectResult(result);
|
||||
@@ -65,8 +65,10 @@ mock.module(path.join(root, 'test/helpers/session-runner.ts'), () => ({ async ru
|
||||
const legacy = options.testName === 'ship-docsync-failure';
|
||||
const scenario = legacy ? 'legacy-completion' : options.testName.slice('ship-docsync-'.length);
|
||||
expect(options.maxTurns).toBe(legacy ? 30 : 24);
|
||||
expect(options.timeout).toBeGreaterThan((legacy ? CAPTURE_LONG_MS : CAPTURE_MS) - 20_000);
|
||||
expect(options.timeout).toBeLessThanOrEqual((legacy ? CAPTURE_LONG_MS : CAPTURE_MS) - 15_000);
|
||||
const remaining = (legacy ? CAPTURE_LONG_MS : CAPTURE_MS) - 15_000;
|
||||
// gstack-timing-ok: runShipDocsFault derives the timeout from elapsed time, so the bound measures the same elapsed time
|
||||
expect(options.timeout).toBeGreaterThanOrEqual(remaining - (Date.now() - bodyStartedAt));
|
||||
expect(options.timeout).toBeLessThanOrEqual(remaining);
|
||||
expect(options.tools).toEqual(['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep']);
|
||||
expect(options.allowedTools).toEqual(options.tools);
|
||||
expect(options.prompt).toContain('BOUNDED_CALLBACK_USED');
|
||||
|
||||
@@ -177,7 +177,7 @@ export const FREE_FIXTURES: Readonly<Record<string, readonly string[]>> = {
|
||||
'test/fixtures/native-auq-devex-clipped-elided-sep21.json': ['test/auq-native-capture.test.ts'],
|
||||
'test/fixtures/native-auq-margin-elided-sep21.json': ['test/auq-native-capture.test.ts'],
|
||||
'test/fixtures/native-auq-packet-clipped-elided-sep21.json': ['test/auq-native-capture.test.ts'],
|
||||
'test/fixtures/outside-review-severity/**': ['test/outside-review-severity.test.ts'],
|
||||
'test/fixtures/outside-review-severity/**': ['test/outside-review-severity.test.ts', 'test/outside-review-unparsed-severity.test.ts'],
|
||||
'test/fixtures/outside-voice-failure-prose-allowlist.json': ['test/outside-voice-failure-policy.test.ts'],
|
||||
'test/fixtures/overlay-v4-replay-37198445662.json': ['test/overlay-measurement.test.ts'],
|
||||
'test/fixtures/paid-report-census/**': ['test/paid-report-census.test.ts', 'test/paid-shards.test.ts'],
|
||||
|
||||
@@ -152,6 +152,30 @@ describe('install verdict keyed by (checkout, project): both twins', () => {
|
||||
expect(both('autoplan', proj, env).detail).toContain('unsupported schema_version');
|
||||
});
|
||||
|
||||
test("GST-1233: a later install for another workflow replaced the shared verdict; both twins admit from the workflow's own record, never from a stale one", () => {
|
||||
const sr = tmp();
|
||||
const proj = project('truther');
|
||||
const shared = writeVerdict(sr, { project: proj, bun_path: '/opt/child/bun', bun_version: '1.4.2', schema_version: 2, for: 'document-release',
|
||||
required: ['claude', 'runtime'], trailer: 'gstack: ok 9.9.9.9 for=document-release' });
|
||||
const own = shared.replace(/\.json$/, '.for/ship.json');
|
||||
const env = { GSTACK_STATE_ROOT: sr };
|
||||
const without = both('ship', proj, env);
|
||||
expect(without).toMatchObject({ refuse: true, status: 'verdict', code: 'INSTALL_UNVERIFIED', detail: 'the install verdict certified for=document-release, which does not cover codex that ship needs' });
|
||||
writeVerdict(sr, { project: proj, bun_path: BUN, bun_version: '1.4.2', schema_version: 2, for: 'ship', trailer: 'gstack: ok 9.9.9.9 for=ship' }, own);
|
||||
expect(both('ship', proj, env)).toMatchObject({ refuse: false, status: 'ok' });
|
||||
expect(bashAdmit('ship', proj, { _GH: sr, ...env }).line).toBe('INSTALL_VERDICT: ok gstack: ok 9.9.9.9 for=ship');
|
||||
const setupFailed = { project: proj, bun_path: '/opt/child/bun', bun_version: '1.4.2', schema_version: 2, for: 'document-release', ok: false, trailer: 'gstack: fail setup' };
|
||||
writeVerdict(sr, setupFailed);
|
||||
expect(both('ship', proj, env)).toMatchObject({ refuse: true, status: 'verdict', detail: 'the install verdict says: gstack: fail setup' });
|
||||
writeVerdict(sr, { ...setupFailed, trailer: 'gstack: fail codex' });
|
||||
expect(both('ship', proj, env)).toMatchObject({ refuse: false, status: 'ok' });
|
||||
writeVerdict(sr, { project: proj, bun_path: '/opt/child/bun', bun_version: '1.4.2', schema_version: 2, for: 'document-release', required: ['claude', 'runtime'], trailer: 'gstack: ok 9.9.9.9 for=document-release' });
|
||||
writeVerdict(sr, { project: proj, bun_path: BUN, bun_version: '1.4.2', schema_version: 2, for: 'ship', head: 'f'.repeat(40) }, own);
|
||||
const stale = both('ship', proj, env);
|
||||
expect(stale).toMatchObject({ refuse: true, status: 'verdict', code: 'INSTALL_UNVERIFIED', detail: without.detail });
|
||||
expect(bashAdmit('ship', proj, { _GH: sr, ...env }).line).toBe(without.line);
|
||||
});
|
||||
|
||||
test('a running Bun other than the recorded one refuses with BUN_RESOLUTION_DRIFT and names both', () => {
|
||||
const sr = tmp();
|
||||
const a = project('a');
|
||||
|
||||
@@ -137,6 +137,7 @@ describe('gstack-models inspector', () => {
|
||||
[['bogus'], "unknown command 'bogus'"],
|
||||
[['resolve'], 'resolve needs --role'],
|
||||
[['resolve', '--role', 'coding'], "unknown role 'coding'"],
|
||||
[['resolve', '--role', 'outside-voice'], "the outside voice follows the harness, not the model policy (docs/model-policy.md"],
|
||||
[['resolve', '--role', 'plan-review'], 'needs --provider'],
|
||||
[['resolve', '--role', 'plan-review', '--provider', 'claude'], "unknown provider 'claude'"],
|
||||
[['resolve', '--role', 'implementation', '--provider', 'OpenAI'], "unknown provider 'OpenAI'"],
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
* forms the issue documents (it describes 13 replies but does not include them).
|
||||
* #3329: that same gate then printed `clean` for a parsed advisory finding
|
||||
* whose last `Verdict:` line says `not ready`. `bare-dash-p2.txt` is unchanged.
|
||||
* #3925: it printed `clean` for a `Verdict: Can't verify` reply, and
|
||||
* `FINDINGS: none` for a numbered finding labeled `Nonblocking` with no P-tag
|
||||
* (fixtures in test/fixtures/outside-review-severity/codex-3925/).
|
||||
*/
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
@@ -184,3 +187,70 @@ describe('#3329 a last not-ready Verdict blocks even with advisory findings', ()
|
||||
expect([failing.verdict, failing.score]).toEqual(['findings', 6]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#3925 an unrecognized verdict is not clean; numbered findings never print FINDINGS: none', () => {
|
||||
const FIX3925 = path.join(ROOT, 'test', 'fixtures', 'outside-review-severity', 'codex-3925');
|
||||
const cli3925 = (gate: OutsideGate, name: string) =>
|
||||
spawnSync(process.execPath, [LIB, '--verdict', '--label', 'Codex consult', '--exit', '0', gate, path.join(FIX3925, name)], { encoding: 'utf8', timeout: 10000 });
|
||||
const textFor = (gate: OutsideGate, text: string) => gate === 'review' ? `${text}\n${REC}` : text;
|
||||
const see = (text: string, gate: OutsideGate) => {
|
||||
const r = classifyOutsideReview({ text: textFor(gate, text), gate });
|
||||
return { verdict: r.verdict as string, reason: (r.reason ?? null) as string | null, unlabeled: r.findings.unlabeled ?? 0 };
|
||||
};
|
||||
|
||||
for (const [name, status, stdout] of [
|
||||
['cant-verify.txt', 4, 'VERDICT: unverified\nFINDINGS: none\nREASON: unverified_verdict\n'],
|
||||
['nonblocking-numbered.txt', 0, 'VERDICT: clean\nFINDINGS: unspecified\n'],
|
||||
['ready-clean.txt', 0, 'VERDICT: clean\nFINDINGS: none\n'],
|
||||
] as const) {
|
||||
test(`${name}: exit ${status}`, () => {
|
||||
const r = cli3925('execution', name);
|
||||
expect([r.status, r.stdout]).toEqual([status, stdout]);
|
||||
});
|
||||
}
|
||||
|
||||
test('a cannot-verify verdict prints its reason, the quoted verdict and the anchor', () => {
|
||||
const r = cli3925('execution', 'cant-verify.txt');
|
||||
expect(r.stderr).toContain('Codex consult: ran, verdict unverified (');
|
||||
expect(r.stderr).toContain("Verdict: Can't verify (one changed file excluded");
|
||||
expect(r.stderr).toContain('docs/troubleshooting.md#outside-review-unverified-verdict');
|
||||
expect(GATE_OUTCOMES.unverified_verdict).toMatchObject({ state: 'ran', anchor: 'outside-review-unverified-verdict' });
|
||||
expect(validateOutsideReview(read('no-findings.txt').replace('Verdict: ready', "Verdict: Can't verify"), 'execution').completed).toBe(false);
|
||||
});
|
||||
|
||||
test('every verdict that is not an approval, and an approval that says something was not checked, is unverified on every review gate', () => {
|
||||
for (const gate of ['execution', 'structured', 'review'] as const)
|
||||
for (const verdictLine of [
|
||||
"Verdict: Can't verify (suites blocked)", 'Verdict: cannot verify', 'Verdict: Unable to verify the Windows path',
|
||||
"**Verdict:** Can\u2019t verify", '### Verdict: blocked', 'Verdict: revise', 'Verdict:', '**Verdict:** `ready`',
|
||||
'Verdict: ready, but I could not verify the migration', 'Verdict: ready (unverified)',
|
||||
'Verdict: ready, though one changed file was excluded', 'Verdict: ready (tests not run, sandbox blocked)',
|
||||
'Verdict: `ready` (tests `not run`)', 'Verdict: Ready? Not until the migration is fixed.', 'Verdict: clean-up required before merge',
|
||||
'Verdict: ready, but I did not execute the suites', 'Verdict: ready (tests not executed)',
|
||||
'Verdict: no_findings', 'Verdict: NO_FINDINGS except the migration', 'Verdict: go with B.', 'Verdict: Proceed with the plan.',
|
||||
'Verdict: Ship it? No.', 'Verdict: Ready ? No.',
|
||||
])
|
||||
expect({ gate, verdictLine, ...see(`No issues found.\n${verdictLine}`, gate) }).toEqual({ gate, verdictLine, verdict: 'unverified', reason: 'unverified_verdict', unlabeled: 0 });
|
||||
});
|
||||
|
||||
test('numbered findings without a P-tag are counted, whatever their label', () => {
|
||||
for (const label of ['**Nonblocking — The log repeats.**', 'Nonblocking: the log repeats.', '**Minor** — the log repeats.', 'The log repeats the attempt count.'])
|
||||
expect({ label, ...see(`1. ${label}\nVerdict: ready`, 'execution') }).toEqual({ label, verdict: 'clean', reason: null, unlabeled: 1 });
|
||||
expect(see('1. **P3 — Rename it.**\n2. Nonblocking — the log repeats.\nVerdict: ready', 'execution')).toEqual({ verdict: 'clean', reason: null, unlabeled: 1 });
|
||||
expect(classifyOutsideReview({ text: fs.readFileSync(path.join(FIX3925, 'nonblocking-numbered.txt'), 'utf8'), gate: 'structured' })).toMatchObject({ verdict: 'unverified', reason: 'untagged_review', findings: { highest: null, unlabeled: 1 } });
|
||||
});
|
||||
|
||||
test('negative controls: real clean replies, consult answers, tagged findings and quoted examples stay as they were', () => {
|
||||
for (const gate of ['execution', 'structured', 'review'] as const) {
|
||||
expect({ gate, ...see(read('no-findings.txt'), gate) }).toEqual({ gate, verdict: 'clean', reason: null, unlabeled: 0 });
|
||||
for (const verdictLine of ['Verdict: Ready to merge.', 'Verdict: LGTM', 'Verdict: Approve', 'Verdict: Ship it', 'Verdict: NO_FINDINGS', 'Verdict: `NO_FINDINGS`', 'Verdict: ready. The `[P1]` from round 1 is fixed.'])
|
||||
expect({ gate, verdictLine, ...see(`No issues found.\n${verdictLine}`, gate) }).toEqual({ gate, verdictLine, verdict: 'clean', reason: null, unlabeled: 0 });
|
||||
expect({ gate, ...see('I checked:\n1. the retry path\n2. every caller\nNo issues found.\nVerdict: ready', gate) }).toEqual({ gate, verdict: 'clean', reason: null, unlabeled: 0 });
|
||||
}
|
||||
expect(see('No issues found.\n## Verdict\nReady.', 'execution')).toEqual({ verdict: 'clean', reason: null, unlabeled: 0 });
|
||||
expect(see('1. Use a queue.\n2. Add a retry cap.', 'execution')).toEqual({ verdict: 'clean', reason: null, unlabeled: 0 });
|
||||
expect(see('1. **P2 — The docs lag.**\n2. **P3 — Rename it.**\nVerdict: ready', 'execution')).toEqual({ verdict: 'clean', reason: null, unlabeled: 0 });
|
||||
expect(see('No issues found.\n```\n1. Nonblocking — example\nVerdict: cannot verify\n```\nVerdict: ready', 'execution')).toEqual({ verdict: 'clean', reason: null, unlabeled: 0 });
|
||||
expect(see('1. The retry path can double-send.\nVerdict: not ready', 'execution')).toEqual({ verdict: 'findings', reason: null, unlabeled: 1 });
|
||||
});
|
||||
});
|
||||
@@ -112,6 +112,12 @@ describe('host-subagent runner', () => {
|
||||
expect(meta.output_sha256).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(meta.verdict.verdict).toBe('clean');
|
||||
});
|
||||
test('prints the shared FINDINGS label: a numbered finding with no P-tag is unspecified, never none (#3925)', () => {
|
||||
const result = path.join(ROOT, 'test', 'fixtures', 'outside-review-severity', 'codex-3925', 'nonblocking-numbered.txt');
|
||||
const r = run(['run', '--runner', 'host-subagent', '--gate', 'structured', '--prompt', promptFile, '--out', path.join(TMP, 'host-3925.md'), '--result', result, '--model', 'openai/gpt-6-astra', '--native-model', 'claude-opus-4-7'], cleanEnv(emptyBin));
|
||||
expect(r.status, r.stderr).toBe(0);
|
||||
expect(r.stdout).toContain('VERDICT: unverified\nFINDINGS: unspecified\n');
|
||||
});
|
||||
test('without --result or --model it is unavailable (exit 3, OUTSIDE_RUNNER_UNAVAILABLE)', () => {
|
||||
const r = run(['run', '--runner', 'host-subagent', '--prompt', promptFile, '--out', path.join(TMP, 'no.md'), '--model', 'gpt-5.4'], cleanEnv(emptyBin));
|
||||
expect(r.status).toBe(3);
|
||||
|
||||
@@ -30,7 +30,7 @@ import * as path from 'node:path';
|
||||
import { afterEach } from 'bun:test';
|
||||
import { EXIT } from '../lib/headless-artifacts';
|
||||
import { capyHost, type CapyHost } from './helpers/capy-host';
|
||||
import { BASE_PREGATE, cleanup, commit, makeFixtureRepo, runBin, write, type FixtureRepo } from './helpers/pregate-fixture';
|
||||
import { BASE_PREGATE, cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture';
|
||||
|
||||
const repos: FixtureRepo[] = [];
|
||||
const hosts: CapyHost[] = [];
|
||||
@@ -50,16 +50,8 @@ const SERIAL_TEST = "const test = require('node:test');\ntest('serial', () => {}
|
||||
|
||||
/** The base branch gains the manifest, its check script and the given pregate config. */
|
||||
function guardedFixture(pregate: Record<string, unknown>): FixtureRepo {
|
||||
const repo = makeFixtureRepo({ pregate });
|
||||
const repo = makeFixtureRepo({ pregate, baseFiles: { 'scripts/check-serial.js': CHECK_SERIAL, 'scripts/serial-files.tsv': 'path\treason\n' } });
|
||||
repos.push(repo);
|
||||
repo.git('checkout', '-q', 'main');
|
||||
write(repo.work, 'scripts/check-serial.js', CHECK_SERIAL);
|
||||
write(repo.work, 'scripts/serial-files.tsv', 'path\treason\n');
|
||||
repo.git('add', '-A');
|
||||
repo.git('commit', '-q', '-m', 'serial manifest');
|
||||
repo.git('push', '-q', 'origin', 'main');
|
||||
repo.git('checkout', '-q', 'feature');
|
||||
repo.git('merge', '-q', '--ff-only', 'main');
|
||||
return repo;
|
||||
}
|
||||
const pregate = (repo: FixtureRepo, args: string[], env: Record<string, string> = {}) => runBin(repo, 'gstack-pregate', ['--base', 'main', ...args], env);
|
||||
@@ -92,7 +84,7 @@ describe('guards (CD1)', () => {
|
||||
expect(r.out).toContain('GSTACK_RESULT: skill=pregate status=incomplete');
|
||||
});
|
||||
|
||||
test('each guard runs in its own process with its timeout: a failing guard does not stop the next, a timed-out guard is incomplete, never pass', () => {
|
||||
test('each guard runs in its own process with its timeout: a failing guard does not stop the next, a timed-out guard never passes', () => {
|
||||
const repo = guardedFixture({ ...BASE_PREGATE, guards: [
|
||||
{ id: 'first', when: ['lib/**'], command: 'echo first-ran; exit 3' },
|
||||
{ id: 'second', when: ['lib/**'], command: 'touch ../second-ran' },
|
||||
@@ -108,6 +100,9 @@ describe('guards (CD1)', () => {
|
||||
expect(row.status).toBe('fail');
|
||||
expect(row.detail).toContain('first');
|
||||
expect(row.detail).not.toContain('second');
|
||||
});
|
||||
|
||||
test('a timed-out guard with no failing guard beside it is incomplete, never pass', () => {
|
||||
const slowOnly = guardedFixture({ ...BASE_PREGATE, guards: [{ id: 'slow', when: ['lib/**'], command: 'sleep 20', timeout_s: 1 }] });
|
||||
commit(slowOnly, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" });
|
||||
expect(pregate(slowOnly, ['--allow-repo-commands', '--stage', 'preflight', '--only', 'guards']).status).toBe(EXIT.fail);
|
||||
@@ -280,7 +275,7 @@ describe("gstack's own pre-push guards (GST-1138)", () => {
|
||||
|
||||
test('the list validates, every guard has a fix, and every test file it names exists', () => {
|
||||
expect(codes(policy)).toEqual([]);
|
||||
expect(guards.map(g => g.id).sort()).toEqual(['context-budget', 'doc-caps', 'goldens', 'module-size', 'parity-suite', 'skill-size', 'typecheck']);
|
||||
expect(guards.map(g => g.id).sort()).toEqual(['conflict-markers', 'context-budget', 'doc-caps', 'goldens', 'module-size', 'parity-suite', 'skill-size', 'typecheck']);
|
||||
for (const g of guards) {
|
||||
expect(g.fix, g.id).toBeTruthy();
|
||||
for (const f of g.command.match(/test\/[\w./-]+\.test\.ts/g) ?? []) expect(fs.existsSync(path.join(GSTACK, f)), `${g.id}: ${f}`).toBe(true);
|
||||
@@ -288,8 +283,8 @@ describe("gstack's own pre-push guards (GST-1138)", () => {
|
||||
});
|
||||
|
||||
test('each guard fires on its own inputs and none fires on a docs-only change', () => {
|
||||
expect(selected('ship/SKILL.md.tmpl')).toEqual(['context-budget', 'goldens', 'parity-suite', 'skill-size']);
|
||||
expect(selected('lib/pregate/index.ts')).toEqual(['module-size', 'typecheck']);
|
||||
expect(selected('ship/SKILL.md.tmpl')).toEqual(['conflict-markers', 'context-budget', 'goldens', 'parity-suite', 'skill-size']);
|
||||
expect(selected('lib/pregate/index.ts')).toEqual(['conflict-markers', 'module-size', 'typecheck']);
|
||||
expect(selected('test/fixtures/golden/claude-ship-SKILL.md')).toEqual(['goldens']);
|
||||
expect(selected('CLAUDE.md')).toEqual(['doc-caps']);
|
||||
expect(selected('docs/pregate.md')).toEqual([]);
|
||||
|
||||
@@ -263,6 +263,7 @@ describe('literals (pure)', () => {
|
||||
for (const [rel, text] of Object.entries(files)) { fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true }); fs.writeFileSync(path.join(root, rel), text); }
|
||||
const all = Object.keys(files);
|
||||
// A one-character value: only the file that names the constant counts; the path fragment alone is not enough for "2".
|
||||
// pregate-literal: GSTACK_CAPY_WRAPPER=3 a fixture's own 2 -> 3 bump, not the shipped wrapper revision
|
||||
expect(consumersOf(root, all, { name: 'GSTACK_CAPY_WRAPPER', old: '2', new: '3', file: 'capy/skill/gstack/scripts/install.sh' })).toEqual(['test/wrapper.test.ts:2']);
|
||||
// A longer value: the constant's name, the module's full file name, or its stem as a path fragment; the bare word "retry" in prose and "preretry.js" do not count.
|
||||
expect(consumersOf(root, all, { name: 'TIMEOUT_MS', old: '5000', new: '9000', file: 'lib/retry.js' })).toEqual(['test/retry.test.ts:1', 'test/retry-path.test.ts:2', 'test/retry-bare.test.ts:2']);
|
||||
|
||||
@@ -19,6 +19,8 @@ import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import { spawnSync } from 'child_process';
|
||||
import { hookChildBudgetMs } from '../hosts/claude/hooks/spawn-bin';
|
||||
import { launchSkipReason } from '../hosts/claude/hooks/question-log-hook.ts';
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, '..');
|
||||
const HOOK = path.join(ROOT, 'hosts', 'claude', 'hooks', 'question-log-hook');
|
||||
@@ -394,3 +396,59 @@ describe('PostToolUse hook (crash safety)', () => {
|
||||
expect(fs.readFileSync(errLog, 'utf-8')).toContain('stdin parse failed');
|
||||
});
|
||||
});
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// One budget for every child (Claude Code kills the hook at 5 s)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
describe('PostToolUse hook (budget)', () => {
|
||||
test('every child shares the registered 5 s budget, less the exit reserve', () => {
|
||||
expect(hookChildBudgetMs(1_000, 1_000)).toBe(4_500);
|
||||
expect(hookChildBudgetMs(1_000, 3_000)).toBe(2_500);
|
||||
expect(hookChildBudgetMs(1_000, 6_000)).toBeLessThan(0);
|
||||
});
|
||||
|
||||
test('a call launches only with at least 250 ms of budget left', () => {
|
||||
expect(launchSkipReason(4_500)).toBeNull();
|
||||
expect(launchSkipReason(250)).toBeNull();
|
||||
expect(launchSkipReason(249)).toBe("the hook's 5000 ms budget is spent (249 ms left, under the 250 ms a call needs)");
|
||||
expect(launchSkipReason(-40)).toBe("the hook's 5000 ms budget is spent (0 ms left, under the 250 ms a call needs)");
|
||||
});
|
||||
|
||||
test('slow children stop at the hook budget and the skipped questions are logged', () => {
|
||||
const fakeBin = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-slow-bun-'));
|
||||
try {
|
||||
fs.writeFileSync(path.join(fakeBin, 'bun'), `#!/bin/sh\nsleep 5\nexec "${process.execPath}" "$@"\n`, { mode: 0o755 });
|
||||
const env: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries(process.env)) {
|
||||
if (v !== undefined) env[k] = v;
|
||||
}
|
||||
env.GSTACK_STATE_ROOT = stateRoot;
|
||||
delete env.GSTACK_HOME;
|
||||
env.GSTACK_QUESTION_LOG_NO_DERIVE = '1';
|
||||
env.PATH = `${fakeBin}${path.delimiter}${env.PATH ?? ''}`;
|
||||
const questions = Array.from({ length: 6 }, (_, i) => ({ question: `Budget question ${i}`, options: ['A', 'B'] }));
|
||||
const res = spawnSync(process.execPath, [path.join(ROOT, 'hosts', 'claude', 'hooks', 'question-log-hook.ts')], {
|
||||
env,
|
||||
input: JSON.stringify({
|
||||
session_id: 'budget',
|
||||
tool_name: 'AskUserQuestion',
|
||||
tool_use_id: 'tu-budget',
|
||||
tool_input: { questions },
|
||||
tool_response: { answers: questions.map(() => ({ option_label: 'A' })) },
|
||||
cwd: ROOT,
|
||||
}),
|
||||
encoding: 'utf-8',
|
||||
cwd: ROOT,
|
||||
timeout: 30_000,
|
||||
});
|
||||
expect(res.status).toBe(0);
|
||||
expect(readLog().length).toBeLessThan(questions.length);
|
||||
const errors = fs.readFileSync(path.join(stateRoot, 'hook-errors.log'), 'utf-8');
|
||||
expect(errors).toMatch(/exited null \(SIG\w+ after \d+ of \d+ ms\)/);
|
||||
expect(errors).toContain('budget is spent');
|
||||
} finally {
|
||||
fs.rmSync(fakeBin, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -208,6 +208,35 @@ describe("pii.ip_public: a four-part version needs a version declaration (#2784)
|
||||
);
|
||||
});
|
||||
|
||||
describe("pii.ip_public: a four-part version gstack names is not an address (GST-1204)", () => {
|
||||
table(
|
||||
"pii.ip_public",
|
||||
"MEDIUM",
|
||||
[
|
||||
"gstack 1.94.4.0",
|
||||
"gstack: ok 1.94.4.0 for=ship",
|
||||
"gstack: fail claude,codex (1.93.37.0)",
|
||||
"upgraded gstack from 1.93.14.0 to 1.94.4.0",
|
||||
"seen on gstack 1.94.4.0 to 1.94.8.0",
|
||||
"(gstack 1.94.4.0-1.94.8.0)",
|
||||
],
|
||||
[
|
||||
"gstack talks to 8.8.8.8",
|
||||
"gstack-proxy 1.128.1.0",
|
||||
"landed in 1.94.4.0",
|
||||
"gstack 1.94.4.0 via 8.8.8.8",
|
||||
"from 1.128.1.0 to 1.128.1.1",
|
||||
"gstack 8.8.8.8",
|
||||
"gstack: fail 8.8.8.8",
|
||||
"upgraded gstack from 8.8.8.8",
|
||||
"my-gstack 1.94.4.0",
|
||||
"/opt/gstack 1.94.4.0",
|
||||
"gstack 1.94.4.0 - 8.8.8.8",
|
||||
"VERSION 1.2.3.4 to 8.8.8.8",
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
describe("db.url_with_password: postgres:postgres only on a loopback host (#2913)", () => {
|
||||
// Assembled from parts so this file's own source never carries a
|
||||
// credential-bearing URL for the repo's secret scan to block.
|
||||
@@ -296,3 +325,30 @@ describe("pii.phone.e164: GitHub Actions run and job ids in their id positions",
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
describe("pii.phone.e164: run ids in a runs= list or an actions/runs/ path (GST-1227)", () => {
|
||||
table(
|
||||
"pii.phone.e164",
|
||||
"MEDIUM",
|
||||
[
|
||||
// The run list a CI carry or run clear prints (lib/run-evidence.ts runReceiptFields): every id, not only the first.
|
||||
"CI_CARRY: cleared pregate.json/remote_gate run tests=412 runs=41629861819/1,41629861820/2 profiles=free-tests heads=2f9d11a0c3e4",
|
||||
'{"remote_gate": "carried runs=41629861819/1,41629861820/1,41629861821/3 profiles=free-tests,windows-smoke"}',
|
||||
"run=41629861819/1,416298618201/1",
|
||||
"see actions/runs/41629861820 for the log",
|
||||
"garrytan/gstack actions/runs/4162986182/attempts/2",
|
||||
],
|
||||
[
|
||||
"call +1 415 555 0123 tomorrow",
|
||||
"call +1 415 555 0123 about runs=41629861819/1,41629861820/2",
|
||||
"runs=+14155550123/1",
|
||||
"runs=1/4155550123",
|
||||
"runs=4155550123",
|
||||
"reruns=4155550123/1",
|
||||
"factions/runs/4155550123",
|
||||
"sales-actions/runs/4155550123",
|
||||
"runs=4162986182/1",
|
||||
"runs=1234567890123/1",
|
||||
],
|
||||
);
|
||||
});
|
||||
@@ -249,6 +249,50 @@ describe('release-cut: planning', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('release-cut: the release gate holds and gates (lib/release-gate.ts records)', () => {
|
||||
const release = (sha: string, verdict: string, run: number) => ({ schema: 1, kind: 'release', repo_key: 'k', sha, verdict, run: { id: run, url: 'u' }, red_cases: verdict === 'RED' ? ['case-a'] : [], created_at: 'x', updated_at: 'x' });
|
||||
const note = (f: ReturnType<typeof fixture>, record: unknown, on: string) => {
|
||||
git(f.seed, 'notes', '--ref=' + NOTES_REF, 'add', '-f', '-m', JSON.stringify(record), on);
|
||||
git(f.seed, 'push', '-q', '-f', 'origin', NOTES_REF);
|
||||
};
|
||||
|
||||
// Value: protects=a red release record is the freeze: every cut is refused while no green gate sits on a later commit that contains the red one,
|
||||
// even when every check run is green, and an incomplete gate or a green gate on an older commit does not lift it; fails_when=release-cut releases a
|
||||
// commit while the newest release gate is red, a green record anywhere clears the hold, or an INCOMPLETE gate clears it; why_new=the freeze tests know
|
||||
// only the train freeze record; seam=none; no_claim=real refs/notes/gstack-trains content (fixture records shaped like ReleaseRecord)
|
||||
test('a red release record refuses the cut; only a green gate on a later commit lifts it', () => {
|
||||
const f = fixture();
|
||||
note(f, release(f.shas['1.0.2']!, 'RED', 41), f.shas['1.0.2']!);
|
||||
note(f, release(f.shas['1.0.1']!, 'GREEN', 40), f.shas['1.0.1']!);
|
||||
const held = planRelease({ repo: f.repo, git: f.git, gh: f.gh });
|
||||
expect(held.ok).toBe(false);
|
||||
if (!held.ok) { expect(held.code).toBe('REFUSED'); expect(held.message).toContain('release gate red on ' + f.shas['1.0.2']!.slice(0, 12)); }
|
||||
note(f, release(f.shas['1.0.3']!, 'INCOMPLETE', 42), f.shas['1.0.3']!);
|
||||
expect(planRelease({ repo: f.repo, git: f.git, gh: f.gh }).ok).toBe(false);
|
||||
note(f, release(f.shas['1.0.3']!, 'GREEN', 43), f.shas['1.0.3']!);
|
||||
const lifted = planRelease({ repo: f.repo, git: f.git, gh: f.gh });
|
||||
expect(lifted.ok, JSON.stringify(lifted)).toBe(true);
|
||||
if (lifted.ok) expect(lifted.plan.sha).toBe(f.shas['1.0.3']);
|
||||
});
|
||||
|
||||
// Value: protects=a green release record gates its commit when the main-backstop check run is absent or neutral (the check publish failed or was
|
||||
// superseded), and the CANDIDATE line names the gate run; a red check run still keeps the commit out; fails_when=a commit the release gate passed is
|
||||
// never released without the check, or release evidence overrides a red check run; why_new=train records were the only notes evidence; seam=none;
|
||||
// no_claim=a live gate run
|
||||
test('a green release record gates a commit whose main-backstop check never ran; a red check run still wins', () => {
|
||||
const f = fixture();
|
||||
const head = f.shas['1.0.3']!;
|
||||
f.state.checks[head] = GREEN.filter(c => c.name !== BACKSTOP_CHECK);
|
||||
note(f, release(head, 'GREEN', 77), head);
|
||||
const gated = planRelease({ repo: f.repo, git: f.git, gh: f.gh });
|
||||
expect(gated.ok, JSON.stringify(gated)).toBe(true);
|
||||
if (gated.ok) { expect(gated.plan.sha).toBe(head); expect(gated.plan.via).toBe('release gate run 77'); }
|
||||
f.state.checks[head] = [...GREEN.filter(c => c.name !== BACKSTOP_CHECK), { name: 'quality', status: 'completed', conclusion: 'failure' }];
|
||||
const red = planRelease({ repo: f.repo, git: f.git, gh: f.gh });
|
||||
if (red.ok) expect(red.plan.sha).not.toBe(head);
|
||||
});
|
||||
});
|
||||
|
||||
describe('release-cut: train evidence gates a commit whose backstop never settled', () => {
|
||||
const train = (nonce: string, state: string, merged: Array<{ sha: string; tree: string }>) =>
|
||||
({ schema: 1, kind: 'train', nonce, state, merged: merged.map(m => ({ pr: '1', at: 'x', ...m })), updated_at: 'x' });
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* The release gate's workflow wiring (docs/ship-policy.md#release-gate):
|
||||
* release-gate.yml runs bin/gstack-release-gate on its schedule and publishes
|
||||
* the gated commit's check run from a code-free job; the per-push backstop
|
||||
* stands down once main's policy declares a release_gate block; evals.yml routes
|
||||
* a release bisect only under that block. Policy steps run for real (bash, git,
|
||||
* jq) against a scratch repository; the rest is read from the YAML.
|
||||
*/
|
||||
import { afterAll, describe, expect, test } from 'bun:test';
|
||||
import { execFileSync, spawnSync } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { RELEASE_GATE_SCHEDULE_HOURS } from '../lib/release-gate-policy';
|
||||
import { RELEASE_BISECT_ARTIFACT } from '../scripts/train-gate';
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, '..');
|
||||
type Step = { id?: string; name?: string; uses?: string; if?: string; run?: string; env?: Record<string, string> };
|
||||
type Job = { if?: string; needs?: string; outputs?: Record<string, string>; permissions?: Record<string, string>; steps: Step[] };
|
||||
type Workflow = { on: Record<string, any>; concurrency: unknown; permissions?: unknown; jobs: Record<string, Job> };
|
||||
const load = (rel: string) => Bun.YAML.parse(fs.readFileSync(path.join(ROOT, rel), 'utf8')) as Workflow;
|
||||
const release = load('.github/workflows/release-gate.yml');
|
||||
const backstop = load('.github/workflows/evals-main-backstop.yml');
|
||||
const evals = load('.github/workflows/evals.yml');
|
||||
const scratch: string[] = [];
|
||||
afterAll(() => { for (const d of scratch) fs.rmSync(d, { recursive: true, force: true }); });
|
||||
const GIT_ENV = { GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@x', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@x' };
|
||||
|
||||
/**
|
||||
* Run a policy step's script in a scratch repo whose one commit holds this policy; returns its GITHUB_OUTPUT lines as an object.
|
||||
* Git Bash's argument conversion is off, as on the Linux runners these steps run on: it rewrites `origin/main:.gstack/…` into a path list.
|
||||
*/
|
||||
function runStep(step: Step, policy: unknown): Record<string, string> {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'release-gate-wf-'));
|
||||
scratch.push(dir);
|
||||
const g = (...args: string[]) => execFileSync('git', args, { cwd: dir, encoding: 'utf8', timeout: 30_000, env: { ...process.env, ...GIT_ENV } }).trim();
|
||||
g('init', '-q', '-b', 'main');
|
||||
if (policy !== undefined) {
|
||||
fs.mkdirSync(path.join(dir, '.gstack'));
|
||||
fs.writeFileSync(path.join(dir, '.gstack/ship-policy.json'), JSON.stringify(policy));
|
||||
}
|
||||
fs.writeFileSync(path.join(dir, 'README'), 'x');
|
||||
g('add', '-A');
|
||||
g('commit', '-q', '-m', 'base');
|
||||
const sha = g('rev-parse', 'HEAD');
|
||||
g('update-ref', 'refs/remotes/origin/main', sha);
|
||||
const out = path.join(dir, 'out');
|
||||
const r = spawnSync('bash', ['-e', '-c', step.run!], {
|
||||
cwd: dir, encoding: 'utf8', timeout: 30_000,
|
||||
env: { ...process.env, MSYS_NO_PATHCONV: '1', MSYS2_ARG_CONV_EXCL: '*', GITHUB_OUTPUT: out, GITHUB_STEP_SUMMARY: path.join(dir, 'summary'), GITHUB_SHA: sha, BASE_SHA: '', DEFAULT_BRANCH: 'main' },
|
||||
});
|
||||
expect(r.status, r.stderr).toBe(0);
|
||||
const lines = (fs.existsSync(out) ? fs.readFileSync(out, 'utf8') : '').split('\n').filter(Boolean);
|
||||
return Object.fromEntries(lines.map(l => [l.slice(0, l.indexOf('=')), l.slice(l.indexOf('=') + 1)]));
|
||||
}
|
||||
const GATE = { cadence_hours: 8, gate_workflow: 'evals.yml', branch: 'main', stable_ref: 'stable', check_name: 'main-backstop', on_red: 'hold-release', bisect_spend_cap_usd: 40 };
|
||||
const TRAIN = { gate_workflow: 'evals.yml', record_artifact: 'gstack-train-record', full_gate_check: 'gstack/full-gate' };
|
||||
|
||||
describe('release-gate.yml', () => {
|
||||
// Value: protects=the schedule fires every RELEASE_GATE_SCHEDULE_HOURS (the cadence floor the policy validates), one gate at a time, only from the
|
||||
// default branch, with contents and actions write but no checks write, and runs the bin without --sha (main's head from the remote, so an open gate on an older commit
|
||||
// is finished first) with its outputs wired, and a held or failed verdict leaves the job green (only a crash fails it, so main's head never carries a
|
||||
// failed native check release-cut would read as red); the policy step
|
||||
// uses git and jq only and is inert without a release_gate block; fails_when=the cron and the cadence drift apart, two gates overlap, the job that
|
||||
// runs repository code can write check runs, or an inert policy reaches bun; why_new=new workflow; seam=none; no_claim=GitHub's cron jitter
|
||||
test('schedule, concurrency, permissions and the gate step', () => {
|
||||
const cron = release.on.schedule[0].cron as string;
|
||||
expect(cron).toMatch(/^\d+ \*\/\d+ \* \* \*$/);
|
||||
expect(Number(cron.split(' ')[1]!.slice(2))).toBe(RELEASE_GATE_SCHEDULE_HOURS);
|
||||
expect(Object.keys(release.on).sort()).toEqual(['schedule', 'workflow_dispatch']);
|
||||
expect(Object.keys(release.on.workflow_dispatch.inputs).sort()).toEqual(['dry_run', 'ignore_cadence']);
|
||||
expect(release.concurrency).toEqual({ group: 'release-gate', 'cancel-in-progress': false });
|
||||
expect(release.permissions).toEqual({});
|
||||
const job = release.jobs['release-gate']!;
|
||||
expect(job.if).toBe('github.ref_name == github.event.repository.default_branch');
|
||||
expect(job.permissions).toEqual({ contents: 'write', actions: 'write', checks: 'read' });
|
||||
const policy = job.steps.find(s => s.id === 'policy')!;
|
||||
expect(policy.run).not.toContain('bun');
|
||||
expect(runStep(policy, undefined)).toEqual({ release: 'false' });
|
||||
expect(runStep(policy, { train: TRAIN })).toEqual({ release: 'false' });
|
||||
expect(runStep(policy, { release_gate: GATE })).toEqual({ release: 'true' });
|
||||
const gate = job.steps.find(s => s.id === 'gate')!;
|
||||
expect(gate.if).toBe("steps.policy.outputs.release == 'true'");
|
||||
expect(gate.run).toContain('./bin/gstack-release-gate run --repo "$GITHUB_REPOSITORY" --budget-minutes');
|
||||
expect(gate.run).not.toContain('--sha');
|
||||
expect(gate.run).toContain("|| rc=$?");
|
||||
expect(gate.run).toContain(`if [ "$rc" != 0 ] && ! grep -qE '^action=(held|failed)$' "$GITHUB_OUTPUT"; then exit "$rc"; fi`);
|
||||
expect(gate.run).toContain('--outputs "$GITHUB_OUTPUT"');
|
||||
expect(job.outputs).toEqual({ action: '${{ steps.gate.outputs.action }}', sha: '${{ steps.gate.outputs.sha }}', check: '${{ steps.gate.outputs.check }}' });
|
||||
});
|
||||
|
||||
// Value: protects=the gated commit's check run (what release-cut reads) comes from a job with checks: write and no checkout or action, only for a
|
||||
// gate that ran (success for gated, failure for held, neutral for failed so a later green on the same sha stays releasable), on a validated sha
|
||||
// and check name; fails_when=repository code runs with checks: write, a skipped or inert run publishes a check, a red gate publishes success, or
|
||||
// an unfinished gate leaves a failure release-cut reads as red; why_new=new workflow; seam=none; no_claim=GitHub's check API
|
||||
test('the check run is published from a code-free job, success only for gated', () => {
|
||||
const job = release.jobs['release-check']!;
|
||||
expect(job.needs).toBe('release-gate');
|
||||
expect(job.if).toContain("contains(fromJSON('[\"gated\",\"held\",\"failed\"]'), needs.release-gate.outputs.action)");
|
||||
expect(job.permissions).toEqual({ checks: 'write' });
|
||||
expect(job.steps.filter(s => s.uses)).toEqual([]);
|
||||
const run = job.steps[0]!.run!;
|
||||
expect(run).toContain('gated) conclusion=success ;;');
|
||||
expect(run).toContain('held) conclusion=failure ;;');
|
||||
expect(run).toContain('failed) conclusion=neutral ;;');
|
||||
expect(run).toContain('[[ "$SHA" =~ ^[0-9a-f]{40}$ ]]');
|
||||
expect(run).toContain('-f name="$CHECK" -f head_sha="$SHA"');
|
||||
expect(run).not.toContain('bun');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the backstop stands down and evals.yml routes the release bisect', () => {
|
||||
// Value: protects=while trains exist the per-push backstop keeps gating, and once main declares release_gate it stands down (train=false: no gate,
|
||||
// no freeze, no check run), so main is never gated twice; fails_when=both gates run on main, or the backstop stops before the release gate is on;
|
||||
// why_new=new stand-down rule; seam=none; no_claim=a live push
|
||||
test('evals-main-backstop.yml: train=true with only a train block, train=false once release_gate is declared', () => {
|
||||
const policy = backstop.jobs.backstop!.steps.find(s => s.id === 'policy')!;
|
||||
expect(runStep(policy, { train: TRAIN })).toEqual({ train: 'true' });
|
||||
expect(runStep(policy, { train: TRAIN, release_gate: GATE })).toEqual({ train: 'false' });
|
||||
});
|
||||
|
||||
// Value: protects=the route job reads release_gate from the base revision with git and jq only and hands it to the route as RELEASE_POLICY, and the
|
||||
// bisect jobs name their artifact from the route's record_artifact first (gstack-release-record for a release bisect); fails_when=a release bisect
|
||||
// publishes under the train artifact name the gate never reads, or repository code decides the release policy; why_new=new route input;
|
||||
// seam=none; no_claim=a live bisect run
|
||||
test('evals.yml: the release policy step, the RELEASE_POLICY input and the record_artifact override', () => {
|
||||
const route = evals.jobs.route!;
|
||||
const step = route.steps.find(s => s.id === 'release_policy')!;
|
||||
expect(step.run).not.toContain('bun');
|
||||
expect(runStep(step, { release_gate: GATE })).toEqual({ release: 'true' });
|
||||
expect(runStep(step, { train: TRAIN })).toEqual({ release: 'false' });
|
||||
expect(runStep(step, undefined)).toEqual({ release: 'false' });
|
||||
const ids = route.steps.map(s => s.id);
|
||||
expect(ids.indexOf('release_policy')).toBeLessThan(ids.indexOf('route'));
|
||||
expect(route.steps.find(s => s.id === 'route')!.env!.RELEASE_POLICY).toBe('${{ steps.release_policy.outputs.release }}');
|
||||
expect(route.outputs!.record_artifact).toBe('${{ steps.route.outputs.record_artifact || steps.policy.outputs.record_artifact }}');
|
||||
expect(RELEASE_BISECT_ARTIFACT).toBe('gstack-release-record');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,396 @@
|
||||
/**
|
||||
* gstack-release-gate (lib/release-gate.ts, docs/ship-policy.md#release-gate):
|
||||
* the full paid gate on main's head at most once per cadence and only when main
|
||||
* moved, a release record in refs/notes/gstack-trains, a bisect of a red gate's
|
||||
* cases over the commits since the last green gate, and the hold release-cut
|
||||
* reads. GitHub is a fake gh (dispatch, run list, run view, artifact download);
|
||||
* git, the notes ref and origin are real (a bare origin on disk).
|
||||
*/
|
||||
import { afterAll, afterEach, describe, expect, test } from 'bun:test';
|
||||
import { execFileSync, spawnSync } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { bunIsolationArgs } from '../lib/bun-isolation';
|
||||
import {
|
||||
MAX_RELEASE_ATTEMPTS, OPEN_GATE_CADENCES, activeHold, bisectGate, classifyRun, gateStatus, loadReleaseGate, narrow, parseReport, planPrefixes, releaseRecords, runGate,
|
||||
type GateEnv, type Run,
|
||||
} from '../lib/release-gate';
|
||||
import { RELEASE_GATE_SCHEDULE_HOURS, releaseGateErrors, type ReleaseGatePolicy } from '../lib/release-gate-policy';
|
||||
import { RELEASE_GATE_KEY_VERSION, validatePolicy } from '../lib/ship-policy';
|
||||
import { NOTES_REF, repoIdentity, type PrefixResult, type ReleaseRecord } from '../lib/ship-queue-train-record';
|
||||
import { gitIn } from '../scripts/train-gate';
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, '..');
|
||||
const GATE: ReleaseGatePolicy = { cadence_hours: 8, gate_workflow: 'evals.yml', branch: 'main', stable_ref: 'stable', check_name: 'main-backstop', on_red: 'hold-release', bisect_spend_cap_usd: 40 };
|
||||
const roots: string[] = [];
|
||||
const savedStateRoot = process.env.GSTACK_STATE_ROOT;
|
||||
afterEach(() => { if (savedStateRoot === undefined) delete process.env.GSTACK_STATE_ROOT; else process.env.GSTACK_STATE_ROOT = savedStateRoot; });
|
||||
afterAll(() => { for (const r of roots) fs.rmSync(r, { recursive: true, force: true }); });
|
||||
|
||||
const ID = { GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@x', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@x' };
|
||||
const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000, env: { ...process.env, ...ID } }).trim();
|
||||
|
||||
/** origin with base (also stable) and c1..c5 on main, and work cloned from it; the state root is the fixture's own. */
|
||||
function fixture() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'release-gate-'));
|
||||
roots.push(root);
|
||||
const origin = path.join(root, 'origin.git');
|
||||
const seed = path.join(root, 'seed');
|
||||
const work = path.join(root, 'work');
|
||||
git(root, 'init', '-q', '--bare', '-b', 'main', origin);
|
||||
fs.mkdirSync(seed);
|
||||
git(seed, 'init', '-q', '-b', 'main');
|
||||
git(seed, 'remote', 'add', 'origin', origin);
|
||||
const commit = (name: string) => { fs.writeFileSync(path.join(seed, 'VERSION'), name + '\n'); git(seed, 'add', '-A'); git(seed, 'commit', '-q', '-m', name); git(seed, 'push', '-q', 'origin', 'main'); return git(seed, 'rev-parse', 'HEAD'); };
|
||||
const base = commit('base');
|
||||
git(seed, 'push', '-q', 'origin', 'main:stable');
|
||||
const c = [1, 2, 3, 4, 5].map(i => commit('c' + i));
|
||||
git(root, 'clone', '-q', origin, work);
|
||||
process.env.GSTACK_STATE_ROOT = path.join(root, 'state');
|
||||
return { root, origin, seed, work, base, c, commit };
|
||||
}
|
||||
|
||||
interface Outcome { conclusion: string; artifacts: Record<string, Record<string, string>>; status?: string }
|
||||
/** A fake gh: each dispatch becomes a completed run whose outcome the test decides; run list, run view and artifact download read it back. */
|
||||
function fakeGh(onDispatch: (inputs: Record<string, string>, ref: string) => Outcome) {
|
||||
const runs: Run[] = [];
|
||||
const artifacts = new Map<number, Record<string, Record<string, string>>>();
|
||||
const dispatches: Array<{ ref: string; inputs: Record<string, string> }> = [];
|
||||
const gh = (args: string[]) => {
|
||||
const ok = (out: unknown) => ({ status: 0, stdout: typeof out === 'string' ? out : JSON.stringify(out), stderr: '' });
|
||||
if (args[0] === 'workflow' && args[1] === 'run') {
|
||||
const ref = args[args.indexOf('--ref') + 1]!;
|
||||
const inputs = Object.fromEntries(args.flatMap((a, i) => (args[i - 1] === '-f' ? [a.split(/=(.*)/s).slice(0, 2)] : [])));
|
||||
dispatches.push({ ref, inputs });
|
||||
const id = 1000 + runs.length;
|
||||
const o = onDispatch(inputs, ref);
|
||||
runs.push({ id, status: o.status ?? 'completed', conclusion: o.conclusion, head_sha: inputs.expected_sha!, display_title: 'E2E Evals [eval-bg ' + inputs.nonce + ']', html_url: 'https://github.com/o/r/actions/runs/' + id, run_attempt: 1 });
|
||||
artifacts.set(id, o.artifacts);
|
||||
return ok('');
|
||||
}
|
||||
if (args[0] === 'api' && args.some(a => /\/actions\/workflows\/[^/]+\/runs$/.test(a))) return ok({ workflow_runs: [...runs].reverse() });
|
||||
const view = args[0] === 'api' ? /actions\/runs\/(\d+)$/.exec(args[1] ?? '') : null;
|
||||
if (view) return ok(runs.find(r => r.id === Number(view[1])));
|
||||
if (args[0] === 'run' && args[1] === 'download') {
|
||||
const files = artifacts.get(Number(args[2]))?.[args[args.indexOf('-n') + 1]!];
|
||||
if (!files) return { status: 1, stdout: '', stderr: 'no artifact matches any of the names or patterns provided' };
|
||||
const dir = args[args.indexOf('-D') + 1]!;
|
||||
for (const [name, text] of Object.entries(files)) { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, name), text); }
|
||||
return ok('');
|
||||
}
|
||||
return { status: 1, stdout: '', stderr: 'unexpected gh ' + args.join(' ') };
|
||||
};
|
||||
return { gh, runs, dispatches };
|
||||
}
|
||||
|
||||
const report = (verdict: 'GREEN' | 'RED', failed: string[] = [], cost = '37.40') => ({ 'report-verdict-a1': { 'report.txt': [
|
||||
'[test:paid] report: 17/17 slices, 85 planned shards, tier=gate, attempt 1',
|
||||
...(failed.length ? ['FAILED cases:', ...failed.map(l => ' ✗ ' + l)] : []),
|
||||
'[test:paid] VERDICT ' + verdict + ' — lane gate/full census, attempt 1',
|
||||
' wall 41m02s · cost $' + cost + ' known + 4 of 139 trial(s) cost unknown',
|
||||
].join('\n') } });
|
||||
const green = (flaky: string[] = []): Outcome => ({ conclusion: 'success', artifacts: { ...report('GREEN'), ...(flaky.length ? { 'flake-records-a1': { 'flake-records.jsonl': flaky.map(c => JSON.stringify({ schema: 1, kind: 'gate-flake', case: c })).join('\n') } } : {}) } });
|
||||
|
||||
function envFor(f: ReturnType<typeof fixture>, gh: (args: string[]) => { status: number; stdout: string; stderr: string }, shiftHours = 0): GateEnv {
|
||||
return { repo: 'o/r', repoRoot: f.work, remote: 'origin', gh, git: gitIn(f.work), now: () => Date.now() + shiftHours * 3_600_000, sleep: () => {}, random: () => 'abc123', pollMs: 1, deadline: Date.now() + 3_600_000 };
|
||||
}
|
||||
const records = (f: ReturnType<typeof fixture>) => {
|
||||
git(f.work, 'fetch', '-q', 'origin', '+' + NOTES_REF + ':' + NOTES_REF);
|
||||
return releaseRecords(gitIn(f.work), repoIdentity(f.work).key);
|
||||
};
|
||||
|
||||
describe('release gate: run', () => {
|
||||
// Value: protects=a gate only when main moved: the first run dispatches the full gate once on main's head (evals_all, expected_sha, a backstop nonce),
|
||||
// records GREEN with its run, cost and rule-16 flaky cases in origin's notes and prints the RELEASE green line without moving stable; a second run on
|
||||
// the same head, and a head equal to stable, skip without dispatching; fails_when=the gate dispatches again on an unchanged main (a $37 repeat), a
|
||||
// green gate moves stable, or the record never reaches origin; why_new=new module; seam=fake gh; no_claim=a live gate run (the PR's one live proof)
|
||||
test('green: one dispatch on the moved head, a GREEN release record on origin, stable untouched; an unchanged main skips', () => {
|
||||
const f = fixture();
|
||||
const fake = fakeGh(() => green(['judge-x']));
|
||||
const head = f.c[4]!;
|
||||
const out = runGate(envFor(f, fake.gh), { gate: GATE, label: 'test', dryRun: false, ignoreCadence: false });
|
||||
expect(out.action, out.lines.join('\n')).toBe('gated');
|
||||
expect(fake.dispatches).toHaveLength(1);
|
||||
expect(fake.dispatches[0]!.ref).toBe('main');
|
||||
expect(fake.dispatches[0]!.inputs).toMatchObject({ evals_all: 'true', expected_sha: head });
|
||||
expect(fake.dispatches[0]!.inputs.nonce).toMatch(/^gate\.backstop-/);
|
||||
expect(out.lines).toContain('RELEASE: green sha=' + head + ' stable=' + f.base + ' run=1000 cost=37.40');
|
||||
expect(out.lines.some(l => l.includes('flaky (failed once, passed its one rule-16 rerun in run 1000): judge-x'))).toBe(true);
|
||||
const [rec] = records(f);
|
||||
expect(rec).toMatchObject({ kind: 'release', sha: head, verdict: 'GREEN', flaky: ['judge-x'], cost_usd: 37.4, since: f.base, attempts: 1, run: { id: 1000 } });
|
||||
expect(git(f.seed, 'ls-remote', 'origin', 'refs/heads/stable').split('\t')[0]).toBe(f.base);
|
||||
|
||||
const again = runGate(envFor(f, fake.gh, 9), { gate: GATE, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(again.action).toBe('skipped');
|
||||
expect(again.lines[0]).toContain('main has not moved since the last gate: GREEN run 1000');
|
||||
git(f.seed, 'push', '-q', '-f', 'origin', 'main:stable');
|
||||
const atStable = runGate(envFor(f, fake.gh), { gate: GATE, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(atStable.lines[0]).toContain('main has not moved since stable');
|
||||
expect(fake.dispatches).toHaveLength(1);
|
||||
});
|
||||
|
||||
// Value: protects=without a release_gate block nothing runs; --dry-run names the head, the base and the pending count and writes and dispatches
|
||||
// nothing; the cadence holds a moved main until cadence_hours minus the grace pass, and --ignore-cadence gates now; fails_when=an inert policy spends,
|
||||
// a dry run writes a record, or the schedule gates more often than the policy says; why_new=new module; seam=fake gh and a shifted clock;
|
||||
// no_claim=GitHub's cron timing
|
||||
test('inert, dry run and cadence: nothing is spent until the policy and the clock allow it', () => {
|
||||
const f = fixture();
|
||||
const fake = fakeGh(() => green());
|
||||
expect(runGate(envFor(f, fake.gh), { gate: null, label: 'origin/main@x', dryRun: false, ignoreCadence: false }).action).toBe('inert');
|
||||
const dry = runGate(envFor(f, fake.gh), { gate: GATE, label: 'test', dryRun: true, ignoreCadence: false });
|
||||
expect(dry.action).toBe('dry-run');
|
||||
expect(dry.lines[0]).toBe('RELEASE: gate sha=' + f.c[4] + ' since=' + f.base.slice(0, 12) + ' (stable) pending=5 stable=' + f.base.slice(0, 12));
|
||||
expect(fake.dispatches).toHaveLength(0);
|
||||
expect(spawnSync('git', ['ls-remote', 'origin', NOTES_REF], { cwd: f.work, encoding: 'utf8', timeout: 30_000 }).stdout).toBe('');
|
||||
|
||||
expect(runGate(envFor(f, fake.gh), { gate: GATE, label: 'test', dryRun: false, ignoreCadence: false }).action).toBe('gated');
|
||||
const next = f.commit('c6');
|
||||
const early = runGate(envFor(f, fake.gh, 2), { gate: GATE, label: 'test', dryRun: false, ignoreCadence: false });
|
||||
expect(early.action).toBe('skipped');
|
||||
expect(early.lines[0]).toMatch(/the last gate was dispatched 2\.0 h ago on [0-9a-f]{12}; cadence 8 h/);
|
||||
const due = runGate(envFor(f, fake.gh, 7.5), { gate: GATE, label: 'test', dryRun: false, ignoreCadence: false });
|
||||
expect(due.action, due.lines.join('\n')).toBe('gated');
|
||||
expect(fake.dispatches.map(d => d.inputs.expected_sha)).toEqual([f.c[4], next]);
|
||||
expect(records(f).find(r => r.sha === next)?.since).toBe(f.c[4]);
|
||||
});
|
||||
|
||||
// Value: protects=an INCOMPLETE census (only INFRA reds) is recorded as such, re-dispatched once by the next run (EVAL_POLICY.infraRedispatch), then
|
||||
// skipped with its run named, and never treated as green or red; fails_when=an infra-only failure holds the release like a red, is retried without
|
||||
// end, or is never retried; why_new=new module; seam=fake gh; no_claim=a real runner loss
|
||||
test('incomplete: recorded, re-dispatched once, then skipped with the run named', () => {
|
||||
const f = fixture();
|
||||
const fake = fakeGh(() => ({ conclusion: 'failure', artifacts: report('RED', ['case-a rule FAIL INFRA']) }));
|
||||
const env = envFor(f, fake.gh);
|
||||
const first = runGate(env, { gate: GATE, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(first.action).toBe('failed');
|
||||
expect(first.lines.at(-1)).toContain('RELEASE: incomplete sha=' + f.c[4] + ' run=1000');
|
||||
expect(first.lines.at(-1)).toContain('the next run re-dispatches it once');
|
||||
expect(runGate(env, { gate: GATE, label: 'test', dryRun: false, ignoreCadence: true }).action).toBe('failed');
|
||||
const third = runGate(env, { gate: GATE, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(third.action).toBe('skipped');
|
||||
expect(third.lines[0]).toContain('incomplete ' + MAX_RELEASE_ATTEMPTS + ' times');
|
||||
expect(fake.dispatches).toHaveLength(MAX_RELEASE_ATTEMPTS);
|
||||
expect(activeHold(records(f), () => true)).toBeNull();
|
||||
});
|
||||
|
||||
// Value: protects=a gate run still going at the budget stays PENDING with its run, and the next run finishes that verdict on the old commit before
|
||||
// gating main's new head, so a red verdict still records RED and holds release-cut after main moved; the new head is gated on the run after;
|
||||
// fails_when=main moving orphans a PENDING record and its red verdict never becomes a hold; why_new=review finding (red-team, l1-p1); seam=fake gh;
|
||||
// no_claim=a real six-hour run
|
||||
test('an unfinished gate is finished on its own commit after main moves, then the new head is gated', () => {
|
||||
const f = fixture();
|
||||
let dispatched = 0;
|
||||
const fake = fakeGh(() => (dispatched++ === 0 ? { conclusion: 'failure', status: 'in_progress', artifacts: report('RED', ['case-a rule FAIL VERDICT']) } : green()));
|
||||
const gate = { ...GATE, bisect_spend_cap_usd: 0 };
|
||||
const first = runGate({ ...envFor(f, fake.gh), deadline: 0 }, { gate, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(first.action).toBe('failed');
|
||||
expect(records(f)[0]).toMatchObject({ sha: f.c[4], verdict: 'PENDING', run: { id: 1000 } });
|
||||
const next = f.commit('c6');
|
||||
fake.runs[0]!.status = 'completed';
|
||||
const dry = runGate(envFor(f, fake.gh), { gate, label: 'test', dryRun: true, ignoreCadence: true });
|
||||
expect(dry.lines[0]).toContain('would finish the open gate on ' + f.c[4]!.slice(0, 12));
|
||||
const second = runGate(envFor(f, fake.gh), { gate, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(second.action, second.lines.join('\n')).toBe('held');
|
||||
expect(second.sha).toBe(f.c[4]);
|
||||
expect(second.lines[0]).toContain('finishing the open gate on ' + f.c[4]!.slice(0, 12));
|
||||
expect(fake.dispatches).toHaveLength(1);
|
||||
expect(activeHold(records(f), () => true)?.sha).toBe(f.c[4]);
|
||||
const third = runGate(envFor(f, fake.gh), { gate, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(third.action, third.lines.join('\n')).toBe('gated');
|
||||
expect(third.sha).toBe(next);
|
||||
expect(fake.dispatches).toHaveLength(2);
|
||||
expect(fake.dispatches[1]!.inputs.expected_sha).toBe(next);
|
||||
});
|
||||
|
||||
// Value: protects=no paid dispatch follows a record that did not reach origin's notes (a fresh checkout reads only origin, so the next run would
|
||||
// dispatch the same $37 gate again); fails_when=a notes push failure repeats the full gate every cadence; why_new=review finding (targeted money,
|
||||
// l1-p2); seam=fake gh and a pre-receive hook on the bare origin; no_claim=a real ruleset
|
||||
test('a record that cannot reach origin dispatches nothing', () => {
|
||||
const f = fixture();
|
||||
const hook = path.join(f.origin, 'hooks', 'pre-receive');
|
||||
fs.writeFileSync(hook, '#!/bin/sh\nwhile read old new ref; do case "$ref" in refs/notes/*) exit 1;; esac; done\nexit 0\n', { mode: 0o755 });
|
||||
const fake = fakeGh(() => green());
|
||||
const out = runGate(envFor(f, fake.gh), { gate: GATE, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(out.action).toBe('failed');
|
||||
expect(out.lines.at(-1)).toContain('nothing dispatched');
|
||||
expect(fake.dispatches).toHaveLength(0);
|
||||
});
|
||||
|
||||
// Value: protects=an open gate is finished even after release-cut moved stable onto its commit, and an open gate older than OPEN_GATE_CADENCES
|
||||
// cadences stops holding up main's head; fails_when=an open record on stable's commit skips forever, or an unresolvable run blocks every later gate;
|
||||
// why_new=review findings (state-machines and red-team, l1-p2); seam=fake gh; no_claim=a real deleted run
|
||||
test('an open gate on the commit stable moved to is still finished; a stale open gate no longer blocks the head', () => {
|
||||
const f = fixture();
|
||||
let dispatched = 0;
|
||||
const fake = fakeGh(() => (dispatched++ === 0 ? { conclusion: 'success', status: 'in_progress', artifacts: report('GREEN') } : green()));
|
||||
expect(runGate({ ...envFor(f, fake.gh), deadline: 0 }, { gate: GATE, label: 'test', dryRun: false, ignoreCadence: true }).action).toBe('failed');
|
||||
git(f.seed, 'push', '-q', '-f', 'origin', f.c[4] + ':refs/heads/stable');
|
||||
f.commit('c6');
|
||||
fake.runs[0]!.status = 'completed';
|
||||
const finished = runGate(envFor(f, fake.gh), { gate: GATE, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(finished.action, finished.lines.join('\n')).toBe('gated');
|
||||
expect(finished.sha).toBe(f.c[4]);
|
||||
|
||||
const g = fixture();
|
||||
const fake2 = fakeGh(() => ({ conclusion: 'success', status: 'in_progress', artifacts: report('GREEN') }));
|
||||
expect(runGate({ ...envFor(g, fake2.gh), deadline: 0 }, { gate: GATE, label: 'test', dryRun: false, ignoreCadence: true }).action).toBe('failed');
|
||||
const head = g.commit('c6');
|
||||
const late = runGate({ ...envFor(g, fake2.gh, OPEN_GATE_CADENCES * GATE.cadence_hours + 1), deadline: 0 }, { gate: GATE, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(late.lines.some(l => l.includes('finishing the open gate'))).toBe(false);
|
||||
expect(fake2.dispatches.at(-1)!.inputs.expected_sha).toBe(head);
|
||||
});
|
||||
});
|
||||
|
||||
describe('release gate: red, bisect and the hold', () => {
|
||||
// Value: protects=a red gate records RED (the hold release-cut reads), bisects only its red verdict cases on release-gate/<id> with prefixes between
|
||||
// stable and the red head, narrows round by round to the first red commit after a green one, deletes the bisect branch, and prints first_bad; a later
|
||||
// green gate on a newer commit lifts the hold; fails_when=a red gate moves or leaves stable releasable, the bisect blames the wrong commit, tests the
|
||||
// known-red head again, leaks its branch, or a green gate on an older commit lifts the hold; why_new=new module; seam=fake gh; no_claim=a live bisect
|
||||
test('red: RED record, a bisect that names first_bad, the branch cleaned up, and the hold until a later green', () => {
|
||||
const f = fixture();
|
||||
const order = [f.base, ...f.c];
|
||||
const fake = fakeGh((inputs) => {
|
||||
if (!inputs.prefix_shas) return { conclusion: 'failure', artifacts: report('RED', ['case-a rule FAIL VERDICT', 'case-z rule FAIL INFRA']) };
|
||||
const files: Record<string, Record<string, string>> = {};
|
||||
for (const sha of inputs.prefix_shas.split(',')) {
|
||||
const red = order.indexOf(sha) >= 3;
|
||||
files['gstack-release-record-bisect-' + sha.slice(0, 12)] = { 'bisect-prefix.json': JSON.stringify({ schema: 1, kind: 'train-bisect-prefix', nonce: inputs.nonce, prefix_sha: sha, checked_out_sha: sha,
|
||||
panels: [{ case: 'case-a', kind: 'rule', status: red ? 'FAIL' : 'PASS', red_class: red ? 'VERDICT' : null, cost_usd: 1.25 }] }) };
|
||||
}
|
||||
return { conclusion: 'success', artifacts: files };
|
||||
});
|
||||
const out = runGate(envFor(f, fake.gh), { gate: GATE, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(out.action, out.lines.join('\n')).toBe('held');
|
||||
expect(out.lines).toContain('RELEASE: red sha=' + f.c[4] + ' first_bad=' + f.c[2] + ' run=1000');
|
||||
expect(fake.dispatches).toHaveLength(2);
|
||||
const bisect = fake.dispatches[1]!;
|
||||
expect(bisect.ref).toMatch(/^release-gate\/abc123-[0-9a-f]{12}$/);
|
||||
expect(bisect.inputs).toMatchObject({ cases: 'case-a', prefix_shas: f.c.slice(0, 4).join(','), expected_sha: f.c[4] });
|
||||
expect(bisect.inputs.nonce).toMatch(/^gate\.bisect-/);
|
||||
expect(git(f.seed, 'ls-remote', 'origin', 'refs/heads/release-gate/*')).toBe('');
|
||||
const recs = records(f);
|
||||
expect(recs[0]).toMatchObject({ verdict: 'RED', red_cases: ['case-a'], bisect: { state: 'found', first_bad: f.c[2], good: f.c[1], bad: f.c[2], spent_usd: 5 } });
|
||||
expect(git(f.seed, 'ls-remote', 'origin', 'refs/heads/stable').split('\t')[0]).toBe(f.base);
|
||||
const isAncestor = (a: string, b: string) => spawnSync('git', ['merge-base', '--is-ancestor', a, b], { cwd: f.work, timeout: 30_000 }).status === 0;
|
||||
expect(activeHold(recs, isAncestor)?.sha).toBe(f.c[4]);
|
||||
const status = gateStatus(envFor(f, fake.gh), { gate: GATE, label: 'test' });
|
||||
expect(status.action).toBe('held');
|
||||
expect(status.lines.find(l => l.startsWith('HOLD:'))).toContain('red on ' + f.c[4]);
|
||||
const older: ReleaseRecord = { ...recs[0]!, sha: f.c[1]!, verdict: 'GREEN', bisect: null };
|
||||
expect(activeHold([...recs, older], isAncestor)?.sha).toBe(f.c[4]);
|
||||
const later: ReleaseRecord = { ...recs[0]!, sha: f.commit('fix'), verdict: 'GREEN', bisect: null };
|
||||
git(f.work, 'fetch', '-q', 'origin');
|
||||
expect(activeHold([later, ...recs], isAncestor)).toBeNull();
|
||||
});
|
||||
|
||||
// Value: protects=the bisect spends within its cap: a 0 cap records no bisect and first_bad unknown, a small cap tests only the prefixes it covers
|
||||
// and stops capped, and bisect --spend-cap resumes a capped one; fails_when=a bisect dispatches past its cap or a capped bisect cannot be resumed;
|
||||
// why_new=new module; seam=fake gh; no_claim=real case prices
|
||||
test('bisect spend: a zero cap skips it, a small cap stops capped, and bisect --spend-cap resumes', () => {
|
||||
const f = fixture();
|
||||
const fake = fakeGh((inputs) => (inputs.prefix_shas ? { conclusion: 'success', artifacts: {} } : { conclusion: 'failure', artifacts: report('RED', ['case-a rule FAIL VERDICT', 'case-b judge FAIL']) }));
|
||||
const none = runGate(envFor(f, fake.gh), { gate: { ...GATE, bisect_spend_cap_usd: 0 }, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(none.lines).toContain('RELEASE: red sha=' + f.c[4] + ' first_bad=unknown run=1000');
|
||||
expect(none.lines.some(l => l.includes('bisect unknown: bisect_spend_cap_usd is 0'))).toBe(true);
|
||||
expect(fake.dispatches).toHaveLength(1);
|
||||
|
||||
const g = fixture();
|
||||
const fake2 = fakeGh((inputs) => (inputs.prefix_shas ? { conclusion: 'success', artifacts: {} } : { conclusion: 'failure', artifacts: report('RED', ['case-a rule FAIL VERDICT', 'case-b judge FAIL']) }));
|
||||
const capped = runGate(envFor(g, fake2.gh), { gate: { ...GATE, bisect_spend_cap_usd: 2 }, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(capped.lines.some(l => l.includes('bisect capped: the next round needs $3.00 a prefix'))).toBe(true);
|
||||
expect(fake2.dispatches).toHaveLength(1);
|
||||
const plan = bisectGate(envFor(g, fake2.gh), { gate: GATE, label: 'test', spendCap: 30, dryRun: true });
|
||||
expect(plan.lines.some(l => l.startsWith('RELEASE: bisect round 1: 2 case(s) on 4 of 4 commit(s)'))).toBe(true);
|
||||
expect(fake2.dispatches).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('release gate: the bisect cap with unknown costs', () => {
|
||||
// Value: protects=a bisect whose prefix records report cost_usd null (what scripts/train-gate.ts writes today) books
|
||||
// RELEASE_TRIAL_RESERVATION_USD per case and prefix, so a later round sees the spend and the bisect stops capped within its cap; fails_when=null
|
||||
// costs count as $0 and every round reserves the whole cap again (about 4x the cap over MAX_BISECT_ROUNDS); why_new=review finding (targeted
|
||||
// money, l1 fix-check); seam=fake gh; no_claim=real case prices
|
||||
test('null prefix costs are charged at the reservation, and the bisect ends capped within its cap', () => {
|
||||
const f = fixture();
|
||||
const order = [f.base, ...f.c, ...[6, 7, 8, 9, 10, 11, 12].map(i => f.commit('c' + i))];
|
||||
const fake = fakeGh((inputs) => {
|
||||
if (!inputs.prefix_shas) return { conclusion: 'failure', artifacts: report('RED', ['case-a rule FAIL VERDICT']) };
|
||||
const files: Record<string, Record<string, string>> = {};
|
||||
for (const sha of inputs.prefix_shas.split(',')) {
|
||||
const red = order.indexOf(sha) >= 7;
|
||||
files['gstack-release-record-bisect-' + sha.slice(0, 12)] = { 'bisect-prefix.json': JSON.stringify({ schema: 1, kind: 'train-bisect-prefix', nonce: inputs.nonce, prefix_sha: sha, checked_out_sha: sha,
|
||||
panels: [{ case: 'case-a', kind: 'rule', status: red ? 'FAIL' : 'PASS', red_class: red ? 'VERDICT' : null, cost_usd: null }] }) };
|
||||
}
|
||||
return { conclusion: 'success', artifacts: files };
|
||||
});
|
||||
const out = runGate(envFor(f, fake.gh), { gate: { ...GATE, bisect_spend_cap_usd: 4 }, label: 'test', dryRun: false, ignoreCadence: true });
|
||||
expect(out.action, out.lines.join('\n')).toBe('held');
|
||||
const bisect = records(f)[0]!.bisect!;
|
||||
expect(bisect).toMatchObject({ state: 'capped', spent_usd: 3 });
|
||||
expect(bisect.spent_usd).toBeLessThanOrEqual(4);
|
||||
expect(fake.dispatches).toHaveLength(2);
|
||||
expect(fake.dispatches[1]!.inputs.prefix_shas!.split(',')).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('release gate: verdict, range and policy units', () => {
|
||||
test('parseReport and classifyRun: verdict reds bisect, other classes keep a red incomplete, success is green, and a contradiction is incomplete', () => {
|
||||
const r = parseReport(report('RED', ['case-a rule FAIL VERDICT', 'judge one judge FAIL', 'case-z rule FAIL INFRA'])['report-verdict-a1']['report.txt']);
|
||||
expect(r).toEqual({ verdict: 'RED', red: ['case-a', 'judge one'], other: ['case-z'], cost: 37.4 });
|
||||
expect(classifyRun({ status: 'completed', conclusion: 'failure' }, r)).toMatchObject({ verdict: 'RED', red: ['case-a', 'judge one'] });
|
||||
expect(classifyRun({ status: 'completed', conclusion: 'failure' }, { ...r, red: [] }).verdict).toBe('INCOMPLETE');
|
||||
expect(classifyRun({ status: 'completed', conclusion: 'cancelled' }, null).verdict).toBe('INCOMPLETE');
|
||||
expect(classifyRun({ status: 'completed', conclusion: 'success' }, { ...r, verdict: 'GREEN' }).verdict).toBe('GREEN');
|
||||
expect(classifyRun({ status: 'completed', conclusion: 'success' }, r).verdict).toBe('INCOMPLETE');
|
||||
expect(classifyRun({ status: 'in_progress', conclusion: null }, null).verdict).toBe('PENDING');
|
||||
});
|
||||
|
||||
test('planPrefixes spreads at most MAX_PREFIXES over the interior; narrow moves good and bad and refuses a non-monotone or missing result', () => {
|
||||
const shas = Array.from({ length: 20 }, (_, i) => String(i).padStart(40, '0'));
|
||||
expect(planPrefixes(shas.slice(0, 3))).toEqual(shas.slice(0, 3));
|
||||
const picked = planPrefixes(shas, 7);
|
||||
expect(picked).toHaveLength(7);
|
||||
expect(new Set(picked).size).toBe(7);
|
||||
expect(picked[0]).not.toBe(shas[0]);
|
||||
const t = (rs: string[]) => rs.map((r, i): { sha: string; results: Record<string, PrefixResult> } => ({ sha: shas[i]!, results: r === '?' ? {} : { a: r === 'R' ? 'red' : 'green' } }));
|
||||
expect(narrow({ good: 'g', bad: 'b' }, t(['G', 'G', 'R']), ['a'])).toEqual({ good: shas[1], bad: shas[2] });
|
||||
expect(narrow({ good: 'g', bad: 'b' }, t(['G', 'G']), ['a'])).toEqual({ good: shas[1], bad: 'b' });
|
||||
expect(narrow({ good: 'g', bad: 'b' }, t(['R', 'R']), ['a'])).toEqual({ good: 'g', bad: shas[0] });
|
||||
expect(narrow({ good: 'g', bad: 'b' }, t(['G', 'R', 'G']), ['a'])).toEqual({ unknown: 'a is not monotone over the tested commits (GRG)' });
|
||||
expect(narrow({ good: 'g', bad: 'b' }, t(['G', '?']), ['a'])).toHaveProperty('unknown');
|
||||
});
|
||||
|
||||
// Value: protects=the release_gate key is read only with min_gstack_version at its introducing version, validates every field (cadence at least the
|
||||
// workflow schedule, a workflow file, branch names, hold-release), and --policy runs the same validation; fails_when=an older gstack reads the block
|
||||
// silently, a bad field passes, or the command-line policy skips validation; why_new=new key; seam=none; no_claim=the json adoption (a follow-up PR)
|
||||
test('policy: the release_gate key needs its min_gstack_version and every field; --policy is validated the same way', () => {
|
||||
const raw = { release_gate: GATE };
|
||||
expect(validatePolicy(raw).map(e => e.path)).toEqual(['release_gate']);
|
||||
expect(validatePolicy({ ...raw, min_gstack_version: RELEASE_GATE_KEY_VERSION })).toEqual([]);
|
||||
expect(releaseGateErrors({ ...GATE, cadence_hours: RELEASE_GATE_SCHEDULE_HOURS - 1, on_red: 'freeze', stable_ref: 'main', extra: 1 }).map(e => e.path).sort())
|
||||
.toEqual(['release_gate.cadence_hours', 'release_gate.extra', 'release_gate.on_red', 'release_gate.stable_ref']);
|
||||
expect(releaseGateErrors({ cadence_hours: 8 }).filter(e => e.message.startsWith('missing'))).toHaveLength(6);
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'release-gate-policy-'));
|
||||
roots.push(dir);
|
||||
const good = path.join(dir, 'good.json');
|
||||
fs.writeFileSync(good, JSON.stringify({ ...raw, min_gstack_version: RELEASE_GATE_KEY_VERSION }));
|
||||
expect(loadReleaseGate(ROOT, { policyFile: good })).toEqual({ gate: GATE, label: good });
|
||||
const bad = path.join(dir, 'bad.json');
|
||||
fs.writeFileSync(bad, JSON.stringify(raw));
|
||||
expect((loadReleaseGate(ROOT, { policyFile: bad }) as { error: string }).error).toContain('release_gate introduced in gstack ' + RELEASE_GATE_KEY_VERSION);
|
||||
});
|
||||
|
||||
test('bin/gstack-release-gate: usage exits 2; an inert policy file exits 0 without touching GitHub', () => {
|
||||
const bin = path.join(ROOT, 'bin/gstack-release-gate');
|
||||
const usage = spawnSync('bun', [...bunIsolationArgs(), bin, 'frobnicate'], { cwd: ROOT, encoding: 'utf8', timeout: 60_000 });
|
||||
expect(usage.status).toBe(2);
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'release-gate-bin-'));
|
||||
roots.push(dir);
|
||||
const inert = path.join(dir, 'policy.json');
|
||||
fs.writeFileSync(inert, '{}');
|
||||
const r = spawnSync('bun', [...bunIsolationArgs(), bin, 'run', '--repo', 'o/r', '--policy', inert], { cwd: ROOT, encoding: 'utf8', timeout: 60_000 });
|
||||
expect(r.status, r.stderr).toBe(0);
|
||||
expect(r.stdout.trim()).toBe('RELEASE: inert (' + inert + ' declares no release_gate block; the per-push main backstop gates main)');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* A foreign version on a line the PR added to a stamp file is not the PR's stamp (GST-1245, HARN-7 on gstack
|
||||
* 1.94.19.0): harness-evals#235 added three README.md lines saying "QM v0.1.15", README.md was in stamp_files,
|
||||
* and the land stamp turned all three into "QM v0.0.115" (the repo's new VERSION), then "QM v0.0.116" on the
|
||||
* next stamp, because the stamp_paths stage read any built-in `vX` mention newer than the fork point on a
|
||||
* branch-added line as the branch's tentative stamp. The tree receipt called the rewrite stamp-only for the same
|
||||
* reason. The stamper and every stamp-only check now move a built-in form above the version being stamped
|
||||
* only when the branch itself recorded it (its version source at its fork point or at any of its own
|
||||
* commits); a declared stamp_patterns slot keeps the fork-point bound (#3512).
|
||||
*/
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { EXIT } from '../lib/headless-artifacts';
|
||||
import { tentativeMentions } from '../lib/restamp';
|
||||
import { stampOnlyLine } from '../lib/stamp-only';
|
||||
import { BASE_POLICY, cleanup, makeFixtureRepo, makePr, mergeMain, mergeToMain, readFile, restamp, runBin, type FixtureRepo } from './helpers/restamp-fixture';
|
||||
|
||||
const repos: FixtureRepo[] = [];
|
||||
afterEach(() => { while (repos.length) cleanup(repos.pop()!); });
|
||||
|
||||
const POLICY = { ...BASE_POLICY, release_tool: null, release_outputs: [], stamp_files: ['VERSION', 'package.json', 'package-lock.json', 'CHANGELOG.md', 'README.md'] };
|
||||
const BASE_README = '# harness\n\nScored with qm v0.1.15 since the start.\n';
|
||||
const QM = ['QM v0.1.15 grades every run.', 'Pin QM v0.1.15 in CI.', 'Upgrade notes for QM v0.1.15 are below.'];
|
||||
|
||||
/** harness-evals' shape: a three-part repo at 0.0.114 whose README.md (a stamp file) already mentions qm v0.1.15. */
|
||||
function harness(): FixtureRepo {
|
||||
const repo = makeFixtureRepo({ prefix: 'restamp-foreign-', policy: POLICY, version: '0.0.114' });
|
||||
repos.push(repo);
|
||||
fs.writeFileSync(path.join(repo.work, 'README.md'), BASE_README);
|
||||
repo.git('add', '-A'); repo.git('commit', '-qm', 'readme'); repo.git('push', '-q', 'origin', 'main');
|
||||
return repo;
|
||||
}
|
||||
const addReadme = (repo: FixtureRepo, lines: string[]) => fs.writeFileSync(path.join(repo.work, 'README.md'), BASE_README + lines.join('\n') + '\n');
|
||||
|
||||
describe('a foreign version on a PR-added stamp_files line (GST-1245)', () => {
|
||||
// Value: protects=a third-party version a PR writes into a stamp file survives the stamp byte for byte (HARN-7's
|
||||
// "QM v0.1.15" -> "QM v0.0.115"); fails_when=the stamp_paths stage reads any vX newer than the fork point on a
|
||||
// branch-added line as the branch's own stamp; why_new=no case put a foreign same-width version on a branch line;
|
||||
// seam=lib/restamp.ts rewriteStampPaths; no_claim=versions of another width (already never candidates)
|
||||
test('the stamp leaves three PR-added "QM v0.1.15" lines and the base\'s qm line exactly as written', () => {
|
||||
const repo = harness();
|
||||
makePr(repo, 'pr-235');
|
||||
addReadme(repo, QM);
|
||||
repo.git('commit', '-qam', 'docs: QM v0.1.15');
|
||||
const pinned = readFile(repo, 'README.md');
|
||||
const r = restamp(repo, ['--next']);
|
||||
expect(r.status, r.err).toBe(EXIT.ok);
|
||||
expect(readFile(repo, 'VERSION')).toBe('0.0.115\n');
|
||||
expect(readFile(repo, 'README.md')).toBe(pinned);
|
||||
expect(r.out).not.toContain('0.1.15 -> 0.0.115');
|
||||
});
|
||||
|
||||
// Value: protects=the PR's own recorded version still moves on its own lines while the foreign one beside it stays
|
||||
// (the negative control; harness-evals' second stamp d6801432 moved the QM lines again); fails_when=the fix stops
|
||||
// moving the branch's own tentative stamp after it lost its slot; why_new=the lost-slot cases carry no foreign
|
||||
// version; seam=lib/restamp.ts recordedVersions + tentativeMentions; no_claim=none beyond protects
|
||||
test('control: after a lost slot the PR\'s own v0.0.115 line moves to v0.0.116 and the QM lines beside it do not', () => {
|
||||
const repo = harness();
|
||||
makePr(repo, 'pr-235');
|
||||
fs.writeFileSync(path.join(repo.work, 'VERSION'), '0.0.115\n');
|
||||
addReadme(repo, [...QM, 'harness v0.0.115 adds QM grading.']);
|
||||
repo.git('commit', '-qam', 'docs and my tentative stamp');
|
||||
makePr(repo, 'pr-other');
|
||||
expect(restamp(repo, ['--next']).status).toBe(EXIT.ok);
|
||||
repo.git('commit', '-qam', 'stamp other');
|
||||
mergeToMain(repo, 'pr-other');
|
||||
repo.git('checkout', '-q', 'pr-235');
|
||||
mergeMain(repo);
|
||||
fs.writeFileSync(path.join(repo.work, 'VERSION'), '0.0.115\n');
|
||||
const r = restamp(repo, ['--next']);
|
||||
expect(r.status, r.err).toBe(EXIT.ok);
|
||||
expect(readFile(repo, 'VERSION')).toBe('0.0.116\n');
|
||||
expect(readFile(repo, 'README.md')).toBe(BASE_README + [...QM, 'harness v0.0.116 adds QM grading.'].join('\n') + '\n');
|
||||
});
|
||||
|
||||
// Value: protects=the tree receipt (stamp, verify, gate-ahead replay) reads a rewritten foreign version as product,
|
||||
// so a corrupting stamp can no longer pass as stamp-only; fails_when=stampOnlyLine accepts any moved version at or
|
||||
// above the gated head's or the fork point's; why_new=no receipt case moved a foreign same-width version;
|
||||
// seam=lib/stamp-only.ts stampOnlyWithin; no_claim=none beyond protects
|
||||
test('the tree receipt calls the corrupt stamp a product change in README.md and the honest stamp stamp-only', () => {
|
||||
const repo = harness();
|
||||
makePr(repo, 'pr-235');
|
||||
addReadme(repo, QM);
|
||||
repo.git('commit', '-qam', 'docs: QM v0.1.15');
|
||||
const gated = repo.git('rev-parse', 'HEAD');
|
||||
expect(restamp(repo, ['--next']).status).toBe(EXIT.ok);
|
||||
repo.git('commit', '-qam', 'honest stamp');
|
||||
const honest = runBin(repo, 'gstack-tree-receipt', ['--gated', gated, '--base', 'main']);
|
||||
expect(honest.out, honest.err).toContain('TREE: same-modulo-stamps');
|
||||
fs.writeFileSync(path.join(repo.work, 'README.md'), readFile(repo, 'README.md').replace(/QM v0\.1\.15/g, 'QM v0.0.115'));
|
||||
repo.git('commit', '-q', '--allow-empty', '-am', 'the 1.94.19.0 stamp: QM rewritten');
|
||||
const corrupt = runBin(repo, 'gstack-tree-receipt', ['--gated', gated, '--base', 'main']);
|
||||
expect(corrupt.out).toMatch(/^TREE: changed \(README\.md\)$/m);
|
||||
expect(corrupt.out).toContain('changed README.md (stamp_files: "QM v0.1.15 grades every run." -> "QM v0.0.115 grades every run.")');
|
||||
});
|
||||
|
||||
// Value: protects=a declared stamp_patterns slot moves only inside its own match, so the same foreign version in a
|
||||
// built-in form beside it (same line or another PR line) survives, and the receipt agrees (GST-1245 outside voice);
|
||||
// fails_when=a template match marks the version tentative and every form of it moves; why_new=no case mixed a slot
|
||||
// and a foreign built-in mention of one version; seam=lib/restamp.ts slotOnly + lib/stamp-only.ts free; no_claim=none
|
||||
test('a template slot at an unrecorded version moves alone; the same version as "QM v0.1.15" beside it stays', () => {
|
||||
const repo = makeFixtureRepo({ prefix: 'restamp-foreign-slot-', policy: { ...POLICY, stamp_patterns: ["_KEY_VERSION = '{version}'"] }, version: '0.0.114' });
|
||||
repos.push(repo);
|
||||
fs.writeFileSync(path.join(repo.work, 'README.md'), BASE_README);
|
||||
repo.git('add', '-A'); repo.git('commit', '-qm', 'readme'); repo.git('push', '-q', 'origin', 'main');
|
||||
makePr(repo, 'pr-slot');
|
||||
addReadme(repo, ["export const T_KEY_VERSION = '0.1.15'; // QM v0.1.15", QM[0]!]);
|
||||
repo.git('commit', '-qam', 'a key at a guessed version and a QM line');
|
||||
const gated = repo.git('rev-parse', 'HEAD');
|
||||
expect(restamp(repo, ['--next']).status).toBe(EXIT.ok);
|
||||
expect(readFile(repo, 'README.md')).toBe(BASE_README + ["export const T_KEY_VERSION = '0.0.115'; // QM v0.1.15", QM[0]!].join('\n') + '\n');
|
||||
repo.git('commit', '-qam', 'stamp');
|
||||
const receipt = runBin(repo, 'gstack-tree-receipt', ['--gated', gated, '--base', 'main']);
|
||||
expect(receipt.out, receipt.err).toContain('TREE: same-modulo-stamps');
|
||||
});
|
||||
|
||||
// Value: protects=the pure seams agree: a built-in form moves only a recorded version, a declared template slot keeps
|
||||
// the fork bound (#3512's next-minor key); fails_when=either seam reads an unrecorded built-in mention as a stamp,
|
||||
// or the template slot stops moving; why_new=the seams took no recorded set; seam=tentativeMentions, stampOnlyLine;
|
||||
// no_claim=none beyond protects
|
||||
test('pure: tentativeMentions and stampOnlyLine take a built-in mention above the new version only when the branch recorded it', () => {
|
||||
const added = new Map([['README.md', new Set([...QM, 'harness v0.0.117', 'since: 0.0.115', "export const X_KEY_VERSION = '0.1.0';"])]]);
|
||||
expect(tentativeMentions(added, '0.0.114', '0.0.116', ["_KEY_VERSION = '{version}'"], new Set(['0.0.114', '0.0.117'])).sort()).toEqual(['0.0.115', '0.0.117', '0.1.0']);
|
||||
expect(stampOnlyLine(QM[0]!, 'QM v0.0.115 grades every run.', '0.0.114', '0.0.115')).toBe(false);
|
||||
const side = { fork: '0.0.114', added: new Set([QM[0]!]), at: new Set([4]) };
|
||||
expect(stampOnlyLine(QM[0]!, 'QM v0.0.115 grades every run.', '0.0.114', '0.0.115', [], side, 4)).toBe(false);
|
||||
expect(stampOnlyLine('harness v0.0.114', 'harness v0.0.115', '0.0.114', '0.0.115')).toBe(true);
|
||||
expect(stampOnlyLine('harness v0.0.117', 'harness v0.0.116', '0.0.114', '0.0.116', [], { ...side, added: new Set(['harness v0.0.117']), recorded: new Set(['0.0.114', '0.0.117']) }, 4)).toBe(true);
|
||||
expect(stampOnlyLine('harness v0.0.117', 'harness v0.0.116', '0.0.114', '0.0.116', [], { ...side, added: new Set(['harness v0.0.117']) }, 4)).toBe(false);
|
||||
expect(stampOnlyLine('since: 0.0.115', 'since: 0.0.116', '0.0.114', '0.0.116', [], { ...side, added: new Set(['since: 0.0.115']) }, 4)).toBe(true);
|
||||
const key = "export const T_KEY_VERSION = '0.1.15'; // QM v0.1.15";
|
||||
const tpl = ["_KEY_VERSION = '{version}'"];
|
||||
expect(stampOnlyLine(key, "export const T_KEY_VERSION = '0.0.115'; // QM v0.1.15", '0.0.114', '0.0.115', tpl, { ...side, added: new Set([key]) }, 4)).toBe(true);
|
||||
expect(stampOnlyLine(key, "export const T_KEY_VERSION = '0.0.115'; // QM v0.0.115", '0.0.114', '0.0.115', tpl, { ...side, added: new Set([key]) }, 4)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -108,7 +108,11 @@ const run = async opts => {
|
||||
fixturePaths.push(opts.workingDirectory);
|
||||
captureOptions.push({ timeout: opts.timeout, maxTurns: opts.maxTurns, model: opts.model ?? null, signal: !!opts.signal });
|
||||
opts.signal?.addEventListener('abort', () => events.push('abort-' + attempt), { once: true });
|
||||
await Bun.sleep(attempt === 1 ? captureMs + drainMs : 80);
|
||||
if (attempt === 1) {
|
||||
await new Promise(resolve => opts.signal.addEventListener('abort', resolve, { once: true }));
|
||||
// gstack-timing-ok: the drain after cancellation is the behavior under test; no deadline remains during it
|
||||
await Bun.sleep(drainMs);
|
||||
}
|
||||
expect(fs.existsSync(opts.workingDirectory)).toBe(true);
|
||||
events.push('capture-done-' + attempt);
|
||||
if (attempt === 2) fs.writeFileSync(path.join(opts.workingDirectory, 'review-output.md'), ${JSON.stringify(validReport ? 'RED TEAM REVIEW' : 'ordinary unrelated prose')});
|
||||
|
||||
@@ -100,6 +100,67 @@ describe('collectCommit: git objects only', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('GSTA-258 L7 Addendum 1 and 7: executables among data-named paths', () => {
|
||||
// Value: protects=an exec bit or a shebang keeps a logs/ or .out path code in both collectors; fails_when=scripts/logs/prune
|
||||
// or an executable .out reaches classifyDiff as data (docs, light); seam=collectCommit/collectLive -> depthOfCommitInput
|
||||
test('the exec bit or a shebang lists the path as executable; a plain log does not', () => {
|
||||
const r = repo({});
|
||||
r.write({ 'scripts/logs/prune': '#!/bin/sh\nrm -rf "$1"\n', 'bin/tool.out': 'ELF-ish\n', 'logs/run.txt': 'ok\n', 'docs/r/logs/ready': 'yes\n' });
|
||||
fs.chmodSync(path.join(r.dir, 'bin/tool.out'), 0o755);
|
||||
const head = r.commit({});
|
||||
const c = collectCommit(r.dir, r.baseSha, head);
|
||||
expect(c.executables).toEqual(['bin/tool.out', 'scripts/logs/prune']);
|
||||
expect(depthOfCommitInput({ ...c, gateTagged: 0 }).class).toBe('code');
|
||||
r.write({ 'docs/r/logs/later': '#!/usr/bin/env bash\necho\n' });
|
||||
expect(collectLive(r.dir, 'main').executables).toEqual(['bin/tool.out', 'docs/r/logs/later', 'scripts/logs/prune']);
|
||||
const plain = repo({});
|
||||
const ph = plain.commit({ 'logs/run.txt': 'ok\n', 'docs/r/logs/ready': 'yes\n', 'docs/r/agent.out': 'done\n' });
|
||||
const pc = collectCommit(plain.dir, plain.baseSha, ph);
|
||||
expect(pc.executables).toEqual([]);
|
||||
expect(depthOfCommitInput({ ...pc, gateTagged: 0 }).class).toBe('docs');
|
||||
});
|
||||
// Value: protects=a deleted log is absent, not unreadable, and an unrelated large blob never forces the fail-closed default;
|
||||
// fails_when=removing logs/run classes as gate, or a big text file in the diff makes r.log executable; seam=executablesAt
|
||||
test('a deleted log is not executable, and only candidates are read (two bytes each)', () => {
|
||||
const r = repo({ 'logs/run': 'ok\n', 'r.log': 'ok\n', 'big.txt': 'a'.repeat(1024 * 1024) });
|
||||
const del = r.commit({ 'logs/run': null, 'r.log': 'ok2\n', 'big.txt': 'b' + 'a'.repeat(1024 * 1024) });
|
||||
const c = collectCommit(r.dir, r.baseSha, del);
|
||||
expect(c.executables).toEqual([]);
|
||||
expect(depthOfCommitInput({ ...c, gateTagged: 0 }).class).toBe('docs');
|
||||
r.write({ 'r.log': null });
|
||||
expect(collectLive(r.dir, 'main').executables).toEqual([]);
|
||||
});
|
||||
// Value: protects=a docs or config name never hides an executable's lines, and a symlink is never opened (outside voice on #3972);
|
||||
// fails_when=a 755 prune.txt or prune.json with rm -rf classes light with no security, or a logs/ symlink is read through;
|
||||
// seam=collectors -> classifyDiff -> matchRisk
|
||||
test('executable .txt and .json scripts are code with security lines; a symlink counts as executable without being read', () => {
|
||||
const r = repo({});
|
||||
const script = '#!/bin/sh\nrm -rf "$1"\n';
|
||||
r.write({ 'scripts/logs/prune.txt': script, 'tools/prune.json': script });
|
||||
for (const p of ['scripts/logs/prune.txt', 'tools/prune.json']) fs.chmodSync(path.join(r.dir, p), 0o755);
|
||||
fs.mkdirSync(path.join(r.dir, 'logs'));
|
||||
fs.symlinkSync('/dev/null', path.join(r.dir, 'logs/run'));
|
||||
const head = r.commit({});
|
||||
for (const c of [collectCommit(r.dir, r.baseSha, head), collectLive(r.dir, 'main')]) {
|
||||
expect(c.executables).toEqual(['logs/run', 'scripts/logs/prune.txt', 'tools/prune.json']);
|
||||
const d = depthOfCommitInput({ ...c, gateTagged: 0 });
|
||||
expect([d.class, d.risk.includes('security'), d.depth]).toEqual(['code', true, 'full']);
|
||||
}
|
||||
});
|
||||
// Value: protects=collectLive never opens a symlinked SVG (GStack Minder second exception on #3972); fails_when=a tracked
|
||||
// art.svg linked to a FIFO blocks the drawing read; seam=drawingsAmong's live reader
|
||||
test('a symlinked SVG is not read as a drawing in collectLive', () => {
|
||||
const r = repo({});
|
||||
const fifo = path.join(r.dir, '.git', 'fifo');
|
||||
spawnSync('mkfifo', [fifo], { timeout: 5_000 });
|
||||
fs.symlinkSync(fifo, path.join(r.dir, 'art.svg'));
|
||||
r.commit({});
|
||||
const t0 = Date.now();
|
||||
expect(collectLive(r.dir, 'main').drawings).toEqual([]);
|
||||
expect(Date.now() - t0).toBeLessThan(20_000);
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
describe('collectLive: the working tree', () => {
|
||||
test('tracked uncommitted edits and untracked files count per path; scratch under .gstack/tmp/ does not', () => {
|
||||
const r = repo({ 'src/a.ts': lines(1) });
|
||||
|
||||
@@ -28,6 +28,35 @@ describe('HARN-1 false triggers (harness-evals#231 on 1.93.7.0): data, config an
|
||||
expect([c.class, c.risk]).toEqual(['docs', []]);
|
||||
expect(classifyDiff({ paths: ['src/logs/rotate.ts'], gateTagged: 0 }).class).toBe('code');
|
||||
});
|
||||
// Value: protects=a directory name or a data extension never downgrades an executable (GSTA-258 L7 Addendum 1 and 7);
|
||||
// fails_when=scripts/logs/prune or an executable .out classes as docs; seam=collector executables -> classifyDiff
|
||||
test('an executable (exec bit or shebang) under logs/ or named .out stays code; plain logs stay docs', () => {
|
||||
const exe = ['scripts/logs/prune', 'tools/build/runner.out'];
|
||||
const c = classifyDiff({ paths: [...exe, 'logs/run.txt'], gateTagged: 0, executables: exe });
|
||||
expect(c.class).toBe('code');
|
||||
expect(c.reasons).toEqual(expect.arrayContaining(['code: scripts/logs/prune']));
|
||||
for (const p of exe) expect(classifyDiff({ paths: [p], gateTagged: 0, executables: [p] }).class).toBe('code');
|
||||
const txt = 'scripts/logs/prune.txt';
|
||||
const printsKey = classifyDiff({ paths: [txt], gateTagged: 0, executables: [txt], added: { [txt]: ['curl -H "Authorization: Bearer abcdefgh12345678"'] } });
|
||||
expect([printsKey.class, printsKey.risk]).toEqual(['code', ['security']]);
|
||||
expect(classifyDiff({ paths: ['logs/run.txt', 'docs/r/logs/ready'], gateTagged: 0, executables: [] }).class).toBe('docs');
|
||||
});
|
||||
// Value: protects=sealed custody and outside-model prompt egress plan full depth (GST-1177: harness-evals#237, gstack #3921);
|
||||
// fails_when=scripts/sealed/seal.ts or the #3921 secret-egress lines class light with no risk; seam=matchRisk path and line rules
|
||||
test('sealed custody and code that redacts or ships repo content to an outside model are security', () => {
|
||||
const sec = (p: string, lines: string[] = ['export const x = 1;']) => matchRisk({ codePaths: [p], added: { [p]: lines }, scopeAuth: false }).has('security');
|
||||
expect(sec('scripts/sealed/seal.ts')).toBe(true);
|
||||
expect(sec('lib/eval-custody.ts')).toBe(true);
|
||||
expect(sec('lib/autoplan-lean.ts', ["import { redactFindingSpans } from './redact-engine';"])).toBe(true);
|
||||
expect(sec('lib/autoplan-lean.ts', [' const redacted = (patch: string) => redactFindingSpans(patch) ?? "";'])).toBe(true);
|
||||
expect(sec('lib/autoplan-lean.ts', ['const SECRET_NAME = /(^|\\/)(\\.env[^/]*)$/i;'])).toBe(true);
|
||||
expect(sec('lib/review-x.ts', ["import { runOutsideVoice } from './outside-voice-runner';"])).toBe(true);
|
||||
for (const l of ['out = redact_secrets(text)', 'from gstack.redact import scrub', "import './outside-voice';", 'SECRET_PATTERNS = [/sk-[a-z]+/]', 'const CREDENTIAL_RE = new RegExp(src);']) expect(sec('lib/x.ts', [l])).toBe(true);
|
||||
expect(sec('lib/autoplan-lean.ts', ['const INLINE_DRAFT_BYTES = 64_000;'])).toBe(false);
|
||||
expect(sec('lib/x.ts', ['const SECRET_COUNT = total / 2;', "import { readFile } from 'node:fs';"])).toBe(false);
|
||||
expect(sec('lib/seasonal.ts')).toBe(false);
|
||||
expect(classifyDiff({ paths: ['scripts/sealed/seal.ts'], gateTagged: 0 }).risk).toContain('security');
|
||||
});
|
||||
test('a sqlite file is data even when a script names it', () => {
|
||||
const c = classifyDiff({ paths: [sqlite, 'scripts/load.py'], gateTagged: 0, perPath: [{ path: sqlite, lines: 0, binary: true }, { path: 'scripts/load.py', lines: 4, binary: false }], consumed: [sqlite] });
|
||||
expect([c.class, c.errors.map(e => e.code), c.runtimeLines]).toEqual(['code', [], 4]);
|
||||
@@ -222,6 +251,17 @@ describe('C7 merged reader brief and the outside voice reading its diff from dis
|
||||
expect(sliceNote(s, 100)).toMatch(/2 of 3 files.*big\.json/);
|
||||
expect(sliceDiff(sec('a.ts', 10), 100).sliced).toBe(false);
|
||||
});
|
||||
// Value: protects=no file leaves the outside voice's slice unnamed (GSTA-258 L7 Addendum 1.2); fails_when=a git-quoted header
|
||||
// before the first plain one is dropped unlisted, or glued onto the file before it; seam=sliceDiff headers
|
||||
test('a git-quoted or spaced filename is its own file in the slice and is named when left out', () => {
|
||||
const quoted = (p: string, n: number) => `diff --git "a/${p}" "b/${p}"\n+${'x'.repeat(n)}\n`;
|
||||
const sec = (p: string, n: number) => `diff --git a/${p} b/${p}\n+${'x'.repeat(n)}\n`;
|
||||
const s = sliceDiff(quoted('t\\303\\251st.sql', 500) + sec('a.ts', 10) + quoted('tab\\there.ts', 10), 100);
|
||||
expect([s.files, s.kept, s.left]).toEqual([3, 2, ['"t\\303\\251st.sql"']]);
|
||||
expect(s.text).toContain('tab\\there.ts');
|
||||
const spaced = sliceDiff(sec('my notes/big data.csv', 500) + sec('a.ts', 10), 100);
|
||||
expect(spaced.left).toEqual(['my notes/big data.csv']);
|
||||
});
|
||||
test('the outside voice gets a path and a hash, not the pasted diff', () => {
|
||||
const text = renderBrief('outside-voice', { diff_base: sha, diff_file: '/tmp/o/outside-voice.diff', diff_sha256: 'd'.repeat(64), diff_bytes: '1234' }, t);
|
||||
expect(text).toContain('/tmp/o/outside-voice.diff');
|
||||
|
||||
@@ -249,6 +249,31 @@ describe('gstack-review-dispatch sent, collect, judge and verify: nothing change
|
||||
expect([tampered.status, tampered.stdout.includes('OUTPUT outside-voice MISMATCH')]).toEqual([1, true]);
|
||||
});
|
||||
|
||||
// Value: protects=a pass whose readers all came back clean records "nothing to judge" without a hand-written judged.jsonl, and a pass with findings still needs lead judgment's file; fails_when=judge crashes on the absent judged set of an empty merge (gstack-evals#191 /ship), or an absent judged set passes a merge that holds findings;
|
||||
// why_new=judge always read --judged; seam=judge and verify; no_claim=that Step 9.4 runs judge at all on an empty merge
|
||||
test('judge on an empty merge records nothing to judge without a judged set; a merge with findings still needs one', () => {
|
||||
const p = pass();
|
||||
run(['sent', '--ledger', p.ledger, '--role', 'specialist', '--name', 'testing', '--sent', p.file]);
|
||||
expect(run(['collect', '--ledger', p.ledger, '--role', 'specialist', '--name', 'testing', '--output', p.w('none.out', 'NO FINDINGS\n'), '--merged', p.merged]).status).toBe(0);
|
||||
expect(fs.readFileSync(p.merged, 'utf8')).toBe('');
|
||||
const judged = path.join(p.out, 'judged.jsonl');
|
||||
const empty = run(['judge', '--ledger', p.ledger, '--merged', p.merged, '--judged', judged]);
|
||||
expect([empty.status, empty.stderr, empty.stdout.trim()]).toEqual([0, '', `JUDGMENT: ok nothing to judge (${p.merged} holds no findings; wrote an empty ${judged})`]);
|
||||
expect(fs.readFileSync(judged, 'utf8')).toBe('');
|
||||
const v = run(['verify', '--ledger', p.ledger]);
|
||||
expect([v.status, v.stdout.includes('JUDGE - OK'), v.stdout.includes('VERIFY: clean briefs=1 outputs=1')]).toEqual([0, true, true]);
|
||||
const q = pass();
|
||||
run(['sent', '--ledger', q.ledger, '--role', 'specialist', '--name', 'testing', '--sent', q.file]);
|
||||
const finding = q.w('spec.out', '{"severity":"CRITICAL","path":"a.ts","line":3,"category":"logic","summary":"x","specialist":"testing"}\n');
|
||||
expect(run(['collect', '--ledger', q.ledger, '--role', 'specialist', '--name', 'testing', '--output', finding, '--merged', q.merged]).status).toBe(0);
|
||||
const missing = path.join(q.out, 'judged.jsonl');
|
||||
const needed = run(['judge', '--ledger', q.ledger, '--merged', q.merged, '--judged', missing]);
|
||||
expect([needed.status, needed.stdout]).toEqual([2, '']);
|
||||
expect(needed.stderr.trim()).toBe(`gstack-review-dispatch judge: ${missing} does not exist; ${q.merged} holds 1 finding, so lead judgment writes one judged line per finding first`);
|
||||
expect(fs.existsSync(missing)).toBe(false);
|
||||
expect(fs.readFileSync(q.ledger, 'utf8')).not.toContain('"event":"judge"');
|
||||
});
|
||||
|
||||
// Value: protects=verify is clean only when every collected output came from a brief rendered and sent verbatim, nothing was collected after the judgment, and the judged set still passes as recorded; a fold keeps a standalone survivor; fails_when=outputs from hand-written briefs, a finding collected after judge, a judged.jsonl edited after judge, a self-fold or a fold cycle still read clean (/ship #3648 pass-1 Red Team);
|
||||
// why_new=the first gate trusted the last verdict and any duplicate_of; seam=verify and judge; no_claim=the host's dispatch
|
||||
test('verify is dirty for an unrendered reader, an output after judge and a judged set edited after judge; self-folds and fold cycles are drops', () => {
|
||||
|
||||
@@ -59,6 +59,37 @@ describe('review loop counts bind by finding id (GST-1168)', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test('GBEV-3: a voided pass (its ledger never judged, no row names it) is left out by name, and the restarted pass counts alone', () => {
|
||||
const rows = [row('review', 30, [{ fingerprint: 'src/a.ts:10:correctness', severity: 'CRITICAL', action: 'fixed', blocking: true, raised_by: 'red-team', ledger_id: 'p2/red-team#1' }], { pass: 2 })];
|
||||
const ledgers = [[blocker('p1', 'red-team#1', 'src/a.ts:10'), blocker('p1', 'red-team#2', 'src/c.ts:5')], [blocker('p2', 'red-team#1', 'src/a.ts:10')]];
|
||||
const passes = [{ ...pass(0, ['p1/red-team#1', 'p1/red-team#2']), name: 'p1', judged: false }, { ...pass(20, ['p2/red-team#1']), name: 'p2', judged: true }];
|
||||
const s = summarizeReviewLoop(rows, SINCE, ledgers, passes);
|
||||
expect({ found: s.blocking_found, fixed: s.fixed, unrecorded: s.unrecorded, unbound: s.unbound }).toEqual({ found: 1, fixed: 1, unrecorded: undefined, unbound: undefined });
|
||||
expect(s.voided).toEqual(['pass p1: its ledger was never judged and no review-log row names it (an abandoned pass), so its 2 collected findings are left out']);
|
||||
});
|
||||
|
||||
test('an unjudged fix-check ledger with no row still counts as a fix-check, never voided', () => {
|
||||
const rows = [row('review', 20, [], { pass: 1 })];
|
||||
const passes = [{ ...pass(0, ['p1/red-team#1']), name: 'p1', judged: true }, { ...pass(40, ['fc/fix-check#1'], true), name: 'fc', judged: false }];
|
||||
const s = summarizeReviewLoop(rows, SINCE, [[], []], passes);
|
||||
expect(s.voided).toBeUndefined();
|
||||
expect(s.fix_checks).toBe(1);
|
||||
});
|
||||
|
||||
test('the last pass is never voided: an unjudged pass no later pass replaced keeps its blockers', () => {
|
||||
const ledgers = [[blocker('p1', 'red-team#1', 'src/a.ts:10')]];
|
||||
const s = summarizeReviewLoop([], SINCE, ledgers, [{ ...pass(0, ['p1/red-team#1']), name: 'p1', judged: false }]);
|
||||
expect(s.voided).toBeUndefined();
|
||||
expect(s.blocking_found).toBe(1);
|
||||
});
|
||||
|
||||
test('a judged pass with no row is still named unbound, never voided', () => {
|
||||
const rows = [row('review', 30, [], { pass: 2 })];
|
||||
const s = summarizeReviewLoop(rows, SINCE, [[blocker('p1', 'red-team#1', 'src/a.ts:10')], []], [{ ...pass(0, ['p1/red-team#1']), name: 'p1', judged: true }, { ...pass(20, []), name: 'p2', judged: true }]);
|
||||
expect(s.voided).toBeUndefined();
|
||||
expect(s.unbound).toEqual(['pass 1 (ledger p1): no review-log row, so its fixes and dispositions cannot be counted']);
|
||||
});
|
||||
|
||||
test('#3911 at 4340ed4c: a fix-check row written twice counts once, and pass 1 with no row is named', () => {
|
||||
const fc = { skill: 'review-fix-check', via: 'ship', pass: 2, commit: '4340ed4c', review_binding: { started_at: at(40) }, findings: [{ fingerprint: 'lib/p.ts:9:correctness', severity: 'CRITICAL', action: 'fixed', blocking: true, raised_by: 'fix-check', ledger_id: 'fc/fix-check#1' }] };
|
||||
const rows = [row('review', 20, [], { pass: 2, commit: '1111111' }), fc, { ...fc }];
|
||||
|
||||
@@ -678,6 +678,29 @@ describe('Capy pass program (fake host, real bins)', () => {
|
||||
expect(bin(dir, env, ['pass', '--base', 'main', '--out', path.join(dir, '.state/run/d2'), '--pass', 'x16b', '--audit-only']).status).not.toBe(0);
|
||||
}, 240_000);
|
||||
|
||||
// Value: protects=a pass id typed in capitals is read as its lowercase id, so the manifest, its titles and a resume agree, and an id with other characters is still refused naming the rule; fails_when=--pass P1 is refused as a missing flag (gstack-evals#191 /ship), a capitalized resume of p1 reads as another pass, or p_1 is accepted;
|
||||
// why_new=the id was matched case-sensitively and its refusal read as a missing flag; seam=gstack-review-dispatch pass; no_claim=the reviewer plan, which --audit-only skips
|
||||
test('pass reads its id as lowercase; an id with other characters is still refused with the rule', () => {
|
||||
const { dir, env } = repo();
|
||||
const out = path.join(dir, '.state/run/docs');
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
fs.writeFileSync(path.join(out, 'docs.prompt.md'), 'Run Step 14.5 as written.\n');
|
||||
const extras = path.join(dir, '.state/extras.json');
|
||||
fs.writeFileSync(extras, JSON.stringify([{ name: 'docs', prompt_file: path.join(out, 'docs.prompt.md'), first: true }]));
|
||||
const args = (id: string) => ['pass', '--base', 'main', '--out', out, '--pass', id, '--audit-only', '--extras', extras];
|
||||
const upper = bin(dir, env, args('Docs-P1'));
|
||||
expect(upper.status, upper.stderr).toBe(0);
|
||||
expect(upper.stdout).toContain(`MANIFEST: file=${path.join(out, 'pass-manifest.json')} pass=docs-p1 readers=1 audit-only`);
|
||||
const m = JSON.parse(fs.readFileSync(path.join(out, 'pass-manifest.json'), 'utf8'));
|
||||
expect([m.pass, m.readers[0].title]).toEqual(['docs-p1', 'ship docs-p1 audit/docs']);
|
||||
const resumed = bin(dir, env, args('docs-p1'));
|
||||
expect([resumed.status, resumed.stdout.includes('pass=docs-p1 readers=1 resumed')]).toEqual([0, true]);
|
||||
for (const bad of ['p_1', 'p 1', 'p1/']) {
|
||||
const r = bin(dir, env, args(bad));
|
||||
expect([r.status, r.stderr.trim()]).toEqual([2, `gstack-review-dispatch pass: --pass ${JSON.stringify(bad)} is not a pass id: use letters, digits and dashes (read as lowercase, so P1 is p1)`]);
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
test('Step 11 notes its own growth from its first dispatch, not from the pass\'s starting reading', async () => {
|
||||
const { dir, env } = repo();
|
||||
const rec = path.join(dir, '.state/rec.md');
|
||||
|
||||
+145
-1
@@ -4,10 +4,11 @@
|
||||
* moved into the bin; each STOP is a place the prose leaves the decision to the agent.
|
||||
*/
|
||||
import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { laneConcurrency } from '../lib/ship-bin-common';
|
||||
import { lineOf, PREFLIGHT, shipFixture, type ShipFx } from './helpers/ship-bin-fixture';
|
||||
import { lineOf, PREFLIGHT, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture';
|
||||
|
||||
setDefaultTimeout(60_000);
|
||||
const fixtures: ShipFx[] = [];
|
||||
@@ -397,3 +398,146 @@ describe('gstack-ship-preflight Step 5 pregate: head policy and timeout_s (GST-4
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('gstack-ship-preflight during an open /ship run (GST-1204)', () => {
|
||||
const CHECKOUT = { GSTACK_LEASE_DIR: '' };
|
||||
const leaseFile = (f: ShipFx) => path.join(f.work, '.git', 'gstack-leases', String(process.pid));
|
||||
const wtree = (f: ShipFx) => f.run(path.join(path.dirname(RELEASE), 'gstack-wtree'), [], CHECKOUT).stdout.trim();
|
||||
/** Steps 12-16 in the fixture: the version bump, the docs snapshot and finish (the step that ends the run's hold on the base merge). */
|
||||
const finish = (f: ShipFx) => {
|
||||
const reviewed = wtree(f);
|
||||
expect(f.run(RELEASE, ['version', '--base', 'main', '--bump', 'micro'], CHECKOUT).status).toBe(0);
|
||||
const post = path.join(f.root, 'post.json');
|
||||
expect(f.run(path.join(path.dirname(RELEASE), 'gstack-docs-candidate'), ['snapshot', '--out', post, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'README.md'], CHECKOUT).status).toBe(0);
|
||||
const done = f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--lane', LANE], CHECKOUT);
|
||||
expect(done.status, done.stdout).toBe(0);
|
||||
};
|
||||
const refusedUntouched = (f: ShipFx, args: string[], run: string, added = 'docs/new.md') => {
|
||||
const head = f.git('rev-parse', 'HEAD').stdout.trim();
|
||||
const tracked = f.git('rev-parse', 'origin/main').stdout.trim();
|
||||
const r = f.run(PREFLIGHT, args, CHECKOUT);
|
||||
expect(r.status).toBe(3);
|
||||
expect(r.stdout).toContain(`STOP: /ship run ${run} is open on this checkout and past its preflight (`);
|
||||
expect(r.stdout).toContain('rerun Step 5 with --tests-only');
|
||||
expect(r.stdout).toMatch(/if it is no longer running, rm \S+gstack-ship-run, then rerun/);
|
||||
expect(r.stdout).not.toContain('MERGE:');
|
||||
expect(f.git('rev-parse', 'HEAD').stdout.trim()).toBe(head);
|
||||
expect(f.git('rev-parse', 'origin/main').stdout.trim()).toBe(tracked);
|
||||
expect(f.git('status', '--porcelain').stdout).toBe('');
|
||||
expect(fs.existsSync(path.join(f.work, added))).toBe(false);
|
||||
};
|
||||
|
||||
// Value: protects=a full preflight run again while this checkout's /ship run is open and past its own preflight stops before the fetch, so review readers never diff a tree the base merge moved;
|
||||
// fails_when=the rerun fetches or merges origin/<base> into the tree readers are diffing (gbrain-evals#317 voided a review pass), with or without --run; why_new=GST-1204;
|
||||
// seam=the run marker and gstack-lease open on the checkout's own lease; no_claim=a preflight that never passed --run
|
||||
test('a full preflight while this checkout\'s /ship run is open and past its preflight refuses before the fetch and leaves the tree untouched', () => {
|
||||
const f = fx();
|
||||
const run = `${process.pid}-${Math.floor(Date.now() / 1000)}-ab12cd34`;
|
||||
expect(f.run(PREFLIGHT, ['--base', 'main', '--run', run], CHECKOUT).status).toBe(0);
|
||||
f.advanceBase({ 'docs/new.md': '# new\n' });
|
||||
refusedUntouched(f, ['--base', 'main', '--run', run], run);
|
||||
refusedUntouched(f, ['--base', 'main'], run);
|
||||
});
|
||||
|
||||
// Value: protects=the Capy driver's sequence (ship/DRIVER.md Phase 2: preflight with --run and lanes, then --audit; repairs rerun --tests-only) is covered, and a mid-run full preflight is refused;
|
||||
// fails_when=the guard needs a workflow lease the driver never takes (GBEV-3 was a Capy lane), or it blocks --audit or --tests-only; why_new=GST-1204 driver coverage;
|
||||
// seam=the checkout lease gstack-ship-preflight opens itself; no_claim=reader dispatch
|
||||
test('the driver\'s sequence: Phase 2 preflight with --run, --audit and --tests-only go on; a mid-run full preflight is refused', () => {
|
||||
const f = fx();
|
||||
const phase2 = f.run(PREFLIGHT, ['--base', 'main', '--run', 'ship-run-7', '--lane', LANE], CHECKOUT);
|
||||
expect(phase2.status).toBe(0);
|
||||
expect(lineOf(phase2.stdout, 'LANE')).toMatch(/^LANE: tests pass/);
|
||||
expect(f.run(PREFLIGHT, ['--audit', '--base', 'main', '--out', path.join(f.root, 'run')], CHECKOUT).status).toBe(0);
|
||||
f.advanceBase({ 'docs/new.md': '# new\n' });
|
||||
refusedUntouched(f, ['--base', 'main', '--lane', LANE], 'ship-run-7');
|
||||
refusedUntouched(f, ['--base', 'main', '--run', 'ship-run-7', '--lane', LANE], 'ship-run-7');
|
||||
const repair = f.run(PREFLIGHT, ['--tests-only', '--base', 'main', '--lane', LANE], CHECKOUT);
|
||||
expect(repair.status).toBe(0);
|
||||
expect(lineOf(repair.stdout, 'LANE')).toMatch(/^LANE: tests pass exit=0 tests_ran=3/);
|
||||
});
|
||||
|
||||
// Value: protects=finish ends the run's hold, and a run past the 120-minute window (GST-1205's fresh rule) no longer blocks the next preflight;
|
||||
// fails_when=a marker left by an earlier /ship refuses every later preflight on the checkout; why_new=GST-1204 negative control; seam=finish clears the marker, gstack-lease fresh; no_claim=dead or reused holders, covered in test/gstack-lease.test.ts
|
||||
test('a finished or aged-out /ship run does not block a full preflight', () => {
|
||||
const ends: Record<string, (f: ShipFx) => void> = {
|
||||
finished: finish,
|
||||
'aged out': f => fs.writeFileSync(leaseFile(f), fs.readFileSync(leaseFile(f), 'utf8').replace(/^(run \S+ )(\d+)$/m, (_, p, t) => `${p}${Number(t) - 7300}`)),
|
||||
};
|
||||
for (const [why, end] of Object.entries(ends)) {
|
||||
const f = fx();
|
||||
expect(f.run(PREFLIGHT, ['--base', 'main', '--run', 'ship-run-7'], CHECKOUT).status).toBe(0);
|
||||
end(f);
|
||||
f.advanceBase({ 'docs/new.md': '# new\n' });
|
||||
const r = f.run(PREFLIGHT, ['--base', 'main'], CHECKOUT);
|
||||
expect({ why, status: r.status }).toEqual({ why, status: 0 });
|
||||
expect(lineOf(r.stdout, 'MERGE')).toMatch(/^MERGE: merged origin\/main at /);
|
||||
}
|
||||
});
|
||||
|
||||
// Value: protects=a /ship that stopped before finish does not block the next /ship from the same harness: gstack-skill-end's real release closes only the install lease, so the
|
||||
// new run id replaces the open one; another live holder's open run (another session) is still refused; fails_when=a stopped run blocks its own harness for 120 minutes
|
||||
// (#3950 review), or any new id passes another session's open run; why_new=GST-1204 review fix 1; seam=gstack-lease open --from (the caller's harness); no_claim=Capy, where every session shares capy-server
|
||||
test('a stopped /ship (skill-end released it) does not block a new run id from the same holder; another live holder\'s run is still refused', () => {
|
||||
const f = fx();
|
||||
const stopped = `${process.pid}-${Math.floor(Date.now() / 1000)}-ab12cd34`;
|
||||
expect(f.run(PREFLIGHT, ['--base', 'main', '--run', stopped], CHECKOUT).status).toBe(0);
|
||||
const end = f.run(path.join(path.dirname(PREFLIGHT), 'gstack-skill-end'), ['--skill', 'ship', '--outcome', 'error', '--session-id', stopped, '--tel-start', '0'], { GSTACK_LEASE_DIR: path.join(f.root, 'install-leases') });
|
||||
expect(end.status, end.stdout + end.stderr).toBe(0);
|
||||
f.advanceBase({ 'docs/new.md': '# new\n' });
|
||||
refusedUntouched(f, ['--base', 'main', '--run', stopped], stopped);
|
||||
const next = f.run(PREFLIGHT, ['--base', 'main', '--run', 'ship-run-8'], CHECKOUT);
|
||||
expect(next.status, next.stdout).toBe(0);
|
||||
expect(lineOf(next.stdout, 'MERGE')).toMatch(/^MERGE: merged origin\/main at /);
|
||||
const other = spawn('sleep', ['300'], { stdio: 'ignore' });
|
||||
try {
|
||||
const touch = spawnSync('bash', [path.join(path.dirname(PREFLIGHT), 'gstack-lease'), 'touch', '--root', f.work, '--pid', String(other.pid), '--run', 'other-session'], { encoding: 'utf8', env: { ...process.env, ...CHECKOUT }, timeout: 30_000 });
|
||||
expect(touch.status).toBe(0);
|
||||
fs.writeFileSync(path.join(f.work, '.git', 'gstack-ship-run'), 'other-session\n');
|
||||
f.advanceBase({ 'docs/other.md': '# other\n' });
|
||||
refusedUntouched(f, ['--base', 'main', '--run', 'ship-run-9'], 'other-session', 'docs/other.md');
|
||||
} finally { other.kill('SIGKILL'); }
|
||||
});
|
||||
|
||||
// Value: protects=a --run that cannot be recorded on the lease (a live process holds its lock) stops before the fetch instead of going on unprotected; fails_when=preflight exits 0
|
||||
// with no record, so a later full preflight merges the base under the run's reviews (#3950 outside voice); why_new=GST-1204 review fix 2; seam=gstack-lease touch exit 3; no_claim=which process holds the lock
|
||||
test('a --run the lease cannot record stops before the fetch', () => {
|
||||
const f = fx();
|
||||
const lock = path.join(f.work, '.git', 'gstack-leases', '.lock');
|
||||
fs.mkdirSync(lock, { recursive: true });
|
||||
fs.writeFileSync(path.join(lock, 'owner'), `${process.pid} \n`);
|
||||
f.advanceBase({ 'docs/new.md': '# new\n' });
|
||||
const tracked = f.git('rev-parse', 'origin/main').stdout.trim();
|
||||
const r = f.run(PREFLIGHT, ['--base', 'main', '--run', 'ship-run-7'], { ...CHECKOUT, GSTACK_LEASE_LOCK_TRIES: '2' });
|
||||
expect(r.status).toBe(3);
|
||||
expect(r.stdout).toContain('STOP: cannot record /ship run ship-run-7 on this checkout\'s lease (gstack-lease: the lease directory is locked by live process');
|
||||
expect(r.stdout).not.toContain('MERGE:');
|
||||
expect(f.git('rev-parse', 'origin/main').stdout.trim()).toBe(tracked);
|
||||
expect(fs.existsSync(path.join(f.work, '.git', 'gstack-ship-run'))).toBe(false);
|
||||
});
|
||||
|
||||
// Value: protects=/ship's own first preflight runs, and a first preflight that stopped (Step 3's conflict: commit and rerun) reruns in the same /ship run;
|
||||
// fails_when=the run is recorded before Steps 1-3 pass, so /ship blocks itself; why_new=GST-1204 negative control; seam=the marker is written only once Steps 1-3 pass; no_claim=conflict resolution
|
||||
test('/ship\'s own first preflight runs, and a stopped first preflight reruns in the same run', () => {
|
||||
const f = fx({}, { 'src/a.ts': 'export const a = 2;\n' });
|
||||
f.advanceBase({ 'src/a.ts': 'export const a = 3;\n' });
|
||||
const first = f.run(PREFLIGHT, ['--base', 'main', '--run', 'ship-run-7'], CHECKOUT);
|
||||
expect(first.status).toBe(3);
|
||||
expect(first.stdout).toContain('STOP: merge conflicts in src/a.ts');
|
||||
f.write({ 'src/a.ts': 'export const a = 4;\n' });
|
||||
f.commit('merge main');
|
||||
const again = f.run(PREFLIGHT, ['--base', 'main', '--run', 'ship-run-7'], CHECKOUT);
|
||||
expect(again.status).toBe(0);
|
||||
expect(lineOf(again.stdout, 'MERGE')).toBe('MERGE: up to date');
|
||||
});
|
||||
|
||||
// Value: protects=--run takes only a plain token, so a crafted value cannot become a path or split a lease entry; fails_when=any string is recorded and looked up;
|
||||
// why_new=GST-1204; seam=flag parsing; no_claim=none
|
||||
test('--run that is not a plain run id is usage', () => {
|
||||
const f = fx();
|
||||
for (const bad of [['--run', '../x'], ['--run', 'a b'], ['--run', '-x'], ['--run']]) {
|
||||
const r = f.run(PREFLIGHT, ['--base', 'main', ...bad]);
|
||||
expect(r.status).toBe(2);
|
||||
expect(r.stderr).toContain('--run needs a run id');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,419 @@
|
||||
/**
|
||||
* gstack-ship-queue land --pr <n> --pin <sha> (docs/ship-policy.md#land-direct): B1's direct land over real fixture
|
||||
* repos (bare origin, lane clone) and a gh shim that answers pr view (with mergeable, mergeStateStatus and the merge
|
||||
* commit), check runs and a squash merge against the bare origin. Covers the happy path for an unstamped,
|
||||
* fragment-only head, a base that moved but still merges clean, a refusal for each condition, the post-merge tree
|
||||
* check, the land note, train build under merge: direct, and the policy key's validation.
|
||||
*/
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { EXIT } from '../lib/headless-artifacts';
|
||||
import { MERGE_KEY_VERSION, validatePolicy } from '../lib/ship-policy';
|
||||
import { BASE_POLICY, cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture';
|
||||
import { shippedBody } from './helpers/ship-queue-train-fixture';
|
||||
import { persist, repoIdentity } from '../lib/ship-queue-train-record';
|
||||
import { rewriteStamps, tentativeMentions } from '../lib/restamp';
|
||||
import { bumpVersion } from '../lib/version-gate-train';
|
||||
|
||||
const REQUIRED = ['free-tests', 'Check VERSION is not stale vs queue'];
|
||||
const POLICY = { ...BASE_POLICY, release_tool: null, release_outputs: [], changelog_fragments: { dir: 'changelog.d', required_checks: REQUIRED }, merge: 'direct', min_gstack_version: MERGE_KEY_VERSION };
|
||||
const repos: FixtureRepo[] = [];
|
||||
afterEach(() => { while (repos.length) cleanup(repos.pop()!); });
|
||||
|
||||
interface Fx { repo: FixtureRepo; env: Record<string, string>; write: (fn: (d: any) => void) => void; read: () => any }
|
||||
function setup(policy: Record<string, unknown> = POLICY): Fx {
|
||||
const repo = makeFixtureRepo({ policy, prefix: 'gstack-land-direct-fx-' });
|
||||
repos.push(repo);
|
||||
const dir = path.join(repo.root, 'gh-shim');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const data = path.join(dir, 'data.json');
|
||||
fs.writeFileSync(data, JSON.stringify({ prs: {}, checks: {}, defaultChecks: REQUIRED }));
|
||||
fs.writeFileSync(path.join(dir, 'gh'), [
|
||||
'#!/usr/bin/env node',
|
||||
"const fs=require('fs');const {execFileSync}=require('child_process');",
|
||||
'const D=process.env.LAND_SHIM_DATA, O=process.env.LAND_SHIM_ORIGIN;',
|
||||
"const d=JSON.parse(fs.readFileSync(D,'utf8'));const a=process.argv.slice(2);",
|
||||
"const g=(...x)=>execFileSync('git',['--git-dir',O,...x],{encoding:'utf8',timeout:30000}).trim();",
|
||||
"const save=()=>fs.writeFileSync(D,JSON.stringify(d));",
|
||||
"if(a[0]==='pr'&&a[1]==='view'){const p=d.prs[a[2]];if(!p){console.error('no pr');process.exit(1)}",
|
||||
" let head='';try{head=g('rev-parse','refs/heads/'+p.headRefName)}catch{};",
|
||||
" console.log(JSON.stringify({mergeable:'MERGEABLE',mergeStateStatus:'CLEAN',...p,headRefOid:p.headRefOid??head,mergeCommit:p.mergeSha?{oid:p.mergeSha}:null}));process.exit(0)}",
|
||||
"if(a[0]==='api'){const m=/commits\\/([0-9a-f]+)\\/(check-runs|status)/.exec(a[1]);if(!m)process.exit(1);",
|
||||
" if(m[2]==='status'){console.log(JSON.stringify({total_count:0,statuses:[]}));process.exit(0)}",
|
||||
" const set=d.checks[m[1]]??Object.fromEntries(d.defaultChecks.map(n=>[n,'success']));",
|
||||
" const runs=Object.entries(set).map(([name,c],i)=>({id:i+1,name,status:c==='pending'?'in_progress':'completed',conclusion:c==='pending'?null:c,completed_at:'2026-11-03T00:00:00Z',app:{id:1}}));",
|
||||
" console.log(JSON.stringify({total_count:runs.length,check_runs:runs}));process.exit(0)}",
|
||||
"if(a[0]==='pr'&&a[1]==='merge'){const p=d.prs[a[2]];const want=a[a.indexOf('--match-head-commit')+1];const head=g('rev-parse','refs/heads/'+p.headRefName);",
|
||||
" if(head!==want){console.error('Head branch was modified');process.exit(1)}",
|
||||
" const main=g('rev-parse','refs/heads/main');let tree=g('merge-tree','--write-tree',main,want).split('\\n')[0];",
|
||||
" if(d.strayOnMerge){tree=g('rev-parse',main+'^{tree}')}",
|
||||
" const sq=g('commit-tree',tree,'-p',main,'-m','squash #'+a[2]);g('update-ref','refs/heads/main',sq);",
|
||||
" d.mergeArgs=a.slice(2);p.state='MERGED';p.mergeSha=sq;save();process.exit(0)}",
|
||||
"console.error('gh shim: unsupported '+a.join(' '));process.exit(1);",
|
||||
'',
|
||||
].join('\n'), { mode: 0o755 });
|
||||
const env = { PATH: dir + ':' + (process.env.PATH ?? ''), LAND_SHIM_DATA: data, LAND_SHIM_ORIGIN: repo.origin };
|
||||
const read = () => JSON.parse(fs.readFileSync(data, 'utf8'));
|
||||
return { repo, env, read, write: fn => { const d = read(); fn(d); fs.writeFileSync(data, JSON.stringify(d)); } };
|
||||
}
|
||||
|
||||
/** The READY receipt gstack-ship-queue ready records (a note on origin refs/notes/gstack-trains), written from another state root. */
|
||||
function markReady(fx: Fx, pr: string, head: string): void {
|
||||
const prior = process.env.GSTACK_STATE_ROOT;
|
||||
process.env.GSTACK_STATE_ROOT = path.join(fx.repo.root, 'ready-state');
|
||||
try {
|
||||
const now = new Date().toISOString();
|
||||
persist(fx.repo.work, [{ schema: 1, kind: 'ready', repo_key: repoIdentity(fx.repo.work).key, pr, head, base_sha: fx.repo.git('rev-parse', 'origin/main'), ready_at: now, screen: { choice: 'no-screen', policy: null, nonce: null, run: null, merge_sha: null }, updated_at: now }]);
|
||||
} finally { if (prior === undefined) delete process.env.GSTACK_STATE_ROOT; else process.env.GSTACK_STATE_ROOT = prior; }
|
||||
}
|
||||
|
||||
/** A PR branch from origin/main with one product file and a fragment, pushed, shipped (receipt at its head) and READY. */
|
||||
function openPr(fx: Fx, pr: string, opts: { edit?: (work: string) => void; shipped?: boolean; ready?: boolean; fork?: boolean } = {}): string {
|
||||
const { repo } = fx;
|
||||
repo.git('fetch', '-q', 'origin');
|
||||
repo.git('checkout', '-q', 'origin/main', '-B', 'pr-' + pr);
|
||||
fs.writeFileSync(path.join(repo.work, 'pr-' + pr + '.txt'), pr + '\n');
|
||||
fs.mkdirSync(path.join(repo.work, 'changelog.d'), { recursive: true });
|
||||
fs.writeFileSync(path.join(repo.work, 'changelog.d', 'pr-' + pr + '.md'), '- #' + pr + ' change\n');
|
||||
opts.edit?.(repo.work);
|
||||
repo.git('add', '-A');
|
||||
repo.git('commit', '-q', '-m', 'pr ' + pr);
|
||||
repo.git('push', '-q', '-f', 'origin', 'HEAD:refs/heads/pr-' + pr);
|
||||
const head = repo.git('rev-parse', 'HEAD');
|
||||
fx.write(d => { d.prs[pr] = { state: 'OPEN', baseRefName: 'main', headRefName: 'pr-' + pr, isCrossRepository: !!opts.fork, title: 'PR ' + pr, body: opts.shipped === false ? '' : shippedBody(pr, head) }; });
|
||||
if (opts.ready !== false) markReady(fx, pr, head);
|
||||
repo.git('checkout', '-q', '--detach', 'origin/main');
|
||||
return head;
|
||||
}
|
||||
const land = (fx: Fx, pr: string, pin: string, extra: string[] = []) => runBin(fx.repo, 'gstack-ship-queue', ['land', '--pr', pr, '--pin', pin, '--base', 'main', ...extra], fx.env);
|
||||
const remote = (fx: Fx, ref: string) => { fx.repo.git('fetch', '-q', 'origin', '+refs/heads/*:refs/remotes/origin/*'); return fx.repo.git('rev-parse', 'origin/' + ref); };
|
||||
const show = (fx: Fx, rev: string) => fx.repo.git('show', rev);
|
||||
const landNotes = (fx: Fx) => {
|
||||
const notes = (...a: string[]) => fx.repo.git('--git-dir', fx.repo.origin, 'notes', '--ref=refs/notes/gstack-trains', ...a);
|
||||
let list = '';
|
||||
try { list = notes('list'); } catch { return []; }
|
||||
return list.split('\n').filter(Boolean).map(l => JSON.parse(notes('show', l.split(' ')[1]!))).filter(r => r.kind === 'land');
|
||||
};
|
||||
/** Whether a clone holds a commit. */
|
||||
const spawnCheck = (dir: string, sha: string) => spawnSync('git', ['-C', dir, 'cat-file', '-e', `${sha}^{commit}`], { timeout: 30_000 }).status === 0;
|
||||
/** Commit a file straight onto origin/main (another PR that landed first). */
|
||||
function moveMain(fx: Fx, file: string, text: string): string {
|
||||
const { repo } = fx;
|
||||
repo.git('fetch', '-q', 'origin');
|
||||
repo.git('checkout', '-q', '--detach', 'origin/main');
|
||||
fs.writeFileSync(path.join(repo.work, file), text);
|
||||
repo.git('add', '-A');
|
||||
repo.git('commit', '-q', '-m', 'other change on main');
|
||||
repo.git('push', '-q', 'origin', 'HEAD:refs/heads/main');
|
||||
return repo.git('rev-parse', 'HEAD');
|
||||
}
|
||||
|
||||
describe('land --pin: direct merge at the PR\'s own green head', () => {
|
||||
test('happy path: an unstamped, fragment-only head merges with --squash --match-head-commit, main keeps its VERSION, and a land note is written', () => {
|
||||
const fx = setup();
|
||||
const base = remote(fx, 'main');
|
||||
const pin = openPr(fx, '7');
|
||||
const r = land(fx, '7', pin);
|
||||
expect(r.err).toBe('');
|
||||
expect(r.status).toBe(EXIT.ok);
|
||||
expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin]);
|
||||
const main = remote(fx, 'main');
|
||||
expect(fx.repo.git('rev-parse', main + '^1')).toBe(base);
|
||||
expect(r.out).toContain('MERGED: #7 as ' + main);
|
||||
expect(r.out).toMatch(/^LANDED: origin\/main tree [0-9a-f]+ equals the pin merged onto [0-9a-f]+$/m);
|
||||
expect(show(fx, main + ':VERSION')).toBe(show(fx, base + ':VERSION'));
|
||||
expect(show(fx, main + ':changelog.d/pr-7.md')).toBe('- #7 change');
|
||||
const notes = landNotes(fx);
|
||||
expect(notes).toHaveLength(1);
|
||||
expect(notes[0]).toMatchObject({ kind: 'land', pr: '7', pin, merge_sha: main, base_sha: base });
|
||||
}, 90_000);
|
||||
|
||||
test('the base moved and the PR still merges clean: it lands as it is, on the new base, with no restamp or extra CI round', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '8');
|
||||
const moved = moveMain(fx, 'other.txt', 'other\n');
|
||||
const r = land(fx, '8', pin);
|
||||
expect(r.err).toBe('');
|
||||
expect(r.status).toBe(EXIT.ok);
|
||||
const main = remote(fx, 'main');
|
||||
expect(fx.repo.git('rev-parse', main + '^1')).toBe(moved);
|
||||
expect(show(fx, main + ':other.txt')).toBe('other');
|
||||
expect(show(fx, main + ':pr-8.txt')).toBe('8');
|
||||
expect(fx.repo.git('rev-parse', 'origin/pr-8')).toBe(pin);
|
||||
}, 90_000);
|
||||
|
||||
test('a rerun after GitHub merged the PR goes straight to the tree check and lands', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '9');
|
||||
expect(land(fx, '9', pin).status).toBe(EXIT.ok);
|
||||
const again = land(fx, '9', pin);
|
||||
expect(again.err).toBe('');
|
||||
expect(again.status).toBe(EXIT.ok);
|
||||
expect(again.out).toContain('already merged');
|
||||
expect(again.out).toMatch(/^LANDED: /m);
|
||||
}, 90_000);
|
||||
|
||||
test('--dry-run checks everything and merges nothing', () => {
|
||||
const fx = setup();
|
||||
const base = remote(fx, 'main');
|
||||
const pin = openPr(fx, '10');
|
||||
const r = land(fx, '10', pin, ['--dry-run']);
|
||||
expect(r.err).toBe('');
|
||||
expect(r.out).toContain('DRY-RUN: nothing merged');
|
||||
expect(remote(fx, 'main')).toBe(base);
|
||||
}, 90_000);
|
||||
});
|
||||
|
||||
describe('land --pin: refusals (nothing merged)', () => {
|
||||
const refused = (fx: Fx, r: { status: number | null; err: string }, code: string) => {
|
||||
expect(r.status).not.toBe(EXIT.ok);
|
||||
expect(r.err).toContain('(' + code + ')');
|
||||
expect(fx.read().mergeArgs).toBeUndefined();
|
||||
};
|
||||
|
||||
test('QUEUE_LAND_STAMPED: a head that bumps VERSION names the one-command fix', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '11', { edit: w => fs.writeFileSync(path.join(w, 'VERSION'), '1.2.4.0\n') });
|
||||
const r = land(fx, '11', pin);
|
||||
refused(fx, r, 'QUEUE_LAND_STAMPED');
|
||||
expect(r.err).toContain('git checkout $(git merge-base origin/main HEAD) -- VERSION');
|
||||
}, 90_000);
|
||||
|
||||
test('QUEUE_LAND_STAMPED: a head that edits the CHANGELOG or the package.json version', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '12', {
|
||||
edit: w => {
|
||||
fs.appendFileSync(path.join(w, 'CHANGELOG.md'), '\n- stray\n');
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(w, 'package.json'), 'utf8')); pkg.version = '9.9.9';
|
||||
fs.writeFileSync(path.join(w, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');
|
||||
},
|
||||
});
|
||||
const r = land(fx, '12', pin);
|
||||
refused(fx, r, 'QUEUE_LAND_STAMPED');
|
||||
expect(r.err).toContain('CHANGELOG.md');
|
||||
expect(r.err).toContain('package.json version');
|
||||
}, 90_000);
|
||||
|
||||
test('a package.json dependency edit is not a stamp', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '13', {
|
||||
edit: w => { const pkg = JSON.parse(fs.readFileSync(path.join(w, 'package.json'), 'utf8')); pkg.dependencies = { ...(pkg.dependencies ?? {}), 'left-pad': '1.3.0' }; fs.writeFileSync(path.join(w, 'package.json'), JSON.stringify(pkg, null, 2) + '\n'); },
|
||||
});
|
||||
const r = land(fx, '13', pin);
|
||||
expect(r.err).toBe('');
|
||||
expect(r.status).toBe(EXIT.ok);
|
||||
}, 90_000);
|
||||
|
||||
test('QUEUE_LAND_PIN_MOVED: the PR head is not the pin', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '14');
|
||||
fx.write(d => { d.prs['14'].headRefOid = 'a'.repeat(40); });
|
||||
refused(fx, land(fx, '14', pin), 'QUEUE_LAND_PIN_MOVED');
|
||||
}, 90_000);
|
||||
|
||||
test('QUEUE_RECEIPT_MISSING: no /ship receipt in the PR body', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '15', { shipped: false });
|
||||
refused(fx, land(fx, '15', pin), 'QUEUE_RECEIPT_MISSING');
|
||||
}, 90_000);
|
||||
|
||||
test('QUEUE_NOT_READY: no READY note at the pin', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '16', { ready: false });
|
||||
const r = land(fx, '16', pin);
|
||||
refused(fx, r, 'QUEUE_NOT_READY');
|
||||
expect(r.err).toContain('gstack-ship-queue ready --pr 16');
|
||||
}, 90_000);
|
||||
|
||||
test('QUEUE_LAND_CHECKS: a red check, a pending check, and a required check GitHub never scheduled', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '17');
|
||||
fx.write(d => { d.checks[pin] = { 'free-tests': 'success', 'Check VERSION is not stale vs queue': 'success', other: 'failure' }; });
|
||||
expect(land(fx, '17', pin).err).toMatch(/red at .*\(QUEUE_LAND_CHECKS\)/);
|
||||
fx.write(d => { d.checks[pin] = { 'free-tests': 'pending', 'Check VERSION is not stale vs queue': 'success' }; });
|
||||
expect(land(fx, '17', pin).err).toMatch(/pending at .*\(QUEUE_LAND_CHECKS\)/);
|
||||
fx.write(d => { d.checks[pin] = { 'free-tests': 'success' }; });
|
||||
const missing = land(fx, '17', pin);
|
||||
refused(fx, missing, 'QUEUE_LAND_CHECKS');
|
||||
expect(missing.err).toContain('Check VERSION is not stale vs queue');
|
||||
}, 90_000);
|
||||
|
||||
test('QUEUE_LAND_NOT_CLEAN: GitHub does not report the PR mergeable and clean', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '18');
|
||||
fx.write(d => { d.prs['18'].mergeable = 'CONFLICTING'; d.prs['18'].mergeStateStatus = 'DIRTY'; });
|
||||
const r = land(fx, '18', pin);
|
||||
refused(fx, r, 'QUEUE_LAND_NOT_CLEAN');
|
||||
expect(r.err).toContain('DIRTY');
|
||||
}, 90_000);
|
||||
|
||||
test('QUEUE_TRAIN_UNTRUSTED: a fork head', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '19', { fork: true });
|
||||
refused(fx, land(fx, '19', pin), 'QUEUE_TRAIN_UNTRUSTED');
|
||||
}, 90_000);
|
||||
|
||||
test('QUEUE_NOT_READY: the base policy merges through trains', () => {
|
||||
const fx = setup({ ...POLICY, merge: 'train' });
|
||||
const pin = openPr(fx, '20');
|
||||
const r = land(fx, '20', pin);
|
||||
refused(fx, r, 'QUEUE_NOT_READY');
|
||||
expect(r.err).toContain('merge: train');
|
||||
}, 90_000);
|
||||
|
||||
test('QUEUE_LAND_UNVERIFIED: main\'s tree after the merge is not the pin merged onto its parent', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '21');
|
||||
fx.write(d => { d.strayOnMerge = true; });
|
||||
const r = land(fx, '21', pin);
|
||||
expect(r.status).not.toBe(EXIT.ok);
|
||||
expect(r.err).toContain('(QUEUE_LAND_UNVERIFIED)');
|
||||
expect(landNotes(fx)).toHaveLength(0);
|
||||
}, 90_000);
|
||||
});
|
||||
|
||||
describe('land --pin: fail closed and merge methods', () => {
|
||||
test('the old stamping land refuses under merge: direct, and a --pin with no sha is a usage error', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '23');
|
||||
const old = runBin(fx.repo, 'gstack-ship-queue', ['land', '--pr', '23', '--base', 'main', '--no-wait'], fx.env);
|
||||
expect(old.status).not.toBe(EXIT.ok);
|
||||
expect(old.err).toContain('merge: direct');
|
||||
expect(old.err).toContain('land --pr 23 --pin');
|
||||
expect(remote(fx, 'pr-23')).toBe(pin);
|
||||
const dangling = runBin(fx.repo, 'gstack-ship-queue', ['land', '--pr', '23', '--base', 'main', '--pin'], fx.env);
|
||||
expect(dangling.status).toBe(EXIT.usage);
|
||||
expect(fx.read().mergeArgs).toBeUndefined();
|
||||
}, 90_000);
|
||||
|
||||
test('a pin with no merge base on the base branch refuses instead of skipping the release-file check', () => {
|
||||
const fx = setup();
|
||||
const { repo } = fx;
|
||||
repo.git('checkout', '-q', '--orphan', 'pr-24');
|
||||
fs.writeFileSync(path.join(repo.work, 'VERSION'), '9.9.9.9\n');
|
||||
repo.git('add', '-A');
|
||||
repo.git('commit', '-q', '-m', 'unrelated history');
|
||||
repo.git('push', '-q', '-f', 'origin', 'HEAD:refs/heads/pr-24');
|
||||
const pin = repo.git('rev-parse', 'HEAD');
|
||||
fx.write(d => { d.prs['24'] = { state: 'OPEN', baseRefName: 'main', headRefName: 'pr-24', isCrossRepository: false, title: 'PR 24', body: shippedBody('24', pin) }; });
|
||||
markReady(fx, '24', pin);
|
||||
repo.git('checkout', '-q', '--detach', 'origin/main');
|
||||
const r = land(fx, '24', pin);
|
||||
expect(r.status).not.toBe(EXIT.ok);
|
||||
expect(r.err).toContain('cannot compute the merge base');
|
||||
expect(fx.read().mergeArgs).toBeUndefined();
|
||||
}, 90_000);
|
||||
|
||||
test('history: merge-only merges with --merge; a PR on another base refuses', () => {
|
||||
const fx = setup({ ...POLICY, history: 'merge-only' });
|
||||
const pin = openPr(fx, '25');
|
||||
fx.write(d => { d.prs['25'].baseRefName = 'dev'; });
|
||||
const other = land(fx, '25', pin);
|
||||
expect(other.err).toContain('targets dev, not main');
|
||||
expect(fx.read().mergeArgs).toBeUndefined();
|
||||
fx.write(d => { d.prs['25'].baseRefName = 'main'; });
|
||||
const r = land(fx, '25', pin);
|
||||
expect(r.err).toBe('');
|
||||
expect(fx.read().mergeArgs).toEqual(['25', '--merge', '--match-head-commit', pin]);
|
||||
}, 90_000);
|
||||
|
||||
test('land reads the policy after fetching the base: a required check main added since the last fetch is enforced', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '27');
|
||||
const other = fx.repo.root + '/other';
|
||||
fx.repo.git('clone', '-q', fx.repo.origin, other);
|
||||
fs.writeFileSync(path.join(other, '.gstack', 'ship-policy.json'), JSON.stringify({ ...POLICY, changelog_fragments: { dir: 'changelog.d', required_checks: [...REQUIRED, 'security-scan'] } }, null, 2) + '\n');
|
||||
fx.repo.git('-C', other, 'commit', '-qam', 'require security-scan');
|
||||
fx.repo.git('-C', other, 'push', '-q', 'origin', 'HEAD:refs/heads/main');
|
||||
const r = land(fx, '27', pin, ['--dry-run']);
|
||||
expect(r.err).toContain('security-scan');
|
||||
expect(r.err).toContain('(QUEUE_LAND_CHECKS)');
|
||||
}, 90_000);
|
||||
|
||||
test('a rerun from a fresh clone after the branch was deleted fetches the pin from refs/pull/<n>/head and lands', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '28');
|
||||
expect(land(fx, '28', pin).status).toBe(EXIT.ok);
|
||||
const g = (...a: string[]) => fx.repo.git('--git-dir', fx.repo.origin, ...a);
|
||||
g('update-ref', 'refs/pull/28/head', pin);
|
||||
fx.write(d => { d.prs['28'].headRefOid = pin; });
|
||||
g('update-ref', '-d', 'refs/heads/pr-28');
|
||||
const fresh = fx.repo.root + '/fresh';
|
||||
fx.repo.git('clone', '-q', '--no-local', '--single-branch', '--branch', 'main', fx.repo.origin, fresh);
|
||||
expect(spawnCheck(fresh, pin)).toBe(false);
|
||||
const r = runBin(fx.repo, 'gstack-ship-queue', ['land', '--pr', '28', '--pin', pin, '--base', 'main'], fx.env, fresh);
|
||||
expect(r.err).toBe('');
|
||||
expect(r.status).toBe(EXIT.ok);
|
||||
expect(r.out).toMatch(/^LANDED: /m);
|
||||
}, 90_000);
|
||||
|
||||
test('QUEUE_LAND_STAMPED: a head that repoints .gstack/version-path', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '29', { edit: w => { fs.mkdirSync(path.join(w, '.gstack'), { recursive: true }); fs.writeFileSync(path.join(w, 'OTHER_VERSION'), fs.readFileSync(path.join(w, 'VERSION'))); fs.writeFileSync(path.join(w, '.gstack', 'version-path'), 'OTHER_VERSION\n'); fs.writeFileSync(path.join(w, 'VERSION'), '9.9.9.9\n'); } });
|
||||
const r = land(fx, '29', pin);
|
||||
expect(r.err).toContain('(QUEUE_LAND_STAMPED)');
|
||||
expect(r.err).toContain('.gstack/version-path');
|
||||
expect(fx.read().mergeArgs).toBeUndefined();
|
||||
}, 90_000);
|
||||
|
||||
test('merge: direct without changelog_fragments refuses with the key to add', () => {
|
||||
const fx = setup({ ...POLICY, changelog_fragments: null });
|
||||
const pin = openPr(fx, '26');
|
||||
const r = land(fx, '26', pin);
|
||||
expect(r.err).toContain('merge: direct needs changelog_fragments');
|
||||
expect(fx.read().mergeArgs).toBeUndefined();
|
||||
}, 90_000);
|
||||
});
|
||||
|
||||
describe('merge: direct | train', () => {
|
||||
test('train build refuses under merge: direct and names land', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '22');
|
||||
const r = runBin(fx.repo, 'gstack-ship-queue', ['train', 'build', '--prs', '22@' + pin, '--base', 'main'], fx.env);
|
||||
expect(r.status).not.toBe(EXIT.ok);
|
||||
expect(r.err).toContain('merge: direct');
|
||||
expect(r.err).toContain('gstack-ship-queue land --pr <n> --pin <sha>');
|
||||
}, 90_000);
|
||||
|
||||
test('the key validates its values and needs min_gstack_version', () => {
|
||||
const errs = (o: Record<string, unknown>) => validatePolicy(o).map(e => e.path + ': ' + e.message).join('\n');
|
||||
expect(errs({ merge: 'direct', min_gstack_version: MERGE_KEY_VERSION })).toBe('');
|
||||
expect(errs({ merge: 'train' })).toBe('');
|
||||
expect(errs({ merge: 'sideways', min_gstack_version: MERGE_KEY_VERSION })).toContain('merge: must be one of direct | train');
|
||||
expect(errs({ merge: 'direct' })).toContain('introduced in gstack ' + MERGE_KEY_VERSION);
|
||||
});
|
||||
|
||||
test('the key floor follows the stamp: the train restamp moves MERGE_KEY_VERSION to the stamped 1.x.N, an N install reads a policy with min N, an N-1 install gets the upgrade message', () => {
|
||||
const root = path.resolve(import.meta.dir, '..');
|
||||
const fork = fs.readFileSync(path.join(root, 'VERSION'), 'utf8').trim();
|
||||
const stamped = bumpVersion(fork, 'patch')!;
|
||||
const tentative = bumpVersion(fork, 'minor')!;
|
||||
const policy = JSON.parse(fs.readFileSync(path.join(root, '.gstack', 'ship-policy.json'), 'utf8'));
|
||||
const templates: string[] = policy.stamp_patterns;
|
||||
expect(policy.stamp_paths).toContain('lib/ship-policy.ts');
|
||||
expect(templates).toContain("_KEY_VERSION = '{version}'");
|
||||
expect(fs.readFileSync(path.join(root, 'lib', 'ship-policy.ts'), 'utf8')).toContain(`export const MERGE_KEY_VERSION = '${MERGE_KEY_VERSION}';`);
|
||||
const line = `export const MERGE_KEY_VERSION = '${tentative}';`;
|
||||
expect(tentativeMentions(new Map([['lib/ship-policy.ts', new Set([line])]]), fork, stamped, templates)).toEqual([tentative]);
|
||||
const out = rewriteStamps(line, tentative, stamped, templates);
|
||||
expect(out.count).toBe(1);
|
||||
expect(out.text).toBe(`export const MERGE_KEY_VERSION = '${stamped}';`);
|
||||
const errs = (min: string, running: string) => validatePolicy({ merge: 'direct', min_gstack_version: min }, { gstackVersion: running });
|
||||
expect(errs(MERGE_KEY_VERSION, MERGE_KEY_VERSION)).toEqual([]);
|
||||
const parts = MERGE_KEY_VERSION.split('.').map(Number);
|
||||
const at = parts.findLastIndex(n => n > 0);
|
||||
parts[at] = parts[at]! - 1;
|
||||
const older = parts.join('.');
|
||||
const tooOld = errs(MERGE_KEY_VERSION, older);
|
||||
expect(tooOld.map(e => e.code)).toContain('POLICY_GSTACK_TOO_OLD');
|
||||
expect(tooOld.map(e => e.message).join('\n')).toContain(`this policy needs gstack ${MERGE_KEY_VERSION} or later; this gstack is ${older}`);
|
||||
});
|
||||
|
||||
test("gstack's own policy does not set merge before the key's release exists (min_gstack_version must name a published version)", () => {
|
||||
const raw = JSON.parse(fs.readFileSync(path.resolve(import.meta.dir, '..', '.gstack', 'ship-policy.json'), 'utf8'));
|
||||
const fork = fs.readFileSync(path.resolve(import.meta.dir, '..', 'VERSION'), 'utf8').trim();
|
||||
if ('merge' in raw) expect(validatePolicy(raw, { gstackVersion: fork })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -540,6 +540,69 @@ describe('land: one pass, base, lock and history', () => {
|
||||
expect(remote(fx, 'pr-11')).toBe(head);
|
||||
}, 90_000);
|
||||
|
||||
// Value: protects=a PR that writes a third-party version into a stamp_files line lands it byte for byte, while its own
|
||||
// fork-version token still moves (GST-1245, HARN-7: harness-evals#235's "QM v0.1.15" landed as "QM v0.0.115");
|
||||
// fails_when=land's restamp reads any vX newer than the fork point on a PR line as the PR's stamp; why_new=no land
|
||||
// case put a version in a stamp file; seam=lib/restamp.ts rewriteStampPaths via buildStamp; no_claim=none beyond protects
|
||||
test('a foreign version on a PR-added stamp_files line lands byte for byte; the PR\'s own fork-version token moves (GST-1245)', () => {
|
||||
const fx = setup({ ...POLICY, stamp_files: ['VERSION', 'package.json', 'package-lock.json', 'CHANGELOG.md', 'README.md'] });
|
||||
const qm = 'QM v2.1.15.0 grades every run.\nPin QM v2.1.15.0 in CI.\nUpgrade notes for QM v2.1.15.0 are below.\n';
|
||||
openPr(fx, '235', { edit: work => fs.writeFileSync(path.join(work, 'README.md'), qm + 'Written at fixture v1.2.3.0 by this PR.\n') });
|
||||
const r = land(fx, ['--pr', '235']);
|
||||
expect(r.err).toBe('');
|
||||
const stamp = remote(fx, 'pr-235');
|
||||
expect(show(fx, stamp + ':VERSION')).toBe('1.2.4.0');
|
||||
expect(show(fx, stamp + ':README.md')).toBe(qm + 'Written at fixture v1.2.4.0 by this PR.');
|
||||
}, 90_000);
|
||||
|
||||
// Value: protects=a stamp reset back to the reviewed pin restamps instead of resuming a journal whose stamp commit the
|
||||
// branch no longer holds (GST-1245, HARN-7: "resuming at stamped", then QUEUE_TRAIN_MOVED until the journal was removed
|
||||
// by hand); fails_when=land keeps the journal because the pin is one of the heads it names; why_new=every resume case
|
||||
// keeps the stamp commit on the branch; seam=lib/ship-queue-land.ts land; no_claim=the lock: own-lock resume already
|
||||
// matches on PR and journal path, and this case asserts it needs no --break-lock
|
||||
test.each([['pushed'], ['stamped']])('a stamp reset to the pin at phase %s discards the journal and restamps, with no --break-lock (GST-1245)', phase => {
|
||||
const fx = setup();
|
||||
const base = remote(fx, 'main');
|
||||
const pin = openPr(fx, '14');
|
||||
expect(land(fx, ['--pr', '14']).status).toBe(EXIT.ok);
|
||||
const first = remote(fx, 'pr-14');
|
||||
const file = path.join(fx.repo.work, '.gstack', 'tmp', 'ship-queue', 'land', '14.json');
|
||||
const journal = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
expect([journal.phase, journal.stamp_commit, journal.last_pushed_head]).toEqual(['pushed', first, first]);
|
||||
// phase stamped: a restamp built its commit and stopped before the push (the state HARN-7's rerun resumed at).
|
||||
if (phase === 'stamped') fs.writeFileSync(file, JSON.stringify({ ...journal, phase: 'stamped' }));
|
||||
fx.repo.git('push', '-q', '-f', 'origin', pin + ':refs/heads/pr-14');
|
||||
const again = land(fx, ['--pr', '14']);
|
||||
expect(again.err).toBe('');
|
||||
expect(again.status).toBe(EXIT.ok);
|
||||
expect(again.out).not.toContain('resuming at');
|
||||
expect(again.out).toContain(`JOURNAL: #14's head is the reviewed pin ${pin.slice(0, 12)}, not the stamp commit ${first.slice(0, 12)} (phase ${phase}); discarding the journal and restamping`);
|
||||
expect(again.out).not.toContain('LOCK: broke');
|
||||
expect(again.out).toContain('PUSHED: ');
|
||||
const restamped = remote(fx, 'pr-14');
|
||||
expect(fx.repo.git('rev-list', '--parents', '-n', '1', restamped).split(' ').slice(1)).toEqual([pin, base]);
|
||||
expect(land(fx, ['--pr', '14']).out).toContain('MERGED: #14');
|
||||
}, 90_000);
|
||||
|
||||
// Value: protects=a stamp land built but never pushed still resumes and pushes that commit: the branch never moved,
|
||||
// so nothing is discarded (GST-1245 review); fails_when=the reset check fires on any journal whose head is the pin;
|
||||
// why_new=the reset cases above all pushed a stamp first; seam=lib/ship-queue-land.ts land; no_claim=none beyond protects
|
||||
test('a stamp built but never pushed resumes at stamped and pushes that commit, discarding nothing (GST-1245)', () => {
|
||||
const fx = setup();
|
||||
const pin = openPr(fx, '15');
|
||||
expect(land(fx, ['--pr', '15']).status).toBe(EXIT.ok);
|
||||
const first = remote(fx, 'pr-15');
|
||||
const file = path.join(fx.repo.work, '.gstack', 'tmp', 'ship-queue', 'land', '15.json');
|
||||
fs.writeFileSync(file, JSON.stringify({ ...JSON.parse(fs.readFileSync(file, 'utf8')), phase: 'stamped', last_pushed_head: null }));
|
||||
fx.repo.git('push', '-q', '-f', 'origin', pin + ':refs/heads/pr-15');
|
||||
const again = land(fx, ['--pr', '15']);
|
||||
expect(again.err).toBe('');
|
||||
expect(again.out).toContain('(resuming at stamped)');
|
||||
expect(again.out).not.toContain('JOURNAL:');
|
||||
expect(again.out).toContain(`PUSHED: ${first}`);
|
||||
expect(remote(fx, 'pr-15')).toBe(first);
|
||||
}, 90_000);
|
||||
|
||||
// Value: protects=a lost local journal resumes from the stamp commit's pin; fails_when=the stamp commit is treated as the pin and the receipt refuses; why_new=resume cases keep the journal; seam=none; no_claim=none beyond protects
|
||||
test('with the local journal gone, a head that is land\'s stamp commit resumes from its pin', () => {
|
||||
const fx = setup();
|
||||
|
||||
@@ -151,4 +151,24 @@ describe('stamped train prefixes', () => {
|
||||
expect(out.stamped.map(s => s.version)).toEqual(['1.2.4.0']);
|
||||
expect(show(r, out.stamped[0]!.commit + ':docs/f.md')).toBe('// since: 1.2.4.0');
|
||||
}, 60_000);
|
||||
|
||||
// Value: protects=a slot whose own claim is above the version the train gives it still moves its built-in-form row,
|
||||
// because the claim is read from the pin's own commits through the train merge (GST-1245 red team); fails_when=the
|
||||
// recorded versions walk only the merge's first parent (the predecessor), so the row stays at the stale claim and
|
||||
// the train's own receipt passes it; seam=lib/restamp.ts recordedVersions via stampChain and stampMismatch
|
||||
test('a pin claiming 1.2.6.0 above its slot\'s 1.2.5.0 moves its own since: 1.2.6.0 row (GST-1245)', () => {
|
||||
const r = makeFixtureRepo({ policy: POLICY, prefix: 'train-stamp-' }); repos.push(r);
|
||||
pin(r, 'g', 'origin/main', '- g change\n');
|
||||
r.git('checkout', '-q', '--detach', 'origin/main');
|
||||
fs.writeFileSync(path.join(r.work, 'VERSION'), '1.2.4.0\n');
|
||||
r.git('commit', '-qam', 'main releases 1.2.4.0'); r.git('push', '-q', 'origin', 'HEAD:refs/heads/main'); r.git('fetch', '-q', 'origin');
|
||||
r.git('checkout', '-q', 'g');
|
||||
fs.writeFileSync(path.join(r.work, 'VERSION'), '1.2.6.0\n');
|
||||
fs.writeFileSync(path.join(r.work, 'docs', 'g.md'), '// since: 1.2.6.0\nQM v9.9.9.0 stays\n');
|
||||
r.git('add', '-A'); r.git('commit', '-q', '-m', 'g: claims 1.2.6.0, row at its claim, a foreign version beside it');
|
||||
const out = stampChain(chain(r, [['1', r.git('rev-parse', 'HEAD')]]));
|
||||
if ('code' in out) throw new Error(`${out.code}: ${out.message}`);
|
||||
expect(out.stamped.map(s => s.version)).toEqual(['1.2.5.0']);
|
||||
expect(show(r, out.stamped[0]!.commit + ':docs/g.md')).toBe('// since: 1.2.5.0\nQM v9.9.9.0 stays');
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"bytes": 2,
|
||||
"why": "GST-1204: Step 1 passes --run <SESSION_ID> so a full preflight rerun cannot merge the base under an open run's reviews"
|
||||
}
|
||||
@@ -9,10 +9,12 @@ let output: string;
|
||||
|
||||
beforeAll(() => {
|
||||
output = mkdtempSync(join(tmpdir(), 'gstack-spec-gate-render-'));
|
||||
const rendered = Bun.spawnSync(['bun', 'run', 'scripts/gen-skill-docs.ts', '--host', 'all', '--out-dir', output], {
|
||||
cwd: ROOT, stdout: 'pipe', stderr: 'pipe', timeout: 120_000,
|
||||
});
|
||||
if (rendered.exitCode !== 0) throw new Error(rendered.stderr.toString());
|
||||
for (const host of ['claude', 'codex']) {
|
||||
const rendered = Bun.spawnSync(['bun', 'run', 'scripts/gen-skill-docs.ts', '--host', host, '--out-dir', output], {
|
||||
cwd: ROOT, stdout: 'pipe', stderr: 'pipe', timeout: 120_000,
|
||||
});
|
||||
if (rendered.exitCode !== 0) throw new Error(rendered.stderr.toString());
|
||||
}
|
||||
});
|
||||
afterAll(() => { if (output) rmSync(output, { recursive: true, force: true }); });
|
||||
|
||||
|
||||
@@ -241,6 +241,7 @@ const BASELINE = [
|
||||
'test/test-free-shards-capture.test.ts',
|
||||
'test/timeline.test.ts',
|
||||
'test/ubicloud-runner-reattach.test.ts', // GSTA-151: split from test/ubicloud-runner.test.ts for shard time; runs scripts/ubicloud/ubi-runner.sh through test/helpers/ubi-runner-fake-vm.ts
|
||||
'test/ubicloud-runner-recovery.test.ts', // GST-1220: recovery bundle and results sink; runs scripts/ubicloud/ubi-runner.sh through test/helpers/ubi-runner-fake-vm.ts
|
||||
'test/ubicloud-runner-tiers.test.ts', // GSTA-151: split from test/ubicloud-runner.test.ts for shard time; runs scripts/ubicloud/ubi-runner.sh through test/helpers/ubi-runner-fake-vm.ts
|
||||
'test/workflow-judge-cache.test.ts', // slices test/skill-llm-eval.test.ts source (recorded 2026-10 when the ratchet learned paid-source slicing)
|
||||
'test/workflow-judge-input.test.ts', // slices test/skill-llm-eval.test.ts source (recorded 2026-10 when the ratchet learned paid-source slicing)
|
||||
|
||||
@@ -54,6 +54,20 @@ describe('routeDispatch: every run keeps its mode, and train inputs are validate
|
||||
expect((route({ ...screen, trainPolicy: false }) as { error: string }).error).toContain('needs a train block');
|
||||
});
|
||||
|
||||
// Value: protects=the release gate's bisect (lib/release-gate.ts) routes on its own release-gate/<id> ref under a release_gate policy, names its own
|
||||
// prefix artifact, keeps every train bisect check (nonce, head, cases, prefixes), and is refused without the policy or on any other ref;
|
||||
// fails_when=a release bisect needs a train block (it stops working once trains go), a release-gate/ ref routes without a release_gate policy, or a
|
||||
// train/ bisect starts accepting the release policy alone; why_new=the bisect test below covers train/<nonce> only; seam=none; no_claim=a live run
|
||||
test('a release bisect runs on release-gate/<id> under a release_gate policy, with the train checks and its own artifact', () => {
|
||||
const bisect = { nonce: bisectNonce, refName: 'release-gate/abc123-aaaaaaaaaaaa', expectedSha: A, cases: 'case-a', prefixShas: B, releasePolicy: true };
|
||||
expect(route(bisect)).toEqual({ mode: 'bisect', cases: ['case-a'], prefixes: [B], artifact: 'gstack-release-record' });
|
||||
expect((route({ ...bisect, releasePolicy: false, trainPolicy: true }) as { error: string }).error).toContain('needs a release_gate block');
|
||||
expect((route({ ...bisect, prefixShas: C }) as { error: string }).error).toContain('is not an ancestor');
|
||||
expect((route({ ...bisect, expectedSha: B }) as { error: string }).error).toContain('is not the train head');
|
||||
expect((route({ ...bisect, refName: 'train/t1', trainPolicy: false }) as { error: string }).error).toContain('needs a train block');
|
||||
expect((route({ ...bisect, refName: 'main' }) as { error: string }).error).toContain('runs on train/<nonce>');
|
||||
});
|
||||
|
||||
test('a bisect needs a bisect nonce on train/<nonce>, the train head, plan case ids and ancestor prefixes', () => {
|
||||
const bisect = { nonce: bisectNonce, refName: 'train/t1', expectedSha: A, cases: 'case-a, review/SKILL.md workflow', prefixShas: `${A},${B}`, trainPolicy: true };
|
||||
expect(route(bisect)).toEqual({ mode: 'bisect', cases: ['case-a', 'review/SKILL.md workflow'], prefixes: [A, B] });
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
/**
|
||||
* GST-1220: a dead controller strands nothing. The VM pushes its own results to the
|
||||
* caller's sink, and `recover` rebuilds a VM's local state on another controller
|
||||
* from the encrypted bundle `up` wrote. Offline: the fake API and fake VM only.
|
||||
*/
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { creates, fakeVm, gitSrc, run, until, vmDirs, type FakeVm } from './helpers/ubi-runner-fake-vm';
|
||||
|
||||
const fixtures: FakeVm[] = [];
|
||||
const make = () => { const f = fakeVm(); fixtures.push(f); return f; };
|
||||
const stopSink = (f: FakeVm) => {
|
||||
const pidFile = join(f.vm, '.ubirun-sink.pid');
|
||||
if (!existsSync(pidFile)) return;
|
||||
const pid = Number(readFileSync(pidFile, 'utf8').trim());
|
||||
if (!pid) return;
|
||||
try { process.kill(-pid, 'SIGKILL'); } catch { /* not a group leader or gone */ }
|
||||
try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ }
|
||||
};
|
||||
afterEach(() => {
|
||||
for (const f of fixtures.splice(0)) { stopSink(f); rmSync(f.root, { recursive: true, force: true }); }
|
||||
});
|
||||
const out = (r: { stdout: Buffer; stderr: Buffer }) => r.stdout.toString() + r.stderr.toString();
|
||||
const tarList = (tgz: string) => Bun.spawnSync(['tar', '-tzf', tgz], { timeout: 10_000 }).stdout.toString();
|
||||
const heartbeat = (tgz: string) => {
|
||||
const r = Bun.spawnSync(['tar', '-xzOf', tgz, 'heartbeat.json'], { timeout: 10_000 });
|
||||
try { return JSON.parse(r.stdout.toString()) as { vm: string; seq: number }; } catch { return { vm: '', seq: 0 }; }
|
||||
};
|
||||
const fileSink = (f: FakeVm, dir = join(f.root, 'sink')) => ({ UBI_SINK: 'file:' + dir, UBI_SINK_ALLOW_FILE: '1', UBI_SINK_INTERVAL: '1', UBI_REAP: '0' });
|
||||
const keyBody = (key: string) => key.split('\n').filter(l => l && !l.startsWith('-----'));
|
||||
|
||||
describe('ubi-runner results sink (GST-1220 a)', () => {
|
||||
test('the controller dies after up, and the VM still pushes its results to the sink', async () => {
|
||||
const f = make();
|
||||
const up = run(f, ['up', '--sink-path', 'results'], fileSink(f));
|
||||
expect(out(up)).toContain('sink: pushing');
|
||||
expect(up.exitCode).toBe(0);
|
||||
const name = up.stdout.toString().trim();
|
||||
rmSync(f.state, { recursive: true, force: true });
|
||||
mkdirSync(join(f.vm, 'results'), { recursive: true });
|
||||
writeFileSync(join(f.vm, 'results', 'r.json'), '{"score": 7}\n');
|
||||
const tgz = join(f.root, 'sink', name, 'results.tgz');
|
||||
await until(() => existsSync(tgz) && tarList(tgz).includes('results/r.json'), 30_000);
|
||||
const first = heartbeat(tgz);
|
||||
expect(first.vm).toBe(name);
|
||||
writeFileSync(join(f.vm, 'results', 'r2.json'), '{"score": 8}\n');
|
||||
await until(() => heartbeat(tgz).seq > first.seq && tarList(tgz).includes('results/r2.json'), 30_000);
|
||||
}, 90_000);
|
||||
|
||||
test('a sink must be a presigned https-put URL; file: only under the test switch; nothing is created otherwise', () => {
|
||||
const f = make();
|
||||
for (const spec of ['http://plain.example/x', 'git:https://github.com/a/b', 'file:/tmp/x']) {
|
||||
const r = run(f, ['up'], { UBI_SINK: spec, UBI_REAP: '0' });
|
||||
expect(r.exitCode).not.toBe(0);
|
||||
expect(out(r)).toContain('UBI_SINK_INVALID');
|
||||
}
|
||||
expect(creates(f)).toBe(0);
|
||||
});
|
||||
|
||||
test('the presigned URL reaches the VM only through a 600 file, never a command line or a log', async () => {
|
||||
const f = make();
|
||||
const url = 'https://bucket.example/o?X-Amz-Signature=sekritsig123';
|
||||
const up = run(f, ['up'], { UBI_SINK: 'https-put:' + url, UBI_REAP: '0' });
|
||||
expect(up.exitCode).toBe(0);
|
||||
await until(() => existsSync(join(f.vm, '.ubirun-sink.curl')) && existsSync(join(f.vm, '.ubirun-sink.pid')), 30_000);
|
||||
expect(readFileSync(join(f.vm, '.ubirun-sink.curl'), 'utf8')).toContain('sekritsig123');
|
||||
expect(statSync(join(f.vm, '.ubirun-sink.curl')).mode & 0o777).toBe(0o600);
|
||||
expect(statSync(join(f.vm, '.ubirun-sink.conf')).mode & 0o777).toBe(0o600);
|
||||
expect(f.ssh()).not.toContain('sekritsig123');
|
||||
expect(out(up)).not.toContain('sekritsig123');
|
||||
}, 60_000);
|
||||
|
||||
test('run keeps the presigned URL out of its run record, and a command word --sink stays in it', async () => {
|
||||
const f = make();
|
||||
writeFileSync(join(f.root, 'make-test.sh'), 'echo begin; sleep 3\n');
|
||||
const a = f.spawn(['run', '--sink', 'https-put:https://b.example/o?X-Amz-Signature=sekritsig456', '--src', gitSrc(f), '--', 'make', 'test', '--sink', 'kept'], { UBI_REAP: '0' });
|
||||
await until(() => vmDirs(f).some(d => existsSync(join(f.state, d, 'command.out')) && readFileSync(join(f.state, d, 'command.out'), 'utf8').includes('begin')), 30_000);
|
||||
const name = vmDirs(f)[0]!;
|
||||
const record = readFileSync(join(f.state, name, 'run'), 'utf8');
|
||||
expect(record).not.toContain('sekritsig456');
|
||||
expect(record).toContain(' -- make test --sink kept');
|
||||
expect(await a.exited).toBe(0);
|
||||
expect(f.listed().trim()).toBe('');
|
||||
}, 90_000);
|
||||
|
||||
test('a failed final push prints SINK_FLUSH_FAILED, the VM is destroyed anyway, and run exits 1', () => {
|
||||
const f = make();
|
||||
const blocker = join(f.root, 'blocker');
|
||||
writeFileSync(blocker, 'a file where the sink directory should be\n');
|
||||
const r = run(f, ['run', '--src', gitSrc(f), '--', 'echo hi'], { ...fileSink(f, blocker), UBI_SINK_INTERVAL: '3600' });
|
||||
expect(out(r)).toContain('SINK_FLUSH_FAILED: vm=');
|
||||
expect(r.exitCode).toBe(1);
|
||||
expect(f.listed().trim()).toBe('');
|
||||
}, 90_000);
|
||||
|
||||
test('a snapshot over UBI_SINK_MAX_MB keeps the last good one, and the final flush stops the pusher and fails', async () => {
|
||||
const f = make();
|
||||
const env = { ...fileSink(f), UBI_SINK_MAX_MB: '1' };
|
||||
const up = run(f, ['up', '--sink-path', 'results', '--sink-path', '.'], env);
|
||||
expect(up.exitCode).toBe(0);
|
||||
const name = up.stdout.toString().trim();
|
||||
mkdirSync(join(f.vm, 'results'), { recursive: true });
|
||||
writeFileSync(join(f.vm, 'results', 'r.json'), '{"score": 7}\n');
|
||||
const tgz = join(f.root, 'sink', name, 'results.tgz');
|
||||
await until(() => existsSync(tgz) && tarList(tgz).includes('results/r.json'), 30_000);
|
||||
expect(tarList(tgz)).not.toContain('.ubirun-');
|
||||
const pid = Number(readFileSync(join(f.vm, '.ubirun-sink.pid'), 'utf8').trim());
|
||||
writeFileSync(join(f.vm, 'results', 'big.bin'), Buffer.from(Array.from({ length: 3 << 20 }, () => Math.floor(Math.random() * 256))));
|
||||
const down = run(f, ['down', name], env);
|
||||
expect(down.exitCode).toBe(0);
|
||||
expect(out(down)).toMatch(new RegExp('SINK_FLUSH_FAILED: vm=' + name + ' seq=\\d+ last_push=\\d+ sink_skipped=size'));
|
||||
expect(tarList(tgz)).toContain('results/r.json');
|
||||
expect(tarList(tgz)).not.toContain('big.bin');
|
||||
expect(() => process.kill(pid, 0)).toThrow();
|
||||
}, 90_000);
|
||||
|
||||
test('a reaped VM whose final push fails does not fail a run that passed on its own VM', () => {
|
||||
const f = make();
|
||||
const blocker = join(f.root, 'blocker');
|
||||
writeFileSync(blocker, 'a file where the sink directory should be\n');
|
||||
const old = 'ubirun-thrd1-1000000000-abcd1234-t1';
|
||||
expect(run(f, ['up', '-n', old], { ...fileSink(f, blocker), UBI_SINK_INTERVAL: '3600' }).exitCode).toBe(0);
|
||||
const r = run(f, ['run', '--src', gitSrc(f), '--', 'echo hi']);
|
||||
expect(out(r)).toContain('SINK_FLUSH_FAILED: vm=' + old);
|
||||
expect(r.exitCode).toBe(0);
|
||||
expect(f.listed().trim()).toBe('');
|
||||
}, 90_000);
|
||||
});
|
||||
|
||||
describe('ubi-runner recovery bundle (GST-1220 b)', () => {
|
||||
const setup = () => {
|
||||
const f = make();
|
||||
const rec = join(f.root, 'recovery');
|
||||
const up = run(f, ['up', '--tag', 'shard=3'], { UBI_RECOVERY_DIR: rec, UBI_REAP: '0' });
|
||||
expect(up.exitCode).toBe(0);
|
||||
const name = up.stdout.toString().trim();
|
||||
const key = readFileSync(join(f.state, name, 'key'), 'utf8');
|
||||
const bundle = join(rec, 'thrd1', name + '.bundle');
|
||||
return { f, rec, up, name, key, bundle, state2: join(f.root, 'state2') };
|
||||
};
|
||||
|
||||
test('recover rebuilds a VM on a new controller, and pull and down work from there', () => {
|
||||
const { f, rec, up, name, key, bundle, state2 } = setup();
|
||||
expect(existsSync(bundle)).toBe(true);
|
||||
expect(statSync(bundle).mode & 0o777).toBe(0o600);
|
||||
expect(readFileSync(bundle, 'latin1')).not.toContain('PRIVATE KEY');
|
||||
const env2 = { UBI_RECOVERY_DIR: rec, UBI_RUNNER_STATE: state2, UBI_OWNER: 'thrd2', UBI_REAP: '0' };
|
||||
const r = run(f, ['recover', '--owner', 'thrd1'], env2);
|
||||
expect(r.exitCode).toBe(0);
|
||||
expect(r.stdout.toString()).toContain(`RECOVERED: vm=${name} ip=192.0.2.1 owner=thrd1 tags=shard=3`);
|
||||
expect(readFileSync(join(state2, name, 'key'), 'utf8')).toBe(key);
|
||||
expect(statSync(join(state2, name)).mode & 0o777).toBe(0o700);
|
||||
expect(readFileSync(join(state2, name, 'env'), 'utf8')).toMatch(/^CREATE_PID=$/m);
|
||||
const again = run(f, ['recover', '--owner', 'thrd1'], env2);
|
||||
expect(again.stdout.toString()).toContain(`RECOVER_FAILED: vm=${name} code=RECOVER_EXISTS`);
|
||||
mkdirSync(join(f.root, 'remote-fs', 'results'), { recursive: true });
|
||||
writeFileSync(join(f.root, 'remote-fs', 'results', 'r.json'), '{}\n');
|
||||
expect(run(f, ['pull', name, 'results', join(f.root, 'pulled')], env2).exitCode).toBe(0);
|
||||
expect(existsSync(join(f.root, 'pulled', 'results', 'r.json'))).toBe(true);
|
||||
const down = run(f, ['down', name], env2);
|
||||
expect(down.exitCode).toBe(0);
|
||||
expect(existsSync(bundle)).toBe(false);
|
||||
expect(f.listed().trim()).toBe('');
|
||||
for (const line of keyBody(key)) for (const text of [out(up), out(r), out(down), f.ssh()]) expect(text).not.toContain(line);
|
||||
}, 90_000);
|
||||
|
||||
test('a wrong secret or a tampered bundle never decrypts, writes no state and keeps the bundle', () => {
|
||||
const { f, rec, name, bundle, state2 } = setup();
|
||||
const env2 = { UBI_RECOVERY_DIR: rec, UBI_RUNNER_STATE: state2, UBI_REAP: '0' };
|
||||
const wrong = run(f, ['recover'], { ...env2, UBI_RECOVERY_KEY: 'not-the-secret' });
|
||||
expect(wrong.stdout.toString()).toContain(`RECOVER_FAILED: vm=${name} code=RECOVER_DECRYPT_FAILED`);
|
||||
const bytes = readFileSync(bundle);
|
||||
bytes[bytes.length - 40] ^= 1;
|
||||
writeFileSync(bundle, bytes);
|
||||
chmodSync(bundle, 0o600);
|
||||
const tampered = run(f, ['recover'], env2);
|
||||
expect(tampered.stdout.toString()).toContain(`RECOVER_FAILED: vm=${name} code=RECOVER_DECRYPT_FAILED`);
|
||||
expect(existsSync(join(state2, name))).toBe(false);
|
||||
expect(existsSync(bundle)).toBe(true);
|
||||
}, 60_000);
|
||||
|
||||
test('a valid bundle under another VM or owner name is refused before the API is asked', () => {
|
||||
const { f, rec, name, bundle, state2 } = setup();
|
||||
const other = 'ubirun-other-1700000000-dead1234-t3';
|
||||
writeFileSync(join(rec, 'thrd1', other + '.bundle'), readFileSync(bundle));
|
||||
mkdirSync(join(rec, 'thrd9'), { recursive: true });
|
||||
writeFileSync(join(rec, 'thrd9', name + '.bundle'), readFileSync(bundle));
|
||||
writeFileSync(join(f.root, 'listed'), f.listed() + 'us-east-a2 ' + other + '\n');
|
||||
const env2 = { UBI_RECOVERY_DIR: rec, UBI_RUNNER_STATE: state2, UBI_REAP: '0' };
|
||||
const r = run(f, ['recover'], env2);
|
||||
expect(r.stdout.toString()).toContain(`RECOVER_FAILED: vm=${other} code=RECOVER_DECRYPT_FAILED`);
|
||||
expect(r.stdout.toString()).toContain(`RECOVERED: vm=${name}`);
|
||||
expect(existsSync(join(state2, other))).toBe(false);
|
||||
const adopted = run(f, ['recover', '--owner', 'thrd9'], { ...env2, UBI_RUNNER_STATE: join(f.root, 'state3') });
|
||||
expect(adopted.stdout.toString()).toContain(`RECOVER_FAILED: vm=${name} code=RECOVER_DECRYPT_FAILED`);
|
||||
}, 60_000);
|
||||
|
||||
test('an API outage keeps the bundle; a VM that is gone drops it', () => {
|
||||
const { f, rec, name, bundle, state2 } = setup();
|
||||
const env2 = { UBI_RECOVERY_DIR: rec, UBI_RUNNER_STATE: state2, UBI_REAP: '0' };
|
||||
writeFileSync(join(f.root, 'listed.show-fails'), '');
|
||||
const down = run(f, ['recover'], env2);
|
||||
expect(down.stdout.toString()).toContain(`RECOVER_FAILED: vm=${name} code=RECOVER_API_UNAVAILABLE`);
|
||||
expect(existsSync(bundle)).toBe(true);
|
||||
rmSync(join(f.root, 'listed.show-fails'));
|
||||
writeFileSync(join(f.root, 'listed'), '');
|
||||
const gone = run(f, ['recover'], env2);
|
||||
expect(gone.stdout.toString()).toContain(`RECOVER_GONE: vm=${name}`);
|
||||
expect(existsSync(bundle)).toBe(false);
|
||||
}, 60_000);
|
||||
|
||||
test('a counted run refuses before any create without a recovery directory', () => {
|
||||
const f = make();
|
||||
for (const [args, extra] of [[['up'], { UBI_COUNTED: '1' }], [['up', '--counted'], {}]] as [string[], Record<string, string>][]) {
|
||||
const r = run(f, args, { ...extra, UBI_REAP: '0' });
|
||||
expect(r.exitCode).not.toBe(0);
|
||||
expect(out(r)).toContain('UBI_RECOVERY_REQUIRED');
|
||||
}
|
||||
expect(creates(f)).toBe(0);
|
||||
writeFileSync(join(f.root, 'blocker'), 'a file where the recovery directory should be\n');
|
||||
const unwritable = run(f, ['up', '--counted'], { UBI_RECOVERY_DIR: join(f.root, 'blocker', 'rec'), UBI_REAP: '0' });
|
||||
expect(unwritable.exitCode).not.toBe(0);
|
||||
expect(out(unwritable)).toContain('UBI_RECOVERY_UNAVAILABLE');
|
||||
expect(creates(f)).toBe(0);
|
||||
for (const bad of [['--sink-path', '/etc'], ['--sink-path', 'a/../..'], ['--tag', 'no-equals']]) {
|
||||
const r = run(f, ['up', ...bad], { UBI_REAP: '0' });
|
||||
expect(r.exitCode).not.toBe(0);
|
||||
}
|
||||
expect(creates(f)).toBe(0);
|
||||
const rec = join(f.root, 'recovery');
|
||||
const ok = run(f, ['up', '--counted'], { UBI_RECOVERY_DIR: rec, UBI_REAP: '0' });
|
||||
expect(ok.exitCode).toBe(0);
|
||||
expect(existsSync(join(rec, 'thrd1', ok.stdout.toString().trim() + '.bundle'))).toBe(true);
|
||||
});
|
||||
|
||||
test('a counted rerun refuses to reattach to a VM that has no bundle', async () => {
|
||||
const f = make();
|
||||
const repo = gitSrc(f);
|
||||
writeFileSync(join(f.root, 'make-test.sh'), 'echo begin; sleep 4; echo end\n');
|
||||
const a = f.spawn(['run', '--src', repo, '--', 'make test'], { UBI_REAP: '0' });
|
||||
await until(() => vmDirs(f).some(d => existsSync(join(f.state, d, 'command.out')) && readFileSync(join(f.state, d, 'command.out'), 'utf8').includes('begin')), 30_000);
|
||||
process.kill(a.pid, 'SIGKILL');
|
||||
await a.exited;
|
||||
const name = vmDirs(f)[0]!;
|
||||
const r = run(f, ['run', '--counted', '--src', repo, '--', 'make test'], { UBI_RECOVERY_DIR: join(f.root, 'rec'), UBI_REAP: '0' });
|
||||
expect(out(r)).toContain('UBI_RECOVERY_REQUIRED: a counted run would reattach to ' + name);
|
||||
expect(r.exitCode).not.toBe(0);
|
||||
expect(creates(f)).toBe(1);
|
||||
expect(run(f, ['down', name]).exitCode).toBe(0);
|
||||
}, 90_000);
|
||||
|
||||
test('a counted rerun refuses a bundle that does not open, and reattaches once the bundle is good again', async () => {
|
||||
const f = make();
|
||||
const repo = gitSrc(f);
|
||||
const rec = join(f.root, 'rec');
|
||||
writeFileSync(join(f.root, 'make-test.sh'), 'echo begin; sleep 4; echo end\n');
|
||||
const a = f.spawn(['run', '--src', repo, '--', 'make test'], { UBI_RECOVERY_DIR: rec, UBI_REAP: '0' });
|
||||
await until(() => vmDirs(f).some(d => existsSync(join(f.state, d, 'command.out')) && readFileSync(join(f.state, d, 'command.out'), 'utf8').includes('begin')), 30_000);
|
||||
process.kill(a.pid, 'SIGKILL');
|
||||
await a.exited;
|
||||
const name = vmDirs(f)[0]!;
|
||||
const bundle = join(rec, 'thrd1', name + '.bundle');
|
||||
const good = readFileSync(bundle);
|
||||
writeFileSync(bundle, 'not a bundle\n');
|
||||
const corrupt = run(f, ['run', '--counted', '--src', repo, '--', 'make test'], { UBI_RECOVERY_DIR: rec, UBI_REAP: '0' });
|
||||
expect(out(corrupt)).toContain('UBI_RECOVERY_REQUIRED: a counted run would reattach to ' + name);
|
||||
expect(corrupt.exitCode).not.toBe(0);
|
||||
expect(creates(f)).toBe(1);
|
||||
writeFileSync(bundle, good);
|
||||
const ok = run(f, ['run', '--counted', '--src', repo, '--', 'make test'], { UBI_RECOVERY_DIR: rec, UBI_REAP: '0' });
|
||||
expect(out(ok)).toContain('reattached to ' + name);
|
||||
expect(ok.exitCode).toBe(0);
|
||||
expect(creates(f)).toBe(1);
|
||||
}, 90_000);
|
||||
|
||||
test('the runner never forwards its own variables: --pass and --trust-config both refuse them', () => {
|
||||
const f = make();
|
||||
const dir = gitSrc(f, { command: 'make verify', pass: ['RECOVERY_SECRET'] });
|
||||
const env = { UBI_RECOVERY_KEY: 'recovery-key-value', UBI_SINK: 'https-put:https://b.example/o?X-Amz-Signature=sekritsig321', UBI_REAP: '0' };
|
||||
const trusted = run(f, ['verify', '--src', dir, '--trust-config'], env);
|
||||
expect(trusted.exitCode).toBe(1);
|
||||
expect(out(trusted)).toContain('--pass RECOVERY_SECRET');
|
||||
for (const name of ['RECOVERY_SECRET', 'RECOVERY_DIR', 'OWNER', 'SINK_INTERVAL', 'UBI_RECOVERY_KEY', 'UBI_SINK']) {
|
||||
const r = run(f, ['run', '--pass', name, '--src', dir, '--', 'true'], env);
|
||||
expect(r.exitCode).toBe(1);
|
||||
expect(out(r)).toContain('--pass ' + name);
|
||||
}
|
||||
expect(creates(f)).toBe(0);
|
||||
expect(existsSync(join(f.root, 'ubirun-env'))).toBe(false);
|
||||
});
|
||||
|
||||
test('--pass forwards the value the caller exported, never a runner variable of the same name', () => {
|
||||
const f = make();
|
||||
const sinkDir = join(f.root, 'sink');
|
||||
const repo = gitSrc(f);
|
||||
for (const name of ['opt', 'src', 'sink']) {
|
||||
const r = run(f, ['run', '--pass', name, '--src', repo, '--', 'test "$' + name + '" = caller-' + name], { ...fileSink(f, sinkDir), [name]: 'caller-' + name });
|
||||
expect(out(r)).not.toContain('not in this shell');
|
||||
expect(r.exitCode).toBe(0);
|
||||
}
|
||||
expect(f.ssh()).not.toContain(sinkDir);
|
||||
}, 120_000);
|
||||
|
||||
test('an option value spelled --sink does not carry the presigned URL into the run record', async () => {
|
||||
const f = make();
|
||||
writeFileSync(join(f.root, 'make-test.sh'), 'echo begin; sleep 3\n');
|
||||
const a = f.spawn(['run', '--key-input', '--sink', '--sink', 'https-put:https://b.example/o?X-Amz-Signature=sekritsig789', '--src', gitSrc(f), '--', 'make', 'test'], { UBI_REAP: '0' });
|
||||
await until(() => vmDirs(f).some(d => existsSync(join(f.state, d, 'command.out')) && readFileSync(join(f.state, d, 'command.out'), 'utf8').includes('begin')), 30_000);
|
||||
const name = vmDirs(f)[0]!;
|
||||
const record = readFileSync(join(f.state, name, 'run'), 'utf8');
|
||||
expect(record).not.toContain('sekritsig789');
|
||||
expect(record).toContain('--key-input --sink --src');
|
||||
expect(await a.exited).toBe(0);
|
||||
}, 90_000);
|
||||
});
|
||||
@@ -380,6 +380,29 @@ test('pack ships a linked worktree with a self-contained .git on the checked-out
|
||||
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||
}, 60_000);
|
||||
|
||||
// Value: protects=sync and pack of a subdirectory of a git checkout (gstack-evals' launch.sh syncs quick/laneb/runner) ship that subdirectory's working files; fails_when=pack fetches refs from a path below the work tree's root, which git's local transport refuses, or ships the whole repository's .git so the VM sees every file outside the subdirectory as deleted; why_new=every pack test packs a work tree's root or a plain directory; seam=none
|
||||
test('pack of a subdirectory of a checkout or a linked worktree ships its tracked, edited and untracked files without a .git', () => {
|
||||
const d = mkdtempSync(join(tmpdir(), 'ubi-pack-subdir-'));
|
||||
try {
|
||||
const sh = (cmd: string, cwd: string) => { const r = Bun.spawnSync(['bash', '-c', cmd], { cwd, timeout: 30_000, env: { ...process.env, GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t' } }); expect(r.exitCode, `${cmd}\n${r.stderr.toString()}`).toBe(0); return r.stdout.toString(); };
|
||||
sh('git init -q repo && cd repo && echo top > top && mkdir -p sub/nested && echo a > sub/a && echo b > sub/nested/b && echo g > sub/gone && echo "*.log" > sub/.gitignore && git add -A && git commit -qm one && git worktree add -q ../wt', d);
|
||||
const tree = (dir: string) => sh('find . -type f | sort', dir).split('\n').filter(Boolean);
|
||||
for (const checkout of ['repo', 'wt']) {
|
||||
const sub = join(d, checkout, 'sub');
|
||||
sh('echo edited > a && rm gone && echo n > new && echo x > x.log', sub);
|
||||
const vm = join(d, `vm-${checkout}`);
|
||||
sh(`mkdir ${JSON.stringify(vm)} && bash ${JSON.stringify(join(DIR, 'ubi-runner.sh'))} pack sub | tar -xzf - -C ${JSON.stringify(vm)}`, join(d, checkout));
|
||||
expect(tree(vm)).toEqual(['./.gitignore', './a', './nested/b', './new']);
|
||||
expect(readFileSync(join(vm, 'a'), 'utf8')).toBe('edited\n');
|
||||
}
|
||||
// A subdirectory the checkout ignores lists no files; pack refuses it instead of shipping an empty archive.
|
||||
sh('echo scratch/ > .gitignore && mkdir -p scratch/job && echo s > scratch/job/f', join(d, 'repo'));
|
||||
const ignored = Bun.spawnSync(['bash', join(DIR, 'ubi-runner.sh'), 'pack', 'scratch/job'], { cwd: join(d, 'repo'), timeout: 30_000 });
|
||||
expect(ignored.exitCode).toBe(1);
|
||||
expect(ignored.stderr.toString()).toContain('pack: git lists no files under');
|
||||
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||
}, 60_000);
|
||||
|
||||
test('pack snapshots a plain checkout without reading its live .git: remotes resolve, a detached HEAD gets a branch, and git running beside it cannot fail the tar', () => {
|
||||
const d = mkdtempSync(join(tmpdir(), 'ubi-pack-live-'));
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user