diff --git a/bin/gstack-banned-terms b/bin/gstack-banned-terms index 94c5bdefd7..67ef40b82a 100755 --- a/bin/gstack-banned-terms +++ b/bin/gstack-banned-terms @@ -16,6 +16,7 @@ import { spawnSync } from '../lib/spawn-sync'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { BANNED_TERMS_PATH, addedLines, exampleBannedTermsJson, loadBannedTerms, renderBannedTerms, scanBannedTerms, validateBannedTerms, wholeFiles } from '../lib/banned-terms'; +import { gitDiffInParts, mergeParts } from '../lib/diff-parts'; import { baseArg } from '../lib/gate-diff/git'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { resultLine } from '../lib/result-codes'; @@ -78,9 +79,10 @@ function main(argv: string[]): number { else { const diffBase = flag(rest, '--diff-base') ?? (() => { const mb = spawnSync('git', ['merge-base', baseArg('gstack-banned-terms', base, repoRoot), 'HEAD'], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000 }); return mb.status === 0 ? mb.stdout.trim() : undefined; })(); if (!diffBase) { process.stderr.write(`gstack-banned-terms: no merge base with ${base}; pass --diff-base or --files \n`); return EXIT.usage; } - const diff = spawnSync('git', ['diff', '--unified=0', '--no-color', diffBase], { cwd: repoRoot, encoding: 'utf8', timeout: 120_000, maxBuffer: 256 * 1024 * 1024 }); - if (diff.status !== 0) { process.stderr.write(`gstack-banned-terms: git diff ${diffBase} failed\n`); return EXIT.fail; } - files = addedLines(diff.stdout); + const added = new Map>(); + const diff = gitDiffInParts(['diff', '--unified=0', '--no-color', diffBase], { cwd: repoRoot, timeout: 120_000 }, part => mergeParts(added, addedLines(part))); + if (!diff.ok) { process.stderr.write(`gstack-banned-terms: git diff ${diffBase} failed\n`); return EXIT.fail; } + files = added; } const result = scanBannedTerms(load.config, load.source, files); if (json) process.stdout.write(JSON.stringify(result) + '\n'); else process.stdout.write(renderBannedTerms(result)); diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index fd3f36e1ab..ceb5da707a 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -62,7 +62,7 @@ import { RISK_CLASSES, type RiskClass } from '../lib/review-risk'; import { checkReceiptProse, proseLine } from '../lib/ship-receipt-prose'; import { resolveStateRoot } from '../lib/state-root'; import { readPause, receiptBaseRed } from '../lib/base-red'; -import { publicRuledNote, readRuledNotes, ruledNoteText } from '../lib/ruled-notes'; +import { bodyListsLine, publicRuledNote, readRuledNotes, ruledNoteText } from '../lib/ruled-notes'; import { appliedGateDispositions, gateDispositionText, publicGateDisposition } from '../lib/gate-dispositions'; import { securityFingerprints } from '../lib/security-findings'; import { laneExceptionBodyLines } from '../lib/test-lane-exception'; @@ -304,7 +304,7 @@ async function cmdWrite(rest: string[], json: boolean): Promise { const leaked = securityFingerprints(bodyText); if (leaked.length) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${bodyFile} names security finding ${leaked.join(', ')}: a PR body is public, so a security finding appears only as the redacted line gstack-approvals rulings, dispositions or gstack-review-scope render prints, and its location and reason stay in the private record (docs/troubleshooting.md#security-finding-in-body); nothing written`) + '\n'); return EXIT.fail; } const ruledNotes = readRuledNotes(repoRoot); - const unlisted = bodyFile ? ruledNotes.map(n => `Ruled note: ${ruledNoteText(n)}`).find(l => !bodyText.split(/\r?\n/).some(b => b.trim() === l)) : undefined; + const unlisted = bodyFile ? ruledNotes.map(n => `Ruled note: ${ruledNoteText(n)}`).find(l => !bodyListsLine(bodyText, l)) : undefined; if (unlisted) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${bodyFile} does not list ruled note ${JSON.stringify(unlisted)} (gstack-approvals rulings prints each line the body carries); nothing written`) + '\n'); return EXIT.fail; } let gateDispositions: ReturnType['applied']; try { gateDispositions = appliedGateDispositions(repoRoot, { pin: 'HEAD' }).applied; } diff --git a/changelog.d/large-results-prs-ship-scaling.md b/changelog.d/large-results-prs-ship-scaling.md new file mode 100644 index 0000000000..17e801483f --- /dev/null +++ b/changelog.d/large-results-prs-ship-scaling.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +**`/gstack-ship` now handles very large results PRs.** A repository's `review_exclude_paths` can list up to 256 patterns instead of 64. When a reviewer's diff is still too big, the suggested fix no longer offers to hide `docs/` and never prints a policy gstack would refuse. The pre-merge secrets check and `gstack-banned-terms` read a diff of any size instead of failing past 256 MB. `gstack-review-plan` matches exclusion patterns and searches for files that name excluded paths with a fixed number of git calls, which took a 16,000-file results PR from 180 s to 100 s, and the docs-only check searches for references to every changed doc in one pass instead of one search per file. A PR body may list its `Ruled note:` lines as `- ` or `* ` bullets. diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 7f1008dc4d..f6cb6ef067 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -94,7 +94,11 @@ branch that changes the policy. | `changelog_fragments` | `{ dir, required_checks? }` or `null` | `null` | PRs carry unversioned [CHANGELOG fragments](#changelog-fragments) in `dir` (one flat, repo-relative directory, no `..`) and the merge step ([`land`](#land)) assigns the version (under `merge: direct`, the [release PR](#release-stamp) does). `required_checks` (up to 50 distinct names) are the checks [`train land`](#stamped-trains-under-changelog_fragments-train-land) requires present and green on a stamp commit. `null` keeps `[Unreleased]` sections and per-PR stamps. Needs `min_gstack_version`. | Containment, checked by `validate` and again at write time: paths and globs are -repo-relative with no `..` segment, under 256 characters, at most 64 per list, +repo-relative with no `..` segment, under 256 characters, at most 64 per list +(`review_exclude_paths` takes up to 256, as long as their exclude pathspecs fit +in 24,000 argument bytes together, since every reader's one `git diff` carries +all of them; an older gstack reads a list over 64 as invalid, sets the key aside +and reviews every file), and a glob's regex expansion under 512 characters; `release_tool` is under 512 characters with no newline; a matched file that resolves through a symlink to outside the repository is refused (`POLICY_CONTAINMENT`). A mirror may start @@ -1468,8 +1472,8 @@ the base commit it already resolved (`origin/`, or ``), never the branch's copy, so a branch cannot exclude its own files. A branch that adds the key gets `REVIEW_EXCLUDE: none (head sets review_exclude_paths; it applies after it lands on )` and a normal review. A base policy whose only errors -are in `review_exclude_paths` or `review_content_patterns` (65 patterns, say, -past the limit of 64) does not stop the plan: both keys are set aside, every +are in `review_exclude_paths` or `review_content_patterns` (257 patterns, say, +past the limit of 256) does not stop the plan: both keys are set aside, every file is reviewed as if the base excluded nothing, and every other key, the readers' `forbid_paths` included, applies as committed. The plan prints `REVIEW_EXCLUDE: fallback (WARNING: …)` naming each error and the fix, on @@ -1865,7 +1869,7 @@ with the `gate_id` its gate disposition needs, since a ruling never closes one `gstack-approvals rulings` prints one `Ruled note: …` line per ruling for the Pre-Landing Review and the PR body, `gstack-ship-receipt write` records them as `ruled_notes` (each with its `head`) and refuses a `--body` that does not carry each -line word for word, and the READY block prints each as `RULED_NOTE:`. +line word for word (bare, or as a `- ` or `* ` list item), and the READY block prints each as `RULED_NOTE:`. Step 11.5 reads the same rulings: `gstack-review-read` applies a ruling to a Step 9 or Step 11 row that carries the finding and whose `range_base..commit` holds the ruling's head (a first pass, with no `range_base`: its own commit), lists its diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index db48b5c96b..f35868b894 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -3758,8 +3758,9 @@ a typo never silently means "default". `gstack-ship-policy init --explain` prints each key, its meaning and default. When the invalid file is the base branch's and its only errors are in -`review_exclude_paths` or `review_content_patterns` (for example `more than 64 -patterns`), /gstack-ship does not stop: `gstack-review-plan` prints `REVIEW_EXCLUDE: +`review_exclude_paths` or `review_content_patterns` (for example `more than 256 +patterns` in `review_exclude_paths`, or `more than 64 patterns` in +`review_content_patterns`), /gstack-ship does not stop: `gstack-review-plan` prints `REVIEW_EXCLUDE: fallback (WARNING: …)`, reviews every file and applies the base's other keys, so open a PR that corrects the list and ship it as usual ([review_exclude_paths](ship-policy.md#review-exclude-paths)). Any other error @@ -4011,7 +4012,8 @@ record only when it changes no binary file, adds no numeric claim, touches no results, prereg or eval path, and names no money, security, secret or auth topic; any other docs change needs the reader again (GST-1195). With `--body`, write also refuses, writing nothing, a body that does not carry each line the receipt requires as one line, -word for word: every `Ruled note: …` line `gstack-approvals rulings` prints, +word for word: every `Ruled note: …` line `gstack-approvals rulings` prints +(bare, or as a `- ` or `* ` list item), every `Gate disposition: …` line `gstack-approvals dispositions` prints (and while a gate disposition applies at HEAD, write refuses to run without `--body`), finish's `MECHANICAL:` lines as `Mechanical retake: …`, and accept's @@ -4090,7 +4092,11 @@ the base policy commit. - **A pattern keeps too many files** stops the plan with [`REVIEW_EXCLUDE_KEEP_TOO_LARGE`](#review-exclude-keep-too-large) before any reader runs. - **Still over after exclusion:** add the printed folders to the base policy, or - split the PR. When published data under a pattern is kept as `code` + split the PR. The fix only suggests data, log and binary folders, never `docs/` + (the report is what the reviewer is there to read), and when the printed folders + would take the base list past 256 patterns or its 24,000-byte pathspec budget it + prints no JSON and asks for the existing patterns to be merged under fewer + folder globs instead. 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)), and so diff --git a/lib/diff-parts.ts b/lib/diff-parts.ts new file mode 100644 index 0000000000..5769d18edf --- /dev/null +++ b/lib/diff-parts.ts @@ -0,0 +1,64 @@ +/** + * diff-parts — one `git diff` read with no output buffer to fill (GST-4003). + * + * A pipe read with spawnSync stops at its maxBuffer: harness-evals#616's added lines came to 255.7 MB against the secrets + * scan's 256 MiB, so a slightly larger results PR could not be scanned at all. Here git writes to a private file (mode + * 0600 in a 0700 directory, removed afterwards), and the caller gets it back in parts of about `partBytes`, each ending + * where the next `diff --` header starts. Inside a hunk every line starts with ' ', '+', '-', '\\' or '@@', and git quotes + * a name holding a newline, so a line starting `diff --` is always a file header: each file's section arrives whole in one + * part, and the parts joined are git's output byte for byte. A per-file parser fed every part in order therefore sees + * what it saw on the whole text. + */ +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { spawnSync } from './spawn-sync'; + +export const DIFF_PART_BYTES = 64 * 1024 * 1024; +const HEADER = Buffer.from('\ndiff --'); + +export interface DiffRun { cwd: string; timeout: number; env?: NodeJS.ProcessEnv } +export type DiffRead = { ok: true } | { ok: false; why: string }; + +/** Run `git ` and hand each part of its stdout to `each` in order; a git that did not finish (an exit, a kill, a timeout) is not ok. */ +export function gitDiffInParts(args: readonly string[], run: DiffRun, each: (part: string) => void, partBytes = DIFF_PART_BYTES): DiffRead { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-diff-')); + try { + fs.chmodSync(dir, 0o700); + const file = path.join(dir, 'out.diff'); + const fd = fs.openSync(file, 'w', 0o600); + let r: ReturnType; + try { r = spawnSync('git', [...args], { cwd: run.cwd, env: run.env, stdio: ['ignore', fd, 'pipe'], encoding: 'utf8', timeout: run.timeout }); } finally { fs.closeSync(fd); } + if (r.error || r.status !== 0) return { ok: false, why: r.error?.message ?? (r.status === null ? `killed by ${r.signal}` : `exit ${r.status}: ${String(r.stderr ?? '').trim().split('\n').pop() ?? ''}`) }; + const input = fs.openSync(file, 'r'); + try { + const pending: Buffer[] = []; + let held = 0; + let tail = Buffer.alloc(0); + for (;;) { + const chunk = Buffer.alloc(Math.max(1, partBytes)); + const n = fs.readSync(input, chunk, 0, chunk.length, null); + if (n <= 0) break; + const read = chunk.subarray(0, n); + const seen = Buffer.concat([tail, read]); + let cut = -1; + for (let at = seen.indexOf(HEADER); at >= 0; at = seen.indexOf(HEADER, at + 1)) cut = held - tail.length + at + 1; + pending.push(read); + held += n; + tail = Buffer.from(seen.subarray(Math.max(0, seen.length - HEADER.length + 1))); + if (cut <= 0) continue; + const all = Buffer.concat(pending, held); + each(all.subarray(0, cut).toString('utf8')); + pending.splice(0, pending.length, Buffer.from(all.subarray(cut))); + held -= cut; + } + if (held) each(Buffer.concat(pending, held).toString('utf8')); + } finally { fs.closeSync(input); } + return { ok: true }; + } finally { fs.rmSync(dir, { recursive: true, force: true }); } +} + +/** Fold per-part maps from a per-file parser into one, in the order the whole text would have built it. */ +export function mergeParts(into: Map, part: Map): void { + for (const [k, v] of part) { const have = into.get(k); if (have) for (const x of v) have.push(x); else into.set(k, v); } +} diff --git a/lib/docs-only.ts b/lib/docs-only.ts index 3849049c34..b4abd8e672 100644 --- a/lib/docs-only.ts +++ b/lib/docs-only.ts @@ -60,8 +60,8 @@ export class DocsOnlyError extends Error { constructor(readonly command: string, readonly detail: string, readonly fix: string) { super(`${command}: ${detail}`); } } -function git(root: string, args: string[], okCodes = [0]): string { - const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); +function git(root: string, args: string[], okCodes = [0], input?: string): string { + const r = spawnSync('git', args, { cwd: root, input, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); if (r.error || r.status === null || !okCodes.includes(r.status)) { const detail = (r.error?.message ?? r.stderr ?? '').trim().split('\n')[0] || `exit ${r.status}`; throw new DocsOnlyError(`git ${args.join(' ')}`, detail, /bad revision|unknown revision|no merge base|ambiguous argument/i.test(detail) @@ -158,6 +158,57 @@ export function referencesTo(root: string, p: string, tree?: string, repo: RepoD return grepFiles(root, [p], tree).filter(f => f !== p && !PROSE_REFERENCE.test(f) && pathRefusal(f, root, gen, repo) !== null); } +/** + * referencesTo for every one of `paths` at once (GST-4003: one `git grep` per path took minutes on a 16,000-file PR). One + * `git grep -l -F -f -` lists the files naming any of them, the outside-prose ones among those are read once, and each path + * gets the files whose bytes hold it, which is what a per-path `git grep -l -F -e ` lists (a path holds no newline, so a + * line match is a substring match). A path with a newline, which `-f` cannot carry, is still grepped alone. + */ +export function referencesToAll(root: string, paths: readonly string[], tree?: string, repo: RepoDocs = NO_REPO_DOCS): Map { + const out = new Map(); + const plain = [...new Set(paths)].filter(p => p && !p.includes('\n')); + for (const p of paths) if (!p || p.includes('\n')) out.set(p, referencesTo(root, p, tree, repo)); + for (const p of plain) out.set(p, []); + if (!plain.length) return out; + const gen = generatedOutputs(root); + const prefix = tree ? `${tree}:` : ''; + const named = git(root, ['grep', '-l', '-z', '-F', '-I', '-f', '-', ...(tree ? [tree] : []), '--'], [0, 1], plain.join('\n') + '\n').split('\0').filter(Boolean) + .map(f => (f.startsWith(prefix) ? f.slice(prefix.length) : f)).filter(f => !PROSE_REFERENCE.test(f) && pathRefusal(f, root, gen, repo) !== null); + const needles = plain.map(p => [p, Buffer.from(p)] as const); + const fromIndex = tree ? new Set() : indexRead(root); + for (let i = 0; i < named.length; i += 256) { + const files = named.slice(i, i + 256); + const cached = files.filter(f => fromIndex.has(f)); + const blobs = new Map(cached.length ? treeBlobs(root, '', cached).map((b, k) => [cached[k]!, b] as const) : []); + const texts = tree ? treeBlobs(root, tree, files) : files.map(f => blobs.get(f) ?? fs.readFileSync(path.join(root, f))); + files.forEach((f, k) => { for (const [p, needle] of needles) if (f !== p && texts[k]!.includes(needle)) out.get(p)!.push(f); }); + } + return out; +} + +/** Tracked paths a working-tree `git grep` reads from the index, as it does for skip-worktree and assume-unchanged entries (`git ls-files -v` tags them S or in lowercase). */ +function indexRead(root: string): Set { + return new Set(git(root, ['ls-files', '-v', '-z']).split('\0').filter(e => e.length > 2 && (e[0] === 'S' || e[0] !== e[0]!.toUpperCase())).map(e => e.slice(2))); +} + +/** The blobs of `files` at `tree` (the index when it is ''), through one `git cat-file --batch` (a name with a newline is read alone); any git failure throws DocsOnlyError. */ +function treeBlobs(root: string, tree: string, files: readonly string[]): Buffer[] { + const fail = (what: string): never => { throw new DocsOnlyError(`git cat-file ${tree}`, what, 'rerun in a git checkout of this repository'); }; + const one = (f: string) => { const r = spawnSync('git', ['cat-file', 'blob', `${tree}:${f}`], { cwd: root, timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); return r.status === 0 && Buffer.isBuffer(r.stdout) ? r.stdout : fail(`cannot read ${f}`); }; + const batched = files.filter(f => !f.includes('\n')); + const r = batched.length ? spawnSync('git', ['cat-file', '--batch'], { cwd: root, input: batched.map(f => `${tree}:${f}`).join('\n') + '\n', timeout: 60_000, maxBuffer: 1024 * 1024 * 1024 }) : null; + if (r && (r.error || r.status !== 0 || !Buffer.isBuffer(r.stdout))) fail((r.error?.message ?? String(r.stderr ?? '')).trim().split('\n')[0] || `exit ${r.status}`); + const read = new Map(); + for (let at = 0, k = 0; r && k < batched.length; k++) { + const nl = r.stdout.indexOf(10, at); + const size = Number(/^[0-9a-f]+ blob (\d+)$/.exec(r.stdout.subarray(at, nl).toString())?.[1] ?? NaN); + if (!Number.isInteger(size)) fail(`cannot read ${batched[k]}`); + read.set(batched[k]!, r.stdout.subarray(nl + 1, nl + 1 + size)); + at = nl + 2 + size; + } + return files.map(f => read.get(f) ?? one(f)); +} + /** * Non-docs tracked files that name a directory holding the repo-admitted path `p` ("wiki/", 'wiki', './wiki', root + '/wiki') and are tied to * none of the repository's docs_only.tests: a script that lists a directory reads every post in it, which the literal @@ -220,7 +271,11 @@ export function classifyDocsOnly(o: { root: string; base: string; head?: string; const repo = 'error' in policy ? NO_REPO_DOCS : policy; const changed = new Set(entries.flatMap(e => [e.path, ...(e.from ? [e.from] : [])])); const outside = (f: string) => !changed.has(f) || pathRefusal(f, o.root, undefined, repo) !== null; - const r = classifyEntries(entries, o.root, p => referencesTo(o.root, p, o.head, repo).filter(outside), repo, p => directoryReaders(o.root, p, repo, o.head).filter(outside)); + const gen = generatedOutputs(o.root); + const refs = referencesToAll(o.root, [...changed].filter(p => pathRefusal(p, o.root, gen, repo) === null), o.head, repo); + const readers = new Map(); + const readersOf = (p: string) => { const k = `${builtIn(p)}\0${path.posix.dirname(p)}`; if (!readers.has(k)) readers.set(k, directoryReaders(o.root, p, repo, o.head)); return readers.get(k)!; }; + const r = classifyEntries(entries, o.root, p => (refs.get(p) ?? referencesTo(o.root, p, o.head, repo)).filter(outside), repo, p => readersOf(p).filter(outside)); if ('error' in policy) return { ...r, docsOnly: false, tests: [], refusals: [{ path: SHIP_POLICY_PATH, reason: policy.error }, ...r.refusals] }; const missing = r.tests.filter(t => repo.tests.includes(t) && (o.head ? !git(o.root, ['ls-tree', '--name-only', o.head, '--', t]).trim() : !fs.existsSync(path.join(o.root, t)))); return missing.length ? { ...r, docsOnly: false, tests: [], refusals: missing.map(t => ({ path: t, reason: `listed in docs_only.tests at ${repo.label} but missing from this tree; restore it or correct the list` })) } : r; diff --git a/lib/pregate/checks/secrets.ts b/lib/pregate/checks/secrets.ts index 11a7892d0e..cd956849e0 100644 --- a/lib/pregate/checks/secrets.ts +++ b/lib/pregate/checks/secrets.ts @@ -10,6 +10,7 @@ * scanned in overlapping line-aligned parts (scanParts); a single line over * it fails. Runs regardless of lint tools. */ +import { gitDiffInParts, mergeParts } from '../../diff-parts'; import { spawnSync } from '../../spawn-sync'; import * as fs from 'node:fs'; import * as path from 'node:path'; @@ -155,6 +156,8 @@ function scratchNames(part: { file: string; keep?: number[] }): string[] { return gitMangledPath(part.file) && name !== 'added.txt' ? [name, 'added.txt'] : [name]; } const WHOLE_FILE_MAX_BYTES = 4 * 1024 * 1024; +/** Postimage text the full-context diff may hold in all: past it every file is scanned on its added lines, as when that diff overran its 256 MiB buffer. */ +const FULL_CONTEXT_MAX_BYTES = 256 * 1024 * 1024; /** * Added lines from the merge-base to the working tree, plus every line of @@ -171,23 +174,30 @@ const WHOLE_FILE_MAX_BYTES = 4 * 1024 * 1024; * `-diff` attribute the branch itself can add) from printing "Binary files * differ" in place of its added lines; each such file is marked `binary`, * carries every reading scannableReadings gives and is held to its credential findings. A diff git did not finish (an exit, a kill, a - * full buffer) throws: its partial output is never scanned as complete. + * timeout) throws: its partial output is never scanned as complete. git writes each diff to a private file read back in + * whole-file parts (lib/diff-parts.ts), so no output buffer caps a PR's size (GST-4003, harness-evals#616's 255.7 MB). */ export function addedLines(ctx: PregateContext): Array<{ file: string; texts: string[]; keep?: number[]; binary?: boolean }> { - const diff = spawnSync('git', ['diff', '--text', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/', '--unified=0', '--diff-filter=ACMR', ctx.mergeBase, '--'], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024, env: ctx.env }); - if (diff.error || diff.status !== 0) throw new Error(`git diff ${ctx.mergeBase.slice(0, 12)} did not finish (${diff.error?.message ?? (diff.status === null ? `killed by ${diff.signal}` : `exit ${diff.status}: ${(diff.stderr ?? '').trim().split('\n').pop() ?? ''}`)})`); - const files = parseAddedLines(diff.stdout ?? ''); - const numbers = parseAddedLineNumbers(diff.stdout ?? ''); + const files = new Map(); + const numbers = new Map(); + const run = { cwd: ctx.repoRoot, timeout: 60_000, env: ctx.env }; + const diff = gitDiffInParts(['diff', '--text', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/', '--unified=0', '--diff-filter=ACMR', ctx.mergeBase, '--'], run, part => { mergeParts(files, parseAddedLines(part)); mergeParts(numbers, parseAddedLineNumbers(part)); }); + if (!diff.ok) throw new Error(`git diff ${ctx.mergeBase.slice(0, 12)} did not finish (${diff.why})`); const whole = new Map(); const sources = [...numbers.keys()].filter(file => LEXICAL_CONTEXT_SOURCE.test(file)); if (sources.length) { - const full = spawnSync('git', ['-c', 'diff.suppressBlankEmpty=false', 'diff', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/', '--unified=100000000', '--diff-filter=ACMR', ctx.mergeBase, '--', ...sources.map(file => `:(literal)${file}`)], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024, env: ctx.env }); - for (const [file, post] of parsePostimages(full.status === 0 ? full.stdout ?? '' : '')) { - const keep = numbers.get(file) ?? []; - const added = files.get(file) ?? []; - const text = post.join('\n'); - if (text.length <= WHOLE_FILE_MAX_BYTES && keep.length === added.length && keep.every((n, k) => post[n - 1] === added[k])) whole.set(file, { text, keep }); - } + let held = 0; + const full = gitDiffInParts(['-c', 'diff.suppressBlankEmpty=false', 'diff', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/', '--unified=100000000', '--diff-filter=ACMR', ctx.mergeBase, '--', ...sources.map(file => `:(literal)${file}`)], run, part => { + if (held > FULL_CONTEXT_MAX_BYTES) return; + for (const [file, post] of parsePostimages(part)) { + const size = post.reduce((n, line) => n + line.length + 1, 0) - 1; + held += size; + const keep = numbers.get(file) ?? []; + const added = files.get(file) ?? []; + if (size <= WHOLE_FILE_MAX_BYTES && keep.length === added.length && keep.every((n, k) => post[n - 1] === added[k])) whole.set(file, { text: post.join('\n'), keep }); + } + }); + if (!full.ok || held > FULL_CONTEXT_MAX_BYTES) whole.clear(); } for (const t of ctx.touched) { if (!t.uncommitted || t.status === 'D') continue; diff --git a/lib/review-exclude-match.ts b/lib/review-exclude-match.ts new file mode 100644 index 0000000000..d2292679c8 --- /dev/null +++ b/lib/review-exclude-match.ts @@ -0,0 +1,105 @@ +/** + * review-exclude-match — which changed paths each review_exclude_paths pattern matches, and which fixed strings a file + * holds, at a cost that does not grow with the number of patterns or strings (GST-4003; harness-evals#616, 16,165 files). + */ +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { spawnSync } from './spawn-sync'; + +const MAX_BUFFER = 256 * 1024 * 1024; +function git(root: string, args: string[], input?: string, env?: NodeJS.ProcessEnv): { ok: boolean; status: number | null; out: string; err: string } { + const r = spawnSync('git', ['-c', 'core.quotePath=false', ...args], { cwd: root, input, env, encoding: 'utf8', timeout: 120_000, maxBuffer: MAX_BUFFER }); + return { ok: r.status === 0, status: r.status, out: r.stdout ?? '', err: (r.stderr ?? '').trim() }; +} + +export interface SelectInput { root: string; mergeBase: string; head?: string } +export interface Matched { oldMode: string; newMode: string; oldSha: string; newSha: string } + +/** Every changed path each pattern matches, with its modes, from git's raw diff; untracked files are never part of it, since no reader's git diff shows them and the receipt reads the committed head. */ +export function select(i: SelectInput, patterns: readonly string[]): { byPattern: Map; files: Map } | { error: string } { + const byPattern = new Map(); + const files = new Map(); + if (!patterns.length) return { byPattern, files }; + const range = i.head ? [i.mergeBase, i.head] : [i.mergeBase]; + const specs = patterns.map(p => `:(top,glob)${p}`); + const raw = git(i.root, ['diff', '--raw', '-z', '--no-abbrev', '--no-renames', ...range, '--', ...specs]); + if (!raw.ok) return { error: `git diff --raw ${range.join(' ')} -- ${specs.join(' ')}: ${raw.err.split('\n')[0] || `exit ${raw.status}`}` }; + const parts = raw.out.split('\0'); + for (let k = 0; k + 1 < parts.length; k += 2) { + const [oldMode, newMode, oldSha, newSha] = parts[k]!.slice(1).split(' '); + const f = parts[k + 1]!; + if (f && !files.has(f)) files.set(f, { oldMode: oldMode ?? '', newMode: newMode ?? '', oldSha: oldSha ?? '', newSha: newSha ?? '' }); + } + if (patterns.length === 1) return { byPattern: new Map([[patterns[0]!, [...files.keys()]]]), files }; + // GST-4003: one diff for every pattern, then each pattern's share from git's own pathspec match over scratch indexes of just + // those paths (a diff per pattern took 0.2 s each over harness-evals#616's 16,165 files, and the cap is now 256 patterns). + // A deleted path and a new one can be a file and a directory of the same name (data/x/a.json gone, data/x added), which one + // index cannot hold, so the head side and the deleted side get an index each; one that does not list every path it was + // given sends every pattern back to its own diff. A pattern with a bracket class or a backslash gets its own diff too: git's + // tree walk also matches a directory whose name spells the pattern out (res/[0-9]*/), and ls-files' wildmatch does not. + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-select-')); + try { + const sides = [[...files].filter(([, m]) => m.newMode !== '000000'), [...files].filter(([, m]) => m.newMode === '000000')].filter(s => s.length); + const hits = patterns.map(() => new Set()); + for (const [n, side] of sides.entries()) { + const env = { ...process.env, GIT_INDEX_FILE: path.join(dir, `index-${n}`) }; + const entries = side.map(([f, m]) => `${m.newMode !== '000000' ? m.newMode : m.oldMode} e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0\t${f}`); + const listed = git(i.root, ['update-index', '-z', '--index-info'], entries.join('\0') + '\0', env).ok ? git(i.root, ['ls-files', '-z', '--full-name'], undefined, env) : null; + if (!listed?.ok || listed.out.split('\0').filter(Boolean).length !== side.length) return perPattern(i, patterns, range, files); + for (const [k, spec] of specs.entries()) { + const ls = git(i.root, ['ls-files', '-z', '--full-name', '--', spec], undefined, env); + if (!ls.ok) return { error: `git ls-files -- ${spec}: ${ls.err.split('\n')[0] || `exit ${ls.status}`}` }; + for (const f of ls.out.split('\0')) if (f) hits[k]!.add(f); + } + } + for (const [k, p] of patterns.entries()) byPattern.set(p, [...files.keys()].filter(f => hits[k]!.has(f))); + } finally { fs.rmSync(dir, { recursive: true, force: true }); } + const literal = patterns.filter(p => /[[\\]/.test(p)); + const own = literal.length ? perPattern(i, literal, range, files) : null; + if (own && 'error' in own) return own; + for (const [p, matched] of own?.byPattern ?? []) byPattern.set(p, matched); + return { byPattern, files }; +} + +/** Each pattern's paths from its own `git diff --raw`, as select read them before GST-4003: the fallback when a scratch index cannot hold the paths. */ +function perPattern(i: SelectInput, patterns: readonly string[], range: readonly string[], files: Map): ReturnType { + const byPattern = new Map(); + for (const p of patterns) { + const spec = `:(top,glob)${p}`; + const raw = git(i.root, ['diff', '--raw', '-z', '--no-abbrev', '--no-renames', ...range, '--', spec]); + if (!raw.ok) return { error: `git diff --raw ${range.join(' ')} -- ${spec}: ${raw.err.split('\n')[0] || `exit ${raw.status}`}` }; + byPattern.set(p, raw.out.split('\0').filter((f, k) => k % 2 === 1 && f)); + } + return { byPattern, files }; +} + +/** + * A fixed-string search that hands git only each string's last-segment suffix (its extension, or the whole last segment + * when it has none), so `git grep -f` reads a handful of patterns instead of thousands: git tries every pattern on every + * line, and 16,165 paths over harness-evals' code took 37 s where their 9 extensions took 0.4 s. Every string ends with its + * token, so a file holding a string holds its token (git's list is a superset), and `holds` then finds exactly the strings + * a body contains by checking, at the end of each token occurrence, the strings of each length that end there. + */ +export function fixedIndex(strings: readonly string[]): { tokens: string[]; holds: (body: string) => Set } { + const groups = new Map>>(); + for (const s of strings) { + const base = s.slice(s.lastIndexOf('/', s.length - 2) + 1); + const dot = base.lastIndexOf('.'); + const token = dot > 0 ? base.slice(dot) : base; + const byLength = groups.get(token) ?? groups.set(token, new Map()).get(token)!; + (byLength.get(s.length) ?? byLength.set(s.length, new Set()).get(s.length)!).add(s); + } + const holds = (body: string) => { + const out = new Set(); + for (const [token, byLength] of groups) { + if (!token) { out.add(''); continue; } + for (let at = body.indexOf(token); at >= 0; at = body.indexOf(token, at + 1)) { + const end = at + token.length; + for (const [n, set] of byLength) if (end >= n && set.has(body.slice(end - n, end))) out.add(body.slice(end - n, end)); + } + } + return out; + }; + return { tokens: [...groups.keys()], holds }; +} diff --git a/lib/review-exclude.ts b/lib/review-exclude.ts index ccebb25edb..f61fcbff47 100644 --- a/lib/review-exclude.ts +++ b/lib/review-exclude.ts @@ -42,7 +42,8 @@ import { shannonEntropy } from './redact-patterns'; import { KEY_NAME, RESULTS_TREE, SECRET_LINE, hashManifest, secretPath } from './review-risk'; import { secretExcerpt } from './review-secret-excerpt'; import { cmpVersion, parseVersion } from './version-source'; -import { REVIEW_EXCLUDE_KEY_VERSION, SHIP_POLICY_PATH, isUnavailable, policyUnavailableLine } from './ship-policy'; +import { REVIEW_EXCLUDE_KEY_VERSION, SHIP_POLICY_PATH, excludeListTooLarge, isUnavailable, policyUnavailableLine } from './ship-policy'; +import { fixedIndex, select, type Matched } from './review-exclude-match'; import { loadPolicyAt } from './ship-policy-at'; import { resolveStateRoot } from './state-root'; import { vendoredCacheRoot, vendoredPolicy, vendoredSelection, type VendoredSelection } from './review-vendored'; @@ -195,31 +196,6 @@ export function literalPrefix(pattern: string): string { return head.slice(0, head.lastIndexOf('/') + 1); } -interface Matched { oldMode: string; newMode: string; oldSha: string; newSha: string } - -/** Every changed path each pattern matches, with its modes, from git's raw diff; untracked files are never part of it, since no reader's git diff shows them and the receipt reads the committed head. */ -function select(i: ExcludeInput, patterns: readonly string[]): { byPattern: Map; files: Map } | { error: string } { - const byPattern = new Map(); - const files = new Map(); - const range = i.head ? [i.mergeBase, i.head] : [i.mergeBase]; - for (const p of patterns) { - const spec = `:(top,glob)${p}`; - const raw = git(i.root, ['diff', '--raw', '-z', '--no-abbrev', '--no-renames', ...range, '--', spec]); - if (!raw.ok) return { error: `git diff --raw ${range.join(' ')} -- ${spec}: ${raw.err.split('\n')[0] || `exit ${raw.status}`}` }; - const parts = raw.out.split('\0'); - const hit: string[] = []; - for (let k = 0; k + 1 < parts.length; k += 2) { - const [oldMode, newMode, oldSha, newSha] = parts[k]!.slice(1).split(' '); - const f = parts[k + 1]!; - if (!f) continue; - hit.push(f); - if (!files.has(f)) files.set(f, { oldMode: oldMode ?? '', newMode: newMode ?? '', oldSha: oldSha ?? '', newSha: newSha ?? '' }); - } - byPattern.set(p, hit); - } - return { byPattern, files }; -} - /** Executable image magic: ELF, Mach-O (thin, universal and 64-bit universal; 0xcafebabe is also a Java class), PE, WebAssembly and a script's #!. */ const NATIVE_MAGIC = [[0x7f, 0x45, 0x4c, 0x46], [0xfe, 0xed, 0xfa, 0xce], [0xfe, 0xed, 0xfa, 0xcf], [0xce, 0xfa, 0xed, 0xfe], [0xcf, 0xfa, 0xed, 0xfe], [0xca, 0xfe, 0xba, 0xbe], [0xca, 0xfe, 0xba, 0xbf], [0x4d, 0x5a], [0x00, 0x61, 0x73, 0x6d], [0x23, 0x21]]; @@ -433,8 +409,9 @@ function contractExample(patterns: ReadonlySet, s: string, file: string, * the scratch index or grep it (a timeout included). Each tree's file list is filtered to consumers first, so the data under * the patterns is never read (GST-1435: a whole-tree grep for 4,354 candidate paths through 30 MB of receipts ran 278 s), and * the consumers go into a scratch index that one git grep reads, so the git calls stay fixed however many files there are - * (GST-1442: 363 chunked greps over a 192k-file tree ran 132 s). `git grep -l` lists the consumers holding any string, and - * only those are read and searched here: git's -o grew with the number of strings (HARN-64: 2,140 candidate paths in one + * (GST-1442: 363 chunked greps over a 192k-file tree ran 132 s). `git grep -l` lists the consumers holding any string's + * token (fixedIndex: its extension or last segment, since git's -l also grew with the number of strings: 16,165 paths took 37 s on + * harness-evals#616, GST-4003), and only those are read and searched here: git's -o grew with the number of strings (HARN-64: 2,140 candidate paths in one * 464 KB pins.sha256 ran past git's 120 s bound, so every candidate stayed in review). A consumer that is a hash or pin * manifest (every line a digest and a path, lib/review-risk.ts) names files without reading them, so it keeps none. On a live tree, an entry git reads from its blob * (skip-worktree or assume-unchanged) goes into a second index grepped with --cached, as git grep itself would read it. @@ -445,7 +422,8 @@ function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-exclude-')); try { const list = path.join(dir, 'patterns'); - fs.writeFileSync(list, strings.join('\n') + '\n'); + const index = fixedIndex(strings); + fs.writeFileSync(list, index.tokens.join('\n') + '\n'); let n = 0; for (const at of [i.head ?? '', ...revs]) { const ls = git(i.root, at ? ['ls-tree', '-r', '-z', at] : ['ls-files', '-s', '-v', '-z']); @@ -469,25 +447,34 @@ function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet const hits = git(i.root, ['grep', ...flags, '-I', '-F', '-l', '-z', '--no-color', '-f', list], undefined, env); if (hits.status !== 0 && hits.status !== 1) return null; const files = hits.out.split('\0').filter(Boolean); - const bodies = new Map(); - if (flags.length && files.length) { - const shas = new Map(entries.map(e => [e.slice(e.indexOf('\t') + 1), e.slice(0, e.indexOf('\t')).split(' ')[1]!])); - const want = files.map(f => shas.get(f)); - if (want.some(s => !s)) return null; - const b = spawnSync('git', ['cat-file', '--batch'], { cwd: i.root, input: want.join('\n') + '\n', timeout: 120_000, maxBuffer: MAX_BUFFER }); + const scan = (file: string, body: string) => { + if (hashManifest(body.split('\n'))) return; + for (const s of index.holds(body)) if (!skip?.(s, file, body)) (found.get(s) ?? found.set(s, new Set()).get(s)!).add(file); + }; + if (!flags.length) { + for (const f of files) { let body: string; try { body = fs.readFileSync(path.join(i.root, f), 'utf8'); } catch { return null; } scan(f, body); } + continue; + } + if (!files.length) continue; + const shas = new Map(entries.map(e => [e.slice(e.indexOf('\t') + 1), e.slice(0, e.indexOf('\t')).split(' ')[1]!])); + const want = files.map(f => shas.get(f)); + if (want.some(s => !s)) return null; + const sized = git(i.root, ['cat-file', '--batch-check'], want.join('\n') + '\n'); + const sizes = sized.out.split('\n').slice(0, want.length).map(l => Number(l.split(' ')[2])); + if (!sized.ok || sizes.length !== want.length || sizes.some(n => !Number.isInteger(n))) return null; + for (let k = 0, end = 0; k < files.length; k = end) { + let bytes = 0; + for (end = k; end < files.length && (end === k || bytes + sizes[end]! <= BLOB_BATCH_BYTES); end++) bytes += sizes[end]!; + const b = spawnSync('git', ['cat-file', '--batch'], { cwd: i.root, input: want.slice(k, end).join('\n') + '\n', timeout: 120_000, maxBuffer: bytes + (end - k) * 128 + 1024 }); if (b.status !== 0 || !b.stdout) return null; let at = 0; - for (const f of files) { + for (const f of files.slice(k, end)) { const nl = b.stdout.indexOf(10, at); const size = Number(b.stdout.subarray(at, nl).toString().split(' ')[2]); if (nl < 0 || !Number.isInteger(size)) return null; - bodies.set(f, b.stdout.subarray(nl + 1, nl + 1 + size).toString('utf8')); + scan(f, b.stdout.subarray(nl + 1, nl + 1 + size).toString('utf8')); at = nl + 2 + size; } - } else for (const f of files) try { bodies.set(f, fs.readFileSync(path.join(i.root, f), 'utf8')); } catch { return null; } - for (const [file, body] of bodies) { - if (hashManifest(body.split('\n'))) continue; - for (const s of strings) if (body.includes(s) && !skip?.(s, file, body)) (found.get(s) ?? found.set(s, new Set()).get(s)!).add(file); } } } @@ -711,15 +698,16 @@ function policyJson(patterns: readonly string[], floor?: string | null): string const excludableByPath = (p: string) => !SOURCE.test(p) && (DATA_PATH.test(p) || /\.log$/i.test(p) || BINARY_CONTENT_EXT.test(p) || classifyPath(p) === 'docs'); /** - * Folders to suggest: the top directories holding the most bytes the policy could exclude (whole folders when only folder - * sizes are known), until what is left would fit; none when they cannot get the reader under the ceiling (#4369). + * Folders to suggest: the top directories holding the most data, log and binary bytes the policy could exclude (whole folders + * when only folder sizes are known), until what is left would fit; none when they cannot get the reader under the ceiling + * (#4369). Docs never count and docs/ is never suggested: a results report is what the reviewer is there to read (GST-4003). */ function suggest(d: { bytes: number; byDir: ReadonlyArray<[string, number]>; byFile?: ReadonlyArray<[string, number]> }): string[] { let byDir = d.byDir; if (d.byFile?.length) { const excludable = new Map(); for (const [file, n] of d.byFile) { - if (!excludableByPath(file)) continue; + if (!excludableByPath(file) || classifyPath(file) === 'docs') continue; const dir = file.includes('/') ? file.split('/')[0]! : '(root)'; excludable.set(dir, (excludable.get(dir) ?? 0) + n); } @@ -729,7 +717,7 @@ function suggest(d: { bytes: number; byDir: ReadonlyArray<[string, number]>; byF let left = d.bytes; for (const [dir, n] of byDir) { if (left <= REVIEW_DIFF_MAX_BYTES || out.length >= 3) break; - if (dir === '(root)') continue; + if (dir === '(root)' || dir === 'docs') continue; out.push(`${dir}/**`); left -= n; } @@ -742,7 +730,8 @@ export function tooLargeLine(context: string, reader: string, d: { bytes: number const top = d.byDir.slice(0, 5).map(([dir, n]) => `${named(dir)}:${n}`).join(',') || 'none'; const largest = (d.byFile ?? []).slice(0, 5); const split = largest.length ? `split the PR (largest files: ${largest.map(([f, n]) => `${named(f)} (${n} bytes)`).join(', ')})` : 'split the PR'; - const land = (patterns: readonly string[]) => `ask the repo owner to land ${policyJson(patterns, c.floor)} in ${SHIP_POLICY_PATH} on ${c.base} as its own PR (docs/ship-policy.md#review-exclude-paths), then bring ${c.base} into this branch and rerun once; if it is still over, ${split}`; + const land = (patterns: readonly string[]) => excludeListTooLarge(patterns) ? `the base policy cannot take these folders as well: with them its review_exclude_paths fails validation (${excludeListTooLarge(patterns)}), so ask the repo owner to merge its patterns under fewer shared folder globs on ${c.base} as its own PR, or ${split}` + : `ask the repo owner to land ${policyJson(patterns, c.floor)} in ${SHIP_POLICY_PATH} on ${c.base} as its own PR (docs/ship-policy.md#review-exclude-paths), then bring ${c.base} into this branch and rerun once; if it is still over, ${split}`; const dirs = suggest(d); const fresh = dirs.filter(p => !c.record?.patterns.includes(p)); const fix = c.state === 'head-only' ? `this branch declares review_exclude_paths, but only the copy on ${c.base} applies: ${land(c.headPatterns ?? [])}` diff --git a/lib/ruled-notes.ts b/lib/ruled-notes.ts index 45173bc40e..180c30827d 100644 --- a/lib/ruled-notes.ts +++ b/lib/ruled-notes.ts @@ -68,6 +68,14 @@ export const publicRuledNote = (n: RuledNote): RuledNote => !isSecurityFinding(n : n.not_security && RED_TEAM.test(n.finding) ? { ...n, finding: n.finding.replace(RED_TEAM, ' (red-team, ruled not security class)') } : { ...n, finding: REDACTED_FINDING, reason: REDACTED_REASON }; +/** + * A PR body line as the receipt checks read it: trimmed, with one leading `- ` or `* ` list bullet dropped, so a body that lists its + * `Ruled note: …` lines as bullets carries them. The rest must still equal the rendered line word for word. + */ +export const bodyLineText = (line: string) => line.trim().replace(/^[-*][ \t]+/, ''); +/** Whether `body` carries `line` as one whole line, bare or as a `- ` / `* ` list item (bodyLineText). */ +export const bodyListsLine = (body: string, line: string) => body.split(/\r?\n/).some(b => bodyLineText(b) === line); + /** The one-line form finish prints after `RULED_NOTE: ` and the PR body carries after `Ruled note: `, from publicRuledNote. */ export const ruledNoteText = (note: RuledNote) => { const n = publicRuledNote(note); return `${n.finding} at ${n.head.slice(0, 12)} ruled by ${n.by}${n.relayed ? ` (relayed from ${n.relayed})` : ''} at ${n.at}: ${n.reason} (approval ${n.approval})`; }; diff --git a/lib/ship-policy-keys.ts b/lib/ship-policy-keys.ts index a855def79f..4bf62b8703 100644 --- a/lib/ship-policy-keys.ts +++ b/lib/ship-policy-keys.ts @@ -59,6 +59,22 @@ export const HISTORY_NO_REWRITE_KEY_VERSION = '1.100.0.0'; export const LAND_MERGE_COMMIT_PATHS_KEY_VERSION = '1.100.0.0'; export const REVIEW_CONTENT_KEY_VERSION = '1.102.0.0'; export const REVIEW_VENDORED_KEY_VERSION = '1.103.0.0'; +/** + * The most review_exclude_paths patterns one policy may list (64, the cap on every other list, until GST-4003: harness-evals' results + * PRs needed more), and the most argument bytes their `:(top,exclude,glob)` pathspecs may take together, shell-quoted: every reader's + * one `git diff` carries all of them, so the sum stays under KEEP_ARG_MAX_BYTES (lib/review-exclude.ts) and Windows' command line. + * The byte cap binds only a list over the old 64, so every list gstack accepted before still validates. + * An older gstack reads a list over 64 as invalid and sets the key aside, which reviews every file. + */ +export const MAX_EXCLUDE_PATTERNS = 256; +const UNCAPPED_EXCLUDE_PATTERNS = 64; +export const EXCLUDE_SPEC_MAX_BYTES = 24_000; +/** The shell-quoted argument bytes of the exclude pathspecs `patterns` become on a reader's command, one separator each. */ +export const excludeSpecBytes = (patterns: readonly string[]) => patterns.reduce((n, p) => n + Buffer.byteLength(`':(top,exclude,glob)${p.replace(/'/g, "'\\''")}'`) + 1, 0); +/** Why `patterns` cannot be a review_exclude_paths list for being too many or too long together, or null when they fit. */ +export const excludeListTooLarge = (patterns: readonly string[]) => patterns.length > MAX_EXCLUDE_PATTERNS ? `more than ${MAX_EXCLUDE_PATTERNS} patterns` + : patterns.length > UNCAPPED_EXCLUDE_PATTERNS && excludeSpecBytes(patterns) > EXCLUDE_SPEC_MAX_BYTES ? `its patterns take ${excludeSpecBytes(patterns)} argument bytes as exclude pathspecs, more than ${EXCLUDE_SPEC_MAX_BYTES}; merge patterns under a shared folder glob` : null; + export const POLICY_KEY_INTRODUCED: Record = { bump: '1.91.73.0', queue_mode: '1.91.73.0', release_tool: '1.91.73.0', release_outputs: '1.91.73.0', stamp_paths: '1.91.73.0', changelog: '1.91.73.0', mirror: '1.91.73.0', history: '1.91.73.0', preregistration_shas: '1.91.73.0', stamp_sensitive_gates: '1.91.73.0', diff --git a/lib/ship-policy.ts b/lib/ship-policy.ts index a378c00479..47121b7ac6 100644 --- a/lib/ship-policy.ts +++ b/lib/ship-policy.ts @@ -23,7 +23,7 @@ import { RESULT_CODES, type ResultCodeName } from './result-codes'; import { reviewErrors, type ReviewPolicy } from './ship-policy-review'; import { READERS_EXPLANATION, readersErrors, type ReadersPolicy } from './ship-policy-readers'; import { VENDORED_EXPLANATION, vendoredErrors, type VendoredPolicyRaw } from './review-vendored'; import { cmpVersion, parseVersion } from './version-source'; -import { POLICY_COMPAT_FLOOR, BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION, POLICY_KEY_INTRODUCED, LAND_DOCS_ONLY_SKIP_KEY_VERSION, HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION } from './ship-policy-keys'; +import { POLICY_COMPAT_FLOOR, BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION, POLICY_KEY_INTRODUCED, LAND_DOCS_ONLY_SKIP_KEY_VERSION, HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION, excludeListTooLarge } from './ship-policy-keys'; import { placeholderErrors, templateErrors } from './ship-policy-stamps'; import { bookkeepingGlobError, globError } from './ship-policy-bookkeeping'; import { MECHANICAL_EXPLANATION, mechanicalErrors, type MechanicalConstant } from './ship-policy-mechanical'; @@ -220,7 +220,7 @@ export const POLICY_EXPLANATIONS: Record = { preregistration_shas: 'Commits that must be ancestors of HEAD before push (preregistered evals); checked by `gstack-evidence ancestor`.', stamp_sensitive_gates: 'Evidence labels (gstack-evidence --label) that read VERSION or generated bytes; the tree receipt never marks them reusable.', review_scope: 'frozen | diff-plus-blocking | all. frozen (default): /ship Step 9 fixes findings in the diff on pass 1, files blocking findings in code the PR did not change as issues, and later passes read only the range since the previous pass and fix only blocking findings; diff-plus-blocking: the same, but a blocking finding in code the PR did not change is fixed in this PR instead of filed; all: every finding is fixed now (the pre-1.91.249 loop).', - review_exclude_paths: 'Git glob pathspecs, root-anchored and case-sensitive (`receipts/**`, `**/*.jsonl`; at most 64, 256 characters each, no leading `:` or `!`): /ship\'s reviewers leave out the data, docs, binary and .log files they match. Read from the base branch only, so a branch cannot exclude its own files. Code, gate paths, agent prose, config, executables, .gstack/ and .github/ files, gate-tagged or secret-bearing files and files a kept code or test file names by full path stay reviewed (docs/ship-policy.md#review-exclude-paths).', + review_exclude_paths: 'Git glob pathspecs, root-anchored and case-sensitive (`receipts/**`, `**/*.jsonl`; at most 256, 256 characters each and 24,000 argument bytes together as exclude pathspecs, no leading `:` or `!`): /ship\'s reviewers leave out the data, docs, binary and .log files they match. Read from the base branch only, so a branch cannot exclude its own files. Code, gate paths, agent prose, config, executables, .gstack/ and .github/ files, gate-tagged or secret-bearing files and files a kept code or test file names by full path stay reviewed (docs/ship-policy.md#review-exclude-paths).', review_content_patterns: 'Git glob pathspecs in the same dialect as review_exclude_paths (`results/*/raw/**`): a file both keys match is content, so the exclusion leaves it out whatever its extension (.patch files, MANIFEST.sha256, extension-less licence texts). Explicit policy only: nothing is inferred, and a pattern here with no review_exclude_paths pattern over the same files excludes nothing. Read from the base branch only. Gate paths, agent prose, config, source files (.ts, .py, .sh and the like), executables, links, native binaries, .gstack/ and .github/ files, gate-tagged or secret-bearing files and files a kept code or test file names by full path stay reviewed (docs/ship-policy.md#review-content-patterns).', review: '{ panel?, reader_model?, platform?, risk_paths? }, read from the base branch only. panel: all (default: today\'s panel and loop everywhere) | risk (opt-in: today\'s panel at full depth on risk class, one reader on the rest) | off (one merged reader on risk class too); risk and off run one fix round. Their one-reader shape has not passed a no-loss replay yet (GSTA-258 C: FIX-METHOD). reader_model: the model of the one reader a lean depth runs, `lane` (default: the lane\'s own model, the native adversarial reader), `cross-family` or a model id. platform: off (default) | on: a docs or tests diff with no numeric, results or prereg claims whose PR carries the platform review (capy-ai[bot]) at the exact head skips /ship\'s readers (review_depth platform); never runtime code. risk_paths: globs of code paths that are risk class on top of R51\'s; data, docs and binary files under them stay out (docs/review-policy.md#review-depth).', readers: READERS_EXPLANATION, review_vendored: VENDORED_EXPLANATION, @@ -336,9 +336,9 @@ function listErrors(key: string, value: unknown, out: PolicyError[], check: (ite /** `review_exclude_paths` and `review_content_patterns`: git glob pathspecs, each one repo-relative line with no pathspec magic of its own; every error is POLICY_INVALID at its index. */ function excludeErrors(key: 'review_exclude_paths' | 'review_content_patterns', value: unknown, out: PolicyError[]): void { if (!Array.isArray(value)) { out.push({ code: 'POLICY_INVALID', path: key, message: 'must be an array of git glob pathspecs' }); return; } - if (value.length > MAX_LIST) out.push({ code: 'POLICY_INVALID', path: key, message: `more than ${MAX_LIST} patterns` }); - value.forEach((p, i) => { - const why = typeof p !== 'string' ? 'must be a string' : containedRelative(p) ?? (/^[:!]/.test(p) ? 'must not start with : or ! (no pathspec magic or negation)' : /[\x00-\x1f\x7f]/.test(p) ? 'contains a control character' : p.replace(/\/+$/, '') === '' || p === '.' ? 'must not name the whole repository' : null); + const tooLarge = key === 'review_exclude_paths' ? excludeListTooLarge(value.filter(p => typeof p === 'string')) : value.length > MAX_LIST ? `more than ${MAX_LIST} patterns` : null; + if (tooLarge) out.push({ code: 'POLICY_INVALID', path: key, message: tooLarge }); + value.forEach((p, i) => { const why = typeof p !== 'string' ? 'must be a string' : containedRelative(p) ?? (/^[:!]/.test(p) ? 'must not start with : or ! (no pathspec magic or negation)' : /[\x00-\x1f\x7f]/.test(p) ? 'contains a control character' : p.replace(/\/+$/, '') === '' || p === '.' ? 'must not name the whole repository' : null); if (why) out.push({ code: 'POLICY_INVALID', path: `${key}[${i}]`, message: `${JSON.stringify(p)} ${why}` }); }); } diff --git a/lib/ship-receipt-prose.ts b/lib/ship-receipt-prose.ts index ae20fba274..1120dd4279 100644 --- a/lib/ship-receipt-prose.ts +++ b/lib/ship-receipt-prose.ts @@ -8,7 +8,7 @@ import { APPROVALS_FOOTER_END, APPROVALS_TABLE_HEADER } from './approval-record'; import { RECEIPT_FENCE } from './ship-receipt'; import { docsExceptionLine, parseReceiptDocs } from './ship-receipt-docs'; -import { ruledNoteText, type RuledNote } from './ruled-notes'; +import { bodyLineText, ruledNoteText, type RuledNote } from './ruled-notes'; import { gateDispositionText, type GateDisposition } from './gate-dispositions'; import { laneExceptionBodyLines } from './test-lane-exception'; import { VISIBLE_CHARS, VISIBLE_LINES, visibleOpening } from './pr-body-shape'; @@ -113,20 +113,21 @@ function withoutApprovalsBlocks(body: string): string { /** * The body without the exception lines the receipt's own exceptions require: the `Documentation exception: …` line (GST-983) and each `Ruled note: …`, `Gate disposition: …`, `Mechanical retake: …` and `Test-lane exception: …` line (GST-1537, GST-2491, GST-1560, GST-1595). write and the receipt check want each word for word, * and each quotes the owner's reason (`outside 1 and 2 skip detector`), not this PR's counters. Only a line whose - * trimmed text is a rendered line, the test write applies, is left out; the same words inside a longer line stay + * trimmed text is a rendered line (a ruled note also as a `- ` or `* ` list item, bodyLineText), the test write applies, is left out; the same words inside a longer line stay * prose. A marker line takes its place so the text on either side never joins into a claim. */ function withoutExceptionLines(body: string, receipt: Record): string { const lines = new Set(); + const ruled = new Set(); const docs = receipt.docs === undefined ? undefined : parseReceiptDocs(receipt.docs); const docsLine = docs?.ok ? docsExceptionLine(docs.docs) : null; if (docsLine) lines.add(docsLine); - if (Array.isArray(receipt.ruled_notes)) for (const n of receipt.ruled_notes) lines.add(`Ruled note: ${ruledNoteText(n as RuledNote)}`); + if (Array.isArray(receipt.ruled_notes)) for (const n of receipt.ruled_notes) ruled.add(`Ruled note: ${ruledNoteText(n as RuledNote)}`); if (Array.isArray(receipt.gate_dispositions)) for (const d of receipt.gate_dispositions) lines.add(`Gate disposition: ${gateDispositionText(d as GateDisposition)}`); if (Array.isArray(receipt.mechanical)) for (const l of receipt.mechanical) if (typeof l === 'string') lines.add(l); for (const l of laneExceptionBodyLines(receipt.ci_carried)) lines.add(l); - if (!lines.size) return body; - return body.split(/(?<=\n)/).map(l => (lines.has(l.trim()) ? '(exception line)\n' : l)).join(''); + if (!lines.size && !ruled.size) return body; + return body.split(/(?<=\n)/).map(l => (lines.has(l.trim()) || ruled.has(bodyLineText(l)) ? '(exception line)\n' : l)).join(''); } /** diff --git a/test/diff-parts.test.ts b/test/diff-parts.test.ts new file mode 100644 index 0000000000..a9082ee96b --- /dev/null +++ b/test/diff-parts.test.ts @@ -0,0 +1,102 @@ +/** + * GST-4003: whole-diff readers no longer stop at a pipe's maxBuffer. gitDiffInParts has git write to a private file and hands + * the output back in whole-file parts; the secrets check (lib/pregate/checks/secrets.ts) and gstack-banned-terms parse each + * part, and must get exactly what parsing the whole text gave them, past any single-read limit. + */ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { gitDiffInParts, mergeParts } from '../lib/diff-parts'; +import { addedLines as bannedAdded } from '../lib/banned-terms'; +import { addedLines, parseAddedLineNumbers, parseAddedLines, parsePostimages } from '../lib/pregate/checks/secrets'; +import type { PregateContext } from '../lib/pregate/types'; + +/** An empty global git config (os.devNull is not a file git can read on Windows). */ +const EMPTY_CONFIG = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'gitcfg-')), 'config'); +fs.writeFileSync(EMPTY_CONFIG, ''); +afterAll(() => fs.rmSync(path.dirname(EMPTY_CONFIG), { recursive: true, force: true })); + +let root = ''; +let base = ''; +const env = { ...process.env, GIT_CONFIG_GLOBAL: EMPTY_CONFIG, GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'F', GIT_AUTHOR_EMAIL: 'f@example.test', GIT_COMMITTER_NAME: 'F', GIT_COMMITTER_EMAIL: 'f@example.test' }; +const git = (...args: string[]) => { + const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', env, timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); + if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`); + return r.stdout; +}; +const put = (rel: string, text: string) => { fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true }); fs.writeFileSync(path.join(root, rel), text); }; +const DIFF = ['diff', '--text', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/', '--unified=0', '--diff-filter=ACMR']; + +beforeAll(() => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'diff-parts-'))); + git('init', '-q', '-b', 'main'); + put('keep.py', 'a = 1\nb = 2\n'); + put('old.txt', 'old\n'); + git('add', '-A'); + git('commit', '-qm', 'base'); + base = git('rev-parse', 'HEAD').trim(); + for (let i = 0; i < 120; i++) put(`results/run-${i % 7}/case-${i}.jsonl`, Array.from({ length: 40 }, (_, j) => JSON.stringify({ i, j, note: 'x'.repeat(j * 3) })).join('\n') + '\n'); + put('results/big.log', Array.from({ length: 30_000 }, (_, j) => `step ${j} ok`).join('\n') + '\n'); + put('notes/fake-header.md', 'diff --git a/x b/x\n+++ b/fake\n@@ -1 +1 @@\n'); + put('docs/é tudes.md', '# études\n'); + put('keep.py', 'a = 1\nsecret = "x"\nb = 2\n'); + put('old.txt', 'old\nnew\n'); + git('add', '-A'); + git('commit', '-qm', 'branch'); +}); +afterAll(() => { if (root) fs.rmSync(root, { recursive: true, force: true }); }); + +const parts = (args: string[], partBytes: number) => { + const out: string[] = []; + const r = gitDiffInParts(args, { cwd: root, timeout: 60_000, env }, p => out.push(p), partBytes); + return { r, out }; +}; + +describe('gitDiffInParts', () => { + test('the parts are git\'s output byte for byte, each after the first starting at a file header', () => { + const whole = git(...DIFF, base, '--'); + for (const size of [7, 64, 257, 4096, 1 << 20]) { + const { r, out } = parts([...DIFF, base, '--'], size); + expect(r).toEqual({ ok: true }); + expect(out.join('')).toBe(whole); + for (const p of out.slice(1)) expect(p.startsWith('diff --')).toBe(true); + } + expect(parts([...DIFF, base, '--'], 257).out.length).toBeGreaterThan(100); + }, 60_000); + + test('every per-file parser folded over the parts gives what it gave on the whole text', () => { + const whole = git(...DIFF, base, '--'); + const fold = (parse: (s: string) => Map) => { const m = new Map(); parts([...DIFF, base, '--'], 300).out.forEach(p => mergeParts(m, parse(p))); return [...m]; }; + expect(fold(parseAddedLines)).toEqual([...parseAddedLines(whole)]); + expect(fold(parseAddedLineNumbers)).toEqual([...parseAddedLineNumbers(whole)]); + expect(fold(bannedAdded)).toEqual([...bannedAdded(whole)]); + const full = ['-c', 'diff.suppressBlankEmpty=false', 'diff', '--no-color', '--unified=100000000', base, '--']; + const posts = new Map(); + parts(full, 200).out.forEach(p => mergeParts(posts, parsePostimages(p))); + expect([...posts]).toEqual([...parsePostimages(git(...full))]); + }); + + test('an output over a pipe read\'s limit still arrives whole, and the secrets check reads it through the parts', () => { + const args = [...DIFF, base, '--']; + const bytes = Buffer.byteLength(git(...args)); + const piped = spawnSync('git', args, { cwd: root, encoding: 'utf8', env, timeout: 60_000, maxBuffer: Math.floor(bytes / 4) }); + expect((piped.error as NodeJS.ErrnoException | undefined)?.code).toBe('ENOBUFS'); + const { r, out } = parts(args, Math.floor(bytes / 8)); + expect(r.ok).toBe(true); + expect(Buffer.byteLength(out.join(''))).toBe(bytes); + const ctx = { repoRoot: root, mergeBase: base, env, touched: [] } as unknown as PregateContext; + const files = addedLines(ctx).map(p => p.file).sort(); + expect(files).toContain('results/big.log'); + expect(files).toContain('notes/fake-header.md'); + expect(files.filter(f => f.startsWith('results/run-')).length).toBe(120); + }); + + test('a git that fails is not ok, and leaves no file behind', () => { + const before = fs.readdirSync(os.tmpdir()).filter(f => f.startsWith('gstack-diff-')).length; + const r = gitDiffInParts(['diff', 'f'.repeat(40), '--'], { cwd: root, timeout: 60_000, env }, () => { throw new Error('no part expected'); }); + expect(r.ok).toBe(false); + expect(fs.readdirSync(os.tmpdir()).filter(f => f.startsWith('gstack-diff-')).length).toBe(before); + }); +}); diff --git a/test/docs-only-batched.test.ts b/test/docs-only-batched.test.ts new file mode 100644 index 0000000000..d175c87c8c --- /dev/null +++ b/test/docs-only-batched.test.ts @@ -0,0 +1,86 @@ +/** + * GST-4003: classifyDocsOnly asks git which files name each changed doc with one batched `git grep -f -` instead of one + * `git grep` per path (harness-evals' 16,000-file results PRs), and gets the same answer referencesTo gives path by path. + */ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { classifyDocsOnly, referencesTo, referencesToAll } from '../lib/docs-only'; + +/** An empty global git config (os.devNull is not a file git can read on Windows). */ +const EMPTY_CONFIG = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'gitcfg-')), 'config'); +fs.writeFileSync(EMPTY_CONFIG, ''); +afterAll(() => fs.rmSync(path.dirname(EMPTY_CONFIG), { recursive: true, force: true })); + +const env = { ...process.env, GIT_CONFIG_GLOBAL: EMPTY_CONFIG, GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'F', GIT_AUTHOR_EMAIL: 'f@example.test', GIT_COMMITTER_NAME: 'F', GIT_COMMITTER_EMAIL: 'f@example.test' }; +let repo = ''; +const git = (...args: string[]) => { + const r = spawnSync('git', args, { cwd: repo, encoding: 'utf8', env, timeout: 30_000 }); + if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`); + return r.stdout; +}; +const put = (rel: string, text: string | Buffer) => { fs.mkdirSync(path.dirname(path.join(repo, rel)), { recursive: true }); fs.writeFileSync(path.join(repo, rel), text); }; +const DOCS = [...Array.from({ length: 40 }, (_, i) => `docs/results/run-${i}.md`), 'README.md', 'docs/README.md', 'docs/guide.md']; + +beforeAll(() => { + repo = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'docs-batch-'))); + git('init', '-q', '-b', 'main'); + for (const d of DOCS) put(d, `# ${d}\n`); + put('lib/a.ts', "export const doc = 'see docs/README.md and docs/results/run-1.md';\n"); + put('lib/é.ts', "// é docs/results/run-2.md\n"); + put('scripts/run.sh', 'cat docs/results/run-3.md docs/results/run-30.md\n'); + put('assets/blob.bin', Buffer.concat([Buffer.from('docs/results/run-4.md'), Buffer.from([0, 1, 2, 0])])); + put('CHANGELOG.md', '- docs/guide.md\n'); + git('add', '-A'); + git('commit', '-qm', 'seed'); + git('tag', 'seed'); + for (const d of DOCS) put(d, `# ${d}\n\nedited\n`); + git('commit', '-qam', 'edit'); +}); +afterAll(() => { if (repo) fs.rmSync(repo, { recursive: true, force: true }); }); + +describe('batched reference scan', () => { + test('referencesToAll gives every path what referencesTo gives it, at a commit and on the working tree', () => { + for (const tree of ['HEAD', undefined]) { + const all = referencesToAll(repo, DOCS, tree); + expect(Object.fromEntries(all)).toEqual(Object.fromEntries(DOCS.map(p => [p, referencesTo(repo, p, tree)]))); + } + const head = referencesToAll(repo, DOCS, 'HEAD'); + expect(head.get('README.md')).toEqual(['lib/a.ts']); + expect(head.get('docs/results/run-3.md')).toEqual(['scripts/run.sh']); + expect(head.get('docs/results/run-2.md')).toEqual(['lib/é.ts']); + expect(head.get('docs/results/run-4.md')).toEqual([]); + expect(head.get('docs/guide.md')).toEqual([]); + }); + + test('on the working tree, a file git grep reads from the index is matched on its index bytes, as referencesTo is', () => { + put('lib/a.ts', 'export {};\n'); + git('update-index', '--assume-unchanged', 'lib/a.ts'); + try { + expect(referencesTo(repo, 'README.md')).toEqual(['lib/a.ts']); + expect(referencesToAll(repo, DOCS).get('README.md')).toEqual(['lib/a.ts']); + } finally { + git('update-index', '--no-assume-unchanged', 'lib/a.ts'); + git('checkout', '--', 'lib/a.ts'); + } + }); + + test('classifyDocsOnly runs a bounded number of git grep calls however many docs change', () => { + const trace = path.join(repo, '..', `${path.basename(repo)}.trace`); + const before = process.env.GIT_TRACE; + process.env.GIT_TRACE = trace; + try { + const r = classifyDocsOnly({ root: repo, base: 'seed', head: 'HEAD' }); + expect(r.docsOnly).toBe(false); + expect(r.refusals.map(x => x.path).sort()).toEqual(['README.md', 'docs/README.md', 'docs/results/run-1.md', 'docs/results/run-2.md', 'docs/results/run-3.md', 'docs/results/run-30.md']); + } finally { + if (before === undefined) delete process.env.GIT_TRACE; else process.env.GIT_TRACE = before; + } + const greps = fs.readFileSync(trace, 'utf8').split('\n').filter(l => /trace: built-in: git grep /.test(l)).length; + fs.rmSync(trace, { force: true }); + expect(greps).toBeGreaterThan(0); + expect(greps).toBeLessThanOrEqual(2); + }); +}); diff --git a/test/review-exclude-base-fallback.test.ts b/test/review-exclude-base-fallback.test.ts index 5a61bc018a..801a5237d6 100644 --- a/test/review-exclude-base-fallback.test.ts +++ b/test/review-exclude-base-fallback.test.ts @@ -29,29 +29,29 @@ const planJson = (repo: FixtureRepo) => { const r = runBin(repo, 'gstack-review- describe('an invalid exclusion list on the base is set aside, never loosened (GST-3399)', () => { // Value: protects=a base whose only error is review_exclude_paths' length plans with every file reviewed and its other keys // applied, with a loud line on stdout and stderr and the record in --json; fails_when=the plan refuses POLICY_INVALID (the - // harness-evals deadlock), applies some of the 65 patterns, or drops the base's readers.forbid_paths with the bad key; + // harness-evals deadlock), applies some of the 257 patterns, or drops the base's readers.forbid_paths with the bad key; // why_new=GST-3399; seam=gstack-review-plan on a real repository; no_claim=what reviewers do with the files - test('65 patterns on the base: the plan reviews every file, keeps forbid_paths and says why', () => { - const repo = repoWith({ review_exclude_paths: patterns(65) }); + test('257 patterns on the base: the plan reviews every file, keeps forbid_paths and says why', () => { + const repo = repoWith({ review_exclude_paths: patterns(257) }); const r = plan(repo); expect(r.status, r.err).toBe(EXIT.ok); expect(r.out).toContain('REVIEW_EXCLUDE: fallback (WARNING: the base policy origin/main@'); - expect(r.out).toContain('review_exclude_paths: more than 64 patterns'); + expect(r.out).toContain('review_exclude_paths: more than 256 patterns'); expect(r.out).toContain('every file is reviewed'); expect(r.err).toContain('gstack-review-plan: REVIEW_EXCLUDE: fallback (WARNING'); expect(r.out).toMatch(/READERS: forbid_fetch=0 forbid_paths=1 /); const j = planJson(repo); expect(j.review_exclude.state).toBe('fallback'); - expect(j.review_exclude.errors).toEqual(['review_exclude_paths: more than 64 patterns']); + expect(j.review_exclude.errors).toEqual(['review_exclude_paths: more than 256 patterns']); expect(j.paths).toContain('data/p0/r.json'); expect(j.readers.forbid_paths).toEqual(['private/**']); - expect(receiptExcludeFallback(j.review_exclude)).toEqual({ source: j.review_exclude.source, errors: ['review_exclude_paths: more than 64 patterns'] }); + expect(receiptExcludeFallback(j.review_exclude)).toEqual({ source: j.review_exclude.source, errors: ['review_exclude_paths: more than 256 patterns'] }); }, 120_000); // Value: protects=the PR that fixes the list is planned under the base's (set-aside) list, not its own valid one; fails_when= // the head's 61 patterns are applied before they land; seam=gstack-review-plan --json; no_claim=the land step test('the PR that shortens the list is still planned with nothing excluded', () => { - const repo = repoWith({ review_exclude_paths: patterns(65) }, { '.gstack/ship-policy.json': policyText({ review_exclude_paths: patterns(61) }) }); + const repo = repoWith({ review_exclude_paths: patterns(257) }, { '.gstack/ship-policy.json': policyText({ review_exclude_paths: patterns(61) }) }); const j = planJson(repo); expect(j.review_exclude.state).toBe('fallback'); expect(j.paths).toContain('data/p0/r.json'); @@ -60,11 +60,11 @@ describe('an invalid exclusion list on the base is set aside, never loosened (GS // Value: protects=a valid base list plans exactly as before (negative control); fails_when=a valid list falls back or stops // excluding; seam=gstack-review-plan; no_claim=the excluded file count beyond this fixture test('a valid base list still excludes its files', () => { - const repo = repoWith({ review_exclude_paths: patterns(64) }); + const repo = repoWith({ review_exclude_paths: patterns(256) }); const r = plan(repo); expect(r.status, r.err).toBe(EXIT.ok); expect(r.out).not.toContain('fallback'); - expect(r.out).toMatch(/REVIEW_EXCLUDE: patterns=1\/64 excluded=1 /); + expect(r.out).toMatch(/REVIEW_EXCLUDE: patterns=1\/256 excluded=1 /); expect(planJson(repo).review_exclude.state).toBe('active'); }, 120_000); @@ -82,7 +82,7 @@ describe('an invalid exclusion list on the base is set aside, never loosened (GS // fails_when=the fallback swallows an error in a key whose default would loosen review or readers; seam=gstack-review-plan // and gstack-ship-queue's loadBasePolicy; no_claim=the wording of the refusal test('a base with another invalid key still refuses, in the plan and in the queue', () => { - const repo = repoWith({ review_exclude_paths: patterns(65), review: { panel: 'some' } }); + const repo = repoWith({ review_exclude_paths: patterns(257), review: { panel: 'some' } }); const r = plan(repo); expect(r.status).toBe(EXIT.refused); expect(r.err).toContain('POLICY_INVALID'); @@ -95,7 +95,7 @@ describe('an invalid exclusion list on the base is set aside, never loosened (GS // (review_exclude_paths[0]) is an error of its own and still refuses; fails_when=the key filter is unanchored and drops that key // with the list; seam=lib/ship-policy.ts finish; no_claim=the wording of the refusal test('an unknown key that starts with an exclusion key name still refuses', () => { - const repo = repoWith({ review_exclude_paths: patterns(65), 'review_exclude_paths[0]': 'data/**' }); + const repo = repoWith({ review_exclude_paths: patterns(257), 'review_exclude_paths[0]': 'data/**' }); const r = plan(repo); expect(r.status).toBe(EXIT.refused); expect(r.err).toContain('POLICY_INVALID'); @@ -105,7 +105,7 @@ describe('an invalid exclusion list on the base is set aside, never loosened (GS // Value: protects=the merge step reads a base that fails only on its exclusion list, with its other keys, so the PR that fixes // the list can land; fails_when=gstack-ship-queue refuses POLICY_INVALID on it; seam=loadBasePolicy; no_claim=land's checks test('the queue reads such a base with its other keys', () => { - const repo = repoWith({ review_exclude_paths: patterns(65) }); + const repo = repoWith({ review_exclude_paths: patterns(257) }); const q = loadBasePolicy({ repoRoot: repo.work, base: 'main', gh: () => ({ ok: false, out: '' }) }); expect('code' in q ? q : null).toBeNull(); expect('policy' in q && q.policy.review_exclude_paths).toEqual([]); @@ -116,18 +116,18 @@ describe('an invalid exclusion list on the base is set aside, never loosened (GS // owner fixes it; fails_when=gstack-ship-policy validate --policy-from base reports such a base valid; seam=the validate CLI; // no_claim=validate's other output test('validate still reports the base list as invalid', () => { - const repo = repoWith({ review_exclude_paths: patterns(65) }); + const repo = repoWith({ review_exclude_paths: patterns(257) }); const r = runBin(repo, 'gstack-ship-policy', ['validate', '--policy-from', 'base', '--base', 'main']); expect(r.status).toBe(EXIT.fail); expect(r.out).toContain('POLICY_INVALID: 1 error(s)'); - expect(r.err).toContain('more than 64 patterns at review_exclude_paths'); + expect(r.err).toContain('more than 256 patterns at review_exclude_paths'); }, 120_000); // Value: protects=show-effective, which /ship's POLICY line and /land-and-deploy's stamp check read, reports such a base valid // with its other keys and the loud fallback line; fails_when=it exits 1 with valid:false (land-and-deploy then reads no // queue_mode) or drops the warning; seam=the show-effective CLI; no_claim=renderEffective's other lines test('show-effective reads the base with its other keys and warns', () => { - const repo = repoWith({ review_exclude_paths: patterns(65), queue_mode: 'stamp-at-merge' }); + const repo = repoWith({ review_exclude_paths: patterns(257), queue_mode: 'stamp-at-merge' }); const r = runBin(repo, 'gstack-ship-policy', ['show-effective', '--base', 'main', '--json']); expect(r.status, r.err).toBe(EXIT.ok); const j = JSON.parse(r.out); diff --git a/test/review-exclude-match.test.ts b/test/review-exclude-match.test.ts new file mode 100644 index 0000000000..3c2c300a74 --- /dev/null +++ b/test/review-exclude-match.test.ts @@ -0,0 +1,109 @@ +/** + * GST-4003: review_exclude_paths selection and the named-by-code scan cost the same however many patterns and paths a PR + * has. select reads one diff for every pattern and splits it by git's own pathspec match; fixedIndex hands git one token + * per string and finds exactly the strings a body holds. + */ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { fixedIndex, select } from '../lib/review-exclude-match'; + +/** An empty global git config (os.devNull is not a file git can read on Windows). */ +const EMPTY_CONFIG = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'gitcfg-')), 'config'); +fs.writeFileSync(EMPTY_CONFIG, ''); +afterAll(() => fs.rmSync(path.dirname(EMPTY_CONFIG), { recursive: true, force: true })); + +describe('fixedIndex', () => { + const strings = ['docs/a.json', 'a.json', 'results/run-1/a.json', 'results/', 'LICENSE', 'vendor/x/LICENSE', 'data/b.jsonl', 'c.', 'é/ü.json']; + const naive = (body: string) => new Set(strings.filter(s => body.includes(s))); + test('finds exactly the strings body.includes finds, overlaps and prefixes included', () => { + const bodies = ['see docs/a.json and data/b.jsonl', "load('results/run-1/a.json')", 'LICENSE vendor/x/LICENSE', 'a.jsonl only', 'results/ results/run-2', 'c.d c.', 'path é/ü.json', '', 'docs/a.jsonx', 'xdocs/a.json']; + const ix = fixedIndex(strings); + for (const b of bodies) expect([...ix.holds(b)].sort()).toEqual([...naive(b)].sort()); + }); + test('git gets one token per distinct suffix, and every string ends with its token', () => { + const ix = fixedIndex(strings); + expect(ix.tokens.sort()).toEqual(['.', '.json', '.jsonl', 'LICENSE', 'results/'].sort()); + for (const s of strings) expect(ix.tokens.some(t => s.endsWith(t))).toBe(true); + const many = Array.from({ length: 16_000 }, (_, i) => `docs/benchmarks/run-${i % 40}/results/case-${i}.json`); + expect(fixedIndex(many).tokens).toEqual(['.json']); + expect([...fixedIndex(many).holds("x = 'docs/benchmarks/run-3/results/case-43.json'")]).toEqual(['docs/benchmarks/run-3/results/case-43.json']); + }); +}); + +describe('select', () => { + let root = ''; + let base = ''; + const env = { ...process.env, GIT_CONFIG_GLOBAL: EMPTY_CONFIG, GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'F', GIT_AUTHOR_EMAIL: 'f@example.test', GIT_COMMITTER_NAME: 'F', GIT_COMMITTER_EMAIL: 'f@example.test' }; + const git = (...args: string[]) => { const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', env, timeout: 30_000 }); if (r.status !== 0) throw new Error(r.stderr); return r.stdout; }; + const put = (rel: string, text: string) => { fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true }); fs.writeFileSync(path.join(root, rel), text); }; + beforeAll(() => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'exclude-select-'))); + git('init', '-q', '-b', 'main'); + put('results/old.json', '1\n'); + put('src/a.ts', 'a\n'); + git('add', '-A'); git('commit', '-qm', 'base'); + base = git('rev-parse', 'HEAD').trim(); + for (let i = 0; i < 30; i++) put(`results/run-${i % 3}/raw/c${i}.json`, `${i}\n`); + put('results/run-0/logs/x.log', 'log\n'); + put('docs/r.md', '# r\n'); + put('a.b/x.json', '1\n'); + fs.rmSync(path.join(root, 'results/old.json')); + git('add', '-A'); git('commit', '-qm', 'branch'); + }); + afterAll(() => { if (root) fs.rmSync(root, { recursive: true, force: true }); }); + + test('each pattern gets what its own git diff --raw lists, in the same order, deletions included', () => { + const patterns = ['results/**/raw/**', 'results/**', '**/*.json', '**/*.log', 'nothing/**', 'docs/*.md', 'a.b/**']; + const head = git('rev-parse', 'HEAD').trim(); + const one = (p: string) => git('diff', '--raw', '-z', '--no-abbrev', '--no-renames', base, head, '--', `:(top,glob)${p}`).split('\0').filter((_, k) => k % 2 === 1).filter(Boolean); + const s = select({ root, mergeBase: base, head }, patterns); + if ('error' in s) throw new Error(s.error); + for (const p of patterns) expect(s.byPattern.get(p)).toEqual(one(p)); + expect(s.byPattern.get('results/**')).toContain('results/old.json'); + expect(s.files.get('results/old.json')!.newMode).toBe('000000'); + const single = select({ root, mergeBase: base, head }, ['results/**']); + expect('error' in single ? single : single.byPattern.get('results/**')).toEqual(one('results/**')); + const none = select({ root, mergeBase: base, head }, []); + expect('error' in none ? none : none.files.size).toBe(0); + }); + + test('a file that replaces a directory of the same name stays matched (one index cannot hold both)', () => { + const head = git('rev-parse', 'HEAD').trim(); + try { + put('data/x/a.json', '{}\n'); + git('add', '-A'); git('commit', '-qm', 'dir'); + const before = git('rev-parse', 'HEAD').trim(); + fs.rmSync(path.join(root, 'data/x'), { recursive: true }); + put('data/x', '#!/bin/sh\necho hi\n'); + fs.chmodSync(path.join(root, 'data/x'), 0o755); + git('add', '-A'); git('commit', '-qm', 'swap'); + const after = git('rev-parse', 'HEAD').trim(); + const patterns = ['data/**', '**/*.json']; + const one = (p: string) => git('diff', '--raw', '-z', '--no-abbrev', '--no-renames', before, after, '--', `:(top,glob)${p}`).split('\0').filter((_, k) => k % 2 === 1).filter(Boolean); + const s = select({ root, mergeBase: before, head: after }, patterns); + if ('error' in s) throw new Error(s.error); + expect(s.byPattern.get('data/**')).toEqual(['data/x', 'data/x/a.json']); + for (const p of patterns) expect(s.byPattern.get(p)).toEqual(one(p)); + } finally { git('reset', '-q', '--hard', head); } + }); + + test.skipIf(process.platform === 'win32')('a bracket pattern matches what git diff matches, a directory that spells it out included', () => { + const head = git('rev-parse', 'HEAD').trim(); + try { + put('res/1/a.json', '{}\n'); + put('res/[0-9]*/evil.ts', 'export {};\n'); + put('lit\\x/b.json', '{}\n'); + git('add', '-A'); git('commit', '-qm', 'brackets'); + const after = git('rev-parse', 'HEAD').trim(); + const patterns = ['res/[0-9]*/**', 'lit\\\\x/**', '**/*.json']; + const one = (p: string) => git('diff', '--raw', '-z', '--no-abbrev', '--no-renames', head, after, '--', `:(top,glob)${p}`).split('\0').filter((_, k) => k % 2 === 1).filter(Boolean); + const s = select({ root, mergeBase: head, head: after }, patterns); + if ('error' in s) throw new Error(s.error); + expect(s.byPattern.get('res/[0-9]*/**')).toEqual(['res/1/a.json', 'res/[0-9]*/evil.ts']); + for (const p of patterns) expect(s.byPattern.get(p)).toEqual(one(p)); + } finally { git('reset', '-q', '--hard', head); } + }); +}); diff --git a/test/review-exclude-pattern-cap.test.ts b/test/review-exclude-pattern-cap.test.ts new file mode 100644 index 0000000000..5f07ca9e74 --- /dev/null +++ b/test/review-exclude-pattern-cap.test.ts @@ -0,0 +1,65 @@ +/** + * GST-4003: review_exclude_paths takes up to 256 patterns (harness-evals#619 hit the old 64), as long as their exclude + * pathspecs fit one reader command; and a REVIEW_DIFF_TOO_LARGE fix never suggests hiding docs/ or prints a policy gstack + * itself would refuse. + */ +import { describe, expect, test } from 'bun:test'; +import { tooLargeLine } from '../lib/review-exclude'; +import { EXCLUDE_SPEC_MAX_BYTES, MAX_EXCLUDE_PATTERNS, REVIEW_EXCLUDE_KEY_VERSION, excludeSpecBytes, validatePolicy } from '../lib/ship-policy'; + +const codes = (p: unknown) => validatePolicy(p).map(e => `${e.code}:${e.path}:${e.message}`); +const list = (n: number, width = 0) => Array.from({ length: n }, (_, i) => `results/run-${i}/${'r'.repeat(width)}/**`); +const policy = (patterns: string[]) => ({ review_exclude_paths: patterns, min_gstack_version: REVIEW_EXCLUDE_KEY_VERSION }); +const landed = (line: string) => { const m = line.match(/land (\{.*?\}) in /); return m ? JSON.parse(m[1]!) : null; }; + +describe('the review_exclude_paths cap', () => { + test('256 patterns validate, 257 do not, and review_content_patterns keeps its 64', () => { + expect(MAX_EXCLUDE_PATTERNS).toBe(256); + expect(codes(policy(list(256)))).toEqual([]); + expect(codes(policy(list(257)))).toEqual(['POLICY_INVALID:review_exclude_paths:more than 256 patterns']); + expect(codes({ ...policy(list(1)), review_content_patterns: list(65) }).some(c => c.startsWith('POLICY_INVALID:review_content_patterns:more than 64'))).toBe(true); + }); + + test('patterns too long together for one reader command are refused, and no list the old 64 cap admitted is', () => { + const long = list(120, 200); + expect(excludeSpecBytes(long)).toBeGreaterThan(EXCLUDE_SPEC_MAX_BYTES); + expect(codes(policy(long))).toEqual([`POLICY_INVALID:review_exclude_paths:its patterns take ${excludeSpecBytes(long)} argument bytes as exclude pathspecs, more than ${EXCLUDE_SPEC_MAX_BYTES}; merge patterns under a shared folder glob`]); + const widest = Array.from({ length: 64 }, (_, i) => `d${String(i).padStart(2, '0')}/${'x'.repeat(251)}`); + expect(widest.every(p => p.length === 255)).toBe(true); + expect(codes(policy(widest))).toEqual([]); + const wide = Array.from({ length: 64 }, (_, i) => `d${String(i).padStart(2, '0')}/${'é'.repeat(230)}/**`); + expect(excludeSpecBytes(wide)).toBeGreaterThan(EXCLUDE_SPEC_MAX_BYTES); + expect(codes(policy(wide))).toEqual([]); + expect(codes(policy([...wide, 'x/**']))[0]).toContain('argument bytes as exclude pathspecs'); + }); +}); + +describe('the REVIEW_DIFF_TOO_LARGE fix', () => { + const none = { state: 'none' as const, base: 'main', source: 'origin/main@abc' }; + test('docs/ is never suggested, whatever its bytes; data folders still are', () => { + const d = { bytes: 6_000_000, byDir: [['docs', 4_000_000], ['results', 1_500_000], ['src', 500_000]] as Array<[string, number]>, + byFile: [['docs/report.md', 2_000_000], ['docs/benchmarks/run/results/a.json', 2_000_000], ['results/a.jsonl', 1_500_000], ['src/a.ts', 500_000]] as Array<[string, number]> }; + const line = tooLargeLine('ctx', 'batched', d, none).line; + expect(line).not.toContain('docs/**'); + expect(landed(line)).toBeNull(); + expect(line).toContain('split the PR'); + const dataHeavy = { ...d, byDir: [['results', 4_500_000], ['docs', 1_000_000], ['src', 500_000]] as Array<[string, number]>, + byFile: [['results/a.jsonl', 4_500_000], ['docs/report.md', 1_000_000], ['src/a.ts', 500_000]] as Array<[string, number]> }; + expect(landed(tooLargeLine('ctx', 'batched', dataHeavy, none).line).review_exclude_paths).toEqual(['results/**']); + const byDirOnly = { bytes: 6_000_000, byDir: [['docs', 4_500_000], ['results', 1_400_000]] as Array<[string, number]> }; + expect(tooLargeLine('ctx', 'batched', byDirOnly, none).line).not.toContain('docs/**'); + }); + + test('a suggestion that would pass the pattern cap prints no policy JSON and says to merge patterns instead', () => { + const d = { bytes: 3_000_000, byDir: [['logs', 1_500_000], ['src', 1_500_000]] as Array<[string, number]>, byFile: [['logs/run.log', 1_500_000], ['src/a.ts', 1_500_000]] as Array<[string, number]> }; + const at = (n: number) => tooLargeLine('ctx', 'batched', d, { ...none, state: 'active', record: { patterns: list(n), excluded: 9 } }).line; + const fits = landed(at(255)); + expect(fits.review_exclude_paths).toHaveLength(256); + expect(codes(fits)).toEqual([]); + const full = at(256); + expect(landed(full)).toBeNull(); + expect(full).toContain('fails validation (more than 256 patterns)'); + expect(full).toContain('merge its patterns under fewer shared folder globs on main'); + expect(full).toEndWith('nothing was written (REVIEW_DIFF_TOO_LARGE)'); + }); +}); diff --git a/test/review-exclude.test.ts b/test/review-exclude.test.ts index 1f6bbdf56a..3f77eeb0e1 100644 --- a/test/review-exclude.test.ts +++ b/test/review-exclude.test.ts @@ -626,12 +626,12 @@ describe('the receipt binds the selection the reviewers read', () => { // seam=gstack-ship-receipt write and carry; no_claim=the queue's reading of the field test('a base list that is set aside writes the fallback record and refuses carry of the narrower review', () => { const { repo, body } = reviewed(); - policyOnBaseOnly(repo, policyText(Array.from({ length: 65 }, (_, i) => `data/p${i}/**`))); + policyOnBaseOnly(repo, policyText(Array.from({ length: 257 }, (_, i) => `data/p${i}/**`))); const w = writeWith(repo, []); expect({ status: w.status, err: w.status === EXIT.ok ? '' : w.err }).toEqual({ status: EXIT.ok, err: '' }); const written = receiptIn(path.join(repo.root, 'body-w.md')); expect(written.review_exclude).toBeUndefined(); - expect(written.review_exclude_fallback!.errors).toEqual(['review_exclude_paths: more than 64 patterns']); + expect(written.review_exclude_fallback!.errors).toEqual(['review_exclude_paths: more than 256 patterns']); repo.git('merge', '-q', '--no-edit', 'origin/main'); const refused = carry(repo, body); expect(refused.status).toBe(EXIT.refused); diff --git a/test/ruled-note-bullets.test.ts b/test/ruled-note-bullets.test.ts new file mode 100644 index 0000000000..4e6f1eb8c8 --- /dev/null +++ b/test/ruled-note-bullets.test.ts @@ -0,0 +1,29 @@ +/** + * GST-4003: a PR body may list its `Ruled note: …` lines as markdown bullets (`- ` or `* `). gstack-ship-receipt write and + * the receipt-versus-prose check read such a line as the bare one, and still want the rest of it word for word. + */ +import { describe, expect, test } from 'bun:test'; +import { bodyLineText, bodyListsLine, ruledNoteText, type RuledNote } from '../lib/ruled-notes'; +import { checkReceiptProse } from '../lib/ship-receipt-prose'; + +const note: RuledNote = { finding: 'lib/a.ts:12:correctness', head: 'b'.repeat(40), by: 'GStack Minder (GSTA-36)', reason: 'ships with 3 passes noted', at: '2026-11-26T14:00:00Z', approval: 'a-123' }; +const line = `Ruled note: ${ruledNoteText(note)}`; + +describe('ruled-note body lines', () => { + test('a bare line and a - or * list item carry the note', () => { + for (const body of [line, `- ${line}`, `* ${line}`, ` - ${line} `, `*\t${line}`, `intro\r\n- ${line}\r\noutro`]) expect(bodyListsLine(body, line)).toBe(true); + expect(bodyLineText(`- ${line}`)).toBe(line); + }); + + test('anything weaker or different does not', () => { + for (const body of [`- ${line} (and more)`, `-- ${line}`, `- - ${line}`, `+ ${line}`, `1. ${line}`, `> ${line}`, `-${line}`, `see ${line}`, + `- ${line.replace('a-123', 'a-124')}`, `- Ruled note:`, '']) expect(bodyListsLine(body, line)).toBe(false); + }); + + test('the prose check leaves a bulleted ruled note out of its counter claims, and only an exact one', () => { + const receipt = { schema_version: 1, pr: 7, head: 'a'.repeat(40), base: 'main', version: '1.2.3.0', review_loop: { passes: 2 }, ruled_notes: [note] }; + expect(checkReceiptProse(receipt, `Summary.\n\n- ${line}\n`).mismatches).toEqual([]); + expect(checkReceiptProse(receipt, `Summary.\n\n* ${line}\n`).mismatches).toEqual([]); + expect(checkReceiptProse(receipt, `Summary.\n\n- ${line} again\n`).mismatches).toEqual([{ field: 'review_loop.passes', prose: 3, receipt: 2 }]); + }); +});