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

+64
View File
@@ -0,0 +1,64 @@
/**
* diff-parts — one `git diff` read with no output buffer to fill (GST-4003).
*
* A pipe read with spawnSync stops at its maxBuffer: harness-evals#616's added lines came to 255.7 MB against the secrets
* scan's 256 MiB, so a slightly larger results PR could not be scanned at all. Here git writes to a private file (mode
* 0600 in a 0700 directory, removed afterwards), and the caller gets it back in parts of about `partBytes`, each ending
* where the next `diff --` header starts. Inside a hunk every line starts with ' ', '+', '-', '\\' or '@@', and git quotes
* a name holding a newline, so a line starting `diff --` is always a file header: each file's section arrives whole in one
* part, and the parts joined are git's output byte for byte. A per-file parser fed every part in order therefore sees
* what it saw on the whole text.
*/
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { spawnSync } from './spawn-sync';
export const DIFF_PART_BYTES = 64 * 1024 * 1024;
const HEADER = Buffer.from('\ndiff --');
export interface DiffRun { cwd: string; timeout: number; env?: NodeJS.ProcessEnv }
export type DiffRead = { ok: true } | { ok: false; why: string };
/** Run `git <args>` and hand each part of its stdout to `each` in order; a git that did not finish (an exit, a kill, a timeout) is not ok. */
export function gitDiffInParts(args: readonly string[], run: DiffRun, each: (part: string) => void, partBytes = DIFF_PART_BYTES): DiffRead {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-diff-'));
try {
fs.chmodSync(dir, 0o700);
const file = path.join(dir, 'out.diff');
const fd = fs.openSync(file, 'w', 0o600);
let r: ReturnType<typeof spawnSync>;
try { r = spawnSync('git', [...args], { cwd: run.cwd, env: run.env, stdio: ['ignore', fd, 'pipe'], encoding: 'utf8', timeout: run.timeout }); } finally { fs.closeSync(fd); }
if (r.error || r.status !== 0) return { ok: false, why: r.error?.message ?? (r.status === null ? `killed by ${r.signal}` : `exit ${r.status}: ${String(r.stderr ?? '').trim().split('\n').pop() ?? ''}`) };
const input = fs.openSync(file, 'r');
try {
const pending: Buffer[] = [];
let held = 0;
let tail = Buffer.alloc(0);
for (;;) {
const chunk = Buffer.alloc(Math.max(1, partBytes));
const n = fs.readSync(input, chunk, 0, chunk.length, null);
if (n <= 0) break;
const read = chunk.subarray(0, n);
const seen = Buffer.concat([tail, read]);
let cut = -1;
for (let at = seen.indexOf(HEADER); at >= 0; at = seen.indexOf(HEADER, at + 1)) cut = held - tail.length + at + 1;
pending.push(read);
held += n;
tail = Buffer.from(seen.subarray(Math.max(0, seen.length - HEADER.length + 1)));
if (cut <= 0) continue;
const all = Buffer.concat(pending, held);
each(all.subarray(0, cut).toString('utf8'));
pending.splice(0, pending.length, Buffer.from(all.subarray(cut)));
held -= cut;
}
if (held) each(Buffer.concat(pending, held).toString('utf8'));
} finally { fs.closeSync(input); }
return { ok: true };
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
}
/** Fold per-part maps from a per-file parser into one, in the order the whole text would have built it. */
export function mergeParts<T>(into: Map<string, T[]>, part: Map<string, T[]>): void {
for (const [k, v] of part) { const have = into.get(k); if (have) for (const x of v) have.push(x); else into.set(k, v); }
}
+58 -3
View File
@@ -60,8 +60,8 @@ export class DocsOnlyError extends Error {
constructor(readonly command: string, readonly detail: string, readonly fix: string) { super(`${command}: ${detail}`); }
}
function git(root: string, args: string[], okCodes = [0]): string {
const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 });
function git(root: string, args: string[], okCodes = [0], input?: string): string {
const r = spawnSync('git', args, { cwd: root, input, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 });
if (r.error || r.status === null || !okCodes.includes(r.status)) {
const detail = (r.error?.message ?? r.stderr ?? '').trim().split('\n')[0] || `exit ${r.status}`;
throw new DocsOnlyError(`git ${args.join(' ')}`, detail, /bad revision|unknown revision|no merge base|ambiguous argument/i.test(detail)
@@ -158,6 +158,57 @@ export function referencesTo(root: string, p: string, tree?: string, repo: RepoD
return grepFiles(root, [p], tree).filter(f => f !== p && !PROSE_REFERENCE.test(f) && pathRefusal(f, root, gen, repo) !== null);
}
/**
* referencesTo for every one of `paths` at once (GST-4003: one `git grep` per path took minutes on a 16,000-file PR). One
* `git grep -l -F -f -` lists the files naming any of them, the outside-prose ones among those are read once, and each path
* gets the files whose bytes hold it, which is what a per-path `git grep -l -F -e <path>` lists (a path holds no newline, so a
* line match is a substring match). A path with a newline, which `-f` cannot carry, is still grepped alone.
*/
export function referencesToAll(root: string, paths: readonly string[], tree?: string, repo: RepoDocs = NO_REPO_DOCS): Map<string, string[]> {
const out = new Map<string, string[]>();
const plain = [...new Set(paths)].filter(p => p && !p.includes('\n'));
for (const p of paths) if (!p || p.includes('\n')) out.set(p, referencesTo(root, p, tree, repo));
for (const p of plain) out.set(p, []);
if (!plain.length) return out;
const gen = generatedOutputs(root);
const prefix = tree ? `${tree}:` : '';
const named = git(root, ['grep', '-l', '-z', '-F', '-I', '-f', '-', ...(tree ? [tree] : []), '--'], [0, 1], plain.join('\n') + '\n').split('\0').filter(Boolean)
.map(f => (f.startsWith(prefix) ? f.slice(prefix.length) : f)).filter(f => !PROSE_REFERENCE.test(f) && pathRefusal(f, root, gen, repo) !== null);
const needles = plain.map(p => [p, Buffer.from(p)] as const);
const fromIndex = tree ? new Set<string>() : indexRead(root);
for (let i = 0; i < named.length; i += 256) {
const files = named.slice(i, i + 256);
const cached = files.filter(f => fromIndex.has(f));
const blobs = new Map(cached.length ? treeBlobs(root, '', cached).map((b, k) => [cached[k]!, b] as const) : []);
const texts = tree ? treeBlobs(root, tree, files) : files.map(f => blobs.get(f) ?? fs.readFileSync(path.join(root, f)));
files.forEach((f, k) => { for (const [p, needle] of needles) if (f !== p && texts[k]!.includes(needle)) out.get(p)!.push(f); });
}
return out;
}
/** Tracked paths a working-tree `git grep` reads from the index, as it does for skip-worktree and assume-unchanged entries (`git ls-files -v` tags them S or in lowercase). */
function indexRead(root: string): Set<string> {
return new Set(git(root, ['ls-files', '-v', '-z']).split('\0').filter(e => e.length > 2 && (e[0] === 'S' || e[0] !== e[0]!.toUpperCase())).map(e => e.slice(2)));
}
/** The blobs of `files` at `tree` (the index when it is ''), through one `git cat-file --batch` (a name with a newline is read alone); any git failure throws DocsOnlyError. */
function treeBlobs(root: string, tree: string, files: readonly string[]): Buffer[] {
const fail = (what: string): never => { throw new DocsOnlyError(`git cat-file ${tree}`, what, 'rerun in a git checkout of this repository'); };
const one = (f: string) => { const r = spawnSync('git', ['cat-file', 'blob', `${tree}:${f}`], { cwd: root, timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); return r.status === 0 && Buffer.isBuffer(r.stdout) ? r.stdout : fail(`cannot read ${f}`); };
const batched = files.filter(f => !f.includes('\n'));
const r = batched.length ? spawnSync('git', ['cat-file', '--batch'], { cwd: root, input: batched.map(f => `${tree}:${f}`).join('\n') + '\n', timeout: 60_000, maxBuffer: 1024 * 1024 * 1024 }) : null;
if (r && (r.error || r.status !== 0 || !Buffer.isBuffer(r.stdout))) fail((r.error?.message ?? String(r.stderr ?? '')).trim().split('\n')[0] || `exit ${r.status}`);
const read = new Map<string, Buffer>();
for (let at = 0, k = 0; r && k < batched.length; k++) {
const nl = r.stdout.indexOf(10, at);
const size = Number(/^[0-9a-f]+ blob (\d+)$/.exec(r.stdout.subarray(at, nl).toString())?.[1] ?? NaN);
if (!Number.isInteger(size)) fail(`cannot read ${batched[k]}`);
read.set(batched[k]!, r.stdout.subarray(nl + 1, nl + 1 + size));
at = nl + 2 + size;
}
return files.map(f => read.get(f) ?? one(f));
}
/**
* Non-docs tracked files that name a directory holding the repo-admitted path `p` ("wiki/", 'wiki', './wiki', root + '/wiki') and are tied to
* none of the repository's docs_only.tests: a script that lists a directory reads every post in it, which the literal
@@ -220,7 +271,11 @@ export function classifyDocsOnly(o: { root: string; base: string; head?: string;
const repo = 'error' in policy ? NO_REPO_DOCS : policy;
const changed = new Set(entries.flatMap(e => [e.path, ...(e.from ? [e.from] : [])]));
const outside = (f: string) => !changed.has(f) || pathRefusal(f, o.root, undefined, repo) !== null;
const r = classifyEntries(entries, o.root, p => referencesTo(o.root, p, o.head, repo).filter(outside), repo, p => directoryReaders(o.root, p, repo, o.head).filter(outside));
const gen = generatedOutputs(o.root);
const refs = referencesToAll(o.root, [...changed].filter(p => pathRefusal(p, o.root, gen, repo) === null), o.head, repo);
const readers = new Map<string, string[]>();
const readersOf = (p: string) => { const k = `${builtIn(p)}\0${path.posix.dirname(p)}`; if (!readers.has(k)) readers.set(k, directoryReaders(o.root, p, repo, o.head)); return readers.get(k)!; };
const r = classifyEntries(entries, o.root, p => (refs.get(p) ?? referencesTo(o.root, p, o.head, repo)).filter(outside), repo, p => readersOf(p).filter(outside));
if ('error' in policy) return { ...r, docsOnly: false, tests: [], refusals: [{ path: SHIP_POLICY_PATH, reason: policy.error }, ...r.refusals] };
const missing = r.tests.filter(t => repo.tests.includes(t) && (o.head ? !git(o.root, ['ls-tree', '--name-only', o.head, '--', t]).trim() : !fs.existsSync(path.join(o.root, t))));
return missing.length ? { ...r, docsOnly: false, tests: [], refusals: missing.map(t => ({ path: t, reason: `listed in docs_only.tests at ${repo.label} but missing from this tree; restore it or correct the list` })) } : r;
+22 -12
View File
@@ -10,6 +10,7 @@
* scanned in overlapping line-aligned parts (scanParts); a single line over
* it fails. Runs regardless of lint tools.
*/
import { gitDiffInParts, mergeParts } from '../../diff-parts';
import { spawnSync } from '../../spawn-sync';
import * as fs from 'node:fs';
import * as path from 'node:path';
@@ -155,6 +156,8 @@ function scratchNames(part: { file: string; keep?: number[] }): string[] {
return gitMangledPath(part.file) && name !== 'added.txt' ? [name, 'added.txt'] : [name];
}
const WHOLE_FILE_MAX_BYTES = 4 * 1024 * 1024;
/** Postimage text the full-context diff may hold in all: past it every file is scanned on its added lines, as when that diff overran its 256 MiB buffer. */
const FULL_CONTEXT_MAX_BYTES = 256 * 1024 * 1024;
/**
* Added lines from the merge-base to the working tree, plus every line of
@@ -171,23 +174,30 @@ const WHOLE_FILE_MAX_BYTES = 4 * 1024 * 1024;
* `-diff` attribute the branch itself can add) from printing "Binary files
* differ" in place of its added lines; each such file is marked `binary`,
* carries every reading scannableReadings gives and is held to its credential findings. A diff git did not finish (an exit, a kill, a
* full buffer) throws: its partial output is never scanned as complete.
* timeout) throws: its partial output is never scanned as complete. git writes each diff to a private file read back in
* whole-file parts (lib/diff-parts.ts), so no output buffer caps a PR's size (GST-4003, harness-evals#616's 255.7 MB).
*/
export function addedLines(ctx: PregateContext): Array<{ file: string; texts: string[]; keep?: number[]; binary?: boolean }> {
const diff = spawnSync('git', ['diff', '--text', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/', '--unified=0', '--diff-filter=ACMR', ctx.mergeBase, '--'], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024, env: ctx.env });
if (diff.error || diff.status !== 0) throw new Error(`git diff ${ctx.mergeBase.slice(0, 12)} did not finish (${diff.error?.message ?? (diff.status === null ? `killed by ${diff.signal}` : `exit ${diff.status}: ${(diff.stderr ?? '').trim().split('\n').pop() ?? ''}`)})`);
const files = parseAddedLines(diff.stdout ?? '');
const numbers = parseAddedLineNumbers(diff.stdout ?? '');
const files = new Map<string, string[]>();
const numbers = new Map<string, number[]>();
const run = { cwd: ctx.repoRoot, timeout: 60_000, env: ctx.env };
const diff = gitDiffInParts(['diff', '--text', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/', '--unified=0', '--diff-filter=ACMR', ctx.mergeBase, '--'], run, part => { mergeParts(files, parseAddedLines(part)); mergeParts(numbers, parseAddedLineNumbers(part)); });
if (!diff.ok) throw new Error(`git diff ${ctx.mergeBase.slice(0, 12)} did not finish (${diff.why})`);
const whole = new Map<string, { text: string; keep: number[] }>();
const sources = [...numbers.keys()].filter(file => LEXICAL_CONTEXT_SOURCE.test(file));
if (sources.length) {
const full = spawnSync('git', ['-c', 'diff.suppressBlankEmpty=false', 'diff', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/', '--unified=100000000', '--diff-filter=ACMR', ctx.mergeBase, '--', ...sources.map(file => `:(literal)${file}`)], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024, env: ctx.env });
for (const [file, post] of parsePostimages(full.status === 0 ? full.stdout ?? '' : '')) {
const keep = numbers.get(file) ?? [];
const added = files.get(file) ?? [];
const text = post.join('\n');
if (text.length <= WHOLE_FILE_MAX_BYTES && keep.length === added.length && keep.every((n, k) => post[n - 1] === added[k])) whole.set(file, { text, keep });
}
let held = 0;
const full = gitDiffInParts(['-c', 'diff.suppressBlankEmpty=false', 'diff', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/', '--unified=100000000', '--diff-filter=ACMR', ctx.mergeBase, '--', ...sources.map(file => `:(literal)${file}`)], run, part => {
if (held > FULL_CONTEXT_MAX_BYTES) return;
for (const [file, post] of parsePostimages(part)) {
const size = post.reduce((n, line) => n + line.length + 1, 0) - 1;
held += size;
const keep = numbers.get(file) ?? [];
const added = files.get(file) ?? [];
if (size <= WHOLE_FILE_MAX_BYTES && keep.length === added.length && keep.every((n, k) => post[n - 1] === added[k])) whole.set(file, { text: post.join('\n'), keep });
}
});
if (!full.ok || held > FULL_CONTEXT_MAX_BYTES) whole.clear();
}
for (const t of ctx.touched) {
if (!t.uncommitted || t.status === 'D') continue;
+105
View File
@@ -0,0 +1,105 @@
/**
* review-exclude-match — which changed paths each review_exclude_paths pattern matches, and which fixed strings a file
* holds, at a cost that does not grow with the number of patterns or strings (GST-4003; harness-evals#616, 16,165 files).
*/
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { spawnSync } from './spawn-sync';
const MAX_BUFFER = 256 * 1024 * 1024;
function git(root: string, args: string[], input?: string, env?: NodeJS.ProcessEnv): { ok: boolean; status: number | null; out: string; err: string } {
const r = spawnSync('git', ['-c', 'core.quotePath=false', ...args], { cwd: root, input, env, encoding: 'utf8', timeout: 120_000, maxBuffer: MAX_BUFFER });
return { ok: r.status === 0, status: r.status, out: r.stdout ?? '', err: (r.stderr ?? '').trim() };
}
export interface SelectInput { root: string; mergeBase: string; head?: string }
export interface Matched { oldMode: string; newMode: string; oldSha: string; newSha: string }
/** Every changed path each pattern matches, with its modes, from git's raw diff; untracked files are never part of it, since no reader's git diff shows them and the receipt reads the committed head. */
export function select(i: SelectInput, patterns: readonly string[]): { byPattern: Map<string, string[]>; files: Map<string, Matched> } | { error: string } {
const byPattern = new Map<string, string[]>();
const files = new Map<string, Matched>();
if (!patterns.length) return { byPattern, files };
const range = i.head ? [i.mergeBase, i.head] : [i.mergeBase];
const specs = patterns.map(p => `:(top,glob)${p}`);
const raw = git(i.root, ['diff', '--raw', '-z', '--no-abbrev', '--no-renames', ...range, '--', ...specs]);
if (!raw.ok) return { error: `git diff --raw ${range.join(' ')} -- ${specs.join(' ')}: ${raw.err.split('\n')[0] || `exit ${raw.status}`}` };
const parts = raw.out.split('\0');
for (let k = 0; k + 1 < parts.length; k += 2) {
const [oldMode, newMode, oldSha, newSha] = parts[k]!.slice(1).split(' ');
const f = parts[k + 1]!;
if (f && !files.has(f)) files.set(f, { oldMode: oldMode ?? '', newMode: newMode ?? '', oldSha: oldSha ?? '', newSha: newSha ?? '' });
}
if (patterns.length === 1) return { byPattern: new Map([[patterns[0]!, [...files.keys()]]]), files };
// GST-4003: one diff for every pattern, then each pattern's share from git's own pathspec match over scratch indexes of just
// those paths (a diff per pattern took 0.2 s each over harness-evals#616's 16,165 files, and the cap is now 256 patterns).
// A deleted path and a new one can be a file and a directory of the same name (data/x/a.json gone, data/x added), which one
// index cannot hold, so the head side and the deleted side get an index each; one that does not list every path it was
// given sends every pattern back to its own diff. A pattern with a bracket class or a backslash gets its own diff too: git's
// tree walk also matches a directory whose name spells the pattern out (res/[0-9]*/), and ls-files' wildmatch does not.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-select-'));
try {
const sides = [[...files].filter(([, m]) => m.newMode !== '000000'), [...files].filter(([, m]) => m.newMode === '000000')].filter(s => s.length);
const hits = patterns.map(() => new Set<string>());
for (const [n, side] of sides.entries()) {
const env = { ...process.env, GIT_INDEX_FILE: path.join(dir, `index-${n}`) };
const entries = side.map(([f, m]) => `${m.newMode !== '000000' ? m.newMode : m.oldMode} e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0\t${f}`);
const listed = git(i.root, ['update-index', '-z', '--index-info'], entries.join('\0') + '\0', env).ok ? git(i.root, ['ls-files', '-z', '--full-name'], undefined, env) : null;
if (!listed?.ok || listed.out.split('\0').filter(Boolean).length !== side.length) return perPattern(i, patterns, range, files);
for (const [k, spec] of specs.entries()) {
const ls = git(i.root, ['ls-files', '-z', '--full-name', '--', spec], undefined, env);
if (!ls.ok) return { error: `git ls-files -- ${spec}: ${ls.err.split('\n')[0] || `exit ${ls.status}`}` };
for (const f of ls.out.split('\0')) if (f) hits[k]!.add(f);
}
}
for (const [k, p] of patterns.entries()) byPattern.set(p, [...files.keys()].filter(f => hits[k]!.has(f)));
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
const literal = patterns.filter(p => /[[\\]/.test(p));
const own = literal.length ? perPattern(i, literal, range, files) : null;
if (own && 'error' in own) return own;
for (const [p, matched] of own?.byPattern ?? []) byPattern.set(p, matched);
return { byPattern, files };
}
/** Each pattern's paths from its own `git diff --raw`, as select read them before GST-4003: the fallback when a scratch index cannot hold the paths. */
function perPattern(i: SelectInput, patterns: readonly string[], range: readonly string[], files: Map<string, Matched>): ReturnType<typeof select> {
const byPattern = new Map<string, string[]>();
for (const p of patterns) {
const spec = `:(top,glob)${p}`;
const raw = git(i.root, ['diff', '--raw', '-z', '--no-abbrev', '--no-renames', ...range, '--', spec]);
if (!raw.ok) return { error: `git diff --raw ${range.join(' ')} -- ${spec}: ${raw.err.split('\n')[0] || `exit ${raw.status}`}` };
byPattern.set(p, raw.out.split('\0').filter((f, k) => k % 2 === 1 && f));
}
return { byPattern, files };
}
/**
* A fixed-string search that hands git only each string's last-segment suffix (its extension, or the whole last segment
* when it has none), so `git grep -f` reads a handful of patterns instead of thousands: git tries every pattern on every
* line, and 16,165 paths over harness-evals' code took 37 s where their 9 extensions took 0.4 s. Every string ends with its
* token, so a file holding a string holds its token (git's list is a superset), and `holds` then finds exactly the strings
* a body contains by checking, at the end of each token occurrence, the strings of each length that end there.
*/
export function fixedIndex(strings: readonly string[]): { tokens: string[]; holds: (body: string) => Set<string> } {
const groups = new Map<string, Map<number, Set<string>>>();
for (const s of strings) {
const base = s.slice(s.lastIndexOf('/', s.length - 2) + 1);
const dot = base.lastIndexOf('.');
const token = dot > 0 ? base.slice(dot) : base;
const byLength = groups.get(token) ?? groups.set(token, new Map()).get(token)!;
(byLength.get(s.length) ?? byLength.set(s.length, new Set()).get(s.length)!).add(s);
}
const holds = (body: string) => {
const out = new Set<string>();
for (const [token, byLength] of groups) {
if (!token) { out.add(''); continue; }
for (let at = body.indexOf(token); at >= 0; at = body.indexOf(token, at + 1)) {
const end = at + token.length;
for (const [n, set] of byLength) if (end >= n && set.has(body.slice(end - n, end))) out.add(body.slice(end - n, end));
}
}
return out;
};
return { tokens: [...groups.keys()], holds };
}
+35 -46
View File
@@ -42,7 +42,8 @@ import { shannonEntropy } from './redact-patterns';
import { KEY_NAME, RESULTS_TREE, SECRET_LINE, hashManifest, secretPath } from './review-risk';
import { secretExcerpt } from './review-secret-excerpt';
import { cmpVersion, parseVersion } from './version-source';
import { REVIEW_EXCLUDE_KEY_VERSION, SHIP_POLICY_PATH, isUnavailable, policyUnavailableLine } from './ship-policy';
import { REVIEW_EXCLUDE_KEY_VERSION, SHIP_POLICY_PATH, excludeListTooLarge, isUnavailable, policyUnavailableLine } from './ship-policy';
import { fixedIndex, select, type Matched } from './review-exclude-match';
import { loadPolicyAt } from './ship-policy-at';
import { resolveStateRoot } from './state-root';
import { vendoredCacheRoot, vendoredPolicy, vendoredSelection, type VendoredSelection } from './review-vendored';
@@ -195,31 +196,6 @@ export function literalPrefix(pattern: string): string {
return head.slice(0, head.lastIndexOf('/') + 1);
}
interface Matched { oldMode: string; newMode: string; oldSha: string; newSha: string }
/** Every changed path each pattern matches, with its modes, from git's raw diff; untracked files are never part of it, since no reader's git diff shows them and the receipt reads the committed head. */
function select(i: ExcludeInput, patterns: readonly string[]): { byPattern: Map<string, string[]>; files: Map<string, Matched> } | { error: string } {
const byPattern = new Map<string, string[]>();
const files = new Map<string, Matched>();
const range = i.head ? [i.mergeBase, i.head] : [i.mergeBase];
for (const p of patterns) {
const spec = `:(top,glob)${p}`;
const raw = git(i.root, ['diff', '--raw', '-z', '--no-abbrev', '--no-renames', ...range, '--', spec]);
if (!raw.ok) return { error: `git diff --raw ${range.join(' ')} -- ${spec}: ${raw.err.split('\n')[0] || `exit ${raw.status}`}` };
const parts = raw.out.split('\0');
const hit: string[] = [];
for (let k = 0; k + 1 < parts.length; k += 2) {
const [oldMode, newMode, oldSha, newSha] = parts[k]!.slice(1).split(' ');
const f = parts[k + 1]!;
if (!f) continue;
hit.push(f);
if (!files.has(f)) files.set(f, { oldMode: oldMode ?? '', newMode: newMode ?? '', oldSha: oldSha ?? '', newSha: newSha ?? '' });
}
byPattern.set(p, hit);
}
return { byPattern, files };
}
/** Executable image magic: ELF, Mach-O (thin, universal and 64-bit universal; 0xcafebabe is also a Java class), PE, WebAssembly and a script's #!. */
const NATIVE_MAGIC = [[0x7f, 0x45, 0x4c, 0x46], [0xfe, 0xed, 0xfa, 0xce], [0xfe, 0xed, 0xfa, 0xcf], [0xce, 0xfa, 0xed, 0xfe], [0xcf, 0xfa, 0xed, 0xfe], [0xca, 0xfe, 0xba, 0xbe], [0xca, 0xfe, 0xba, 0xbf], [0x4d, 0x5a], [0x00, 0x61, 0x73, 0x6d], [0x23, 0x21]];
@@ -433,8 +409,9 @@ function contractExample(patterns: ReadonlySet<string>, s: string, file: string,
* the scratch index or grep it (a timeout included). Each tree's file list is filtered to consumers first, so the data under
* the patterns is never read (GST-1435: a whole-tree grep for 4,354 candidate paths through 30 MB of receipts ran 278 s), and
* the consumers go into a scratch index that one git grep reads, so the git calls stay fixed however many files there are
* (GST-1442: 363 chunked greps over a 192k-file tree ran 132 s). `git grep -l` lists the consumers holding any string, and
* only those are read and searched here: git's -o grew with the number of strings (HARN-64: 2,140 candidate paths in one
* (GST-1442: 363 chunked greps over a 192k-file tree ran 132 s). `git grep -l` lists the consumers holding any string's
* token (fixedIndex: its extension or last segment, since git's -l also grew with the number of strings: 16,165 paths took 37 s on
* harness-evals#616, GST-4003), and only those are read and searched here: git's -o grew with the number of strings (HARN-64: 2,140 candidate paths in one
* 464 KB pins.sha256 ran past git's 120 s bound, so every candidate stayed in review). A consumer that is a hash or pin
* manifest (every line a digest and a path, lib/review-risk.ts) names files without reading them, so it keeps none. On a live tree, an entry git reads from its blob
* (skip-worktree or assume-unchanged) goes into a second index grepped with --cached, as git grep itself would read it.
@@ -445,7 +422,8 @@ function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-exclude-'));
try {
const list = path.join(dir, 'patterns');
fs.writeFileSync(list, strings.join('\n') + '\n');
const index = fixedIndex(strings);
fs.writeFileSync(list, index.tokens.join('\n') + '\n');
let n = 0;
for (const at of [i.head ?? '', ...revs]) {
const ls = git(i.root, at ? ['ls-tree', '-r', '-z', at] : ['ls-files', '-s', '-v', '-z']);
@@ -469,25 +447,34 @@ function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet
const hits = git(i.root, ['grep', ...flags, '-I', '-F', '-l', '-z', '--no-color', '-f', list], undefined, env);
if (hits.status !== 0 && hits.status !== 1) return null;
const files = hits.out.split('\0').filter(Boolean);
const bodies = new Map<string, string>();
if (flags.length && files.length) {
const shas = new Map(entries.map(e => [e.slice(e.indexOf('\t') + 1), e.slice(0, e.indexOf('\t')).split(' ')[1]!]));
const want = files.map(f => shas.get(f));
if (want.some(s => !s)) return null;
const b = spawnSync('git', ['cat-file', '--batch'], { cwd: i.root, input: want.join('\n') + '\n', timeout: 120_000, maxBuffer: MAX_BUFFER });
const scan = (file: string, body: string) => {
if (hashManifest(body.split('\n'))) return;
for (const s of index.holds(body)) if (!skip?.(s, file, body)) (found.get(s) ?? found.set(s, new Set()).get(s)!).add(file);
};
if (!flags.length) {
for (const f of files) { let body: string; try { body = fs.readFileSync(path.join(i.root, f), 'utf8'); } catch { return null; } scan(f, body); }
continue;
}
if (!files.length) continue;
const shas = new Map(entries.map(e => [e.slice(e.indexOf('\t') + 1), e.slice(0, e.indexOf('\t')).split(' ')[1]!]));
const want = files.map(f => shas.get(f));
if (want.some(s => !s)) return null;
const sized = git(i.root, ['cat-file', '--batch-check'], want.join('\n') + '\n');
const sizes = sized.out.split('\n').slice(0, want.length).map(l => Number(l.split(' ')[2]));
if (!sized.ok || sizes.length !== want.length || sizes.some(n => !Number.isInteger(n))) return null;
for (let k = 0, end = 0; k < files.length; k = end) {
let bytes = 0;
for (end = k; end < files.length && (end === k || bytes + sizes[end]! <= BLOB_BATCH_BYTES); end++) bytes += sizes[end]!;
const b = spawnSync('git', ['cat-file', '--batch'], { cwd: i.root, input: want.slice(k, end).join('\n') + '\n', timeout: 120_000, maxBuffer: bytes + (end - k) * 128 + 1024 });
if (b.status !== 0 || !b.stdout) return null;
let at = 0;
for (const f of files) {
for (const f of files.slice(k, end)) {
const nl = b.stdout.indexOf(10, at);
const size = Number(b.stdout.subarray(at, nl).toString().split(' ')[2]);
if (nl < 0 || !Number.isInteger(size)) return null;
bodies.set(f, b.stdout.subarray(nl + 1, nl + 1 + size).toString('utf8'));
scan(f, b.stdout.subarray(nl + 1, nl + 1 + size).toString('utf8'));
at = nl + 2 + size;
}
} else for (const f of files) try { bodies.set(f, fs.readFileSync(path.join(i.root, f), 'utf8')); } catch { return null; }
for (const [file, body] of bodies) {
if (hashManifest(body.split('\n'))) continue;
for (const s of strings) if (body.includes(s) && !skip?.(s, file, body)) (found.get(s) ?? found.set(s, new Set()).get(s)!).add(file);
}
}
}
@@ -711,15 +698,16 @@ function policyJson(patterns: readonly string[], floor?: string | null): string
const excludableByPath = (p: string) => !SOURCE.test(p) && (DATA_PATH.test(p) || /\.log$/i.test(p) || BINARY_CONTENT_EXT.test(p) || classifyPath(p) === 'docs');
/**
* Folders to suggest: the top directories holding the most bytes the policy could exclude (whole folders when only folder
* sizes are known), until what is left would fit; none when they cannot get the reader under the ceiling (#4369).
* Folders to suggest: the top directories holding the most data, log and binary bytes the policy could exclude (whole folders
* when only folder sizes are known), until what is left would fit; none when they cannot get the reader under the ceiling
* (#4369). Docs never count and docs/ is never suggested: a results report is what the reviewer is there to read (GST-4003).
*/
function suggest(d: { bytes: number; byDir: ReadonlyArray<[string, number]>; byFile?: ReadonlyArray<[string, number]> }): string[] {
let byDir = d.byDir;
if (d.byFile?.length) {
const excludable = new Map<string, number>();
for (const [file, n] of d.byFile) {
if (!excludableByPath(file)) continue;
if (!excludableByPath(file) || classifyPath(file) === 'docs') continue;
const dir = file.includes('/') ? file.split('/')[0]! : '(root)';
excludable.set(dir, (excludable.get(dir) ?? 0) + n);
}
@@ -729,7 +717,7 @@ function suggest(d: { bytes: number; byDir: ReadonlyArray<[string, number]>; byF
let left = d.bytes;
for (const [dir, n] of byDir) {
if (left <= REVIEW_DIFF_MAX_BYTES || out.length >= 3) break;
if (dir === '(root)') continue;
if (dir === '(root)' || dir === 'docs') continue;
out.push(`${dir}/**`);
left -= n;
}
@@ -742,7 +730,8 @@ export function tooLargeLine(context: string, reader: string, d: { bytes: number
const top = d.byDir.slice(0, 5).map(([dir, n]) => `${named(dir)}:${n}`).join(',') || 'none';
const largest = (d.byFile ?? []).slice(0, 5);
const split = largest.length ? `split the PR (largest files: ${largest.map(([f, n]) => `${named(f)} (${n} bytes)`).join(', ')})` : 'split the PR';
const land = (patterns: readonly string[]) => `ask the repo owner to land ${policyJson(patterns, c.floor)} in ${SHIP_POLICY_PATH} on ${c.base} as its own PR (docs/ship-policy.md#review-exclude-paths), then bring ${c.base} into this branch and rerun once; if it is still over, ${split}`;
const land = (patterns: readonly string[]) => excludeListTooLarge(patterns) ? `the base policy cannot take these folders as well: with them its review_exclude_paths fails validation (${excludeListTooLarge(patterns)}), so ask the repo owner to merge its patterns under fewer shared folder globs on ${c.base} as its own PR, or ${split}`
: `ask the repo owner to land ${policyJson(patterns, c.floor)} in ${SHIP_POLICY_PATH} on ${c.base} as its own PR (docs/ship-policy.md#review-exclude-paths), then bring ${c.base} into this branch and rerun once; if it is still over, ${split}`;
const dirs = suggest(d);
const fresh = dirs.filter(p => !c.record?.patterns.includes(p));
const fix = c.state === 'head-only' ? `this branch declares review_exclude_paths, but only the copy on ${c.base} applies: ${land(c.headPatterns ?? [])}`
+8
View File
@@ -68,6 +68,14 @@ export const publicRuledNote = (n: RuledNote): RuledNote => !isSecurityFinding(n
: n.not_security && RED_TEAM.test(n.finding) ? { ...n, finding: n.finding.replace(RED_TEAM, ' (red-team, ruled not security class)') }
: { ...n, finding: REDACTED_FINDING, reason: REDACTED_REASON };
/**
* A PR body line as the receipt checks read it: trimmed, with one leading `- ` or `* ` list bullet dropped, so a body that lists its
* `Ruled note: …` lines as bullets carries them. The rest must still equal the rendered line word for word.
*/
export const bodyLineText = (line: string) => line.trim().replace(/^[-*][ \t]+/, '');
/** Whether `body` carries `line` as one whole line, bare or as a `- ` / `* ` list item (bodyLineText). */
export const bodyListsLine = (body: string, line: string) => body.split(/\r?\n/).some(b => bodyLineText(b) === line);
/** The one-line form finish prints after `RULED_NOTE: ` and the PR body carries after `Ruled note: `, from publicRuledNote. */
export const ruledNoteText = (note: RuledNote) => { const n = publicRuledNote(note); return `${n.finding} at ${n.head.slice(0, 12)} ruled by ${n.by}${n.relayed ? ` (relayed from ${n.relayed})` : ''} at ${n.at}: ${n.reason} (approval ${n.approval})`; };
+16
View File
@@ -59,6 +59,22 @@ export const HISTORY_NO_REWRITE_KEY_VERSION = '1.100.0.0';
export const LAND_MERGE_COMMIT_PATHS_KEY_VERSION = '1.100.0.0';
export const REVIEW_CONTENT_KEY_VERSION = '1.102.0.0';
export const REVIEW_VENDORED_KEY_VERSION = '1.103.0.0';
/**
* The most review_exclude_paths patterns one policy may list (64, the cap on every other list, until GST-4003: harness-evals' results
* PRs needed more), and the most argument bytes their `:(top,exclude,glob)` pathspecs may take together, shell-quoted: every reader's
* one `git diff` carries all of them, so the sum stays under KEEP_ARG_MAX_BYTES (lib/review-exclude.ts) and Windows' command line.
* The byte cap binds only a list over the old 64, so every list gstack accepted before still validates.
* An older gstack reads a list over 64 as invalid and sets the key aside, which reviews every file.
*/
export const MAX_EXCLUDE_PATTERNS = 256;
const UNCAPPED_EXCLUDE_PATTERNS = 64;
export const EXCLUDE_SPEC_MAX_BYTES = 24_000;
/** The shell-quoted argument bytes of the exclude pathspecs `patterns` become on a reader's command, one separator each. */
export const excludeSpecBytes = (patterns: readonly string[]) => patterns.reduce((n, p) => n + Buffer.byteLength(`':(top,exclude,glob)${p.replace(/'/g, "'\\''")}'`) + 1, 0);
/** Why `patterns` cannot be a review_exclude_paths list for being too many or too long together, or null when they fit. */
export const excludeListTooLarge = (patterns: readonly string[]) => patterns.length > MAX_EXCLUDE_PATTERNS ? `more than ${MAX_EXCLUDE_PATTERNS} patterns`
: patterns.length > UNCAPPED_EXCLUDE_PATTERNS && excludeSpecBytes(patterns) > EXCLUDE_SPEC_MAX_BYTES ? `its patterns take ${excludeSpecBytes(patterns)} argument bytes as exclude pathspecs, more than ${EXCLUDE_SPEC_MAX_BYTES}; merge patterns under a shared folder glob` : null;
export const POLICY_KEY_INTRODUCED: Record<PolicyKey, string> = {
bump: '1.91.73.0', queue_mode: '1.91.73.0', release_tool: '1.91.73.0', release_outputs: '1.91.73.0', stamp_paths: '1.91.73.0',
changelog: '1.91.73.0', mirror: '1.91.73.0', history: '1.91.73.0', preregistration_shas: '1.91.73.0', stamp_sensitive_gates: '1.91.73.0',
+5 -5
View File
@@ -23,7 +23,7 @@ import { RESULT_CODES, type ResultCodeName } from './result-codes';
import { reviewErrors, type ReviewPolicy } from './ship-policy-review';
import { READERS_EXPLANATION, readersErrors, type ReadersPolicy } from './ship-policy-readers'; import { VENDORED_EXPLANATION, vendoredErrors, type VendoredPolicyRaw } from './review-vendored';
import { cmpVersion, parseVersion } from './version-source';
import { POLICY_COMPAT_FLOOR, BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION, POLICY_KEY_INTRODUCED, LAND_DOCS_ONLY_SKIP_KEY_VERSION, HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION } from './ship-policy-keys';
import { POLICY_COMPAT_FLOOR, BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION, POLICY_KEY_INTRODUCED, LAND_DOCS_ONLY_SKIP_KEY_VERSION, HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION, excludeListTooLarge } from './ship-policy-keys';
import { placeholderErrors, templateErrors } from './ship-policy-stamps';
import { bookkeepingGlobError, globError } from './ship-policy-bookkeeping';
import { MECHANICAL_EXPLANATION, mechanicalErrors, type MechanicalConstant } from './ship-policy-mechanical';
@@ -220,7 +220,7 @@ export const POLICY_EXPLANATIONS: Record<PolicyKey, string> = {
preregistration_shas: 'Commits that must be ancestors of HEAD before push (preregistered evals); checked by `gstack-evidence ancestor`.',
stamp_sensitive_gates: 'Evidence labels (gstack-evidence --label) that read VERSION or generated bytes; the tree receipt never marks them reusable.',
review_scope: 'frozen | diff-plus-blocking | all. frozen (default): /ship Step 9 fixes findings in the diff on pass 1, files blocking findings in code the PR did not change as issues, and later passes read only the range since the previous pass and fix only blocking findings; diff-plus-blocking: the same, but a blocking finding in code the PR did not change is fixed in this PR instead of filed; all: every finding is fixed now (the pre-1.91.249 loop).',
review_exclude_paths: 'Git glob pathspecs, root-anchored and case-sensitive (`receipts/**`, `**/*.jsonl`; at most 64, 256 characters each, no leading `:` or `!`): /ship\'s reviewers leave out the data, docs, binary and .log files they match. Read from the base branch only, so a branch cannot exclude its own files. Code, gate paths, agent prose, config, executables, .gstack/ and .github/ files, gate-tagged or secret-bearing files and files a kept code or test file names by full path stay reviewed (docs/ship-policy.md#review-exclude-paths).',
review_exclude_paths: 'Git glob pathspecs, root-anchored and case-sensitive (`receipts/**`, `**/*.jsonl`; at most 256, 256 characters each and 24,000 argument bytes together as exclude pathspecs, no leading `:` or `!`): /ship\'s reviewers leave out the data, docs, binary and .log files they match. Read from the base branch only, so a branch cannot exclude its own files. Code, gate paths, agent prose, config, executables, .gstack/ and .github/ files, gate-tagged or secret-bearing files and files a kept code or test file names by full path stay reviewed (docs/ship-policy.md#review-exclude-paths).',
review_content_patterns: 'Git glob pathspecs in the same dialect as review_exclude_paths (`results/*/raw/**`): a file both keys match is content, so the exclusion leaves it out whatever its extension (.patch files, MANIFEST.sha256, extension-less licence texts). Explicit policy only: nothing is inferred, and a pattern here with no review_exclude_paths pattern over the same files excludes nothing. Read from the base branch only. Gate paths, agent prose, config, source files (.ts, .py, .sh and the like), executables, links, native binaries, .gstack/ and .github/ files, gate-tagged or secret-bearing files and files a kept code or test file names by full path stay reviewed (docs/ship-policy.md#review-content-patterns).',
review: '{ panel?, reader_model?, platform?, risk_paths? }, read from the base branch only. panel: all (default: today\'s panel and loop everywhere) | risk (opt-in: today\'s panel at full depth on risk class, one reader on the rest) | off (one merged reader on risk class too); risk and off run one fix round. Their one-reader shape has not passed a no-loss replay yet (GSTA-258 C: FIX-METHOD). reader_model: the model of the one reader a lean depth runs, `lane` (default: the lane\'s own model, the native adversarial reader), `cross-family` or a model id. platform: off (default) | on: a docs or tests diff with no numeric, results or prereg claims whose PR carries the platform review (capy-ai[bot]) at the exact head skips /ship\'s readers (review_depth platform); never runtime code. risk_paths: globs of code paths that are risk class on top of R51\'s; data, docs and binary files under them stay out (docs/review-policy.md#review-depth).',
readers: READERS_EXPLANATION, review_vendored: VENDORED_EXPLANATION,
@@ -336,9 +336,9 @@ function listErrors(key: string, value: unknown, out: PolicyError[], check: (ite
/** `review_exclude_paths` and `review_content_patterns`: git glob pathspecs, each one repo-relative line with no pathspec magic of its own; every error is POLICY_INVALID at its index. */
function excludeErrors(key: 'review_exclude_paths' | 'review_content_patterns', value: unknown, out: PolicyError[]): void {
if (!Array.isArray(value)) { out.push({ code: 'POLICY_INVALID', path: key, message: 'must be an array of git glob pathspecs' }); return; }
if (value.length > MAX_LIST) out.push({ code: 'POLICY_INVALID', path: key, message: `more than ${MAX_LIST} patterns` });
value.forEach((p, i) => {
const why = typeof p !== 'string' ? 'must be a string' : containedRelative(p) ?? (/^[:!]/.test(p) ? 'must not start with : or ! (no pathspec magic or negation)' : /[\x00-\x1f\x7f]/.test(p) ? 'contains a control character' : p.replace(/\/+$/, '') === '' || p === '.' ? 'must not name the whole repository' : null);
const tooLarge = key === 'review_exclude_paths' ? excludeListTooLarge(value.filter(p => typeof p === 'string')) : value.length > MAX_LIST ? `more than ${MAX_LIST} patterns` : null;
if (tooLarge) out.push({ code: 'POLICY_INVALID', path: key, message: tooLarge });
value.forEach((p, i) => { const why = typeof p !== 'string' ? 'must be a string' : containedRelative(p) ?? (/^[:!]/.test(p) ? 'must not start with : or ! (no pathspec magic or negation)' : /[\x00-\x1f\x7f]/.test(p) ? 'contains a control character' : p.replace(/\/+$/, '') === '' || p === '.' ? 'must not name the whole repository' : null);
if (why) out.push({ code: 'POLICY_INVALID', path: `${key}[${i}]`, message: `${JSON.stringify(p)} ${why}` });
});
}
+6 -5
View File
@@ -8,7 +8,7 @@
import { APPROVALS_FOOTER_END, APPROVALS_TABLE_HEADER } from './approval-record';
import { RECEIPT_FENCE } from './ship-receipt';
import { docsExceptionLine, parseReceiptDocs } from './ship-receipt-docs';
import { ruledNoteText, type RuledNote } from './ruled-notes';
import { bodyLineText, ruledNoteText, type RuledNote } from './ruled-notes';
import { gateDispositionText, type GateDisposition } from './gate-dispositions';
import { laneExceptionBodyLines } from './test-lane-exception';
import { VISIBLE_CHARS, VISIBLE_LINES, visibleOpening } from './pr-body-shape';
@@ -113,20 +113,21 @@ function withoutApprovalsBlocks(body: string): string {
/**
* The body without the exception lines the receipt's own exceptions require: the `Documentation exception: …` line (GST-983) and each `Ruled note: …`, `Gate disposition: …`, `Mechanical retake: …` and `Test-lane exception: …` line (GST-1537, GST-2491, GST-1560, GST-1595). write and the receipt check want each word for word,
* and each quotes the owner's reason (`outside 1 and 2 skip detector`), not this PR's counters. Only a line whose
* trimmed text is a rendered line, the test write applies, is left out; the same words inside a longer line stay
* trimmed text is a rendered line (a ruled note also as a `- ` or `* ` list item, bodyLineText), the test write applies, is left out; the same words inside a longer line stay
* prose. A marker line takes its place so the text on either side never joins into a claim.
*/
function withoutExceptionLines(body: string, receipt: Record<string, unknown>): string {
const lines = new Set<string>();
const ruled = new Set<string>();
const docs = receipt.docs === undefined ? undefined : parseReceiptDocs(receipt.docs);
const docsLine = docs?.ok ? docsExceptionLine(docs.docs) : null;
if (docsLine) lines.add(docsLine);
if (Array.isArray(receipt.ruled_notes)) for (const n of receipt.ruled_notes) lines.add(`Ruled note: ${ruledNoteText(n as RuledNote)}`);
if (Array.isArray(receipt.ruled_notes)) for (const n of receipt.ruled_notes) ruled.add(`Ruled note: ${ruledNoteText(n as RuledNote)}`);
if (Array.isArray(receipt.gate_dispositions)) for (const d of receipt.gate_dispositions) lines.add(`Gate disposition: ${gateDispositionText(d as GateDisposition)}`);
if (Array.isArray(receipt.mechanical)) for (const l of receipt.mechanical) if (typeof l === 'string') lines.add(l);
for (const l of laneExceptionBodyLines(receipt.ci_carried)) lines.add(l);
if (!lines.size) return body;
return body.split(/(?<=\n)/).map(l => (lines.has(l.trim()) ? '(exception line)\n' : l)).join('');
if (!lines.size && !ruled.size) return body;
return body.split(/(?<=\n)/).map(l => (lines.has(l.trim()) || ruled.has(bodyLineText(l)) ? '(exception line)\n' : l)).join('');
}
/**