Results PRs with large agent transcripts can be reviewed again (GST-3273) (#4574)

Results PRs that commit captured agent sessions no longer stop at the 2
MB review limit: a data file kept in review only because a session
quotes a lint pragma, an env check or a `--no-verify` push now reaches
readers as those lines with context.

Why: harness-evals#494 (25 transcripts, 11.3 MB) could not be reviewed
at all. Only a strict set of files is cut, so anything in doubt still
goes to readers whole.

Nothing to do: the gate review still runs, and the change follows the
review policy you already have.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-20 21:34:22 +00:00
1 parent 593d7e1634
commit ad65f62edf
12 files changed
+468 -52

No files matched your search

+4 -3
View File
@@ -212,13 +212,14 @@ export function unquoteGitPath(p: string): string {
return Buffer.from(bytes).toString('utf-8');
}
/** A ---/+++ path; the caller drops the tab git appends after an unquoted name holding a space. */
function stripPrefix(p: string, prefix: 'a/' | 'b/'): string {
const u = unquoteGitPath(p);
return u.startsWith(prefix) ? u.slice(2) : u;
}
/** Split `diff --git a/x b/y` into (x, y); equal paths resolve exactly, renames with spaces fall back to the middle ` b/`. */
function splitDiffGitLine(rest: string): [string, string] {
export function splitDiffGitLine(rest: string): [string, string] {
if (rest.startsWith('"')) {
const m = /^("(?:[^"\\]|\\.)*") ("(?:[^"\\]|\\.)*")$/.exec(rest);
if (m) return [stripPrefix(m[1], 'a/'), stripPrefix(m[2], 'b/')];
@@ -284,8 +285,8 @@ function sectionToFile(sec: Section): FileDiff {
else if (h.startsWith('copy to ')) { newPath = unquoteGitPath(h.slice(8)); status = 'copied'; }
else if (h.startsWith('new file mode')) status = 'added';
else if (h.startsWith('deleted file mode')) status = 'deleted';
else if (h.startsWith('--- ') && !h.startsWith('--- /dev/null')) oldPath = stripPrefix(h.slice(4), 'a/');
else if (h.startsWith('+++ ') && !h.startsWith('+++ /dev/null')) newPath = stripPrefix(h.slice(4), 'b/');
else if (h.startsWith('--- ') && !h.startsWith('--- /dev/null')) oldPath = stripPrefix(h.slice(4).replace(/\t$/, ''), 'a/');
else if (h.startsWith('+++ ') && !h.startsWith('+++ /dev/null')) newPath = stripPrefix(h.slice(4).replace(/\t$/, ''), 'b/');
if (/\b120000\b/.test(h) && /mode/.test(h)) unsupported = 'symlink';
if (/^index [0-9a-f]+\.\.[0-9a-f]+ 160000$/.test(h) || /\b160000\b/.test(h) && /mode/.test(h)) unsupported = 'submodule';
if (h.startsWith('Binary files ')) unsupported = unsupported ?? 'binary';
+18 -2
View File
@@ -103,8 +103,8 @@ function anyMatch(lines: string[], idioms: RegExp[]): boolean {
return lines.some((l) => idioms.some((re) => re.test(l)));
}
/** Multi-line empty catch / `except:` + `pass` across consecutive added lines. */
function swallowsAcrossLines(adds: string[]): boolean {
/** Multi-line empty catch / `except:` + `pass` across consecutive added lines: the one detector off the floor that reads more than one added line. */
export function swallowsAcrossLines(adds: string[]): boolean {
for (let i = 0; i + 1 < adds.length; i++) {
const a = adds[i].trim();
const b = adds[i + 1].trim();
@@ -274,6 +274,22 @@ export function tagHunk(h: Hunk, ctx: TagContext): TagResult {
return { tags: sorted, notes, citation: sorted.length ? findCitation(adds) : null };
}
/** Every idiom one added line can carry a tag by on its own (the floor-free part of tagHunk): where a tagged line's matches sit. */
const LINE_IDIOMS = [...SKIP_IDIOMS, ...PLACEHOLDER_IDIOMS, ...ENV_SNIFF_IDIOMS, ...SUPPRESSION_IDIOMS, ...BYPASS_IDIOMS, ...SWALLOW_SINGLE_LINE].map((r) => new RegExp(r.source, r.flags.includes('g') ? r.flags : r.flags + 'g'));
/**
* The tags one added line carries alone, outside the floor (tagHunk on a one-line hunk), and the spans its idioms matched:
* what a gate-tagged data excerpt shows (lib/review-secret-excerpt.ts, GST-3273). A tag no single line carries (RH-1's
* removed declarations, RH-3, RH-15, RH-16 across lines) never appears here, so a file holding one is never cut.
*/
export function lineTags(text: string, path: string): { tags: string[]; spans: Array<[number, number]> } {
const tags = tagHunk({ header: '', lines: [{ kind: 'add', text }] }, { floor: null, path, allPaths: new Set([path]) }).tags;
if (!tags.length) return { tags, spans: [] };
const spans: Array<[number, number]> = [];
for (const r of LINE_IDIOMS) for (const m of text.matchAll(r)) if (m[0]) spans.push([m.index ?? 0, (m.index ?? 0) + m[0].length]);
return { tags, spans };
}
/** RH ids in numeric order; a `?` variant follows its base. */
export function compareTags(a: string, b: string): number {
const num = (t: string) => Number.parseInt(t.replace(/^RH-/, ''), 10);
+1 -1
View File
@@ -140,7 +140,7 @@ export function renderBrief(role: BriefRole, slots: Slots, t: SectionTexts): str
for (const k of keys) held[k] = `\u0000${nonce}:${k}\u0000`;
const rendered = renderRole(role, held, t);
const keep = slots.keep ? ` Read the files kept despite a match as well: \`git diff ${slots.diff_base} -- ${slots.keep}\`.` : '';
const excerpt = slots.excerpt_file ? ` ${need(slots, 'excerpt_files')} kept files have no keep reason but a changed line that reads a credential, so no git diff command above shows them: read every such line, with context, in the file ${slots.excerpt_file} (${need(slots, 'excerpt_bytes')} bytes, sha256 ${need(slots, 'excerpt_sha256')}).` : '';
const excerpt = slots.excerpt_file ? ` ${need(slots, 'excerpt_files')} kept files are in review only for a changed line that reads a credential or a changed line the gate scan tagged in a data file, so no git diff command above shows them: read every such line, with context, in the file ${slots.excerpt_file} (${need(slots, 'excerpt_bytes')} bytes, sha256 ${need(slots, 'excerpt_sha256')}).` : '';
const text = slots.disclosure && role !== 'fix-check' && role !== 'outside-voice' ? `${rendered}\n\n${slots.disclosure}${keep}${excerpt}` : rendered;
const left = role === 'fix-check' || role === 'outside-voice' ? [] : PLACEHOLDERS.filter(p => text.includes(p));
if (left.length) throw new BriefError(`${role}: unfilled placeholder ${left.join(', ')}`);
+75 -22
View File
@@ -18,10 +18,13 @@
* A file kept only for a secret line (a line that names a credential and carries a value, secretValueLine;
* no other reason, under an applied pattern, gate scan and consumer scan both read) is also listed in `excerpt`: pass readers
* get its matched lines in context (lib/review-secret-excerpt.ts, GST-1447) instead of the whole file, readSelection counts
* only that excerpt, and no reader's command names it, so it does not count toward the bound (GST-1967).
* only that excerpt, and no reader's command names it, so it does not count toward the bound (GST-1967). A data file kept
* only because the gate scan tagged it (gateData: a .jsonl, .ndjson, .csv, .tsv or .log file, or a .json under a results
* tree, off every gate floor, not renamed, kept for no other reason, and every tag instance one added line's own tag) is
* excerpted the same way, its tagged lines in context (GST-3273, harness-evals#494); anything else stays whole.
*
* readSelection reads one reader's diff once, with a timeout, and counts its bytes;
* gstack-review-dispatch stops with REVIEW_DIFF_TOO_LARGE above REVIEW_DIFF_MAX_BYTES and
* gstack-review-dispatch stops with REVIEW_DIFF_TOO_LARGE above REVIEW_DIFF_MAX_BYTES, naming the largest files, and
* with REVIEW_DIFF_UNREADABLE when git fails, before it writes a manifest or a brief.
*/
import { spawnSync } from './spawn-sync';
@@ -30,10 +33,13 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { collectLive } from './review-collect';
import { classifyPath as gateFloor, parseGateIntegrityBlock } from './gate-diff/classify';
import { readClaudeMd, splitDiffGitLine } from './gate-diff/git';
import { lineTags, swallowsAcrossLines, tagHunk } from './gate-diff/tags';
import { DATA_PATH, classifyPath, isAgentProse, isDataConfig, isGatePath, type PathLines } from './review-depth';
import { scan } from './redact-engine';
import { shannonEntropy } from './redact-patterns';
import { KEY_NAME, SECRET_LINE, secretPath } from './review-risk';
import { KEY_NAME, RESULTS_TREE, SECRET_LINE, 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';
@@ -58,7 +64,7 @@ export interface ExcludeRecord {
}
export interface ActiveExclusion {
state: 'active'; record: ExcludeRecord; excluded: Set<string>; specs: string[]; keep: string[];
/** The kept files (a subset of keep, as `:(top,literal)` items) whose only reason is a secret line: pass readers get an excerpt. */
/** The kept files (a subset of keep, as `:(top,literal)` items) whose only reason is a secret line, or gate tags on data lines: pass readers get an excerpt. */
excerpt: string[];
kept: Array<{ path: string; reason: KeptReason }>; content: Record<ContentKind, number>; references: Array<{ prefix: string; files: string[] }>;
}
@@ -100,8 +106,18 @@ const valueToken = (text: string) => [...text.replace(VARIABLE_REFERENCE, ' ').m
* `process.env.X`, `os.environ["X"]`, a keychain) holds no value.
*/
export function secretValueLine(p: string, line: string): boolean {
const ends = SECRET_NAMES.flatMap(r => [...line.matchAll(r)].map(m => m.index + m[0].length));
return ends.length > 0 && (ends.some(e => valueToken(line.slice(e, e + 200))) || scan(line, { processEnv: {}, sourcePath: p }).findings.some(f => f.category === 'secret' && f.severity !== 'LOW'));
return secretValueSpans(p, line) !== null;
}
/**
* Where secretValueLine finds a credential value on a line: for each name a credential-shaped run follows, the name and the
* 200 characters the run may start in; [] when only the credential scan finds the value; null when the line holds none.
*/
export function secretValueSpans(p: string, line: string): Array<[number, number]> | null {
const names = SECRET_NAMES.flatMap(r => [...line.matchAll(r)].map(m => [m.index, m.index + m[0].length] as [number, number]));
if (!names.length) return null;
const valued = names.filter(([, e]) => valueToken(line.slice(e, e + 200)));
if (valued.length) return valued.map(([s, e]) => [s, e + 200]);
return scan(line, { processEnv: {}, sourcePath: p }).findings.some(f => f.category === 'secret' && f.severity !== 'LOW') ? [] : null;
}
/** The list_sha256 of a selection that holds no file: no pattern matched the range, so applied, excluded and kept are all empty. */
export const EMPTY_LIST_SHA256 = sha256(JSON.stringify({ applied: [], excluded: [], kept: [] }));
@@ -110,6 +126,31 @@ export const recordedList = (r: Partial<Pick<ExcludeRecord, 'patterns_sha256' |
const shellQuote = (s: string) => `'${s.replace(/'/g, "'\\''")}'`;
const literal = (p: string) => `:(top,literal)${p}`;
const argBytes = (paths: Iterable<string>) => { let n = 0; for (const p of paths) n += Buffer.byteLength(shellQuote(literal(p))) + 1; return n; };
/** The data files a gate-tagged file may be cut on (GST-3273), beside a .json under a results tree; a review_content_patterns declaration alone never qualifies one. */
const GATE_DATA = /\.(?:jsonl|ndjson|csv|tsv|log)$/i;
/**
* Whether every gate tag in a file's added lines is one line's own tag (lineTags), so an excerpt of those lines shows every
* instance (GST-3273): at least one line is tagged, the multi-line detector finds nothing across the added lines, and the
* untagged lines, scanned together as one hunk, tag nothing. Its caller has already ruled out renames and floor paths, where
* removed lines and floor-only rules can tag a file.
*/
function singleLineTags(p: string, added: readonly string[]): boolean {
const adds = added.map(l => l.replace(/\r$/, ''));
const rest = adds.filter(l => !lineTags(l, p).tags.length);
return rest.length < adds.length && !swallowsAcrossLines(adds) && !tagHunk({ header: '', lines: rest.map(text => ({ kind: 'add' as const, text })) }, { floor: null, path: p, allPaths: new Set([p]) }).tags.length;
}
/** The paths the range renames into, as the gate scan's `git diff -M` pairs them; null when git cannot list them. */
function renamedPaths(i: ExcludeInput): Set<string> | null {
const r = spawnSync('git', ['-c', 'core.quotePath=false', 'diff', '-M', '--name-status', '-z', '--diff-filter=R', i.mergeBase, ...(i.head ? [i.head] : [])], { cwd: i.root, encoding: 'utf8', timeout: 120_000, maxBuffer: MAX_BUFFER });
if (r.status !== 0 || typeof r.stdout !== 'string') return null;
const parts = r.stdout.split('\0');
const out = new Set<string>();
for (let k = 0; k + 2 < parts.length; k += 3) out.add(parts[k + 2]!);
return out;
}
/** `paths` in order, split so each chunk's literal pathspecs (`size` bytes each) stay within KEEP_ARG_MAX_BYTES (one path past it is its own chunk). */
function argChunks(paths: readonly string[], size = (p: string) => argBytes([p])): string[][] {
const chunks: string[][] = [];
@@ -417,21 +458,28 @@ export function reviewExclude(i: ExcludeInput): Exclusion {
for (const [p, m] of sel.files) reasons.set(p, unread.has(p) ? 'consumer-scan-unavailable' : pathReason(text, p, m, binary, native) ?? (unseen(p) ? 'consumer-scan-unavailable' : null));
const candidates = new Set([...reasons].filter(([, r]) => r === null).map(([p]) => p));
const secretOnly = [...reasons].filter(([p, r]) => r === 'secret-line' && !p.includes('\n')).map(([p]) => p);
const tagOnly = [...reasons].filter(([p, r]) => r === 'gate-tagged' && !p.includes('\n') && (GATE_DATA.test(p) || (/\.json$/i.test(p) && RESULTS_TREE.test(p)))
&& !binary.has(p) && !unseen(p) && pathReason({ ...text, gateTagged: null }, p, sel.files.get(p)!, binary, native) === null).map(([p]) => p);
const renamed = tagOnly.length ? renamedPaths(i) : null;
const floorCtx = { project: parseGateIntegrityBlock(readClaudeMd(i.root)), specIsTestPath: true };
const gateData = renamed ? tagOnly.filter(p => !renamed.has(p) && gateFloor(p, floorCtx) === null && singleLineTags(p, text.added[p] ?? [])) : [];
const y: Scope = { ...x, keptDeclared: new Set([...reasons].filter(([p, r]) => r !== null && declared.has(p)).map(([p]) => p)) };
const named = grepFixed(y, [...candidates, ...secretOnly].filter(p => !p.includes('\n')), new Set([...candidates, ...secretOnly]), [i.mergeBase]);
const gateNamed = gateData.length ? grepFixed(y, gateData, new Set([...candidates, ...secretOnly]), [i.mergeBase]) : new Map<string, Set<string>>();
for (const p of candidates) {
if (i.gateTagged === null) reasons.set(p, 'gate-scan-unavailable');
else if (named === null || p.includes('\n')) reasons.set(p, 'consumer-scan-unavailable');
else if (named.has(p)) reasons.set(p, 'named-by-code');
}
const excerptable = new Set(i.gateTagged === null || named === null ? [] : secretOnly.filter(p => !named.has(p)));
const secretExcerptable = new Set(i.gateTagged === null || named === null ? [] : secretOnly.filter(p => !named.has(p)));
const excerptable = new Set(i.gateTagged === null || named === null || gateNamed === null ? [...secretExcerptable] : [...secretExcerptable, ...gateData.filter(p => !gateNamed.has(p))]);
const applied: string[] = [];
const keep = new Set<string>();
for (const p of patterns) {
const hit = sel.byPattern.get(p) ?? [];
if (!hit.some(f => reasons.get(f) === null)) continue;
const kept = hit.filter(f => reasons.get(f) !== null);
const bytes = argBytes([...new Set([...keep, ...kept])].filter(f => !excerptable.has(f)));
const bytes = argBytes([...new Set([...keep, ...kept])].filter(f => !secretExcerptable.has(f)));
if (bytes > KEEP_ARG_MAX_BYTES) {
const why = new Map<string, number>();
for (const f of kept) why.set(reasons.get(f)!, (why.get(reasons.get(f)!) ?? 0) + 1);
@@ -479,7 +527,8 @@ export function excludeLines(x: Exclusion, base: string): string[] {
const out = [`REVIEW_EXCLUDE: patterns=${r.applied.length}/${r.patterns.length} excluded=${r.excluded} bytes=${r.excluded_bytes} kept=${r.kept} content=${Object.entries(x.content).filter(([, n]) => n).map(([k, n]) => `${k}:${n}`).join(',') || 'none'} source=${r.source} digest=${r.digest}${r.unmatched.length ? ` unmatched=${r.unmatched.join(',')}` : ''}`];
for (const k of x.kept.slice(0, 20)) out.push(`REVIEW_EXCLUDE_KEPT: ${k.reason} ${k.path}`);
if (x.kept.length > 20) out.push(`REVIEW_EXCLUDE_KEPT: +${x.kept.length - 20} more (gstack-review-plan --json lists every kept file)`);
if (x.excerpt.length) out.push(`REVIEW_EXCLUDE_EXCERPT: ${x.excerpt.length} kept files hold no keep reason but a secret line; gstack-review-dispatch pass gives readers their matched lines in context, not the whole files, and DIFF_KEEP leaves them out`);
const gated = x.excerpt.filter(s => x.kept.some(k => k.reason === 'gate-tagged' && literal(k.path) === s)).length;
if (x.excerpt.length) out.push(`REVIEW_EXCLUDE_EXCERPT: ${x.excerpt.length} kept files hold no keep reason but a secret line${gated ? ` or gate tags on data lines (${gated} gate-tagged)` : ''}; gstack-review-dispatch pass gives readers their matched lines in context, not the whole files, and DIFF_KEEP leaves them out`);
for (const ref of x.references) out.push(`REVIEW_EXCLUDE_REFERENCE: ${ref.prefix} is named by ${ref.files.slice(0, 3).join(', ')}${ref.files.length > 3 ? ` (+${ref.files.length - 3} more)` : ''}; the files stay excluded, so readers see that code without the files it reads (REVIEW_EXCLUDE_REFERENCE)`);
return out;
}
@@ -499,7 +548,7 @@ export function parseTail(tail: string | undefined): string[] {
}
export type ReaderDiff =
| { ok: true; text: string; bytes: number; byDir: Array<[string, number]>; excerpt?: string; whole?: string[] }
| { ok: true; text: string; bytes: number; byDir: Array<[string, number]>; byFile: Array<[string, number]>; excerpt?: string; whole?: string[] }
| { ok: false; reason: 'timeout' | 'git-exit'; exit: number | null; stderr: string; timeoutMs: number };
/** The excerpt of one `git diff --text` over the excerpt files; any throw sends every file whole (fail closed). */
@@ -507,7 +556,7 @@ function excerptOf(out: string, specs: readonly string[]): { text: string; whole
const paths = specs.map(s => s.replace(/^:\(top,literal\)/, ''));
try {
if (specs.some(s => !s.startsWith(':(top,literal)'))) throw new Error('an excerpt item is not a literal pathspec');
const x = secretExcerpt(out, paths);
const x = secretExcerpt(out, paths, secretValueSpans);
return { text: x.text, files: x.files, whole: x.whole.map(literal), wholeText: x.wholeText };
} catch { return { text: '', files: [], whole: [...specs], wholeText: out }; }
}
@@ -539,12 +588,13 @@ export function readSelection(root: string, diffBase: string, pathspecs: readonl
const ex = excerpt.length && !full ? excerptOf(raw, excerpt) : undefined;
if (ex) text += ex.wholeText;
const byDir = new Map<string, number>();
const add = (file: string, bytes: number) => { const dir = file.includes('/') ? file.split('/')[0]! : '(root)'; byDir.set(dir, (byDir.get(dir) ?? 0) + bytes); };
const starts = [...text.matchAll(/^diff --git a\/(\S+)/gm)];
starts.forEach((m, k) => add(m[1]!, Buffer.byteLength(text.slice(m.index!, k + 1 < starts.length ? starts[k + 1]!.index! : text.length))));
const byFile = new Map<string, number>();
const add = (file: string, bytes: number) => { const dir = file.includes('/') ? file.split('/')[0]! : '(root)'; byDir.set(dir, (byDir.get(dir) ?? 0) + bytes); byFile.set(file, (byFile.get(file) ?? 0) + bytes); };
const starts = [...text.matchAll(/^diff --git (.*)$/gm)];
starts.forEach((m, k) => add(splitDiffGitLine(m[1]!)[1], Buffer.byteLength(text.slice(m.index!, k + 1 < starts.length ? starts[k + 1]!.index! : text.length))));
for (const f of ex?.files ?? []) add(f.path, Buffer.byteLength(f.text));
const all = ex?.text ? `${text}${text && !text.endsWith('\n') ? '\n' : ''}${ex.text}` : text;
return { ok: true, text: all, bytes: Buffer.byteLength(all), byDir: [...byDir].sort((a, b) => b[1] - a[1]), ...(ex ? { excerpt: ex.text, whole: ex.whole } : {}) };
return { ok: true, text: all, bytes: Buffer.byteLength(all), byDir: [...byDir].sort((a, b) => b[1] - a[1]), byFile: [...byFile].sort((a, b) => b[1] - a[1]), ...(ex ? { excerpt: ex.text, whole: ex.whole } : {}) };
}
/** Credential-bearing remote URLs and scp-style remotes out of git's stderr. */
@@ -572,16 +622,19 @@ function suggest(byDir: ReadonlyArray<[string, number]>, bytes: number): string[
return out;
}
/** The REVIEW_DIFF_TOO_LARGE line and object: the reader's bytes, the largest folders and a fix chosen by where the policy stands. */
export function tooLargeLine(context: string, reader: string, d: { bytes: number; byDir: ReadonlyArray<[string, number]> }, c: CeilingContext): { line: string; json: Record<string, unknown> } {
/** The REVIEW_DIFF_TOO_LARGE line and object: the reader's bytes, the largest folders and files, and a fix chosen by where the policy stands. */
export function tooLargeLine(context: string, reader: string, d: { bytes: number; byDir: ReadonlyArray<[string, number]>; byFile?: ReadonlyArray<[string, number]> }, c: CeilingContext): { line: string; json: Record<string, unknown> } {
const top = d.byDir.slice(0, 5).map(([dir, n]) => `${dir}:${n}`).join(',') || 'none';
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 the PR`;
const largest = (d.byFile ?? []).slice(0, 5);
const split = largest.length ? `split the PR (largest files: ${largest.map(([f, n]) => `${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 dirs = suggest(d.byDir, d.bytes);
const fix = c.state === 'head-only' ? `this branch declares review_exclude_paths, but only the copy on ${c.base} applies: ${land(c.headPatterns ?? [])}`
: c.state === 'active' ? `still over after excluding ${c.record?.excluded ?? 0} files; ${dirs.length ? land([...(c.record?.patterns ?? []), ...dirs.filter(p => !c.record?.patterns.includes(p))]) : 'split the PR'}`
: dirs.length ? land(dirs) : 'split the PR';
const line = `${context}: the reader's diff is over the review ceiling (reader=${reader} bytes=${d.bytes} max=${REVIEW_DIFF_MAX_BYTES} top=${top} policy=${c.source}); fix: ${fix}; nothing was written (REVIEW_DIFF_TOO_LARGE)`;
return { line, json: { code: 'REVIEW_DIFF_TOO_LARGE', reader, bytes: d.bytes, max: REVIEW_DIFF_MAX_BYTES, top: d.byDir.slice(0, 5).map(([dir, bytes]) => ({ dir, bytes })), policy: c.source, state: c.state, fix, side_effects: 'none' } };
: c.state === 'active' ? `still over after excluding ${c.record?.excluded ?? 0} files; ${dirs.length ? land([...(c.record?.patterns ?? []), ...dirs.filter(p => !c.record?.patterns.includes(p))]) : split}`
: dirs.length ? land(dirs) : split;
const files = largest.length ? ` files=${largest.map(([f, n]) => `${/[\s,:"]/.test(f) ? JSON.stringify(f) : f}:${n}`).join(',')}` : '';
const line = `${context}: the reader's diff is over the review ceiling (reader=${reader} bytes=${d.bytes} max=${REVIEW_DIFF_MAX_BYTES} top=${top}${files} policy=${c.source}); fix: ${fix}; nothing was written (REVIEW_DIFF_TOO_LARGE)`;
return { line, json: { code: 'REVIEW_DIFF_TOO_LARGE', reader, bytes: d.bytes, max: REVIEW_DIFF_MAX_BYTES, top: d.byDir.slice(0, 5).map(([dir, bytes]) => ({ dir, bytes })), files: largest.map(([file, bytes]) => ({ file, bytes })), policy: c.source, state: c.state, fix, side_effects: 'none' } };
}
/** The REVIEW_DIFF_UNREADABLE line: timeout or git exit, the timeout, the base, a redacted first stderr line, and the whole (redacted) stderr written under `logDir`. */
+54 -17
View File
@@ -8,7 +8,17 @@
* every match. It fails closed: a section it cannot tie to one expected path, one with no matched added line (the keep
* reason the excerpt stands in for), and one whose hunks or scanner result cannot be read come back whole, and readSelection
* inlines every file on any other throw.
*
* An allowlisted data file kept only for single-line gate tags (lib/review-exclude.ts gateData, GST-3273:
* captured agent sessions quoting lint pragmas or env checks, harness-evals#494: 25 files, 12.3 MB) gets the same excerpt,
* plus every changed line lineTags tags, under its own heading that names the tags. Such a file with no tagged line here
* goes whole, and so does one whose tagged line runs past EXCERPT_LINE_MAX with no idiom span to show. Every changed line
* holding a credential value by the caller's secretLine rule (lib/review-exclude.ts secretValueSpans, the secret-line keep
* reason) is shown too, with a window around each credential name and the 200 characters its value may start in, so an
* excerpt never leaves out the value a file was kept for; a line past EXCERPT_LINE_MAX whose value only the credential scan
* finds, and that the scan here does not place, sends its file whole.
*/
import { lineTags } from './gate-diff/tags';
import { scan } from './redact-engine';
import { SECRET_LINE } from './review-risk';
@@ -24,7 +34,7 @@ const SCAN_OVERLAP_BYTES = 1024;
export interface SecretExcerpt { text: string; files: Array<{ path: string; text: string }>; whole: string[]; wholeText: string }
interface Line { kind: string; text: string; old: number; new: number }
interface Hit { rule: boolean; shaped: boolean; spans: Array<[number, number]> }
interface Hit { rule: boolean; shaped: boolean; gate: string[]; spans: Array<[number, number]> }
const GLOBAL = SECRET_LINE.map(r => new RegExp(r.source, r.flags.includes('g') ? r.flags : r.flags + 'g'));
@@ -52,12 +62,22 @@ function hunkLines(body: readonly string[]): Line[] {
return out;
}
/** Each changed line SECRET_LINE matches or the scanner finds a secret-shaped value (not LOW) on, with the spans to show. */
function hits(lines: readonly Line[], file: string): Map<number, Hit> {
/** Each changed line SECRET_LINE matches, the scanner finds a secret-shaped value (not LOW) on, or lineTags tags or secretLine reads as a credential value (added lines), with the spans to show. */
function hits(lines: readonly Line[], file: string, secretLine?: (file: string, line: string) => Array<[number, number]> | null): Map<number, Hit> {
const out = new Map<number, Hit>();
const at = (k: number) => out.get(k) ?? out.set(k, { rule: false, shaped: false, spans: [] }).get(k)!;
const at = (k: number) => out.get(k) ?? out.set(k, { rule: false, shaped: false, gate: [], spans: [] }).get(k)!;
const changed = lines.flatMap((l, k) => (l.kind === ' ' ? [] : [k]));
for (const k of changed) {
if (lines[k]!.kind === '+') {
const text = lines[k]!.text.replace(/\r$/, '');
const g = lineTags(text, file);
if (g.tags.length) {
if (text.length > EXCERPT_LINE_MAX && !g.spans.length) throw new Error(`a gate-tagged line in ${file} has no span to show`);
const h = at(k);
h.gate = g.tags;
h.spans.push(...g.spans.map(([a, b]) => [a - EXCERPT_WINDOW, b + EXCERPT_WINDOW] as [number, number]));
}
}
for (const r of GLOBAL) {
r.lastIndex = 0;
for (let m = r.exec(lines[k]!.text); m; m = r.exec(lines[k]!.text)) {
@@ -88,6 +108,15 @@ function hits(lines: readonly Line[], file: string): Map<number, Hit> {
while (back - 1 > from && overlap < SCAN_OVERLAP_BYTES) overlap += size(--back);
from = back;
}
for (const k of changed) {
const spans = lines[k]!.kind === '+' ? secretLine?.(file, lines[k]!.text) : null;
if (!spans) continue;
const scanned = out.get(k)?.shaped === true;
const h = at(k);
h.shaped = true;
h.spans.push(...spans.map(([a, b]) => [a - EXCERPT_WINDOW, b + EXCERPT_WINDOW] as [number, number]));
if (lines[k]!.text.length > EXCERPT_LINE_MAX && !spans.length && !scanned) throw new Error(`a credential line in ${file} has no match to show`);
}
return out;
}
@@ -104,10 +133,10 @@ function shown(text: string, h: Hit | undefined): string {
return `${spans[0]![0] > 0 ? '… ' : ''}${body}${spans[spans.length - 1]![1] < text.length ? ' …' : ''} [a line of ${text.length} characters, shown around each match]`;
}
/** One file's excerpt block, or null when no added line matches the secret-line rule (the reason the file was kept). */
function block(file: string, lines: readonly Line[]): string | null {
const found = hits(lines, file);
if (![...found].some(([k, h]) => h.rule && lines[k]!.kind === '+')) return null;
/** One file's excerpt block and whether gate tags earned it, or null when no added line matches the secret-line rule or carries a gate tag (the reasons the file was kept). */
function block(file: string, lines: readonly Line[], secretLine?: (file: string, line: string) => Array<[number, number]> | null): { text: string; gate: boolean } | null {
const found = hits(lines, file, secretLine);
if (![...found].some(([k, h]) => (h.rule || h.gate.length > 0) && lines[k]!.kind === '+')) return null;
const rows = [...found.keys()].sort((a, b) => a - b);
const windows: Array<[number, number]> = [];
for (const k of rows) {
@@ -116,13 +145,17 @@ function block(file: string, lines: readonly Line[]): string | null {
if (last && a <= last[1] + 1) last[1] = b; else windows.push([a, b]);
}
const rule = rows.filter(k => found.get(k)!.rule).length;
const gated = rows.filter(k => found.get(k)!.gate.length > 0);
const shaped = rows.filter(k => found.get(k)!.shaped && !found.get(k)!.rule).length;
const tags = [...new Set(gated.flatMap(k => found.get(k)!.gate))].sort();
const changed = lines.filter(l => l.kind !== ' ').length;
const out = [`### ${file}`, `${rows.length} changed lines matched (${rule} by the secret-line rule, ${rows.length - rule} with a secret-shaped value) out of ${changed}; each is shown with up to ${EXCERPT_CONTEXT} lines of context.`];
const gate = gated.length ? `, ${gated.length} tagged by the gate scan: ${tags.join(', ')}` : '';
const out = [`### ${file}`, `${rows.length} changed lines matched (${rule} by the secret-line rule, ${gated.length ? shaped : rows.length - rule} with a secret-shaped value${gate}) out of ${changed}; each is shown with up to ${EXCERPT_CONTEXT} lines of context.`];
for (const [a, b] of windows) {
out.push(`@@ -${lines[a]!.old} +${lines[a]!.new} @@`);
for (let k = a; k <= b; k++) out.push(lines[k]!.kind + shown(lines[k]!.text, found.get(k)));
}
return out.join('\n') + '\n';
return { text: out.join('\n') + '\n', gate: gated.length > 0 };
}
/**
@@ -130,10 +163,10 @@ function block(file: string, lines: readonly Line[]): string | null {
* git quoted, that names no expected path or repeats one, that has no matched added line, or whose hunk header or scanner
* result cannot be read goes whole, and so does any expected path no section was excerpted for.
*/
export function secretExcerpt(diff: string, paths: readonly string[]): SecretExcerpt {
export function secretExcerpt(diff: string, paths: readonly string[], secretLine?: (file: string, line: string) => Array<[number, number]> | null): SecretExcerpt {
const want = new Set(paths);
const unattributed: string[] = [];
const byFile = new Map<string, { sections: string[]; text: string | null }>();
const byFile = new Map<string, { sections: string[]; text: string | null; gate?: boolean }>();
for (const section of diff.split(/(?<=\n)(?=diff --git )/).filter(Boolean)) {
const lines = section.split('\n');
const h = lines.findIndex(l => l.startsWith('@@'));
@@ -141,13 +174,17 @@ export function secretExcerpt(diff: string, paths: readonly string[]): SecretExc
if (file === null || !want.has(file)) { unattributed.push(section); continue; }
const prior = byFile.get(file);
if (prior) { prior.sections.push(section); prior.text = null; continue; }
let text: string | null = null;
try { text = h < 0 ? null : block(file, hunkLines(lines.slice(h))); } catch { text = null; }
byFile.set(file, { sections: [section], text });
let b: { text: string; gate: boolean } | null = null;
try { b = h < 0 ? null : block(file, hunkLines(lines.slice(h)), secretLine); } catch { b = null; }
byFile.set(file, { sections: [section], text: b?.text ?? null, gate: b?.gate });
}
const files = paths.flatMap(p => { const text = byFile.get(p)?.text; return text ? [{ path: p, text }] : []; });
const whole = paths.filter(p => !byFile.get(p)?.text);
const wholeParts = [...unattributed, ...whole.flatMap(p => byFile.get(p)?.sections ?? [])];
const head = `## Secret-line excerpts (${files.length} files)\nThese files match review_exclude_paths and stay in review only because a changed line reads a credential; the rest of each file is left out like any excluded file. Each excerpt shows every changed line that matches the secret-line rule or holds a secret-shaped value, with up to ${EXCERPT_CONTEXT} lines of context; a line over ${EXCERPT_LINE_MAX} characters shows ${EXCERPT_WINDOW} characters on each side of each match. Review them for credentials that are leaked or handled unsafely.\n\n`;
return { text: files.length ? head + files.map(f => f.text).join('\n') : '', files, whole, wholeText: wholeParts.join('') };
const secret = files.filter(f => !byFile.get(f.path)!.gate);
const gate = files.filter(f => byFile.get(f.path)!.gate);
const head = `## Secret-line excerpts (${secret.length} files)\nThese files match review_exclude_paths and stay in review only because a changed line reads a credential; the rest of each file is left out like any excluded file. Each excerpt shows every changed line that matches the secret-line rule or holds a secret-shaped value, with up to ${EXCERPT_CONTEXT} lines of context; a line over ${EXCERPT_LINE_MAX} characters shows ${EXCERPT_WINDOW} characters on each side of each match. Review them for credentials that are leaked or handled unsafely.\n\n`;
const gateHead = `## Gate-tagged data excerpts (${gate.length} files)\nThese data files match review_exclude_paths and stay in review only because the gate scan tagged changed lines by their content (a suppression pragma, an env check, a skipped test, a placeholder, a swallowed exception or a gate bypass, often quoted inside captured agent output); the rest of each file is left out like any excluded file. Each excerpt shows every changed line the gate scan's line rules tag, every line that matches the secret-line rule or holds a secret-shaped value, and the tags, with up to ${EXCERPT_CONTEXT} lines of context; a line over ${EXCERPT_LINE_MAX} characters shows ${EXCERPT_WINDOW} characters on each side of each match. Review each tagged line as you would a gate-tagged hunk, and say whether it weakens a check or only records one.\n\n`;
const parts = [...(secret.length ? [head + secret.map(f => f.text).join('\n')] : []), ...(gate.length ? [gateHead + gate.map(f => f.text).join('\n')] : [])];
return { text: parts.join('\n'), files, whole, wholeText: wholeParts.join('') };
}