Let /gstack-ship handle very large results PRs (GST-4003) (#4847)

`/gstack-ship` now works on results PRs with tens of thousands of files
and hundreds of megabytes of diff: more exclusion patterns, a secrets
check with no size limit, a faster review plan and docs check, and
bulleted ruled notes.

Why: two 16,000-file results PRs hit each of these limits in real runs.

Nothing to do: existing policies keep working unchanged.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p2/adversarial-native#1 reader=adversarial-native
Review-Finding: p2/outside-voice#1 reader=outside-voice
Review-Finding: p2/outside-voice#2 reader=outside-voice
Review-Finding: p2/outside-voice#3 reader=outside-voice
Review-Finding: p2/outside-voice#4 reader=outside-voice
Review-Finding: p2/specialist-batched#2 reader=specialist-batched
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-26 16:54:59 +00:00
1 parent 0febbce1e4
commit 77da8a0160
21 files changed
+756 -101

No files matched your search

+102
View File
@@ -0,0 +1,102 @@
/**
* GST-4003: whole-diff readers no longer stop at a pipe's maxBuffer. gitDiffInParts has git write to a private file and hands
* the output back in whole-file parts; the secrets check (lib/pregate/checks/secrets.ts) and gstack-banned-terms parse each
* part, and must get exactly what parsing the whole text gave them, past any single-read limit.
*/
import { afterAll, beforeAll, 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 { gitDiffInParts, mergeParts } from '../lib/diff-parts';
import { addedLines as bannedAdded } from '../lib/banned-terms';
import { addedLines, parseAddedLineNumbers, parseAddedLines, parsePostimages } from '../lib/pregate/checks/secrets';
import type { PregateContext } from '../lib/pregate/types';
/** An empty global git config (os.devNull is not a file git can read on Windows). */
const EMPTY_CONFIG = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'gitcfg-')), 'config');
fs.writeFileSync(EMPTY_CONFIG, '');
afterAll(() => fs.rmSync(path.dirname(EMPTY_CONFIG), { recursive: true, force: true }));
let root = '';
let base = '';
const env = { ...process.env, GIT_CONFIG_GLOBAL: EMPTY_CONFIG, GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'F', GIT_AUTHOR_EMAIL: 'f@example.test', GIT_COMMITTER_NAME: 'F', GIT_COMMITTER_EMAIL: 'f@example.test' };
const git = (...args: string[]) => {
const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', env, timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });
if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);
return r.stdout;
};
const put = (rel: string, text: string) => { fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true }); fs.writeFileSync(path.join(root, rel), text); };
const DIFF = ['diff', '--text', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/', '--unified=0', '--diff-filter=ACMR'];
beforeAll(() => {
root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'diff-parts-')));
git('init', '-q', '-b', 'main');
put('keep.py', 'a = 1\nb = 2\n');
put('old.txt', 'old\n');
git('add', '-A');
git('commit', '-qm', 'base');
base = git('rev-parse', 'HEAD').trim();
for (let i = 0; i < 120; i++) put(`results/run-${i % 7}/case-${i}.jsonl`, Array.from({ length: 40 }, (_, j) => JSON.stringify({ i, j, note: 'x'.repeat(j * 3) })).join('\n') + '\n');
put('results/big.log', Array.from({ length: 30_000 }, (_, j) => `step ${j} ok`).join('\n') + '\n');
put('notes/fake-header.md', 'diff --git a/x b/x\n+++ b/fake\n@@ -1 +1 @@\n');
put('docs/é tudes.md', '# études\n');
put('keep.py', 'a = 1\nsecret = "x"\nb = 2\n');
put('old.txt', 'old\nnew\n');
git('add', '-A');
git('commit', '-qm', 'branch');
});
afterAll(() => { if (root) fs.rmSync(root, { recursive: true, force: true }); });
const parts = (args: string[], partBytes: number) => {
const out: string[] = [];
const r = gitDiffInParts(args, { cwd: root, timeout: 60_000, env }, p => out.push(p), partBytes);
return { r, out };
};
describe('gitDiffInParts', () => {
test('the parts are git\'s output byte for byte, each after the first starting at a file header', () => {
const whole = git(...DIFF, base, '--');
for (const size of [7, 64, 257, 4096, 1 << 20]) {
const { r, out } = parts([...DIFF, base, '--'], size);
expect(r).toEqual({ ok: true });
expect(out.join('')).toBe(whole);
for (const p of out.slice(1)) expect(p.startsWith('diff --')).toBe(true);
}
expect(parts([...DIFF, base, '--'], 257).out.length).toBeGreaterThan(100);
}, 60_000);
test('every per-file parser folded over the parts gives what it gave on the whole text', () => {
const whole = git(...DIFF, base, '--');
const fold = <T>(parse: (s: string) => Map<string, T[]>) => { const m = new Map<string, T[]>(); parts([...DIFF, base, '--'], 300).out.forEach(p => mergeParts(m, parse(p))); return [...m]; };
expect(fold(parseAddedLines)).toEqual([...parseAddedLines(whole)]);
expect(fold(parseAddedLineNumbers)).toEqual([...parseAddedLineNumbers(whole)]);
expect(fold(bannedAdded)).toEqual([...bannedAdded(whole)]);
const full = ['-c', 'diff.suppressBlankEmpty=false', 'diff', '--no-color', '--unified=100000000', base, '--'];
const posts = new Map<string, string[]>();
parts(full, 200).out.forEach(p => mergeParts(posts, parsePostimages(p)));
expect([...posts]).toEqual([...parsePostimages(git(...full))]);
});
test('an output over a pipe read\'s limit still arrives whole, and the secrets check reads it through the parts', () => {
const args = [...DIFF, base, '--'];
const bytes = Buffer.byteLength(git(...args));
const piped = spawnSync('git', args, { cwd: root, encoding: 'utf8', env, timeout: 60_000, maxBuffer: Math.floor(bytes / 4) });
expect((piped.error as NodeJS.ErrnoException | undefined)?.code).toBe('ENOBUFS');
const { r, out } = parts(args, Math.floor(bytes / 8));
expect(r.ok).toBe(true);
expect(Buffer.byteLength(out.join(''))).toBe(bytes);
const ctx = { repoRoot: root, mergeBase: base, env, touched: [] } as unknown as PregateContext;
const files = addedLines(ctx).map(p => p.file).sort();
expect(files).toContain('results/big.log');
expect(files).toContain('notes/fake-header.md');
expect(files.filter(f => f.startsWith('results/run-')).length).toBe(120);
});
test('a git that fails is not ok, and leaves no file behind', () => {
const before = fs.readdirSync(os.tmpdir()).filter(f => f.startsWith('gstack-diff-')).length;
const r = gitDiffInParts(['diff', 'f'.repeat(40), '--'], { cwd: root, timeout: 60_000, env }, () => { throw new Error('no part expected'); });
expect(r.ok).toBe(false);
expect(fs.readdirSync(os.tmpdir()).filter(f => f.startsWith('gstack-diff-')).length).toBe(before);
});
});
+86
View File
@@ -0,0 +1,86 @@
/**
* GST-4003: classifyDocsOnly asks git which files name each changed doc with one batched `git grep -f -` instead of one
* `git grep` per path (harness-evals' 16,000-file results PRs), and gets the same answer referencesTo gives path by path.
*/
import { afterAll, beforeAll, 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 { classifyDocsOnly, referencesTo, referencesToAll } from '../lib/docs-only';
/** An empty global git config (os.devNull is not a file git can read on Windows). */
const EMPTY_CONFIG = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'gitcfg-')), 'config');
fs.writeFileSync(EMPTY_CONFIG, '');
afterAll(() => fs.rmSync(path.dirname(EMPTY_CONFIG), { recursive: true, force: true }));
const env = { ...process.env, GIT_CONFIG_GLOBAL: EMPTY_CONFIG, GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'F', GIT_AUTHOR_EMAIL: 'f@example.test', GIT_COMMITTER_NAME: 'F', GIT_COMMITTER_EMAIL: 'f@example.test' };
let repo = '';
const git = (...args: string[]) => {
const r = spawnSync('git', args, { cwd: repo, encoding: 'utf8', env, timeout: 30_000 });
if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);
return r.stdout;
};
const put = (rel: string, text: string | Buffer) => { fs.mkdirSync(path.dirname(path.join(repo, rel)), { recursive: true }); fs.writeFileSync(path.join(repo, rel), text); };
const DOCS = [...Array.from({ length: 40 }, (_, i) => `docs/results/run-${i}.md`), 'README.md', 'docs/README.md', 'docs/guide.md'];
beforeAll(() => {
repo = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'docs-batch-')));
git('init', '-q', '-b', 'main');
for (const d of DOCS) put(d, `# ${d}\n`);
put('lib/a.ts', "export const doc = 'see docs/README.md and docs/results/run-1.md';\n");
put('lib/é.ts', "// é docs/results/run-2.md\n");
put('scripts/run.sh', 'cat docs/results/run-3.md docs/results/run-30.md\n');
put('assets/blob.bin', Buffer.concat([Buffer.from('docs/results/run-4.md'), Buffer.from([0, 1, 2, 0])]));
put('CHANGELOG.md', '- docs/guide.md\n');
git('add', '-A');
git('commit', '-qm', 'seed');
git('tag', 'seed');
for (const d of DOCS) put(d, `# ${d}\n\nedited\n`);
git('commit', '-qam', 'edit');
});
afterAll(() => { if (repo) fs.rmSync(repo, { recursive: true, force: true }); });
describe('batched reference scan', () => {
test('referencesToAll gives every path what referencesTo gives it, at a commit and on the working tree', () => {
for (const tree of ['HEAD', undefined]) {
const all = referencesToAll(repo, DOCS, tree);
expect(Object.fromEntries(all)).toEqual(Object.fromEntries(DOCS.map(p => [p, referencesTo(repo, p, tree)])));
}
const head = referencesToAll(repo, DOCS, 'HEAD');
expect(head.get('README.md')).toEqual(['lib/a.ts']);
expect(head.get('docs/results/run-3.md')).toEqual(['scripts/run.sh']);
expect(head.get('docs/results/run-2.md')).toEqual(['lib/é.ts']);
expect(head.get('docs/results/run-4.md')).toEqual([]);
expect(head.get('docs/guide.md')).toEqual([]);
});
test('on the working tree, a file git grep reads from the index is matched on its index bytes, as referencesTo is', () => {
put('lib/a.ts', 'export {};\n');
git('update-index', '--assume-unchanged', 'lib/a.ts');
try {
expect(referencesTo(repo, 'README.md')).toEqual(['lib/a.ts']);
expect(referencesToAll(repo, DOCS).get('README.md')).toEqual(['lib/a.ts']);
} finally {
git('update-index', '--no-assume-unchanged', 'lib/a.ts');
git('checkout', '--', 'lib/a.ts');
}
});
test('classifyDocsOnly runs a bounded number of git grep calls however many docs change', () => {
const trace = path.join(repo, '..', `${path.basename(repo)}.trace`);
const before = process.env.GIT_TRACE;
process.env.GIT_TRACE = trace;
try {
const r = classifyDocsOnly({ root: repo, base: 'seed', head: 'HEAD' });
expect(r.docsOnly).toBe(false);
expect(r.refusals.map(x => x.path).sort()).toEqual(['README.md', 'docs/README.md', 'docs/results/run-1.md', 'docs/results/run-2.md', 'docs/results/run-3.md', 'docs/results/run-30.md']);
} finally {
if (before === undefined) delete process.env.GIT_TRACE; else process.env.GIT_TRACE = before;
}
const greps = fs.readFileSync(trace, 'utf8').split('\n').filter(l => /trace: built-in: git grep /.test(l)).length;
fs.rmSync(trace, { force: true });
expect(greps).toBeGreaterThan(0);
expect(greps).toBeLessThanOrEqual(2);
});
});
+15 -15
View File
@@ -29,29 +29,29 @@ const planJson = (repo: FixtureRepo) => { const r = runBin(repo, 'gstack-review-
describe('an invalid exclusion list on the base is set aside, never loosened (GST-3399)', () => {
// Value: protects=a base whose only error is review_exclude_paths' length plans with every file reviewed and its other keys
// applied, with a loud line on stdout and stderr and the record in --json; fails_when=the plan refuses POLICY_INVALID (the
// harness-evals deadlock), applies some of the 65 patterns, or drops the base's readers.forbid_paths with the bad key;
// harness-evals deadlock), applies some of the 257 patterns, or drops the base's readers.forbid_paths with the bad key;
// why_new=GST-3399; seam=gstack-review-plan on a real repository; no_claim=what reviewers do with the files
test('65 patterns on the base: the plan reviews every file, keeps forbid_paths and says why', () => {
const repo = repoWith({ review_exclude_paths: patterns(65) });
test('257 patterns on the base: the plan reviews every file, keeps forbid_paths and says why', () => {
const repo = repoWith({ review_exclude_paths: patterns(257) });
const r = plan(repo);
expect(r.status, r.err).toBe(EXIT.ok);
expect(r.out).toContain('REVIEW_EXCLUDE: fallback (WARNING: the base policy origin/main@');
expect(r.out).toContain('review_exclude_paths: more than 64 patterns');
expect(r.out).toContain('review_exclude_paths: more than 256 patterns');
expect(r.out).toContain('every file is reviewed');
expect(r.err).toContain('gstack-review-plan: REVIEW_EXCLUDE: fallback (WARNING');
expect(r.out).toMatch(/READERS: forbid_fetch=0 forbid_paths=1 /);
const j = planJson(repo);
expect(j.review_exclude.state).toBe('fallback');
expect(j.review_exclude.errors).toEqual(['review_exclude_paths: more than 64 patterns']);
expect(j.review_exclude.errors).toEqual(['review_exclude_paths: more than 256 patterns']);
expect(j.paths).toContain('data/p0/r.json');
expect(j.readers.forbid_paths).toEqual(['private/**']);
expect(receiptExcludeFallback(j.review_exclude)).toEqual({ source: j.review_exclude.source, errors: ['review_exclude_paths: more than 64 patterns'] });
expect(receiptExcludeFallback(j.review_exclude)).toEqual({ source: j.review_exclude.source, errors: ['review_exclude_paths: more than 256 patterns'] });
}, 120_000);
// Value: protects=the PR that fixes the list is planned under the base's (set-aside) list, not its own valid one; fails_when=
// the head's 61 patterns are applied before they land; seam=gstack-review-plan --json; no_claim=the land step
test('the PR that shortens the list is still planned with nothing excluded', () => {
const repo = repoWith({ review_exclude_paths: patterns(65) }, { '.gstack/ship-policy.json': policyText({ review_exclude_paths: patterns(61) }) });
const repo = repoWith({ review_exclude_paths: patterns(257) }, { '.gstack/ship-policy.json': policyText({ review_exclude_paths: patterns(61) }) });
const j = planJson(repo);
expect(j.review_exclude.state).toBe('fallback');
expect(j.paths).toContain('data/p0/r.json');
@@ -60,11 +60,11 @@ describe('an invalid exclusion list on the base is set aside, never loosened (GS
// Value: protects=a valid base list plans exactly as before (negative control); fails_when=a valid list falls back or stops
// excluding; seam=gstack-review-plan; no_claim=the excluded file count beyond this fixture
test('a valid base list still excludes its files', () => {
const repo = repoWith({ review_exclude_paths: patterns(64) });
const repo = repoWith({ review_exclude_paths: patterns(256) });
const r = plan(repo);
expect(r.status, r.err).toBe(EXIT.ok);
expect(r.out).not.toContain('fallback');
expect(r.out).toMatch(/REVIEW_EXCLUDE: patterns=1\/64 excluded=1 /);
expect(r.out).toMatch(/REVIEW_EXCLUDE: patterns=1\/256 excluded=1 /);
expect(planJson(repo).review_exclude.state).toBe('active');
}, 120_000);
@@ -82,7 +82,7 @@ describe('an invalid exclusion list on the base is set aside, never loosened (GS
// fails_when=the fallback swallows an error in a key whose default would loosen review or readers; seam=gstack-review-plan
// and gstack-ship-queue's loadBasePolicy; no_claim=the wording of the refusal
test('a base with another invalid key still refuses, in the plan and in the queue', () => {
const repo = repoWith({ review_exclude_paths: patterns(65), review: { panel: 'some' } });
const repo = repoWith({ review_exclude_paths: patterns(257), review: { panel: 'some' } });
const r = plan(repo);
expect(r.status).toBe(EXIT.refused);
expect(r.err).toContain('POLICY_INVALID');
@@ -95,7 +95,7 @@ describe('an invalid exclusion list on the base is set aside, never loosened (GS
// (review_exclude_paths[0]) is an error of its own and still refuses; fails_when=the key filter is unanchored and drops that key
// with the list; seam=lib/ship-policy.ts finish; no_claim=the wording of the refusal
test('an unknown key that starts with an exclusion key name still refuses', () => {
const repo = repoWith({ review_exclude_paths: patterns(65), 'review_exclude_paths[0]': 'data/**' });
const repo = repoWith({ review_exclude_paths: patterns(257), 'review_exclude_paths[0]': 'data/**' });
const r = plan(repo);
expect(r.status).toBe(EXIT.refused);
expect(r.err).toContain('POLICY_INVALID');
@@ -105,7 +105,7 @@ describe('an invalid exclusion list on the base is set aside, never loosened (GS
// Value: protects=the merge step reads a base that fails only on its exclusion list, with its other keys, so the PR that fixes
// the list can land; fails_when=gstack-ship-queue refuses POLICY_INVALID on it; seam=loadBasePolicy; no_claim=land's checks
test('the queue reads such a base with its other keys', () => {
const repo = repoWith({ review_exclude_paths: patterns(65) });
const repo = repoWith({ review_exclude_paths: patterns(257) });
const q = loadBasePolicy({ repoRoot: repo.work, base: 'main', gh: () => ({ ok: false, out: '' }) });
expect('code' in q ? q : null).toBeNull();
expect('policy' in q && q.policy.review_exclude_paths).toEqual([]);
@@ -116,18 +116,18 @@ describe('an invalid exclusion list on the base is set aside, never loosened (GS
// owner fixes it; fails_when=gstack-ship-policy validate --policy-from base reports such a base valid; seam=the validate CLI;
// no_claim=validate's other output
test('validate still reports the base list as invalid', () => {
const repo = repoWith({ review_exclude_paths: patterns(65) });
const repo = repoWith({ review_exclude_paths: patterns(257) });
const r = runBin(repo, 'gstack-ship-policy', ['validate', '--policy-from', 'base', '--base', 'main']);
expect(r.status).toBe(EXIT.fail);
expect(r.out).toContain('POLICY_INVALID: 1 error(s)');
expect(r.err).toContain('more than 64 patterns at review_exclude_paths');
expect(r.err).toContain('more than 256 patterns at review_exclude_paths');
}, 120_000);
// Value: protects=show-effective, which /ship's POLICY line and /land-and-deploy's stamp check read, reports such a base valid
// with its other keys and the loud fallback line; fails_when=it exits 1 with valid:false (land-and-deploy then reads no
// queue_mode) or drops the warning; seam=the show-effective CLI; no_claim=renderEffective's other lines
test('show-effective reads the base with its other keys and warns', () => {
const repo = repoWith({ review_exclude_paths: patterns(65), queue_mode: 'stamp-at-merge' });
const repo = repoWith({ review_exclude_paths: patterns(257), queue_mode: 'stamp-at-merge' });
const r = runBin(repo, 'gstack-ship-policy', ['show-effective', '--base', 'main', '--json']);
expect(r.status, r.err).toBe(EXIT.ok);
const j = JSON.parse(r.out);
+109
View File
@@ -0,0 +1,109 @@
/**
* GST-4003: review_exclude_paths selection and the named-by-code scan cost the same however many patterns and paths a PR
* has. select reads one diff for every pattern and splits it by git's own pathspec match; fixedIndex hands git one token
* per string and finds exactly the strings a body holds.
*/
import { afterAll, beforeAll, 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 { fixedIndex, select } from '../lib/review-exclude-match';
/** An empty global git config (os.devNull is not a file git can read on Windows). */
const EMPTY_CONFIG = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'gitcfg-')), 'config');
fs.writeFileSync(EMPTY_CONFIG, '');
afterAll(() => fs.rmSync(path.dirname(EMPTY_CONFIG), { recursive: true, force: true }));
describe('fixedIndex', () => {
const strings = ['docs/a.json', 'a.json', 'results/run-1/a.json', 'results/', 'LICENSE', 'vendor/x/LICENSE', 'data/b.jsonl', 'c.', 'é/ü.json'];
const naive = (body: string) => new Set(strings.filter(s => body.includes(s)));
test('finds exactly the strings body.includes finds, overlaps and prefixes included', () => {
const bodies = ['see docs/a.json and data/b.jsonl', "load('results/run-1/a.json')", 'LICENSE vendor/x/LICENSE', 'a.jsonl only', 'results/ results/run-2', 'c.d c.', 'path é/ü.json', '', 'docs/a.jsonx', 'xdocs/a.json'];
const ix = fixedIndex(strings);
for (const b of bodies) expect([...ix.holds(b)].sort()).toEqual([...naive(b)].sort());
});
test('git gets one token per distinct suffix, and every string ends with its token', () => {
const ix = fixedIndex(strings);
expect(ix.tokens.sort()).toEqual(['.', '.json', '.jsonl', 'LICENSE', 'results/'].sort());
for (const s of strings) expect(ix.tokens.some(t => s.endsWith(t))).toBe(true);
const many = Array.from({ length: 16_000 }, (_, i) => `docs/benchmarks/run-${i % 40}/results/case-${i}.json`);
expect(fixedIndex(many).tokens).toEqual(['.json']);
expect([...fixedIndex(many).holds("x = 'docs/benchmarks/run-3/results/case-43.json'")]).toEqual(['docs/benchmarks/run-3/results/case-43.json']);
});
});
describe('select', () => {
let root = '';
let base = '';
const env = { ...process.env, GIT_CONFIG_GLOBAL: EMPTY_CONFIG, GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'F', GIT_AUTHOR_EMAIL: 'f@example.test', GIT_COMMITTER_NAME: 'F', GIT_COMMITTER_EMAIL: 'f@example.test' };
const git = (...args: string[]) => { const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', env, timeout: 30_000 }); if (r.status !== 0) throw new Error(r.stderr); return r.stdout; };
const put = (rel: string, text: string) => { fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true }); fs.writeFileSync(path.join(root, rel), text); };
beforeAll(() => {
root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'exclude-select-')));
git('init', '-q', '-b', 'main');
put('results/old.json', '1\n');
put('src/a.ts', 'a\n');
git('add', '-A'); git('commit', '-qm', 'base');
base = git('rev-parse', 'HEAD').trim();
for (let i = 0; i < 30; i++) put(`results/run-${i % 3}/raw/c${i}.json`, `${i}\n`);
put('results/run-0/logs/x.log', 'log\n');
put('docs/r.md', '# r\n');
put('a.b/x.json', '1\n');
fs.rmSync(path.join(root, 'results/old.json'));
git('add', '-A'); git('commit', '-qm', 'branch');
});
afterAll(() => { if (root) fs.rmSync(root, { recursive: true, force: true }); });
test('each pattern gets what its own git diff --raw lists, in the same order, deletions included', () => {
const patterns = ['results/**/raw/**', 'results/**', '**/*.json', '**/*.log', 'nothing/**', 'docs/*.md', 'a.b/**'];
const head = git('rev-parse', 'HEAD').trim();
const one = (p: string) => git('diff', '--raw', '-z', '--no-abbrev', '--no-renames', base, head, '--', `:(top,glob)${p}`).split('\0').filter((_, k) => k % 2 === 1).filter(Boolean);
const s = select({ root, mergeBase: base, head }, patterns);
if ('error' in s) throw new Error(s.error);
for (const p of patterns) expect(s.byPattern.get(p)).toEqual(one(p));
expect(s.byPattern.get('results/**')).toContain('results/old.json');
expect(s.files.get('results/old.json')!.newMode).toBe('000000');
const single = select({ root, mergeBase: base, head }, ['results/**']);
expect('error' in single ? single : single.byPattern.get('results/**')).toEqual(one('results/**'));
const none = select({ root, mergeBase: base, head }, []);
expect('error' in none ? none : none.files.size).toBe(0);
});
test('a file that replaces a directory of the same name stays matched (one index cannot hold both)', () => {
const head = git('rev-parse', 'HEAD').trim();
try {
put('data/x/a.json', '{}\n');
git('add', '-A'); git('commit', '-qm', 'dir');
const before = git('rev-parse', 'HEAD').trim();
fs.rmSync(path.join(root, 'data/x'), { recursive: true });
put('data/x', '#!/bin/sh\necho hi\n');
fs.chmodSync(path.join(root, 'data/x'), 0o755);
git('add', '-A'); git('commit', '-qm', 'swap');
const after = git('rev-parse', 'HEAD').trim();
const patterns = ['data/**', '**/*.json'];
const one = (p: string) => git('diff', '--raw', '-z', '--no-abbrev', '--no-renames', before, after, '--', `:(top,glob)${p}`).split('\0').filter((_, k) => k % 2 === 1).filter(Boolean);
const s = select({ root, mergeBase: before, head: after }, patterns);
if ('error' in s) throw new Error(s.error);
expect(s.byPattern.get('data/**')).toEqual(['data/x', 'data/x/a.json']);
for (const p of patterns) expect(s.byPattern.get(p)).toEqual(one(p));
} finally { git('reset', '-q', '--hard', head); }
});
test.skipIf(process.platform === 'win32')('a bracket pattern matches what git diff matches, a directory that spells it out included', () => {
const head = git('rev-parse', 'HEAD').trim();
try {
put('res/1/a.json', '{}\n');
put('res/[0-9]*/evil.ts', 'export {};\n');
put('lit\\x/b.json', '{}\n');
git('add', '-A'); git('commit', '-qm', 'brackets');
const after = git('rev-parse', 'HEAD').trim();
const patterns = ['res/[0-9]*/**', 'lit\\\\x/**', '**/*.json'];
const one = (p: string) => git('diff', '--raw', '-z', '--no-abbrev', '--no-renames', head, after, '--', `:(top,glob)${p}`).split('\0').filter((_, k) => k % 2 === 1).filter(Boolean);
const s = select({ root, mergeBase: head, head: after }, patterns);
if ('error' in s) throw new Error(s.error);
expect(s.byPattern.get('res/[0-9]*/**')).toEqual(['res/1/a.json', 'res/[0-9]*/evil.ts']);
for (const p of patterns) expect(s.byPattern.get(p)).toEqual(one(p));
} finally { git('reset', '-q', '--hard', head); }
});
});
+65
View File
@@ -0,0 +1,65 @@
/**
* GST-4003: review_exclude_paths takes up to 256 patterns (harness-evals#619 hit the old 64), as long as their exclude
* pathspecs fit one reader command; and a REVIEW_DIFF_TOO_LARGE fix never suggests hiding docs/ or prints a policy gstack
* itself would refuse.
*/
import { describe, expect, test } from 'bun:test';
import { tooLargeLine } from '../lib/review-exclude';
import { EXCLUDE_SPEC_MAX_BYTES, MAX_EXCLUDE_PATTERNS, REVIEW_EXCLUDE_KEY_VERSION, excludeSpecBytes, validatePolicy } from '../lib/ship-policy';
const codes = (p: unknown) => validatePolicy(p).map(e => `${e.code}:${e.path}:${e.message}`);
const list = (n: number, width = 0) => Array.from({ length: n }, (_, i) => `results/run-${i}/${'r'.repeat(width)}/**`);
const policy = (patterns: string[]) => ({ review_exclude_paths: patterns, min_gstack_version: REVIEW_EXCLUDE_KEY_VERSION });
const landed = (line: string) => { const m = line.match(/land (\{.*?\}) in /); return m ? JSON.parse(m[1]!) : null; };
describe('the review_exclude_paths cap', () => {
test('256 patterns validate, 257 do not, and review_content_patterns keeps its 64', () => {
expect(MAX_EXCLUDE_PATTERNS).toBe(256);
expect(codes(policy(list(256)))).toEqual([]);
expect(codes(policy(list(257)))).toEqual(['POLICY_INVALID:review_exclude_paths:more than 256 patterns']);
expect(codes({ ...policy(list(1)), review_content_patterns: list(65) }).some(c => c.startsWith('POLICY_INVALID:review_content_patterns:more than 64'))).toBe(true);
});
test('patterns too long together for one reader command are refused, and no list the old 64 cap admitted is', () => {
const long = list(120, 200);
expect(excludeSpecBytes(long)).toBeGreaterThan(EXCLUDE_SPEC_MAX_BYTES);
expect(codes(policy(long))).toEqual([`POLICY_INVALID:review_exclude_paths:its patterns take ${excludeSpecBytes(long)} argument bytes as exclude pathspecs, more than ${EXCLUDE_SPEC_MAX_BYTES}; merge patterns under a shared folder glob`]);
const widest = Array.from({ length: 64 }, (_, i) => `d${String(i).padStart(2, '0')}/${'x'.repeat(251)}`);
expect(widest.every(p => p.length === 255)).toBe(true);
expect(codes(policy(widest))).toEqual([]);
const wide = Array.from({ length: 64 }, (_, i) => `d${String(i).padStart(2, '0')}/${'é'.repeat(230)}/**`);
expect(excludeSpecBytes(wide)).toBeGreaterThan(EXCLUDE_SPEC_MAX_BYTES);
expect(codes(policy(wide))).toEqual([]);
expect(codes(policy([...wide, 'x/**']))[0]).toContain('argument bytes as exclude pathspecs');
});
});
describe('the REVIEW_DIFF_TOO_LARGE fix', () => {
const none = { state: 'none' as const, base: 'main', source: 'origin/main@abc' };
test('docs/ is never suggested, whatever its bytes; data folders still are', () => {
const d = { bytes: 6_000_000, byDir: [['docs', 4_000_000], ['results', 1_500_000], ['src', 500_000]] as Array<[string, number]>,
byFile: [['docs/report.md', 2_000_000], ['docs/benchmarks/run/results/a.json', 2_000_000], ['results/a.jsonl', 1_500_000], ['src/a.ts', 500_000]] as Array<[string, number]> };
const line = tooLargeLine('ctx', 'batched', d, none).line;
expect(line).not.toContain('docs/**');
expect(landed(line)).toBeNull();
expect(line).toContain('split the PR');
const dataHeavy = { ...d, byDir: [['results', 4_500_000], ['docs', 1_000_000], ['src', 500_000]] as Array<[string, number]>,
byFile: [['results/a.jsonl', 4_500_000], ['docs/report.md', 1_000_000], ['src/a.ts', 500_000]] as Array<[string, number]> };
expect(landed(tooLargeLine('ctx', 'batched', dataHeavy, none).line).review_exclude_paths).toEqual(['results/**']);
const byDirOnly = { bytes: 6_000_000, byDir: [['docs', 4_500_000], ['results', 1_400_000]] as Array<[string, number]> };
expect(tooLargeLine('ctx', 'batched', byDirOnly, none).line).not.toContain('docs/**');
});
test('a suggestion that would pass the pattern cap prints no policy JSON and says to merge patterns instead', () => {
const d = { bytes: 3_000_000, byDir: [['logs', 1_500_000], ['src', 1_500_000]] as Array<[string, number]>, byFile: [['logs/run.log', 1_500_000], ['src/a.ts', 1_500_000]] as Array<[string, number]> };
const at = (n: number) => tooLargeLine('ctx', 'batched', d, { ...none, state: 'active', record: { patterns: list(n), excluded: 9 } }).line;
const fits = landed(at(255));
expect(fits.review_exclude_paths).toHaveLength(256);
expect(codes(fits)).toEqual([]);
const full = at(256);
expect(landed(full)).toBeNull();
expect(full).toContain('fails validation (more than 256 patterns)');
expect(full).toContain('merge its patterns under fewer shared folder globs on main');
expect(full).toEndWith('nothing was written (REVIEW_DIFF_TOO_LARGE)');
});
});
+2 -2
View File
@@ -626,12 +626,12 @@ describe('the receipt binds the selection the reviewers read', () => {
// seam=gstack-ship-receipt write and carry; no_claim=the queue's reading of the field
test('a base list that is set aside writes the fallback record and refuses carry of the narrower review', () => {
const { repo, body } = reviewed();
policyOnBaseOnly(repo, policyText(Array.from({ length: 65 }, (_, i) => `data/p${i}/**`)));
policyOnBaseOnly(repo, policyText(Array.from({ length: 257 }, (_, i) => `data/p${i}/**`)));
const w = writeWith(repo, []);
expect({ status: w.status, err: w.status === EXIT.ok ? '' : w.err }).toEqual({ status: EXIT.ok, err: '' });
const written = receiptIn(path.join(repo.root, 'body-w.md'));
expect(written.review_exclude).toBeUndefined();
expect(written.review_exclude_fallback!.errors).toEqual(['review_exclude_paths: more than 64 patterns']);
expect(written.review_exclude_fallback!.errors).toEqual(['review_exclude_paths: more than 256 patterns']);
repo.git('merge', '-q', '--no-edit', 'origin/main');
const refused = carry(repo, body);
expect(refused.status).toBe(EXIT.refused);
+29
View File
@@ -0,0 +1,29 @@
/**
* GST-4003: a PR body may list its `Ruled note: …` lines as markdown bullets (`- ` or `* `). gstack-ship-receipt write and
* the receipt-versus-prose check read such a line as the bare one, and still want the rest of it word for word.
*/
import { describe, expect, test } from 'bun:test';
import { bodyLineText, bodyListsLine, ruledNoteText, type RuledNote } from '../lib/ruled-notes';
import { checkReceiptProse } from '../lib/ship-receipt-prose';
const note: RuledNote = { finding: 'lib/a.ts:12:correctness', head: 'b'.repeat(40), by: 'GStack Minder (GSTA-36)', reason: 'ships with 3 passes noted', at: '2026-11-26T14:00:00Z', approval: 'a-123' };
const line = `Ruled note: ${ruledNoteText(note)}`;
describe('ruled-note body lines', () => {
test('a bare line and a - or * list item carry the note', () => {
for (const body of [line, `- ${line}`, `* ${line}`, ` - ${line} `, `*\t${line}`, `intro\r\n- ${line}\r\noutro`]) expect(bodyListsLine(body, line)).toBe(true);
expect(bodyLineText(`- ${line}`)).toBe(line);
});
test('anything weaker or different does not', () => {
for (const body of [`- ${line} (and more)`, `-- ${line}`, `- - ${line}`, `+ ${line}`, `1. ${line}`, `> ${line}`, `-${line}`, `see ${line}`,
`- ${line.replace('a-123', 'a-124')}`, `- Ruled note:`, '']) expect(bodyListsLine(body, line)).toBe(false);
});
test('the prose check leaves a bulleted ruled note out of its counter claims, and only an exact one', () => {
const receipt = { schema_version: 1, pr: 7, head: 'a'.repeat(40), base: 'main', version: '1.2.3.0', review_loop: { passes: 2 }, ruled_notes: [note] };
expect(checkReceiptProse(receipt, `Summary.\n\n- ${line}\n`).mismatches).toEqual([]);
expect(checkReceiptProse(receipt, `Summary.\n\n* ${line}\n`).mismatches).toEqual([]);
expect(checkReceiptProse(receipt, `Summary.\n\n- ${line} again\n`).mismatches).toEqual([{ field: 'review_loop.passes', prose: 3, receipt: 2 }]);
});
});