diff --git a/bin/gstack-review-dispatch b/bin/gstack-review-dispatch index 584a24864..1b84f9174 100755 --- a/bin/gstack-review-dispatch +++ b/bin/gstack-review-dispatch @@ -330,7 +330,7 @@ function ceiling(context: string, base: string, outDir: string, readers: Readonl } /** - * Each reader's secret-line excerpt, written once beside the briefs under its sha256 (the brief names the file, its bytes and + * Each reader's excerpt (secret-line and gate-tagged data files), written once beside the briefs under its sha256 (the brief names the file, its bytes and * hash); a file the excerpt could not be built for moves to the reader's keep list, so its whole diff reaches the reader. */ function settleExcerpts(m: Manifest): void { @@ -339,13 +339,13 @@ function settleExcerpts(m: Manifest): void { function settleExcerpt(r: Pick, diffBase: string, dir: string): void { if (!r.excerpt?.length) return; const d = selectionOf(diffBase, r.exclude, r.keep, r.excerpt); - if (!d.ok) throw new BriefError(`git diff ${diffBase} failed for ${r.reader}'s secret-line excerpt`); + if (!d.ok) throw new BriefError(`git diff ${diffBase} failed for ${r.reader}'s excerpt`); const whole = r.excerpt.filter(s => d.whole?.includes(s)); if (whole.length) r.keep = [...(r.keep ?? []), ...whole]; r.excerpt = r.excerpt.filter(s => !whole.includes(s)); if (!r.excerpt.length || !d.excerpt) { delete r.excerpt; return; } const sha256 = createHash('sha256').update(d.excerpt).digest('hex'); - const file = path.join(dir, `secret-excerpt-${sha256.slice(0, 16)}.md`); + const file = path.join(dir, `excerpt-${sha256.slice(0, 16)}.md`); fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); fs.writeFileSync(file, d.excerpt, { mode: 0o600 }); r.excerpt_file = { file, sha256, bytes: Buffer.byteLength(d.excerpt), files: r.excerpt.length }; diff --git a/changelog.d/review-cuts-gate-tagged-data-files.md b/changelog.d/review-cuts-gate-tagged-data-files.md new file mode 100644 index 000000000..9ad23286e --- /dev/null +++ b/changelog.d/review-cuts-gate-tagged-data-files.md @@ -0,0 +1 @@ +**Results PRs with large captured agent sessions can be reviewed.** When the gate scan tags a data file (a `.jsonl` transcript, a CSV, a log, or a results JSON) only because a captured session quotes a lint pragma, an env check or a `--no-verify` push on single lines, /ship's readers now get those tagged lines with context instead of the whole file, the same way files with a credential line already work. Code, declared-only files, anything under a test, CI, config or snapshot path, renamed files and files with a tag that spans lines still go to readers whole, and the gate review still runs. A diff that is still over the 2 MB review limit now names its largest files, and a gate-tagged file whose name holds a space is no longer dropped from review. diff --git a/docs/review-policy.md b/docs/review-policy.md index 14bf00a22..0e09df397 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -751,7 +751,9 @@ targeted reader) reads the same selection: its `DIFF_CMD:` with one same items, and the `DIFF_KEEP:` command for the kept files under those patterns. A kept file whose only reason is a secret line reaches pass readers as an excerpt of its matched lines in context instead ([secret-line -excerpts](ship-policy.md#secret-line-excerpts)). The outside voice's embedded diff is that selection. Each brief says +excerpts](ship-policy.md#secret-line-excerpts)), and so does an allowlisted data +file kept only for single-line gate tags ([gate-tagged data +excerpts](ship-policy.md#gate-tagged-data-excerpts)). The outside voice's embedded diff is that selection. Each brief says how many files and bytes were left out and that the reader must not report on their absence. Excluded paths count as docs for the depth and never trigger the numeric-claim scan or a targeted class; kept files keep their own class. diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 4fed5fd61..342408659 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1607,6 +1607,32 @@ whole through its keep command. Results PRs that capture model requests need this: their system prompts name `${…_API_KEY}` variables and keychain commands (harness-evals #269: 75 such files, 12.9 MB whole). + +**Gate-tagged data excerpts (GST-3273).** A kept file whose only reason is +`gate-tagged` gets the same excerpt, under its own `## Gate-tagged data +excerpts` heading, only when all of these hold; anything else goes to readers +whole: + +1. It is a `.jsonl`, `.ndjson`, `.csv`, `.tsv` or `.log` file, or a `.json` + file under a docs, results or reports tree. A + [`review_content_patterns`](#review-content-patterns) declaration alone never + qualifies a file. +2. No gate floor covers its path (test, CI, config, snapshot or golden), and it + was not renamed, so no tag can come from the floor or the old path. +3. It is kept for no other reason (not source, agent prose, config, a gate path, + executable, binary or a secret line). +4. Every tag instance in it is one added line's own tag: the multi-line rule + (an empty `catch` or `except: pass` across lines) finds nothing in its added + lines, and its untagged added lines, scanned together, tag nothing. + +The excerpt shows every changed line the gate scan's line rules tag (and every +secret-line or secret-shaped line) and names the tags. The plan and the receipt +apply the same rule to the same input, so they build the same selection. The +gate class and the record's `gate_tagged` list are unchanged: only how much of +the data file a reader sees changes. Results PRs that commit captured agent +sessions need this: the sessions quote lint pragmas, env checks and +`--no-verify` pushes (harness-evals #494: 25 transcripts, 11.4 MB whole). + **One selection for every reader (GST-1476).** Every path that renders a reader's brief builds its diff from the same selection: the policy's diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 98f21c42e..0c0d4f994 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -4164,9 +4164,13 @@ the base policy commit. split the PR. When published data under a pattern is kept as `code` (`REVIEW_EXCLUDE_KEPT: code …` on `.patch`, `.sha256` or extension-less files), add [`review_content_patterns`](ship-policy.md#review-content-patterns) for it. Files kept only for a secret line already count as their - excerpts ([secret-line excerpts](ship-policy.md#secret-line-excerpts)); one in - `DIFF_KEEP:` is kept for another reason, and one the excerpt could not be - built for moves to the reader's keep command and counts whole. + excerpts ([secret-line excerpts](ship-policy.md#secret-line-excerpts)), and so + do allowlisted data files kept only for gate tags ([gate-tagged data + excerpts](ship-policy.md#gate-tagged-data-excerpts)); one in `DIFF_KEEP:` is + kept for another reason, and one the excerpt could not be built for moves to + the reader's keep command and counts whole. The line's `files=` field and the + fix name the largest files left; a name holding a space, a comma or a colon is + quoted in `files=`. There is no override flag. See [the review ceiling](ship-policy.md#review-diff-ceiling). diff --git a/lib/gate-diff/git.ts b/lib/gate-diff/git.ts index 556ae819b..e083bc8af 100644 --- a/lib/gate-diff/git.ts +++ b/lib/gate-diff/git.ts @@ -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'; diff --git a/lib/gate-diff/tags.ts b/lib/gate-diff/tags.ts index 657897377..f013c633e 100644 --- a/lib/gate-diff/tags.ts +++ b/lib/gate-diff/tags.ts @@ -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); diff --git a/lib/review-brief.ts b/lib/review-brief.ts index 5589261a0..57e3dafba 100644 --- a/lib/review-brief.ts +++ b/lib/review-brief.ts @@ -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(', ')}`); diff --git a/lib/review-exclude.ts b/lib/review-exclude.ts index 46af79a1f..f08c218a7 100644 --- a/lib/review-exclude.ts +++ b/lib/review-exclude.ts @@ -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; 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; 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 `'${s.replace(/'/g, "'\\''")}'`; const literal = (p: string) => `:(top,literal)${p}`; const argBytes = (paths: Iterable) => { 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 | 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(); + 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>(); 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(); 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(); 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(); - 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(); + 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 } { +/** 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 } { 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`. */ diff --git a/lib/review-secret-excerpt.ts b/lib/review-secret-excerpt.ts index 2d56b8bc5..88b738eba 100644 --- a/lib/review-secret-excerpt.ts +++ b/lib/review-secret-excerpt.ts @@ -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 { +/** 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 { const out = new Map(); - 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 { 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(); + const byFile = new Map(); 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('') }; } diff --git a/test/fixtures/review-pins/replays/GST-3273.json b/test/fixtures/review-pins/replays/GST-3273.json new file mode 100644 index 000000000..94cf5a936 --- /dev/null +++ b/test/fixtures/review-pins/replays/GST-3273.json @@ -0,0 +1 @@ +{"replay":"GST-3273","justification":"GST-3273 gate-tagged data excerpt no-loss replay, rebuilt as an allowlist (CREW rule 15, GStack Minder ruling '1' 2026-11-20; prereg GStack Minder drive reports/GSTA-667-prereg.md, with the allowlist rebuild recorded as a dated deviation in reports/GSTA-667.md): deterministic, no paid run. On each commit's collectCommit input and one gate scan shared by both sides, reviewExclude from main a529769 and from this branch: harness-evals 60 first-parent main commits to 120f6fb102 all same; gstack-evals 200 to 5f8ff4e4fa all same (the 40 declared .patch files that moved under the first design now stay whole, because a review_content_patterns declaration no longer qualifies a file); gstack 200 to 92c6c8a55c all same (no review_exclude_paths). Every record digest, applied pattern, spec, keep list, kept reason, gate_tagged list and excerpt is identical on all 460. harness-evals #494 at 6a4b6ece15 against its merge base: 25 gate-tagged turn transcripts (.jsonl under results/) move from the whole-file keep list to excerpts and nothing else moves; every added line the gate scan's line rules tag, every secret-line match and every secret-shaped value in those files is in the excerpt (46 lines checked, 0 missing, 0 sent whole), and gstack-review-dispatch pass on that tree exits 0 with a 107,802-byte excerpt where main refuses with REVIEW_DIFF_TOO_LARGE."} diff --git a/test/review-gate-excerpt.test.ts b/test/review-gate-excerpt.test.ts new file mode 100644 index 000000000..bb48694ff --- /dev/null +++ b/test/review-gate-excerpt.test.ts @@ -0,0 +1,275 @@ +/** + * Gate-tagged data excerpts (GST-3273, harness-evals#494): a data file review_exclude_paths matches and keeps only because the + * gate scan tagged a changed line by its content (a suppression pragma or an env check quoted inside a captured agent + * transcript) goes to pass readers as every tagged line with context, the way secret-line files do (GST-1447). Only 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, whose every tag instance is one added line's own tag, is cut; anything else stays whole, and a diff still + * over the ceiling names its largest files. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { EXIT } from '../lib/headless-artifacts'; +import { REVIEW_DIFF_MAX_BYTES, reviewExclude, secretValueLine, secretValueSpans, tooLargeLine } from '../lib/review-exclude'; +import { taggedPaths } from '../lib/ship-receipt-depth'; +import { collectCommit } from '../lib/review-collect'; +import { REVIEW_CONTENT_KEY_VERSION } from '../lib/ship-policy-keys'; +import { secretExcerpt } from '../lib/review-secret-excerpt'; +import { REVIEW_EXCLUDE_KEY_VERSION } from '../lib/ship-policy'; +import { cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture'; + +const repos: FixtureRepo[] = []; +afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); +const policyText = JSON.stringify({ review_exclude_paths: ['docs/benchmarks/**'], min_gstack_version: REVIEW_EXCLUDE_KEY_VERSION }) + '\n'; +const TRIALS = 'docs/benchmarks/demo/results/trials'; +const lit = (p: string) => `:(top,literal)${p}`; + +/** + * One synthetic agent session in the #494 shape: about 2,000 JSONL turns (~230 KB) of plain chatter, with three turns whose + * quoted tool output the gate scan tags (an eslint-disable pragma, a process.env.CI check, and a --no-verify push buried in + * a 6 KB line). Each tagged turn carries a marker unique to its file and line. No real transcript text. + */ +function session(k: number): { text: string; markers: string[] } { + const lines: string[] = []; + const markers: string[] = []; + for (let n = 0; n < 2000; n++) { + const mark = `mark-f${k}-l${n}`; + if (n === 200) { markers.push(mark); lines.push(JSON.stringify({ role: 'tool', content: `patched lint: // eslint-disable-next-line no-console (${mark})` })); } + else if (n === 900) { markers.push(mark); lines.push(JSON.stringify({ role: 'tool', content: `if (process.env.CI) return; (${mark})` })); } + else if (n === 1600) { markers.push(mark); lines.push(JSON.stringify({ role: 'assistant', content: `${'Working through the task. '.repeat(120)}ran git push --no-verify (${mark}) ${'Still working. '.repeat(200)}` })); } + else lines.push(JSON.stringify({ role: n % 2 ? 'assistant' : 'user', content: `turn ${n} of trial ${k}: ${'plain words about the benchmark task '.repeat(2)}` })); + } + return { text: lines.join('\n') + '\n', markers }; +} + +/** A results branch: `files` plus lib/run.js; each trial's small summary.json is what review_exclude_paths leaves out. */ +function branch(files: Record) { + const repo = makeFixtureRepo({ prefix: 'gstack-gate-excerpt-', baseFiles: { '.gstack/ship-policy.json': policyText } }); + repos.push(repo); + commit(repo, { 'lib/run.js': "exports.run = () => 'ok';\n", ...files }); + return repo; +} +const pass = (repo: FixtureRepo) => { + const out = path.join(repo.root, 'pass'); + const r = runBin(repo, 'gstack-review-dispatch', ['pass', '--base', 'main', '--out', out, '--pass', 'p1']); + const file = path.join(out, 'pass-manifest.json'); + return { r, m: fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null }; +}; + +describe('gate-tagged data files go to readers as their tagged lines', () => { + // Value: protects=a results PR whose captured agent sessions quote lint pragmas or env checks reaches review instead of + // stopping at the ceiling, every tagged line still reaches readers, and the gate still fires; fails_when=a gate-tagged + // data file is sent whole (REVIEW_DIFF_TOO_LARGE, harness-evals#494: 25 files, 12.3 MB), a tagged line is missing, or + // a code file, a path-tagged snapshot or a file whose tag spans lines is cut; why_new=GST-3273; + // seam=gstack-review-plan and gstack-review-dispatch pass on a real repository, real gate scan; no_claim=what a model + // does with the excerpt + test('the #494 shape fits under the ceiling; code, path-tagged and multi-line-tagged files stay whole', () => { + const files: Record = {}; + const markers: Record = {}; + for (let k = 0; k < 12; k++) { + const s = session(k); + files[`${TRIALS}/t${k}/session.jsonl`] = s.text; + files[`${TRIALS}/t${k}/summary.json`] = `{"trial": ${k}, "passed": true}\n`; + markers[`${TRIALS}/t${k}/session.jsonl`] = s.markers; + } + const code = 'docs/benchmarks/demo/harness/score.ts'; + const snapshot = 'docs/benchmarks/demo/results/__snapshots__/expected.json'; + const spanning = `${TRIALS}/t99/run.log`; + const hidden = `${TRIALS}/t98/run.log`; + const mixed = `${TRIALS}/t97/run.log`; + files[code] = '// eslint-disable-next-line no-console\nexport const score = (n: number) => n * 2;\n'; + files[snapshot] = '{"score": 2}\n'; + files[spanning] = 'step 1\ntry { run() } catch (e) {\n}\nstep 2\n'; + files[hidden] = `step 1\nif (process.env.CI) try { realGate() } catch (e) {\n}\nrun(); try { a() } catch (e) {}\nstep 2\n`; + files[mixed] = `step 1\ntry { b() } catch (e) {\n}\nrun(); try { a() } catch (e) {}\nstep 2\n`; + const repo = branch(files); + const total = Object.values(files).reduce((n, t) => n + Buffer.byteLength(t), 0); + expect(total).toBeGreaterThan(REVIEW_DIFF_MAX_BYTES); + + const plan = runBin(repo, 'gstack-review-plan', ['--base', 'main']); + expect(plan.status).toBe(0); + expect(plan.out).toMatch(/^REVIEW_CLASS: gate/m); + expect(plan.out).toMatch(/^GATE_SCAN: tagged=([1-9]\d*)/m); + + const { r, m } = pass(repo); + expect(r.err).not.toContain('REVIEW_DIFF_TOO_LARGE'); + expect(r.status).toBe(EXIT.ok); + const readers = m.readers.filter((x: any) => !x.prompt_file); + expect(readers.length).toBeGreaterThan(0); + for (const reader of readers) { + expect(reader.excerpt).toEqual(Object.keys(markers).sort().map(lit)); + expect([...(reader.keep ?? [])].sort()).toEqual([code, snapshot, spanning, hidden, mixed].sort().map(lit)); + expect(reader.excerpt_file.files).toBe(12); + expect(reader.excerpt_file.bytes).toBeLessThan(REVIEW_DIFF_MAX_BYTES / 4); + } + const excerpt = fs.readFileSync(readers[0].excerpt_file.file, 'utf8'); + expect(excerpt).toContain('## Gate-tagged data excerpts (12 files)'); + for (const [file, ms] of Object.entries(markers)) { + expect(excerpt).toContain(`### ${file}`); + expect(excerpt).toContain('3 changed lines matched (0 by the secret-line rule, 0 with a secret-shaped value, 3 tagged by the gate scan: RH-12, RH-13, RH-14) out of 2000'); + for (const mark of ms) expect({ file, mark, found: excerpt.includes(mark) }).toEqual({ file, mark, found: true }); + } + expect(excerpt).not.toContain('turn 500 of trial 0'); + const rendered = readers.filter((x: any) => x.file && x.role !== 'outside-voice'); + expect(rendered.length).toBeGreaterThan(0); + for (const x of rendered) expect(fs.readFileSync(x.file, 'utf8')).toContain('a changed line the gate scan tagged in a data file'); + }, 300_000); + + // Value: protects=a diff still over the ceiling after the cut tells the lane which files to move, not only "split", and a + // gate-tagged file whose path holds a space stays in review; fails_when=REVIEW_DIFF_TOO_LARGE names folders alone or cuts + // a name at its first space, or the gate scan records the path with git's trailing tab so the file is excluded unread; + // why_new=GST-3273 (#494's only printed fix was "split the PR"); seam=gstack-review-dispatch pass on a real repository + test('a diff still over the ceiling after the cut names its largest files', () => { + const line = (k: number, n: number) => JSON.stringify({ role: 'tool', content: `// eslint-disable-next-line f${k} n${n} ${'x'.repeat(200)}` }); + const files: Record = {}; + for (let k = 0; k < 3; k++) { + files[`${TRIALS}/big ${k}/session.jsonl`] = Array.from({ length: 3600 + k * 100 }, (_, n) => line(k, n)).join('\n') + '\n'; + files[`${TRIALS}/big${k}/summary.json`] = `{"trial": ${k}}\n`; + } + const repo = branch(files); + const { r } = pass(repo); + expect(r.status).toBe(EXIT.refused); + expect(r.err).toContain('REVIEW_DIFF_TOO_LARGE'); + const m = / files=(.*?) policy=/.exec(r.err); + expect(m?.[1]?.split(',').slice(0, 3).map(f => JSON.parse(f.replace(/:\d+$/, '')))).toEqual([2, 1, 0].map(k => `${TRIALS}/big ${k}/session.jsonl`)); + expect(r.err).toContain(`largest files: ${TRIALS}/big 2/session.jsonl (`); + }, 300_000); +}); + +describe('a credential line in an excerpted file always reaches readers', () => { + // Value: protects=a kept file whose changed lines carry a credential value (secretValueLine: a key name given a + // credential-shaped run, with no SECRET_LINE or scanner match) never reaches readers as an excerpt without that line; + // fails_when=the gate-tagged excerpt shows only the tagged lines and drops the credential line, which before GST-3273 + // sent the file whole; why_new=/ship review of #4556 (security reader, reproduced); seam=gstack-review-dispatch pass on a + // real repository; no_claim=credential lines in files kept for another reason + test('a gate-tagged session with a credential line shows that line or goes whole', () => { + const blob = Buffer.from('a private signing key that must never reach a results tree 0x5f3759df').toString('base64'); + const file = `${TRIALS}/t0/session.jsonl`; + const lines = session(0).text.split('\n'); + lines[500] = JSON.stringify({ role: 'tool', content: `GH_TOKEN=${blob} (cred-mark-t0)` }); + const repo = branch({ [file]: lines.join('\n'), [`${TRIALS}/t0/summary.json`]: '{"trial": 0}\n' }); + const { r, m } = pass(repo); + expect(r.status).toBe(EXIT.ok); + const readers = m.readers.filter((x: any) => !x.prompt_file); + expect(readers.length).toBeGreaterThan(0); + for (const reader of readers) { + const whole = (reader.keep ?? []).includes(lit(file)); + const shown = reader.excerpt_file ? fs.readFileSync(reader.excerpt_file.file, 'utf8').includes('cred-mark-t0') : false; + expect({ reader: reader.reader, reaches: whole || shown }).toEqual({ reader: reader.reader, reaches: true }); + } + }, 300_000); +}); + +describe('a long credential line keeps its value in the excerpt', () => { + const blob = Buffer.from('a private signing key that must never reach a results tree 0x5f3759df').toString('base64'); + const diffOf = (file: string, line: string) => [`diff --git a/${file} b/${file}`, `--- a/${file}`, `+++ b/${file}`, '@@ -1,1 +1,2 @@', ' ok', '+' + line, ''].join('\n'); + // Value: protects=a credential value on a line past EXCERPT_LINE_MAX reaches readers (or its file goes whole) when another + // match already gave the line a window; fails_when=only the window around a gate tag is shown; why_new=/ship pass 2 on + // #4556 (security reader); seam=secretExcerpt with the predicate excerptOf passes + test('a gate tag far from the credential does not hide it', () => { + const line = '// eslint-disable-next-line ' + 'x'.repeat(900) + ' GH_TOKEN=' + blob + ' (cred-mark)'; + expect(secretValueLine('r/a.jsonl', line)).toBe(true); + const x = secretExcerpt(diffOf('r/a.jsonl', line), ['r/a.jsonl'], secretValueSpans); + expect({ whole: x.whole, shown: x.text.includes(blob) }).toEqual({ whole: [], shown: true }); + }); + // Value: protects=a value starting past the name's own 160-character window but inside secretValueLine's 200-character + // lookahead is shown; fails_when=the excerpt shows the name and cuts the value; why_new=/ship pass 2 on #4556 (red team); + // seam=secretExcerpt with the predicate excerptOf passes + test('a value past the name window but inside the lookahead is shown', () => { + const tok = 'Zq9Lm3Xv7Rt2Bn8Kp4Wd6Hs1Fg5'; + const line = 'x'.repeat(500) + ' k = process.env.DEMO_API_KEY || "' + 'y '.repeat(80) + tok + '"'; + expect(secretValueLine('r/a.jsonl', line)).toBe(true); + const x = secretExcerpt(diffOf('r/a.jsonl', line), ['r/a.jsonl'], secretValueSpans); + expect({ whole: x.whole, shown: x.text.includes(tok) }).toEqual({ whole: [], shown: true }); + }); +}); + +describe('only allowlisted data files are cut, the same way in the plan and the receipt', () => { + /** The plan's selection (gstack-review-plan --json) and the receipt's (reviewExclude on the commit, tags from gstack-gate-diff jsonl). */ + const both = (repo: FixtureRepo) => { + const head = repo.git('rev-parse', 'HEAD'); + const baseSha = repo.git('rev-parse', 'origin/main'); + const planned = runBin(repo, 'gstack-review-plan', ['--base', 'main', '--json']); + const scan = runBin(repo, 'gstack-gate-diff', [baseSha, '--format', 'jsonl']); + const c = collectCommit(repo.work, baseSha, head); + const receipt = reviewExclude({ root: repo.work, baseSha, ref: 'origin/main', mergeBase: c.mergeBase!, head, perPath: c.perPath, added: c.added, classRoot: c.root ?? [], gateTagged: taggedPaths(scan.out), context: 'test' }); + if (receipt.state === 'refused') expect({ status: planned.status, code: planned.err.includes(`(${receipt.code})`) }).toEqual({ status: EXIT.refused, code: true }); + else { + expect(planned.status).toBe(0); + const plan = JSON.parse(planned.out).review_exclude; + expect(receipt.state === 'active' ? { digest: receipt.record.digest, excerpt: receipt.excerpt } : { state: receipt.state }).toEqual(plan?.state === 'active' ? { digest: plan.digest, excerpt: plan.excerpt } : { state: plan?.state ?? 'none' }); + } + return receipt; + }; + const tag = 'patched: // eslint-disable-next-line no-console'; + + // Value: protects=a review_content_patterns declaration never qualifies a file to be cut, while an allowlisted data file + // beside it is cut, and the plan and the receipt agree; fails_when=a declared .out session is excerpted, or the two + // selections differ (RECEIPT_INVALID field=review_exclude); why_new=/ship's final review of #4556 (adversarial reader) + // and the allowlist rebuild; seam=gstack-review-plan and reviewExclude on a real repository + test('a declared .out session stays whole; a results .jsonl beside it is cut', () => { + const policy = JSON.stringify({ review_exclude_paths: ['docs/benchmarks/**'], review_content_patterns: ['docs/benchmarks/**/sessions/**'], min_gstack_version: REVIEW_CONTENT_KEY_VERSION }) + '\n'; + const repo = makeFixtureRepo({ prefix: 'gstack-gate-agree-', baseFiles: { '.gstack/ship-policy.json': policy } }); + repos.push(repo); + const s0 = 'docs/benchmarks/demo/sessions/s0.out'; + const rows = `${TRIALS}/t0/session.jsonl`; + const lines = Array.from({ length: 40 }, (_, n) => n === 5 ? tag : n === 9 ? 'read docs/benchmarks/demo/results/summary.json' : `turn ${n}`); + commit(repo, { 'lib/run.js': "exports.run = () => 'ok';\n", [s0]: lines.join('\n') + '\n', [rows]: lines.map(l => JSON.stringify({ c: l })).join('\n') + '\n', 'docs/benchmarks/demo/results/summary.json': '{"ok": true}\n', 'docs/benchmarks/demo/results/other.json': '{"n": 1}\n' }); + const x = both(repo); + expect(x.state === 'active' && x.excerpt).toEqual([lit(rows)]); + expect(x.state === 'active' && x.keep.includes(lit(s0))).toBe(true); + }, 120_000); + + // Value: protects=a declared .patch under test/, a .jsonl under test/ and a file renamed from code stay whole, so a tag only + // the floor or the old path gives (RH-1's focus and skip idioms) is never hidden behind a one-line tag; fails_when=any of + // them is excerpted; why_new=/ship's fifth review of #4556 (a floor-only RH-1 skip on a declared .patch under test/ behind + // a floor-free RH-1 line) and the allowlist rebuild; seam=gstack-review-plan and reviewExclude on a real repository + test('a declared .patch under test/, a .jsonl under test/ and a renamed code file stay whole', () => { + const policy = JSON.stringify({ review_exclude_paths: ['docs/benchmarks/**'], review_content_patterns: ['docs/benchmarks/**/test/**'], min_gstack_version: REVIEW_CONTENT_KEY_VERSION }) + '\n'; + const legacy = Array.from({ length: 30 }, (_, n) => `const step${n} = ${n};`); + const repo = makeFixtureRepo({ prefix: 'gstack-gate-floor-', baseFiles: { '.gstack/ship-policy.json': policy, 'src/legacy.ts': legacy.join('\n') + '\n' } }); + repos.push(repo); + const patch = 'docs/benchmarks/demo/test/fixtures/fix.patch'; + const underTest = 'docs/benchmarks/demo/test/rows.jsonl'; + const moved = `${TRIALS}/t1/legacy.jsonl`; + const rows = `${TRIALS}/t0/session.jsonl`; + const movedLines = [...legacy]; + movedLines[10] = "it.skip('the real gate', () => {});"; + movedLines[20] = tag; + commit(repo, { + 'lib/run.js': "exports.run = () => 'ok';\n", + [patch]: ['--- a/x.test.ts', '+++ b/x.test.ts', '@@ -1 +1 @@', "+test.only('focus', () => {});", "+it.skip('the real gate', () => {});", ''].join('\n'), + [underTest]: JSON.stringify({ c: tag }) + '\n', + 'src/legacy.ts': null, [moved]: movedLines.join('\n') + '\n', + [rows]: JSON.stringify({ c: tag }) + '\n', + [`${TRIALS}/t0/summary.json`]: '{"ok": true}\n', + }); + const x = both(repo); + expect(x.state).toBe('active'); + if (x.state !== 'active') return; + expect(x.excerpt).toEqual([lit(rows)]); + for (const p of [patch, underTest, moved]) expect({ p, whole: x.keep.includes(lit(p)) }).toEqual({ p, whole: true }); + }, 120_000); + + // Value: protects=many cut files count toward the kept-file argument bound in the plan exactly as in the receipt; + // fails_when=the plan leaves cut files out of KEEP_ARG_MAX_BYTES and applies the pattern while the receipt refuses it; + // why_new=/ship's final review of #4556 (adversarial reader); seam=gstack-review-plan and reviewExclude on a real repository + test('three hundred cut files reach the same verdict on the argument bound', () => { + const repo = branch({}); + const files: Record = { [`${TRIALS}/summary.json`]: '{"ok": true}\n' }; + for (let k = 0; k < 300; k++) files[`${TRIALS}/a-rather-long-trial-folder-name-for-the-bound-${k}/session.jsonl`] = JSON.stringify({ c: tag }) + '\n'; + commit(repo, files); + expect(both(repo).state).toBe('refused'); + }, 120_000); +}); + +describe('REVIEW_DIFF_TOO_LARGE names files with spaces whole', () => { + // Value: protects=the largest-files list names a path holding a space, a comma or a colon as one quoted field; fails_when=the + // name is cut at its first space or splits the files= field; why_new=GST-3273 rebuild; seam=tooLargeLine + test('a path with a space is quoted in files= and named whole in the fix', () => { + const p = 'docs/run 2/session.jsonl'; + const x = tooLargeLine('t', 'r', { bytes: 3_000_000, byDir: [['docs', 3_000_000]], byFile: [[p, 3_000_000], ['docs/b.jsonl', 10]] }, { state: 'none', base: 'main', source: 's' }); + expect(x.line).toContain(`files="${p}":3000000,docs/b.jsonl:10 `); + expect(x.line).toContain(`largest files: ${p} (3000000 bytes)`); + }); +});