Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
Review diffs over the 2 MB ceiling in slices instead of stopping (GST-4019) (#4853)
Garry Tane3f916bf0d0b
diff --git a/bin/gstack-review-dispatch b/bin/gstack-review-dispatchindex b41f59058..93511295d 100755--- a/bin/gstack-review-dispatch+++ b/bin/gstack-review-dispatch@@ -24,6 +24,7 @@ import * as path from 'node:path';import { EXIT, exitTableHelp } from '../lib/headless-artifacts';import { BRIEF_ROLES, BriefError, briefFile, checkReviewedTree, checkoutRoot, checkoutTree, promptHash, renderBrief, sectionTexts, sliceDiff, sliceNote, withWorkspace, type BriefRole, type Slots, type TreeCheck } from '../lib/review-brief';import { cleanMarkers, collect, fixableRaises, mayBeUnavailable, parseReply, readJsonl, readLedger, readerKey, recordJudgment, recordSent, appendEvent, verify, type JudgedLine, type MergedLine, type VerdictCheck, type VerifyRow } from '../lib/review-ledger';+import { SLICE_CAP, listSha, planNote, planSlices, selectionNames, sliceMembers, sliceOf, sliceSelection, verifySlices } from '../lib/review-slices';import { buildManifest, checklistFile, chunkCount, chunkOf, manifestPath, markReader, planCyberRetry, readManifest, renderStage, withAuditModel, writeManifest, STAGES, type Extra, type Manifest, type PassReader, type ReaderState, type Stage } from '../lib/review-pass';import { classifyOutsideReview } from '../lib/outside-review-result';import { gateOutcomeLine } from '../lib/gate-outcomes';@@ -37,7 +38,7 @@ import { resolveBaseBranch } from '../lib/ship-policy';import { auditVerdict, eventsDigest, loadReaders, readersLine, scanEvents, type ToolEvent } from '../lib/review-fetch';import { effectiveReaders, READERS_POLICY_DEFAULT, type EffectiveReaders } from '../lib/ship-policy-readers';import { defaultRoots, foundLines, ignoredLines, inventory, quarantineStage, rerunBlocked, sweepResult, type Inventory } from '../lib/review-sweep';-import { REVIEW_DIFF_MAX_BYTES, ceilingContext, disclosureDigest, disclosureLine, parseTail, readSelection, tooLargeLine, unreadableLine, type PlanExclude, type ReaderDiff } from '../lib/review-exclude';+import { REVIEW_DIFF_MAX_BYTES, ceilingContext, disclosureDigest, disclosureLine, parseTail, readSelection, tooLargeLine, unreadableLine, type PlanExclude, type ReaderDiff, type SliceNote } from '../lib/review-exclude';import { logShipCall } from '../lib/ship-call-log';logShipCall('gstack-review-dispatch');@@ -324,7 +325,51 @@ function ceiling(context: string, base: string, outDir: string, readers: Readonlconst at = r.diff_base ?? diffBase;const d = selectionOf(at, r.exclude, r.keep, r.excerpt);if (!d.ok) return { exit: EXIT.fail, line: unreadableLine(context, r.reader, d, at, base, outDir) };- if (d.bytes > REVIEW_DIFF_MAX_BYTES && r.role !== 'outside-voice') return { exit: EXIT.refused, line: tooLargeLine(context, r.reader, d, ceilingContext(process.cwd(), base, known)).line };+ if (d.bytes > REVIEW_DIFF_MAX_BYTES && r.role !== 'outside-voice') return { exit: EXIT.refused, line: tooLargeLine(context, r.reader, d, ceilingContext(process.cwd(), base, known), unsliced(context, d)).line };+ }+ return null;+}++/** Why a reader the ceiling stops was not reviewed in slices: only pass plans them, and a stage refuses a diff that grew after. */+function unsliced(context: string, d: Extract<ReaderDiff, { ok: true }>): SliceNote {+ const plan = planSlices(d.units ?? []);+ if (!plan.ok) return planNote(plan);+ return { field: `fits=${plan.slices.length}`, fix: context.endsWith(' render')+ ? `this reader's diff fits ${plan.slices.length} slices, which only gstack-review-dispatch pass stages (Step 11's voices: pass --voices): run it through the pass manifest instead of a standalone render`+ : `this reader's diff grew past the ceiling after its pass planned its readers: start a fresh pass under a new --pass and --out, which reviews it in ${plan.slices.length} slices` };+}++/**+ * Each reader over the review ceiling becomes slice readers R#1/k..R#k/k in place (lib/review-slices.ts), before the ceiling+ * check; one that cannot be sliced stops the pass with REVIEW_DIFF_TOO_LARGE and the reason. The outside voice keeps its own+ * cut diff and a fix-check reads named hunks, so neither is sliced; a reader at or under the ceiling is untouched.+ */+function sliceManifest(context: string, base: string, m: Manifest, known: PlanExclude | undefined): { exit: number; line: string } | null {+ const readers: PassReader[] = [];+ for (const r of m.readers) {+ const at = r.diff_base ?? m.diff_base;+ const d = r.prompt_file || r.role === 'outside-voice' || r.role === 'fix-check' ? null : selectionOf(at, r.exclude, r.keep, r.excerpt);+ if (!d?.ok || d.bytes <= REVIEW_DIFF_MAX_BYTES) { readers.push(r); continue; }+ const plan = planSlices(d.units ?? []);+ const s = plan.ok ? sliceSelection(checkoutRoot(), at, r, plan.slices) : null;+ if (!s?.ok) return { exit: EXIT.refused, line: tooLargeLine(context, r.reader, d, ceilingContext(process.cwd(), base, known), plan.ok ? (s as Extract<typeof s, { ok: false }>).note : planNote(plan as Extract<typeof plan, { ok: false }>)).line };+ for (const x of s.slices) {+ const { keep: _k, excerpt: _x, ...rest } = r;+ readers.push({ ...rest, reader: `${r.reader}#${x.index}/${x.total}`, title: `${r.title}#${x.index}/${x.total}`, exclude: x.exclude, ...(x.keep.length ? { keep: [...x.keep] } : {}), ...(x.excerpt.length ? { excerpt: [...x.excerpt] } : {}), slice: x });+ }+ }+ m.readers = readers;+ return null;+}++/** A pending slice reader whose files moved since pass planned it: its slice no longer partitions the reader's selection. */+function slicesMoved(readers: readonly PassReader[]): string | null {+ const kept = new Map<string, boolean>();+ for (const r of readers.filter(x => x.slice)) {+ const s = r.slice!;+ const same = (sel: Parameters<typeof selectionNames>[3], sha: string) => { const n = selectionNames(checkoutRoot(), s.diff_base, undefined, sel); return n.ok && listSha(n.names) === sha; };+ if (!kept.has(s.of)) kept.set(s.of, same(s.base, s.kept_sha256));+ if (!kept.get(s.of) || !same(s, s.files_sha256)) return r.reader;}return null;}@@ -439,7 +484,7 @@ function pass(): number {voiceBase: mergeBase && diffBase !== mergeBase && !planArgs.includes('--adversarial-ran') ? mergeBase : undefined,fixCheck: step === 'fix-check' && (flag('--fix-list') || flag('--hunks') || flag('--tests')) ? { fix_list: flag('--fix-list')!, hunks: flag('--hunks')!, tests: flag('--tests')!, callers: flag('--callers') } : undefined,...planExclude(p.review_exclude), ...(p.readers ? { readers: p.readers } : {}), voices: own.includes('--voices') });- const over = ceiling('gstack-review-dispatch pass', base, m.out, m.readers, m.diff_base, (m.review_exclude as PlanExclude) ?? null);+ const over = sliceManifest('gstack-review-dispatch pass', base, m, (m.review_exclude as PlanExclude) ?? null) ?? ceiling('gstack-review-dispatch pass', base, m.out, m.readers, m.diff_base, (m.review_exclude as PlanExclude) ?? null);if (over) { process.stdout.write(planLines.join('\n') + '\n'); process.stderr.write(over.line + '\n'); return over.exit; }fs.mkdirSync(m.out, { recursive: true, mode: 0o700 });settleExcerpts(m);@@ -468,6 +513,8 @@ function passStep(cmd: string): number {const stage = flag('--stage') as Stage | undefined;if (!stage || !STAGES.includes(stage)) { process.stderr.write(`gstack-review-dispatch stage: --stage ${STAGES.join('|')}\n`); return EXIT.usage; }const pending = m.readers.filter(r => r.stage === stage && r.state === 'planned');+ const moved = slicesMoved(pending);+ if (moved) throw new BriefError(`${moved}'s files changed since pass ${m.pass} planned its slices, so its slices no longer cover that reader's diff exactly; start a fresh pass under a new --pass and --out, which plans them again`);const over = ceiling('gstack-review-dispatch stage', m.base, m.out, pending, m.diff_base, (m.review_exclude as PlanExclude) ?? null);if (over) { process.stderr.write(over.line + '\n'); return over.exit; }const done = renderStage(m, stage, sectionTexts(ROOT), branchDiff);@@ -557,17 +604,23 @@ function program(): number {*/function targetedRecord(ledger: string, rows: VerifyRow[]): { classes: string[]; rules: string; brief_sha: string; status: 'done' | 'failed'; findings: number; raised_by: string; head: string | null } | null {const events = readLedger(ledger);- const render = events.filter(e => e.event === 'rendered' && (e.reader === 'targeted' || (e.reader === 'adversarial-native' && typeof e.brief_sha === 'string'))).at(-1);+ const keyOf = (e: Record<string, unknown>) => sliceOf(e as never)?.of ?? String(e.reader);+ const render = events.filter(e => e.event === 'rendered' && (keyOf(e) === 'targeted' || (keyOf(e) === 'adversarial-native' && typeof e.brief_sha === 'string'))).at(-1);if (!render) return null;- const key = String(render.reader);- const label = rows.filter(r => r.kind === 'BRIEF' && r.reader.split('@')[0] === key).at(-1)?.reader;- const brief = rows.filter(r => r.kind === 'BRIEF' && r.reader === label).at(-1);- const output = rows.filter(r => r.kind === 'OUTPUT' && r.reader === label).at(-1);- const head = typeof render.head === 'string' && /^[0-9a-f]{40,64}$/.test(render.head) ? render.head : null;- const committed = typeof render.patch_id === 'string' && !['uncommitted', 'none'].includes(render.patch_id) && head !== null;- const done = brief?.status === 'MATCH' && output?.status === 'MATCH' && committed;- const ids = events.filter(e => e.event === 'output' && e.reader === key).at(-1)?.ids;- return { classes: (render.classes as string[]) ?? [], rules: String(render.rules), brief_sha: String(render.brief_sha), status: done ? 'done' : 'failed', findings: Array.isArray(ids) ? ids.length : 0, raised_by: key, head };+ const headOf = (e: Record<string, unknown>) => (typeof e.head === 'string' && /^[0-9a-f]{40,64}$/.test(e.head) ? e.head : null);+ const head = headOf(render);+ const read = (sliceOf(render as never) ? sliceMembers(events as never, render as never) : [render]).map(e => {+ if (!e) return { done: false, findings: 0 };+ const key = String(e.reader);+ const label = rows.filter(r => r.kind === 'BRIEF' && r.reader.split('@')[0] === key).at(-1)?.reader;+ const brief = rows.filter(r => r.kind === 'BRIEF' && r.reader === label).at(-1);+ const output = rows.filter(r => r.kind === 'OUTPUT' && r.reader === label).at(-1);+ const committed = typeof e.patch_id === 'string' && !['uncommitted', 'none'].includes(e.patch_id) && headOf(e) !== null && headOf(e) === head;+ const ids = events.filter(x => x.event === 'output' && x.reader === key).at(-1)?.ids;+ return { done: brief?.status === 'MATCH' && output?.status === 'MATCH' && committed, findings: Array.isArray(ids) ? ids.length : 0 };+ });+ const done = read.every(x => x.done);+ return { classes: (render.classes as string[]) ?? [], rules: String(render.rules), brief_sha: String(render.brief_sha), status: done ? 'done' : 'failed', findings: read.reduce((n, x) => n + x.findings, 0), raised_by: keyOf(render), head };}/**@@ -594,7 +647,10 @@ function main(): number {if (['show', 'stage', 'chunk', 'mark', 'retry'].includes(cmd)) return passStep(cmd);const ledger = flag('--ledger');if (!ledger) { process.stderr.write(`gstack-review-dispatch ${cmd}: --ledger <file> is required\n`); return EXIT.usage; }- const reader = flag('--role') ? readerKey(flag('--role')!, flag('--name')) : '';+ const sliceArg = flag('--slice');+ const slice = sliceArg?.match(/^([1-9]\d*)\/([1-9]\d*)$/);+ if (sliceArg !== undefined && (!slice || Number(slice[1]) > Number(slice[2]) || Number(slice[2]) > SLICE_CAP)) { process.stderr.write(`gstack-review-dispatch ${cmd}: --slice takes <i>/<k> with 1 <= i <= k <= ${SLICE_CAP}, got ${JSON.stringify(sliceArg)}\n`); return EXIT.usage; }+ const reader = flag('--role') ? readerKey(flag('--role')!, flag('--name'), slice ? { index: Number(slice[1]), total: Number(slice[2]) } : undefined) : '';if (cmd === 'sent') {const sent = readFile(flag('--sent'), 'sent prompt');if (!reader || sent === undefined) { process.stderr.write('gstack-review-dispatch sent: needs --role and --sent <file>\n'); return EXIT.usage; }@@ -672,7 +728,9 @@ function main(): number {const sel = excludeRecord(ledger);if (sel && 'digest' in sel) process.stdout.write(`REVIEW_EXCLUDE_RECORD: digest=${sel.digest} (gstack-ship-receipt write --review-exclude ${sel.digest})\n`);if (sel && 'mixed' in sel) process.stdout.write(`REVIEW_EXCLUDE_RECORD: mixed digests=${sel.mixed.join(',')} (readers read different review_exclude_paths selections; rerun the review so every reader reads HEAD's)\n`);- const clean = v.clean && !(sel && 'mixed' in sel);+ const slices = verifySlices(readLedger(ledger), v.rows);+ for (const r of slices) process.stdout.write(`${r.kind} ${r.reader} ${r.status} ${r.detail}\n`);+ const clean = v.clean && !(sel && 'mixed' in sel) && slices.every(r => r.status === 'MATCH');if (v.verdicts.asked) process.stdout.write(`VERIFY_VERDICT: agree=${v.verdicts.agree} asked=${v.verdicts.asked} (informational: a disagreeing count already counts its blockers; docs/review-policy.md#verdict-line)\n`);process.stdout.write(`VERIFY: ${clean ? 'clean' : 'dirty'} briefs=${v.briefs} outputs=${v.rows.filter(r => r.kind === 'OUTPUT').length} voided=${v.voided}${v.unavailable ? ` unavailable=${v.unavailable}` : ''}\n`);return clean ? EXIT.ok : EXIT.fail;diff --git a/changelog.d/review-large-diffs-in-slices.md b/changelog.d/review-large-diffs-in-slices.mdnew file mode 100644index 000000000..516f83bdb--- /dev/null+++ b/changelog.d/review-large-diffs-in-slices.md@@ -0,0 +1 @@+**`/gstack-ship` now reviews a diff over the 2 MB review ceiling in slices instead of stopping.** When one reviewer's kept diff is bigger than 2,000,000 bytes, `gstack-review-dispatch pass` splits it into up to 8 slice readers that share no file and together cover every file, keeping each top-level folder in one slice when it fits. Git checks that coverage before any brief is written, and `gstack-review-dispatch verify` checks it again at the reviewed tree, refusing a missing, uncollected, overlapping or dropping slice. A sliced reader is still one reviewer for round counting. One file over 2 MB by itself, a diff that needs more than 8 slices, or a slice that would name more paths than one command can carry still stops with `REVIEW_DIFF_TOO_LARGE`, now naming the reason. Large results PRs and large pure-deletion PRs whose files sit in a few folders or subfolders can now be reviewed in full; a single flat folder of thousands of small files can still hit the path limit. Diffs under the ceiling are reviewed exactly as before.diff --git a/docs/review-policy.md b/docs/review-policy.mdindex 16deefc59..c6c24aa69 100644--- a/docs/review-policy.md+++ b/docs/review-policy.md@@ -729,9 +729,52 @@ how many files and bytes were left out and that the reader must not report ontheir absence. Excluded paths count as docs for the depth and never trigger thenumeric-claim scan or a targeted class; kept files keep their own class.+<a id="review-ceiling"></a>Independently of the key, no reader is handed more than 2,000,000 bytes of-diff: `gstack-review-dispatch` stops with `REVIEW_DIFF_TOO_LARGE` before it writes-anything, instead of a review of the part a reader happened to see.+diff. When one reader's kept diff is bigger than that, `gstack-review-dispatch pass`+reviews it in slices instead of cutting it (`lib/review-slices.ts`):++1. **Plan once.** From the diff it already read, pass packs the reader's files into+ at most 8 slices of at most 2,000,000 bytes each. It keeps each top-level folder+ in one slice when the folder fits, and otherwise splits the folder by its+ subfolders and files in sorted path order. Both sides of a rename stay in one+ slice, and so does a file beside the folder that replaces it.+2. **Each slice is a reader.** Reader `R` becomes `R#1/k` … `R#k/k` in the manifest.+ Every `git diff` command in a slice's brief names that slice's paths as+ `:(top,literal)` items next to the reader's exclude items (a folder whose every+ file is in the slice is named once), kept files under the base policy's patterns+ come back through the slice's own keep command, and the brief says it is slice+ `i` of `k`. A native reader's fixture summary lists only that slice's test,+ fixture and spec files. Collect and sent take `--slice i/k`.+3. **Coverage is checked twice.** Before anything is written, pass asks git for each+ slice's file list and refuses unless the lists share no file, together equal the+ reader's whole kept-file list, and each slice's diff is at or under the ceiling.+ The manifest and each slice's ledger render record the sha256 of the kept-file+ list and of the slice's list. `verify` recomputes them with git at the reviewed+ tree and prints one `SLICE <reader>` row: `MATCH` only when every slice 1..k was+ rendered from one plan on one tree and collected, no two slices share a file and+ no kept file is in no slice. `MISSING`, `NOT_COLLECTED`, `MIXED`, `CHANGED`,+ `OVERLAP`, `DROPPED`, `OVER` or `UNREADABLE` makes it `VERIFY: dirty`, so the+ pass binds no review row and no receipt. A `stage` whose tree moved after pass+ planned the slices refuses before rendering them.+4. **One reviewer.** A sliced reader is still one reviewer: one plan entry, one+ review-log row and one start token (Step 11 takes one `adversarial-review`+ start for a native voice however many slices it has), and one R51 round. Its+ findings are collected under each slice's key and judged together.++What still stops with `REVIEW_DIFF_TOO_LARGE`: one file (one diff section) over+2,000,000 bytes by itself (`slices=refused(file=…)` names it), a diff that needs+more than 8 slices (`slices=refused(needs=N cap=8)`), and a slice whose paths+would take more than the 24,000 argument bytes one command may carry. A standalone+`render` never slices; its refusal says how many slices the pass would use. The+outside voice is not sliced: it keeps its single embedded diff, cut at the ceiling+with the files it left out named in its brief. A reader at or under the ceiling is+unchanged, byte for byte.++Each slice is its own subagent, so a stage of several over-ceiling readers can need+more subagents than the thread may run at once. The Capy pass program queues the+rest and starts them as slots free; a reader still queued after 20 minutes stops the+pass with `still queued`, and rerunning the same program resumes from the manifest.## What readers may fetchdiff --git a/docs/ship-policy.md b/docs/ship-policy.mdindex f6cb6ef06..98bebe6a1 100644--- a/docs/ship-policy.md+++ b/docs/ship-policy.md@@ -1728,7 +1728,11 @@ excluded names its reason.<a id="review-diff-ceiling"></a>**The review ceiling.** Independently of the key, `gstack-review-dispatch` readseach reviewer's diff once before it writes a manifest or a brief (`pass`, `stage`-and `render`). A diff over 2,000,000 bytes (about 500K tokens) stops with+and `render`). `pass` reviews a diff over 2,000,000 bytes (about 500K tokens)+in up to 8 slices that share no file and together cover it+([review slices](review-policy.md#review-ceiling)). One file over the ceiling by+itself, a diff that needs more than 8 slices, a slice whose paths take more than+the 24,000 argument bytes one command may carry, or a standalone `render` stops with[`REVIEW_DIFF_TOO_LARGE`](troubleshooting.md#review-diff-too-large), exit 3, and afix chosen by where the policy stands; a `git diff` that fails or runs past120 seconds stops withdiff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex f35868b89..2917ca864 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -4075,14 +4075,24 @@ of the base can cause that: fetch its history and rerun write).### `REVIEW_DIFF_TOO_LARGE`**Meaning.** One reviewer's diff is over the 2,000,000-byte review ceiling-(about 500K tokens). `gstack-review-dispatch pass`, `stage` and `render` read-each reader's diff once before writing anything, and stop (exit 3, nothing-written) rather than hand a reader more than it can read. The line names the-reader, its bytes, the five largest top-level folders (`top=<dir>:<bytes>`) and-the base policy commit.+(about 500K tokens) and could not be reviewed in slices. `gstack-review-dispatch+pass` splits a bigger diff into up to 8 slice readers+([review slices](review-policy.md#review-ceiling)); this stop means one file is+over the ceiling by itself (`slices=refused(file=<path>:<bytes>)`), the diff needs+more than 8 slices (`slices=refused(needs=<n> cap=8)`), a slice's paths are past the+command-line budget, the diff grew after the pass planned its readers, or a+standalone `render` was asked for a reader the pass would slice (`slices=fits=<n>`:+run it through the pass manifest). `pass`, `stage` and `render` read each reader's+diff once before writing anything, and stop (exit 3, nothing written) rather than+hand a reader more than it can read. The line names the reader, its bytes, the+five largest top-level folders (`top=<dir>:<bytes>`) and the base policy commit.**Fix.** The line prints the fix for where the base policy stands:+- **`slices=fits=<n>`:** the diff fits in slices, so nothing is wrong with the+ policy. A standalone `render` never slices: run the reader through the pass+ manifest instead. If the diff grew after the pass planned its readers, start a+ fresh pass under a new `--pass` and `--out`, which plans the slices again.- **No key:** copy the printed JSON (`{"review_exclude_paths":[…],"min_gstack_version":"…"}`)into `.gstack/ship-policy.json` on the base as its own PR. A lane cannot land onthe base itself: ask the repo owner or the coordinator. Once it merges, bringdiff --git a/lib/capy-review-pass.js b/lib/capy-review-pass.jsindex afa72b072..defc9e290 100644--- a/lib/capy-review-pass.js+++ b/lib/capy-review-pass.js@@ -101,7 +101,7 @@ const briefText = async (r) => {}return text;};-const roleArgs = (r) => ' --role ' + q(r.role) + (r.name ? ' --name ' + q(r.name) : '');+const roleArgs = (r) => ' --role ' + q(r.role) + (r.name ? ' --name ' + q(r.name) : '') + (r.slice ? ' --slice ' + r.slice.index + '/' + r.slice.total : '');const REASONING = { medium: 'medium', light: 'low' };const family = (id) => (typeof id === 'string' && id.includes('/') ? id.slice(0, id.indexOf('/')).toLowerCase() : '');const DEFAULT_OUTSIDE = { model_id: 'openai/gpt-6.2-sol', reasoning_mode: 'medium' };@@ -197,7 +197,7 @@ try {if (reach.exit_code !== 0 || got !== want) return stop('readers on the shared machine cannot reach ' + want + ', the checkout this pass ships: ' + got.slice(-300) + '; no start token was taken and no reader was dispatched. Each brief tells its reader to cd there before anything else, so that path must be readable from the directory readers start in');}const starts = input.stage !== 'voices' && m.next === 'fix-check' ? logStart.map((s) => (s.split(' ')[0] === 'review' ? 'review-fix-check' + s.slice(6) : s)) : [...logStart];- const voiceRows = input.stage === 'voices' ? m.readers.filter((r) => r.stage === 'voices' && !r.retry_of && (r.role === 'adversarial-native' || r.role === 'outside-voice')).length : 0;+ const voiceRows = input.stage === 'voices' ? m.readers.filter((r) => r.stage === 'voices' && !r.retry_of && (r.slice ? r.slice.index : 1) === 1 && (r.role === 'adversarial-native' || r.role === 'outside-voice')).length : 0;while (starts.length < voiceRows) starts.push(starts[0]);const seen = {};for (const s of starts) {diff --git a/lib/review-brief.ts b/lib/review-brief.tsindex 6661b416d..57544de4b 100644--- a/lib/review-brief.ts+++ b/lib/review-brief.ts@@ -138,7 +138,7 @@ export function renderBrief(role: BriefRole, slots: Slots, t: SectionTexts): strconst keys = ['findings', 'learnings'].filter(k => slots[k]?.trim());const held: Slots = { ...slots };for (const k of keys) held[k] = `\u0000${nonce}:${k}\u0000`;- const rendered = renderRole(role, held, t);+ const rendered = slots.slice ? withSlice(role, renderRole(role, held, t), slots) : 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 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;@@ -147,6 +147,22 @@ export function renderBrief(role: BriefRole, slots: Slots, t: SectionTexts): strreturn keys.reduce((out, k) => out.split(held[k]!).join(slots[k]!.trim()), text);}+/**+ * A slice reader's role text (lib/review-slices.ts): every git diff command reads only the slice's paths, and a closing+ * paragraph says which slice this is. A command the rewrite cannot reach (a section that changed) fails the render.+ */+function withSlice(role: BriefRole, text: string, slots: Slots): string {+ const items = need(slots, 'slice_items'), tests = need(slots, 'slice_tests');+ const [index, total] = need(slots, 'slice').split('/');+ const out = text.split('"$DIFF_BASE" -- . ').join(`"$DIFF_BASE" -- ${items} `)+ .split(`"$DIFF_BASE" -- '*test*' '*fixture*' '*.spec.*'`).join(`"$DIFF_BASE" -- ${tests}`)+ .split('"$DIFF_BASE"`').join(`"$DIFF_BASE" -- ${items}\``);+ const commands = [...out.matchAll(/git diff\b[^`]*/g)].map(m => m[0]);+ const loose = commands.filter(c => !c.includes(` -- ${items}`) && !c.includes(` -- ${tests}`));+ if (!commands.length || loose.length) throw new BriefError(`${role} slice ${index}/${total}: a git diff command in the brief does not read the slice's paths (${JSON.stringify((loose[0] ?? 'none').slice(0, 120))}); update withSlice in lib/review-brief.ts`);+ return `${out}\n\nThis review is slice ${index} of ${total}. The branch's diff is over the review ceiling, so ${total} readers review it in parts that share no file: every git diff command in this brief reads only this slice's ${need(slots, 'slice_files')} files (${need(slots, 'slice_bytes')} bytes), and the other slices' readers review the rest. Review this slice in full. Read any file in the checkout for context, but report only on changes in this slice.`;+}+function renderRole(role: BriefRole, slots: Slots, t: SectionTexts): string {const diffBase = role === 'fix-check' ? '' : need(slots, 'diff_base');if (diffBase && !SHA.test(diffBase)) throw new BriefError(`slot diff_base must be a literal commit sha, got ${JSON.stringify(diffBase)}`);@@ -284,6 +300,6 @@ export function checkReviewedTree(output: string, expected: string | null): Tree}/** The file a rendered brief is written to under the run's briefs directory. */-export function briefFile(role: BriefRole, name?: string): string {- return `${role}${name ? `-${name.replace(/[^a-zA-Z0-9._-]/g, '_')}` : ''}.prompt.md`;+export function briefFile(role: BriefRole, name?: string, slice?: { index: number; total: number }): string {+ return `${role}${name ? `-${name.replace(/[^a-zA-Z0-9._-]/g, '_')}` : ''}${slice ? `-slice${slice.index}of${slice.total}` : ''}.prompt.md`;}diff --git a/lib/review-exclude.ts b/lib/review-exclude.tsindex f61fcbff4..93b9a9df2 100644--- a/lib/review-exclude.ts+++ b/lib/review-exclude.ts@@ -34,7 +34,7 @@ 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 { readClaudeMd, splitDiffGitLine, unquoteGitPath } 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';@@ -162,7 +162,7 @@ function renamedPaths(i: ExcludeInput): Set<string> | null {}/** `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[][] {+export function argChunks(paths: readonly string[], size = (p: string) => argBytes([p])): string[][] {const chunks: string[][] = [];let bytes = Infinity;for (const p of paths) {@@ -633,7 +633,7 @@ export function parseTail(tail: string | undefined): string[] {}export type ReaderDiff =- | { ok: true; text: string; bytes: number; byDir: Array<[string, number]>; byFile: 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[]; units?: DiffUnit[] }| { 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). */@@ -653,7 +653,7 @@ function excerptOf(out: string, specs: readonly string[]): { text: string; whole* excerpt, appended to `text` and returned as `excerpt`; a file the excerpt could not be built for counts whole, its* section joins `text` and its item is listed in `whole` for the caller's keep command.*/-export function readSelection(root: string, diffBase: string, pathspecs: readonly string[], keep: readonly string[] = [], excerpt: readonly string[] = [], timeoutMs = REVIEW_DIFF_TIMEOUT_MS): ReaderDiff {+export function readSelection(root: string, diffBase: string, pathspecs: readonly string[], keep: readonly string[] = [], excerpt: readonly string[] = [], timeoutMs = REVIEW_DIFF_TIMEOUT_MS, head?: string): ReaderDiff {let text = '';let raw = '';let full = false;@@ -663,7 +663,7 @@ export function readSelection(root: string, diffBase: string, pathspecs: readonl...argChunks(excerpt, size).map(c => [c, textFlags] as [readonly string[], string[]])];for (const [specs, flags] of reads) {const tail = specs.length ? (specs[0] === '--' ? specs : ['--', ...specs]) : [];- const r = spawnSync('git', ['-c', 'core.quotePath=false', 'diff', '--no-color', '--no-ext-diff', ...flags, diffBase, ...tail], { cwd: root, encoding: 'utf8', timeout: timeoutMs, maxBuffer: MAX_BUFFER });+ const r = spawnSync('git', ['-c', 'core.quotePath=false', 'diff', '--no-color', '--no-ext-diff', ...flags, diffBase, ...(head ? [head] : []), ...tail], { cwd: root, encoding: 'utf8', timeout: timeoutMs, maxBuffer: MAX_BUFFER });const code = (r.error as NodeJS.ErrnoException | undefined)?.code;if (code === 'ENOBUFS') { text += raw + (r.stdout ?? ''); full = true; break; }if (code === 'ETIMEDOUT' || (r.signal && r.status === null)) return { ok: false, reason: 'timeout', exit: null, stderr: r.stderr ?? '', timeoutMs };@@ -679,7 +679,18 @@ export function readSelection(root: string, diffBase: string, pathspecs: readonlstarts.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]), byFile: [...byFile].sort((a, b) => b[1] - a[1]), ...(ex ? { excerpt: ex.text, whole: ex.whole } : {}) };+ const bytes = Buffer.byteLength(all);+ const units = bytes > REVIEW_DIFF_MAX_BYTES ? [...starts.map((m, k) => sectionUnit(text.slice(m.index!, k + 1 < starts.length ? starts[k + 1]!.index! : text.length), m[1]!)), ...(ex?.files ?? []).map(f => ({ paths: [f.path], bytes: Buffer.byteLength(f.text) }))] : undefined;+ return { ok: true, text: all, bytes, 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 } : {}), ...(units ? { units } : {}) };+}++/** One `diff --git` section of an over-ceiling selection (lib/review-slices.ts): the paths it shows (both sides of a rename) and its bytes. */+export interface DiffUnit { paths: string[]; bytes: number }+function sectionUnit(section: string, header: string): DiffUnit {+ const head = section.slice(0, (/^(?:--- |@@ |Binary files )/m.exec(section)?.index) ?? section.length);+ const from = /^rename from (.*)$/m.exec(head)?.[1], to = /^rename to (.*)$/m.exec(head)?.[1];+ const [a, b] = from !== undefined && to !== undefined ? [unquoteGitPath(from), unquoteGitPath(to)] : splitDiffGitLine(header);+ return { paths: a === b ? [a] : [a, b], bytes: Buffer.byteLength(section) };}/** Credential-bearing remote URLs and scp-style remotes out of git's stderr. */@@ -725,7 +736,7 @@ function suggest(d: { bytes: number; byDir: ReadonlyArray<[string, number]>; byF}/** The REVIEW_DIFF_TOO_LARGE line and object: the reader's bytes, the largest folders and files, and a fix chosen by where the policy stands. */-export function tooLargeLine(context: string, reader: string, d: { bytes: number; byDir: ReadonlyArray<[string, number]>; byFile?: ReadonlyArray<[string, number]> }, c: CeilingContext): { line: string; json: Record<string, unknown> } {+export function tooLargeLine(context: string, reader: string, d: { bytes: number; byDir: ReadonlyArray<[string, number]>; byFile?: ReadonlyArray<[string, number]> }, c: CeilingContext, slices?: SliceNote): { line: string; json: Record<string, unknown> } {const named = (name: string) => (/[\x00-\x1f\x7f]/.test(name) ? JSON.stringify(name) : name);const top = d.byDir.slice(0, 5).map(([dir, n]) => `${named(dir)}:${n}`).join(',') || 'none';const largest = (d.byFile ?? []).slice(0, 5);@@ -738,8 +749,13 @@ export function tooLargeLine(context: string, reader: string, d: { bytes: number: c.state === 'active' ? `still over after excluding ${c.record?.excluded ?? 0} files; ${fresh.length ? land([...(c.record?.patterns ?? []), ...fresh]) : 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' } };+ const said = slices ? slices.fix ?? `${slices.lead}: ${fix}` : fix;+ 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}${slices ? ` slices=${slices.field}` : ''}); fix: ${said}; 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: said, ...(slices ? { slices: slices.field } : {}), side_effects: 'none' } };+}++/** Why an over-ceiling reader was not split into slices (lib/review-slices.ts): the line's `slices=` field, and the sentence that leads its fix, or a fix of its own. */+export interface SliceNote { field: string; lead?: string; fix?: string}/** 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-ledger.ts b/lib/review-ledger.tsindex 37138771f..9a192f818 100644--- a/lib/review-ledger.ts+++ b/lib/review-ledger.ts@@ -21,7 +21,9 @@ import { checkReviewedTree, isReviewedTreeLine, promptHash, type TreeCheck } froimport { parseVerdict, withoutVerdictLines } from './review-verdict';export interface LedgerEvent { event: 'rendered' | 'sent' | 'output' | 'judgment' | 'judge' | 'program' | 'quarantined' | 'fetch-sweep'; [k: string]: unknown }-export const readerKey = (role: string, name?: string) => (name ? `${role}/${name}` : role);+export const readerKey = (role: string, name?: string, slice?: { index: number; total: number }) => `${name ? `${role}/${name}` : role}${slice ? `#${slice.index}/${slice.total}` : ''}`;+/** A reader key's role: its first segment before a name (`/`) or a slice of an over-ceiling diff (`#i/k`, lib/review-slices.ts). */+export const roleOf = (reader: string) => reader.split(/[/#]/)[0]!;export function appendEvent(ledger: string, e: LedgerEvent): void {fs.appendFileSync(ledger, JSON.stringify({ ...e, at: new Date().toISOString() }) + '\n', { mode: 0o600 });@@ -102,7 +104,7 @@ const BLOCKS_FIELD = /(?<![A-Za-z0-9])Blocks\**\s*:\s*\**\s*(yes|no)(?![A-Za-z0-/** A native voice's finding whose reader stated `Blocks: no` and one Severity (GST-1031 ruling A): lead judgment may lower it to that Severity, never below, on record with a reason (GST-1406). */const statedLowering = (reader: string, raw: string, to: number) => {const ls = [...raw.matchAll(SEVERITY_FIELD)].flatMap(m => (m[1] ?? m[2]!).match(FIELD_LABELS)!);- return reader.split('/')[0] === 'adversarial-native' && statesNoBlocks(raw) && ls.length === 1 && to >= (rank(ls[0]!) || Infinity);+ return roleOf(reader) === 'adversarial-native' && statesNoBlocks(raw) && ls.length === 1 && to >= (rank(ls[0]!) || Infinity);};export const statesNoBlocks = (raw: string) => { if (raw.startsWith('{') || BLOCKS_YES.test(raw)) return false; const said = [...raw.matchAll(BLOCKS_FIELD)].map(m => m[1]!.toLowerCase()); return said.length > 0 && !said.includes('yes'); };/**@@ -214,7 +216,7 @@ function parseLabelled(reader: string, output: string, fixableRaises: boolean):let gap = false;let prev = '';let treeSeen = false;- const role = reader.split('/')[0];+ const role = roleOf(reader);const named = (l: string) => (role === 'adversarial-native' && l.toUpperCase() === 'FIXABLE' ? 'CRITICAL' : l);const strongestOf = (labels: Array<string | undefined>) => labels.reduce<string | undefined>((a, b) => (a === undefined ? b : b === undefined ? a : stronger(a, b)), undefined);const strongest = (t: string) => strongestOf([...t.matchAll(ALL_LABELS)].map(m => named(m[1]!)));@@ -407,7 +409,7 @@ const CLEAN_MARKERS: Record<string, Array<[string, RegExp]>> = {'adversarial-native': [NO_FINDINGS, RECOMMENDATION], 'outside-voice': [RECOMMENDATION],};/** The markers a reader's zero-finding reply may carry; a role outside the brief roles takes either. */-export const cleanMarkers = (reader: string) => CLEAN_MARKERS[reader.split('/')[0]!] ?? [NO_FINDINGS, RECOMMENDATION];+export const cleanMarkers = (reader: string) => CLEAN_MARKERS[roleOf(reader)] ?? [NO_FINDINGS, RECOMMENDATION];const hasCleanMarker = (reader: string, output: string) => output.replace(/\r\n/g, '\n').split('\n').some(l => cleanMarkers(reader).some(([, re]) => re.test(l.trim())));/**@@ -434,7 +436,7 @@ export function collect(ledger: string, reader: string, output: string, mergedFireturn { sha, lines, review, ...('verdict' in reply && reply.verdict ? { verdict: reply.verdict } : {}) };}/** The outside voice may fail without blocking (ship/sections/adversarial.md): its failure is recorded as unavailable coverage, never as a review. */-export const mayBeUnavailable = (reader: string) => reader.split('/')[0] === 'outside-voice';+export const mayBeUnavailable = (reader: string) => roleOf(reader) === 'outside-voice';const unavailableOutput = (o: LedgerEvent) => typeof o.unavailable === 'string' && mayBeUnavailable(String(o.reader));export function readJsonl<T>(file: string): T[] {@@ -581,7 +583,7 @@ const collectedIds = (events: LedgerEvent[]) => {return events.filter(e => e.event === 'output').flatMap(idsOf).filter(id => !gone.has(id));};-export interface VerifyRow { kind: 'BRIEF' | 'OUTPUT' | 'JUDGE' | 'FETCH' | 'VERDICT'; reader: string; status: string; detail: string }+export interface VerifyRow { kind: 'BRIEF' | 'OUTPUT' | 'JUDGE' | 'FETCH' | 'VERDICT' | 'SLICE'; reader: string; status: string; detail: string }/** Replay every check from a finished run's ledger: briefs dispatched as rendered, outputs merged as returned, judgment without loss. */export function verify(ledger: string): { rows: VerifyRow[]; clean: boolean; briefs: number; voided: number; unavailable: number; verdicts: { asked: number; agree: number } } {diff --git a/lib/review-pass.ts b/lib/review-pass.tsindex dc379459d..b788c281b 100644--- a/lib/review-pass.ts+++ b/lib/review-pass.ts@@ -25,6 +25,7 @@ import { TARGETED_RULES, parseClassList, targetedBriefSha, targetedRead } from 'import type { FetchHit } from './review-fetch';import type { EffectiveReaders } from './ship-policy-readers';import type { StageSweep } from './review-sweep';+import type { Slice } from './review-slices';export const STAGES = ['first', 'specialists', 'red-team', 'voices'] as const;export type Stage = typeof STAGES[number];@@ -56,6 +57,8 @@ export interface PassReader {/** Set when the stage's sweep found a fetch: the reply's new home under <out>/quarantine/; it is never merged, judged or returned. */quarantined?: { file: string; at: string };path?: string; output?: string; error?: string; state_at?: string;+ /** One slice of a reader whose kept diff is over the review ceiling (lib/review-slices.ts): reader R#i/k, its exclude, keep and excerpt cut to the slice. */+ slice?: Slice;}export interface Manifest {version: 1; pass: string; out: string; ledger: string; merged: string; base: string; diff_base: string;@@ -232,12 +235,13 @@ export function renderStage(m: Manifest, stage: Stage, t: SectionTexts, diffFor:...(m.disclosure && r.excerpt_file ? { excerpt_file: r.excerpt_file.file, excerpt_bytes: String(r.excerpt_file.bytes), excerpt_sha256: r.excerpt_file.sha256, excerpt_files: String(r.excerpt_file.files) } : {}) };if (role === 'specialist') slots.checklist = checklistFile(m.checklist_root, r.name ?? '');if (r.read_only) slots.read_only = '1';+ if (r.slice) Object.assign(slots, { slice: `${r.slice.index}/${r.slice.total}`, slice_items: r.slice.items, slice_tests: r.slice.tests, slice_files: String(r.slice.files), slice_bytes: String(r.slice.bytes) });let findingsSha: string | undefined;if (role === 'red-team') {const findings = specialistFindings(m.merged);fs.writeFileSync(path.join(briefs, 'specialist-findings.jsonl'), findings, { mode: 0o600 });findingsSha = promptHash(findings);- const specialists = m.readers.reduce((n, x) => n + (x.role === 'specialist' ? 1 : x.role === 'specialist-batched' ? (x.checklists ?? []).filter(c => c !== 'red-team').length : 0), 0);+ const specialists = m.readers.filter(x => (x.slice?.index ?? 1) === 1).reduce((n, x) => n + (x.role === 'specialist' ? 1 : x.role === 'specialist-batched' ? (x.checklists ?? []).filter(c => c !== 'red-team').length : 0), 0);Object.assign(slots, { checklist: path.join(m.checklist_root, 'review/specialists/red-team.md'), findings, specialists: String(specialists) });}let slice: Record<string, unknown> = {};@@ -262,11 +266,11 @@ export function renderStage(m: Manifest, stage: Stage, t: SectionTexts, diffFor:targeted = { classes: parseClassList(slots.classes!), rules: TARGETED_RULES, brief_sha: targetedBriefSha(checklist), diff_base: slots.diff_base, ...targetedRead(process.cwd(), slots.diff_base!) };}const text = withWorkspace(renderBrief(role, slots, t), workdir, m.fetch_policy, { verdict: true });- const file = path.join(briefs, briefFile(role, r.name));+ const file = path.join(briefs, briefFile(role, r.name, r.slice));fs.writeFileSync(file, text, { mode: 0o600 });const sha = promptHash(text);const bytes = Buffer.byteLength(text);- appendEvent(m.ledger, { event: 'rendered', reader: readerKey(role, r.name), role, name: r.name ?? null, file, sha256: sha, bytes, pass: m.pass, stage, workdir, tree, verdict: 1, ...(findingsSha ? { findings_sha256: findingsSha } : {}), ...targeted, ...slice, ...(disclosureDigest(m.disclosure) ? { exclude: disclosureDigest(m.disclosure) } : {}), ...(m.fetch_policy ? { readers: m.fetch_policy.digest } : {}) });+ appendEvent(m.ledger, { event: 'rendered', reader: readerKey(role, r.name, r.slice), role, name: r.name ?? null, file, sha256: sha, bytes, pass: m.pass, stage, workdir, tree, verdict: 1, ...(findingsSha ? { findings_sha256: findingsSha } : {}), ...targeted, ...slice, ...(disclosureDigest(m.disclosure) ? { exclude: disclosureDigest(m.disclosure) } : {}), ...(m.fetch_policy ? { readers: m.fetch_policy.digest } : {}), ...(r.slice ? { slice: r.slice } : {}) });Object.assign(r, { file, sha256: sha, bytes, chunks: chunkCount(text), state: 'rendered', tree, ...(findingsSha ? { findings_sha256: findingsSha } : {}) });done.push(r);}diff --git a/lib/review-slices.ts b/lib/review-slices.tsnew file mode 100644index 000000000..e2c8c26ba--- /dev/null+++ b/lib/review-slices.ts@@ -0,0 +1,241 @@+/**+ * review-slices — a reader whose kept diff is over the review ceiling, reviewed in full by up to SLICE_CAP slice readers+ * that share no file (GST-4019, docs/review-policy.md#review-ceiling).+ *+ * gstack-review-dispatch pass plans the slices once, from the sections readSelection already read: planSlices packs whole+ * top-level directories while they fit, and splits a directory that does not fit by its subdirectories and files in sorted+ * path order. A section is atomic (both sides of a rename stay together), and so is a path changed beside paths under it+ * (a file that replaces a folder of the same name). One section over the ceiling, or a plan that needs more than+ * SLICE_CAP slices, still stops with REVIEW_DIFF_TOO_LARGE.+ *+ * Each slice is a manifest reader R#i/k whose main diff command names its paths as `:(top,literal)` items (a directory+ * whose every main-command path is in the slice is named once) beside the reader's own exclude items, and whose keep and+ * excerpt lists are the reader's, cut to the slice. sliceSelection checks the plan with git before anything is written:+ * the slices' file lists are pairwise disjoint, their union is the reader's kept-file list, and each slice's diff is at or+ * under the ceiling. The manifest and every slice's ledger render record the sha256 of the kept-file list and of the+ * slice's own list; verifySlices recomputes all of it at the reviewed tree and refuses a missing, uncollected, overlapping,+ * dropping or oversized slice. A sliced reader stays one reviewer: one plan entry, one review-log row, one R51 round.+ */+import { createHash } from 'node:crypto';+import { spawnSync } from './spawn-sync';+import { KEEP_ARG_MAX_BYTES, REVIEW_DIFF_MAX_BYTES, REVIEW_DIFF_TIMEOUT_MS, argChunks, parseTail, readSelection, type DiffUnit, type SliceNote } from './review-exclude';+import type { LedgerEvent, VerifyRow } from './review-ledger';++/** The most slices one reader is split into. */+export const SLICE_CAP = 8;++export type SlicePlan =+ | { ok: true; slices: Array<{ paths: string[]; bytes: number }> }+ | { ok: false; reason: 'file'; file: string; bytes: number }+ | { ok: false; reason: 'cap'; needed: number; cap: number };++interface Atom { key: string; paths: string[]; bytes: number }+interface Node { key: string; bytes: number; kids: Map<string, Node>; atoms: Atom[] }++/**+ * Bin-pack an over-ceiling selection's sections into at most `cap` slices of at most `max` bytes. Deterministic: the same+ * sections give the same slices, whatever their order.+ */+export function planSlices(units: readonly DiffUnit[], max = REVIEW_DIFF_MAX_BYTES, cap = SLICE_CAP): SlicePlan {+ const parent = units.map((_, i) => i);+ const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i]!)));+ const join = (i: number, j: number) => { parent[find(i)] = find(j); };+ const owner = new Map<string, number>();+ units.forEach((u, i) => { for (const p of u.paths) { const j = owner.get(p); if (j === undefined) owner.set(p, i); else join(i, j); } });+ for (const [p, i] of owner) {+ const segs = p.split('/');+ for (let n = 1; n < segs.length; n++) { const j = owner.get(segs.slice(0, n).join('/')); if (j !== undefined) join(i, j); }+ }+ const groups = new Map<number, { paths: Set<string>; bytes: number; largest: [string, number] }>();+ units.forEach((u, i) => {+ const g = groups.get(find(i)) ?? { paths: new Set<string>(), bytes: 0, largest: ['', -1] as [string, number] };+ for (const p of u.paths) g.paths.add(p);+ g.bytes += u.bytes;+ if (u.bytes > g.largest[1]) g.largest = [u.paths.at(-1)!, u.bytes];+ groups.set(find(i), g);+ });+ const atoms = [...groups.values()].map(g => ({ paths: [...g.paths].sort(), bytes: g.bytes, largest: g.largest }));+ const over = atoms.filter(a => a.bytes > max).sort((a, b) => b.bytes - a.bytes || (a.paths[0]! < b.paths[0]! ? -1 : 1))[0];+ if (over) return { ok: false, reason: 'file', file: over.largest[0], bytes: over.bytes };+ const root: Node = { key: '', bytes: 0, kids: new Map(), atoms: [] };+ for (const a of atoms) {+ const dirs = a.paths.map(p => p.split('/').slice(0, -1));+ let common = dirs[0]!;+ for (const d of dirs) { let n = 0; while (n < common.length && n < d.length && common[n] === d[n]) n++; common = common.slice(0, n); }+ let node = root;+ for (let n = 0; n < common.length; n++) {+ const key = common.slice(0, n + 1).join('/');+ if (!node.kids.has(key)) node.kids.set(key, { key, bytes: 0, kids: new Map(), atoms: [] });+ node = node.kids.get(key)!;+ }+ node.atoms.push({ key: a.paths[0]!, paths: a.paths, bytes: a.bytes });+ }+ const total = (n: Node): number => (n.bytes = n.atoms.reduce((s, a) => s + a.bytes, 0) + [...n.kids.values()].reduce((s, k) => s + total(k), 0));+ total(root);+ const slices: Array<{ paths: string[]; bytes: number }> = [];+ let cur: { paths: string[]; bytes: number } = { paths: [], bytes: 0 };+ const flush = () => { if (cur.paths.length) slices.push(cur); cur = { paths: [], bytes: 0 }; };+ const items = (n: Node): Array<Node | Atom> => [...n.kids.values(), ...n.atoms].sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));+ const pathsOf = (x: Node | Atom): string[] => ('paths' in x ? x.paths : items(x).flatMap(pathsOf));+ const place = (x: Node | Atom) => {+ if (cur.bytes + x.bytes <= max) { cur.paths.push(...pathsOf(x)); cur.bytes += x.bytes; return; }+ if (x.bytes <= max) { flush(); cur.paths.push(...pathsOf(x)); cur.bytes = x.bytes; return; }+ for (const y of items(x as Node)) place(y);+ };+ for (const x of items(root)) place(x);+ flush();+ return slices.length > cap ? { ok: false, reason: 'cap', needed: slices.length, cap } : { ok: true, slices };+}++/** A slice reader's manifest entry: its command tail, keep and excerpt lists, and the hashes verify recomputes. */+export interface Slice {+ index: number; total: number; of: string; diff_base: string;+ exclude: string; keep: string[]; excerpt: string[]; items: string; tests: string;+ files: number; files_sha256: string; kept: number; kept_sha256: string; bytes: number;+ /** The reader's whole selection the slices partition. */+ base: { exclude?: string; keep?: string[]; excerpt?: string[] };+}++const shellQuote = (s: string) => `'${s.replace(/'/g, "'\\''")}'`;+const LITERAL = ':(top,literal)';+const literal = (p: string) => `${LITERAL}${p}`;+const SUMMARY = ['test', 'fixture', '.spec.'];+/** The native summary's '*test*' '*fixture*' '*.spec.*' inside one slice: an item whose path already matches, else the patterns under it. */+const summaryItems = (positives: readonly string[]) => positives.flatMap(p => {+ const q = p.slice(LITERAL.length);+ return SUMMARY.some(w => q.includes(w)) ? [p] : SUMMARY.map(w => ':(top)' + q.replace(/[*?[\\]/g, '\\$&') + '/*' + w + '*');+});+const isExclude = (s: string) => /^:(?:\([^)]*\bexclude\b[^)]*\)|[!^])/.test(s);+export const listSha = (names: readonly string[]) => createHash('sha256').update(names.join('\0')).digest('hex');++/**+ * The paths one selection shows, with renames split (`--no-renames`), so both sides of a rename count wherever they are+ * read: its main command, then its keep and excerpt lists in argument chunks, as readSelection reads them.+ */+export function selectionNames(root: string, base: string, head: string | undefined, sel: { exclude?: string; keep?: readonly string[]; excerpt?: readonly string[] }): { ok: true; names: string[] } | { ok: false; err: string } {+ const size = (s: string) => Buffer.byteLength(shellQuote(s)) + 1;+ const main = parseTail(sel.exclude);+ const reads: string[][] = [main.length ? (main[0] === '--' ? main : ['--', ...main]) : [], ...[...argChunks(sel.keep ?? [], size), ...argChunks(sel.excerpt ?? [], size)].map(c => ['--', ...c])];+ const names = new Set<string>();+ for (const tail of reads) {+ const r = spawnSync('git', ['-c', 'core.quotePath=false', 'diff', '--name-only', '-z', '--no-renames', '--no-ext-diff', base, ...(head ? [head] : []), ...tail], { cwd: root, encoding: 'utf8', timeout: REVIEW_DIFF_TIMEOUT_MS, maxBuffer: 256 * 1024 * 1024 });+ if (r.status !== 0) return { ok: false, err: (r.stderr || String(r.error ?? r.signal ?? 'git failed')).trim().slice(0, 300) };+ for (const n of (r.stdout ?? '').split('\0')) if (n) names.add(n);+ }+ return { ok: true, names: [...names].sort() };+}++type Reader = { reader: string; exclude?: string; keep?: string[]; excerpt?: string[] };+const fail = (field: string, lead: string) => ({ ok: false as const, note: { field, lead } });+const sample = (paths: readonly string[]) => paths.slice(0, 5).map(p => JSON.stringify(p)).join(',') + (paths.length > 5 ? `,+${paths.length - 5}` : '');++/**+ * The slice readers for one planned reader: each slice's command tail (a directory whose every main-command path is in the+ * slice is named once), its keep and excerpt lists, and the coverage git confirms before anything is written.+ */+export function sliceSelection(root: string, at: string, r: Reader, plan: Array<{ paths: string[] }>, max = REVIEW_DIFF_MAX_BYTES): { ok: true; slices: Slice[] } | { ok: false; note: SliceNote } {+ const tail = parseTail(r.exclude);+ const strip = (list: readonly string[] | undefined) => (list ?? []).map(s => (s.startsWith(LITERAL) ? s.slice(LITERAL.length) : null));+ const keepPaths = strip(r.keep), excerptPaths = strip(r.excerpt);+ if ((tail.length && !(tail[0] === '--' && tail[1] === '.' && tail.slice(2).every(isExclude))) || keepPaths.includes(null) || excerptPaths.includes(null)) {+ return fail('shape', `this reader's pathspecs are not one \`.\` with exclude items and literal keep files, so gstack cannot cut them into slices`);+ }+ const excl = tail.slice(2);+ const K = new Set(keepPaths as string[]), X = new Set(excerptPaths as string[]);+ const main = plan.map(s => s.paths.filter(p => !K.has(p) && !X.has(p)));+ const owner = new Map<string, Set<number>>();+ main.forEach((ps, i) => { for (const p of ps) { const segs = p.split('/'); for (let n = 1; n <= segs.length; n++) { const q = segs.slice(0, n).join('/'); (owner.get(q) ?? owner.set(q, new Set()).get(q)!).add(i); } } });+ const full = selectionNames(root, at, undefined, r);+ if (!full.ok) return fail('unreadable', `git could not list this reader's files (${JSON.stringify(full.err)})`);+ const slices: Slice[] = [];+ const seen = new Map<string, number>();+ for (const [i, s] of plan.entries()) {+ const items = new Set<string>();+ for (const p of main[i]!) { const segs = p.split('/'); for (let n = 1; n <= segs.length; n++) { const q = segs.slice(0, n).join('/'); if (owner.get(q)!.size === 1) { items.add(q); break; } } }+ const keep = (r.keep ?? []).filter(k => s.paths.includes(k.slice(LITERAL.length)));+ const excerpt = (r.excerpt ?? []).filter(k => s.paths.includes(k.slice(LITERAL.length)));+ const positives = items.size ? [...items].sort().map(literal) : [...keep, ...excerpt];+ if (!positives.length || (!items.size && !excl.length)) return fail('shape', `slice ${i + 1} has no path its main command can name`);+ const tests = summaryItems(positives);+ const args = Math.max(...[positives, tests].map(l => l.reduce((n, p) => n + Buffer.byteLength(shellQuote(p)) + 1, 0)));+ if (args > KEEP_ARG_MAX_BYTES) return fail(`args=${i + 1}:${args}`, `slice ${i + 1}'s paths take ${args} argument bytes, more than the ${KEEP_ARG_MAX_BYTES} one reader command may carry`);+ const exclude = `-- ${[...positives, ...excl].map(shellQuote).join(' ')}`;+ const names = selectionNames(root, at, undefined, { exclude, keep, excerpt });+ if (!names.ok) return fail('unreadable', `git could not list slice ${i + 1}'s files (${JSON.stringify(names.err)})`);+ const twice = names.names.filter(n => seen.has(n));+ if (twice.length) return fail(`overlap=${i + 1}`, `slice ${i + 1} would read files slice ${seen.get(twice[0]!)! + 1} reads (${sample(twice)})`);+ for (const n of names.names) seen.set(n, i);+ const d = readSelection(root, at, parseTail(exclude), keep, excerpt);+ if (!d.ok) return fail('unreadable', `git could not read slice ${i + 1}'s diff`);+ if (d.bytes > max) return fail(`over=${i + 1}:${d.bytes}`, `slice ${i + 1} reads ${d.bytes} bytes, over the ceiling`);+ slices.push({ index: i + 1, total: plan.length, of: r.reader, diff_base: at, exclude, keep, excerpt, items: positives.map(shellQuote).join(' '), tests: tests.map(shellQuote).join(' '),+ files: names.names.length, files_sha256: listSha(names.names), kept: full.names.length, kept_sha256: listSha(full.names), bytes: d.bytes,+ base: { ...(r.exclude ? { exclude: r.exclude } : {}), ...(r.keep?.length ? { keep: [...r.keep] } : {}), ...(r.excerpt?.length ? { excerpt: [...r.excerpt] } : {}) } });+ }+ const dropped = full.names.filter(n => !seen.has(n));+ if (dropped.length) return fail(`dropped=${dropped.length}`, `the slices would leave out ${dropped.length} of this reader's files (${sample(dropped)})`);+ return { ok: true, slices };+}++/** The slices= field and fix for a reader that is over the ceiling and was not sliced. */+export function planNote(p: Extract<SlicePlan, { ok: false }>, max = REVIEW_DIFF_MAX_BYTES): SliceNote {+ return p.reason === 'file'+ ? { field: `refused(file=${JSON.stringify(p.file)}:${p.bytes})`, lead: `${JSON.stringify(p.file)} alone is ${p.bytes} bytes of diff, over the ${max}-byte ceiling, so no slice can hold it` }+ : { field: `refused(needs=${p.needed} cap=${p.cap})`, lead: `the diff needs ${p.needed} slices of at most ${max} bytes and a reader is split into at most ${p.cap}` };+}++export const sliceOf = (e: LedgerEvent): Slice | undefined => (e.slice && typeof e.slice === 'object' ? e.slice as Slice : undefined);++/** For a sliced reader's newest render, the newest render of each of its slices 1..k (undefined for one never rendered). */+export function sliceMembers(events: readonly LedgerEvent[], render: LedgerEvent): Array<LedgerEvent | undefined> {+ const s = sliceOf(render)!;+ return Array.from({ length: s.total }, (_, n) => events.filter(e => e.event === 'rendered' && e.reader === `${s.of}#${n + 1}/${s.total}`).at(-1));+}++/**+ * One SLICE row per reader whose newest render was a slice: MATCH only when every slice 1..k was rendered from one plan on+ * one tree and collected, and git at that tree gives each slice the file list its render recorded, the lists share no file,+ * their union is the reader's whole kept-file list and no slice's diff is over the ceiling.+ */+export function verifySlices(events: readonly LedgerEvent[], rows: readonly VerifyRow[], max = REVIEW_DIFF_MAX_BYTES): VerifyRow[] {+ const renders = events.filter(e => e.event === 'rendered');+ const out: VerifyRow[] = [];+ for (const of of new Set(renders.flatMap(e => (sliceOf(e) ? [sliceOf(e)!.of] : [])))) {+ const newest = renders.filter(e => e.reader === of || sliceOf(e)?.of === of).at(-1)!;+ const s = sliceOf(newest);+ if (!s) continue;+ const row = (status: string, detail: string) => out.push({ kind: 'SLICE', reader: of, status, detail: `slices=${s.total} ${detail}` });+ const members = sliceMembers(renders, newest);+ const missing = members.flatMap((e, n) => (e ? [] : [`${n + 1}/${s.total}`]));+ if (missing.length) { row('MISSING', `missing=${missing.join(',')}`); continue; }+ const plans = new Set(members.map(e => JSON.stringify([sliceOf(e!)!.kept_sha256, sliceOf(e!)!.diff_base, e!.tree, e!.workdir])));+ if (plans.size > 1) { row('MIXED', 'the slices were rendered from different plans or trees'); continue; }+ const label = (e: LedgerEvent) => { const nth = renders.filter(x => x.reader === e.reader && renders.indexOf(x) <= renders.indexOf(e)).length; return nth > 1 ? `${e.reader}@${nth}` : String(e.reader); };+ const open = members.filter(e => rows.find(r => r.kind === 'BRIEF' && r.reader === label(e!))?.status !== 'MATCH').map(e => String(e!.reader));+ if (open.length) { row('NOT_COLLECTED', `open=${open.join(',')}`); continue; }+ const root = String(newest.workdir), tree = String(newest.tree ?? '').split(' ')[0] || undefined;+ const full = selectionNames(root, s.diff_base, tree, s.base);+ if (!full.ok) { row('UNREADABLE', `err=${JSON.stringify(full.err)}`); continue; }+ const notes: string[] = [];+ let status = 'MATCH';+ const flag = (st: string, note: string) => { if (status === 'MATCH') status = st; notes.push(note); };+ if (listSha(full.names) !== s.kept_sha256) flag('CHANGED', `kept_list_changed=${full.names.length}/${s.kept}`);+ const seen = new Map<string, number>();+ for (const e of members) {+ const m = sliceOf(e!)!;+ const names = selectionNames(root, m.diff_base, tree, m);+ if (!names.ok) { flag('UNREADABLE', `slice=${m.index} err=${JSON.stringify(names.err)}`); continue; }+ if (listSha(names.names) !== m.files_sha256) flag('CHANGED', `slice=${m.index} files_changed=${names.names.length}/${m.files}`);+ const twice = names.names.filter(n => seen.has(n));+ if (twice.length) flag('OVERLAP', `slice=${m.index} overlaps=${seen.get(twice[0]!)} paths=${sample(twice)}`);+ for (const n of names.names) seen.set(n, m.index);+ const d = readSelection(root, m.diff_base, parseTail(m.exclude), m.keep, m.excerpt, REVIEW_DIFF_TIMEOUT_MS, tree);+ if (!d.ok) flag('UNREADABLE', `slice=${m.index} diff_unreadable`);+ else if (d.bytes > max) flag('OVER', `slice=${m.index} bytes=${d.bytes} max=${max}`);+ }+ const dropped = full.names.filter(n => !seen.has(n));+ if (dropped.length) flag('DROPPED', `dropped=${dropped.length} paths=${sample(dropped)}`);+ row(status, `files=${full.names.length} kept=${s.kept_sha256.slice(0, 12)}${notes.length ? ' ' + notes.join(' ') : ''}`);+ }+ return out;+}diff --git a/lib/review-sweep.ts b/lib/review-sweep.tsindex 313f3f4db..18318e37a 100644--- a/lib/review-sweep.ts+++ b/lib/review-sweep.ts@@ -256,7 +256,7 @@ export function quarantineStage(m: Manifest, stage: Stage, attempt: number): { qif (r.output && fs.existsSync(r.output)) { fs.renameSync(r.output, file); fs.chmodSync(file, 0o600); }let ids: string[] = [];if (!r.prompt_file && r.role) {- const key = readerKey(r.role, r.name);+ const key = readerKey(r.role, r.name, r.slice);const mine = events.filter(e => e.reader === key && (e.event === 'output' || e.event === 'rendered'));ids = mine.slice(mine.findLastIndex(e => e.event === 'rendered') + 1).flatMap(e => (Array.isArray(e.ids) ? (e.ids as string[]) : []));const gone = new Set(ids);diff --git a/test/fixtures/review-pins/replays/GST-4019.json b/test/fixtures/review-pins/replays/GST-4019.jsonnew file mode 100644index 000000000..f781e02ce--- /dev/null+++ b/test/fixtures/review-pins/replays/GST-4019.json@@ -0,0 +1 @@+{"replay":"GST-4019","justification":"GST-4019 deterministic no-loss replay, no paid run (CREW rule 15). No pinned file changes: ship/sections, review/ checklists, lib/review-depth.ts and lib/review-risk.ts keep their bytes, so every brief body cut from the sections and every depth rule is unchanged. The new text reaches only slice readers, which exist only when one reader's kept diff is over the 2,000,000-byte ceiling, where main stopped with REVIEW_DIFF_TOO_LARGE and no reader ran. Under the ceiling, a replay at main be64b10 and at this branch's final head ran gstack-review-dispatch pass (--depth-floor full) and stage voices on three fixtures (plain code, review_exclude_paths with kept and excerpted files, 20 deleted files): all 12 rendered briefs and payloads, the pass manifests (state_at removed) and the ledgers (at removed) are byte-identical (12 briefs, 27 artifacts compared, 0 differ). Over the ceiling, test/review-slices.test.ts runs every git diff command each slice brief carries against git and checks that the slices share no file and together cover every file the unsliced reader would have read (5 MB across 3 folders, review_exclude_paths with kept files, 92 deleted files, bracket, quote, tab, backslash and non-ASCII paths), so no file a reviewer would have seen is lost; a native slice's fixture summary command lists only that slice's test, fixture and spec files under the same exclusions."}diff --git a/test/review-gate-excerpt.test.ts b/test/review-gate-excerpt.test.tsindex 4334f34a6..263425e31 100644--- a/test/review-gate-excerpt.test.ts+++ b/test/review-gate-excerpt.test.ts@@ -118,12 +118,13 @@ describe('gate-tagged data files go to readers as their tagged lines', () => {// 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+ // why_new=GST-3273 (#494's only printed fix was "split the PR"); seam=gstack-review-dispatch pass on a real repository;+ // each session is over the ceiling by itself, since a diff of smaller files is reviewed in slices (GST-4019)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<string, string> = {};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}/session.jsonl`] = Array.from({ length: 7600 + k * 100 }, (_, n) => line(k, n)).join('\n') + '\n';files[`${TRIALS}/big${k}/summary.json`] = `{"trial": ${k}}\n`;}const repo = branch(files);diff --git a/test/review-slices.test.ts b/test/review-slices.test.tsnew file mode 100644index 000000000..59334cc17--- /dev/null+++ b/test/review-slices.test.ts@@ -0,0 +1,432 @@+/**+ * Over-ceiling reader diffs reviewed in slices (GST-4019, docs/review-policy.md#review-ceiling): planSlices' packing, the pass+ * manifest's R#i/k readers and their briefs, the coverage verify recomputes, and the refusals that stay.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT } from '../lib/headless-artifacts';+import { REVIEW_DIFF_MAX_BYTES, type DiffUnit } from '../lib/review-exclude';+import { SLICE_CAP, planSlices } from '../lib/review-slices';+import type { Manifest } from '../lib/review-pass';+import { quarantinedIds, readLedger } from '../lib/review-ledger';+import { quarantineStage } from '../lib/review-sweep';+import { REVIEW_EXCLUDE_KEY_VERSION } from '../lib/ship-policy';+import { cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture';+import { bin, host, repo as harnessRepo, runPass } from './helpers/review-pass-harness';++const repos: FixtureRepo[] = [];+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });+const POSIX = process.platform !== 'win32';+const MB = 1_000_000;++describe('planSlices', () => {+ const u = (p: string | string[], bytes: number): DiffUnit => ({ paths: Array.isArray(p) ? p : [p], bytes });+ const covered = (plan: ReturnType<typeof planSlices>) => (plan.ok ? plan.slices.flatMap(s => s.paths).sort() : []);++ test('a 5 MB diff across 3 folders plans one slice per folder, every file in exactly one slice', () => {+ const units = ['alpha', 'beta', 'gamma'].flatMap(d => Array.from({ length: 10 }, (_, k) => u(`${d}/m${k}.ts`, 170_000)));+ const plan = planSlices(units);+ expect(plan.ok).toBe(true);+ if (!plan.ok) return;+ expect(plan.slices.length).toBeLessThanOrEqual(SLICE_CAP);+ expect(plan.slices.map(s => [...new Set(s.paths.map(p => p.split('/')[0]))])).toEqual([['alpha'], ['beta'], ['gamma']]);+ expect(covered(plan)).toEqual(units.flatMap(x => x.paths).sort());+ for (const s of plan.slices) expect(s.bytes).toBeLessThanOrEqual(REVIEW_DIFF_MAX_BYTES);+ });++ test('a folder over the ceiling splits by its subfolders first, then its files in path order', () => {+ const units = [...['a', 'b', 'c'].flatMap(s => Array.from({ length: 4 }, (_, k) => u(`big/${s}/f${k}.json`, 400_000))), u('big/z.md', 300_000), u('lib/x.ts', 100_000)];+ const plan = planSlices(units);+ expect(plan.ok).toBe(true);+ if (!plan.ok) return;+ expect(plan.slices.map(s => s.paths)).toEqual([+ [...[0, 1, 2, 3].map(k => `big/a/f${k}.json`)],+ [...[0, 1, 2, 3].map(k => `big/b/f${k}.json`)],+ [...[0, 1, 2, 3].map(k => `big/c/f${k}.json`), 'big/z.md', 'lib/x.ts'],+ ]);+ expect(planSlices([...units].reverse())).toEqual(plan);+ });++ test('both sides of a rename, and a file beside the folder that replaces it, always share a slice', () => {+ const plan = planSlices([u(['old/x.ts', 'new/x.ts'], 1_500_000), u('new/y.ts', 900_000), u('old/z.ts', 900_000), u('p', 1_000_000), u('p/q.ts', 900_000)]);+ expect(plan.ok).toBe(true);+ if (!plan.ok) return;+ const home = (p: string) => plan.slices.findIndex(s => s.paths.includes(p));+ expect(home('old/x.ts')).toBe(home('new/x.ts'));+ expect(home('p')).toBe(home('p/q.ts'));+ });++ test('one file over the ceiling refuses and names the file; a diff needing 9 slices refuses with its count', () => {+ expect(planSlices([u('src/a.ts', 10), u('big/huge.ts', 2_100_000)])).toEqual({ ok: false, reason: 'file', file: 'big/huge.ts', bytes: 2_100_000 });+ expect(planSlices(Array.from({ length: 9 }, (_, k) => u(`d${k}/f.json`, 1_100_000)))).toEqual({ ok: false, reason: 'cap', needed: 9, cap: SLICE_CAP });+ expect(planSlices(Array.from({ length: 8 }, (_, k) => u(`d${k}/f.json`, 1_100_000))).ok).toBe(true);+ });+});++/** A source file of about `kb` kilobytes (one ~75-byte line each). */+const src = (tag: string, kb: number) => Array.from({ length: Math.ceil(kb * 1000 / 76) }, (_, i) => `export const v_${i} = ${i}; // ${tag.replace(/[^a-z0-9]/gi, '_').slice(0, 20).padEnd(20, '_')} ${'x'.repeat(30)}`).join('\n') + '\n';+function fixture(files: Record<string, string | null>, baseFiles: Record<string, string> = {}): FixtureRepo {+ const repo = makeFixtureRepo({ prefix: 'gstack-slices-', baseFiles });+ repos.push(repo);+ commit(repo, files);+ return repo;+}+const runPassBin = (repo: FixtureRepo, extra: string[] = []) => {+ const out = path.join(repo.root, 'pass');+ const r = runBin(repo, 'gstack-review-dispatch', ['pass', '--base', 'main', '--out', out, '--pass', 'p1', ...extra]);+ const file = path.join(out, 'pass-manifest.json');+ return { r, out, file, m: fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) as Manifest : null };+};+const mergeBase = (repo: FixtureRepo) => repo.git('merge-base', 'origin/main', 'HEAD');+/** What every git diff command in a brief shows, as NUL-separated --name-only paths run in the fixture. */+function briefNames(repo: FixtureRepo, brief: string, mb: string): string[][] {+ return [...brief.matchAll(/`((?:DIFF_BASE=[0-9a-f]+ && )?git diff [^`]*)`/g)].map(m => {+ const cmd = m[1]!.replace(/^DIFF_BASE=[0-9a-f]+ && /, '').replace(/^git diff( --stat| --name-status)?/, 'git diff --name-only -z --no-renames');+ const r = spawnSync('bash', ['-c', cmd], { cwd: repo.work, encoding: 'utf8', timeout: 30_000, env: { ...process.env, ...repo.env, DIFF_BASE: mb } });+ expect({ cmd, status: r.status, err: r.stderr }).toMatchObject({ status: 0 });+ return r.stdout.split('\0').filter(Boolean);+ });+}+const fullNames = (repo: FixtureRepo, mb: string) => repo.git('-c', 'core.quotePath=false', 'diff', '--name-only', '-z', '--no-renames', mb).split('\0').filter(Boolean).sort();+/** Send each rendered reader its brief verbatim and collect a clean reply, then judge the empty merge. */+function collectAll(repo: FixtureRepo, m: Manifest, skip: string[] = []) {+ const tree = `REVIEWED_TREE: ${repo.git('rev-parse', 'HEAD^{tree}')} ${fs.realpathSync(repo.work)}`;+ for (const r of m.readers.filter(x => x.state === 'rendered' && !skip.includes(x.reader))) {+ const role = ['--role', r.role!, ...(r.name ? ['--name', r.name] : []), ...(r.slice ? ['--slice', `${r.slice.index}/${r.slice.total}`] : [])];+ expect(runBin(repo, 'gstack-review-dispatch', ['sent', '--ledger', m.ledger, ...role, '--sent', r.file!]).status).toBe(0);+ const reply = path.join(m.out, `${r.reader.replace(/[^a-z0-9]/gi, '_')}.reply.txt`);+ fs.writeFileSync(reply, `${tree}\nREVIEW_VERDICT: blocking=0\nNO FINDINGS\n`);+ const c = runBin(repo, 'gstack-review-dispatch', ['collect', '--ledger', m.ledger, ...role, '--output', reply, '--merged', m.merged]);+ expect({ status: c.status, out: c.out }).toMatchObject({ status: 0 });+ }+ expect(runBin(repo, 'gstack-review-dispatch', ['judge', '--ledger', m.ledger, '--merged', m.merged, '--judged', path.join(m.out, 'judged.jsonl')]).status).toBe(0);+}+const verifyOut = (repo: FixtureRepo, m: Manifest) => runBin(repo, 'gstack-review-dispatch', ['verify', '--ledger', m.ledger]);+/** Rewrite one reader's render events in the ledger, or with no edit drop every event of that reader. */+function editRenders(m: Manifest, reader: string, edit: ((e: Record<string, any>) => Record<string, any>) | null) {+ const lines = fs.readFileSync(m.ledger, 'utf8').trim().split('\n').map(l => JSON.parse(l));+ const kept = lines.flatMap(e => (e.reader !== reader ? [e] : !edit ? [] : e.event === 'rendered' ? [edit(e)] : [e]));+ fs.writeFileSync(m.ledger, kept.map(e => JSON.stringify(e)).join('\n') + '\n');+}++describe('a reader over the ceiling is reviewed in slices', () => {+ const three = () => fixture(Object.fromEntries(['alpha', 'beta', 'gamma'].flatMap(d => Array.from({ length: 6 }, (_, k) => [`${d}/m${k}.ts`, src(`${d}${k}`, 290)]))));++ // Value: protects=a 5 MB kept diff is reviewed in full by slice readers that share no file; fails_when=a slice command shows+ // another slice's file, a file is in no slice, or verify does not replay coverage; why_new=GST-4019 (harness-evals#619 at+ // 2.27 MB after exclusions stopped at REVIEW_DIFF_TOO_LARGE); seam=gstack-review-dispatch pass, the rendered briefs run by git, verify+ test.skipIf(!POSIX)('a 5 MB diff across 3 folders: every brief command reads only its slice, and verify replays full coverage', () => {+ const repo = three();+ const { r, m } = runPassBin(repo);+ expect({ status: r.status, err: r.err }).toEqual({ status: EXIT.ok, err: '' });+ const sliced = m!.readers.filter(x => x.slice);+ expect(sliced.map(x => x.reader)).toEqual(['specialist-batched#1/3', 'specialist-batched#2/3', 'specialist-batched#3/3', 'adversarial-native#1/3', 'adversarial-native#2/3', 'adversarial-native#3/3']);+ const mb = mergeBase(repo);+ const all = fullNames(repo, mb);+ expect(all.length).toBe(18);+ const seen = new Map<string, string>();+ for (const x of sliced.filter(y => y.state === 'rendered')) {+ const brief = fs.readFileSync(x.file!, 'utf8');+ expect(brief).toContain(`This review is slice ${x.slice!.index} of 3.`);+ const names = briefNames(repo, brief, mb);+ expect(names.length).toBeGreaterThan(0);+ for (const n of new Set(names.flat())) { expect(seen.get(n)).toBeUndefined(); seen.set(n, x.reader); }+ expect(x.slice!.bytes).toBeLessThanOrEqual(REVIEW_DIFF_MAX_BYTES);+ }+ expect([...seen.keys()].sort()).toEqual(all);+ collectAll(repo, m!);+ const v = verifyOut(repo, m!);+ expect(v.out).toMatch(/^SLICE specialist-batched MATCH slices=3 files=18 kept=[0-9a-f]{12}$/m);+ expect(v.out).toContain('VERIFY: clean briefs=3 outputs=3');+ }, 300_000);++ // Value: protects=verify refuses a slice set that is incomplete or no longer partitions the reader's files; fails_when=a missing,+ // uncollected, overlapping or dropping slice set verifies clean; why_new=GST-4019 zero-drop check; seam=verify on the ledger+ // and git at the reviewed tree; no_claim=what a reader did with its brief+ test.skipIf(!POSIX)('verify refuses a missing slice, an uncollected slice, an overlap and a dropped file', () => {+ const repo = three();+ const { m } = runPassBin(repo);+ const ledger = fs.readFileSync(m!.ledger, 'utf8');+ collectAll(repo, m!, ['specialist-batched#2/3']);+ let v = verifyOut(repo, m!);+ expect(v.out).toMatch(/^SLICE specialist-batched NOT_COLLECTED slices=3 open=specialist-batched#2\/3$/m);+ expect(v.out).toContain('VERIFY: dirty');+ const reset = () => { fs.writeFileSync(m!.ledger, ledger); fs.rmSync(m!.merged, { force: true }); fs.rmSync(path.join(m!.out, 'judged.jsonl'), { force: true }); };+ reset();+ collectAll(repo, m!);+ expect(verifyOut(repo, m!).out).toContain('VERIFY: clean');+ const done = fs.readFileSync(m!.ledger, 'utf8');+ editRenders(m!, 'specialist-batched#2/3', null);+ v = verifyOut(repo, m!);+ expect(v.out).toMatch(/^SLICE specialist-batched MISSING slices=3 missing=2\/3$/m);+ expect(v.out).toContain('VERIFY: dirty');+ fs.writeFileSync(m!.ledger, done);+ const alpha = m!.readers.find(x => x.reader === 'specialist-batched#1/3')!.slice!.exclude.slice(3);+ editRenders(m!, 'specialist-batched#2/3', e => ({ ...e, slice: { ...e.slice, exclude: `${e.slice.exclude} ${alpha}` } }));+ v = verifyOut(repo, m!);+ expect(v.out).toMatch(/^SLICE specialist-batched CHANGED slices=3 .*overlaps=1 /m);+ expect(v.out).toContain('VERIFY: dirty');+ fs.writeFileSync(m!.ledger, done);+ editRenders(m!, 'specialist-batched#3/3', e => ({ ...e, slice: { ...e.slice, exclude: "-- ':(top,literal)gamma/m0.ts'" } }));+ v = verifyOut(repo, m!);+ expect(v.out).toMatch(/^SLICE specialist-batched CHANGED slices=3 .*dropped=5 paths=/m);+ expect(v.out).toContain('VERIFY: dirty');+ }, 300_000);++ // Value: protects=the one diff slicing cannot help still refuses and names the file; fails_when=a 2.1 MB single file is cut,+ // dropped or sliced; why_new=GST-4019; seam=gstack-review-dispatch pass+ test.skipIf(!POSIX)('a single 2.1 MB file still refuses with REVIEW_DIFF_TOO_LARGE naming the file', () => {+ const repo = fixture({ 'lib/run.ts': src('run', 5), 'big/huge.ts': src('huge', 2_100) });+ const { r, m } = runPassBin(repo);+ expect(r.status).toBe(EXIT.refused);+ expect(m).toBeNull();+ expect(r.err).toContain('slices=refused(file="big/huge.ts":');+ expect(r.err).toContain('"big/huge.ts" alone is ');+ expect(r.err).toEndWith('nothing was written (REVIEW_DIFF_TOO_LARGE)\n');+ }, 300_000);++ // Value: protects=a diff past the slice cap refuses honestly with the count it needed; fails_when=it is sliced into more than+ // 8 readers or some slices are dropped; why_new=GST-4019; seam=gstack-review-dispatch pass+ test.skipIf(!POSIX)('a diff needing 9 slices still refuses, naming the slices it needs and the cap', () => {+ const repo = fixture(Object.fromEntries(Array.from({ length: 9 }, (_, k) => [`d${k}/f.ts`, src(`d${k}`, 1_100)])));+ const { r, m } = runPassBin(repo);+ expect(r.status).toBe(EXIT.refused);+ expect(m).toBeNull();+ expect(r.err).toContain('slices=refused(needs=9 cap=8)');+ expect(r.err).toContain('the diff needs 9 slices of at most 2000000 bytes and a reader is split into at most 8');+ }, 300_000);++ // Value: protects=a large pure-deletion PR plans, renders and verifies like any other; fails_when=deleted files are left out+ // of every slice or a slice command shows nothing for them; why_new=gstack #4837 and #4833 (92 deleted files); seam=pass and verify+ test.skipIf(!POSIX)('92 deleted files (the #4837 and #4833 shape) plan, render and verify cleanly', () => {+ const gone = Object.fromEntries(Array.from({ length: 92 }, (_, k) => [`${['bin', 'lib', 'test', 'docs'][k % 4]}/old${k}.ts`, src(`old${k}`, 30)]));+ const repo = fixture(Object.fromEntries(Object.keys(gone).map(f => [f, null])), gone);+ const { r, m } = runPassBin(repo);+ expect({ status: r.status, err: r.err }).toEqual({ status: EXIT.ok, err: '' });+ const mb = mergeBase(repo);+ expect(fullNames(repo, mb)).toEqual(Object.keys(gone).sort());+ const sliced = m!.readers.filter(x => x.slice && x.state === 'rendered');+ expect(sliced.length).toBeGreaterThan(1);+ const read = sliced.flatMap(x => [...new Set(briefNames(repo, fs.readFileSync(x.file!, 'utf8'), mb).flat())]);+ expect(read.sort()).toEqual(Object.keys(gone).sort());+ collectAll(repo, m!);+ const v = verifyOut(repo, m!);+ expect(v.out).toMatch(/^SLICE specialist-batched MATCH slices=\d files=92 /m);+ expect(v.out).toContain('VERIFY: clean');+ }, 300_000);++ // Value: protects=paths holding glob, quote, space, tab, backslash and non-ASCII characters land in exactly one slice and+ // each slice's commands show them byte for byte; fails_when=a bracket path is read as a glob, a quoted diff header is+ // parsed with its quotes, or a path is dropped; why_new=GST-4019 (#4847's bracket-glob finding); seam=pass, git and verify+ test.skipIf(!POSIX)('bracket and special-character paths match identically in every slice', () => {+ const odd = ['odd/[abc]/x*?.ts', "odd/a b/it's \"q\".ts", 'odd/\u00fc/\u00f1.ts', 'odd/tab\there.ts', 'odd/back\\slash.ts', 'odd/[abc].ts', 'odd/a/plain.ts'];+ const repo = fixture(Object.fromEntries(odd.map((f, k) => [f, src(`odd${k}`, 700)])));+ const { r, m } = runPassBin(repo);+ expect({ status: r.status, err: r.err }).toEqual({ status: EXIT.ok, err: '' });+ const mb = mergeBase(repo);+ expect(fullNames(repo, mb)).toEqual([...odd].sort());+ const sliced = m!.readers.filter(x => x.slice && x.state === 'rendered');+ expect(sliced.length).toBeGreaterThan(1);+ const seen: string[] = [];+ for (const x of sliced) seen.push(...new Set(briefNames(repo, fs.readFileSync(x.file!, 'utf8'), mb).flat()));+ expect(seen.sort()).toEqual([...odd].sort());+ collectAll(repo, m!);+ expect(verifyOut(repo, m!).out).toContain('VERIFY: clean');+ }, 300_000);++ // Value: protects=under review_exclude_paths each slice reads its part of the kept selection, kept files through its own keep+ // command, and no excluded file; fails_when=a slice command shows an excluded file, a kept file under the pattern is in no+ // slice, or the keep command repeats another slice's file; why_new=GST-4019 (harness-evals#619 is over the ceiling after+ // exclusions); seam=pass on a real repository with a base policy, the briefs run by git, verify+ test.skipIf(!POSIX)('under review_exclude_paths the slices partition the kept selection, kept files included', () => {+ const keep = Array.from({ length: 3 }, (_, k) => `results/b/keep${k}.json`);+ const files: Record<string, string> = {+ 'src1/reader.ts': `export const files = ${JSON.stringify(keep)};\n`,+ ...Object.fromEntries(keep.map((f, k) => [f, JSON.stringify({ rows: src(`keep${k}`, 200).split('\n') }) + '\n'])),+ ...Object.fromEntries(Array.from({ length: 6 }, (_, k) => [`results/a/x${k}.json`, JSON.stringify({ rows: src(`x${k}`, 500).split('\n') }) + '\n'])),+ ...Object.fromEntries(['src1', 'src2'].flatMap(d => Array.from({ length: 4 }, (_, k) => [`${d}/m${k}.ts`, src(`${d}${k}`, 280)]))),+ };+ const repo = fixture(files, { '.gstack/ship-policy.json': JSON.stringify({ review_exclude_paths: ['results/**'], min_gstack_version: REVIEW_EXCLUDE_KEY_VERSION }) + '\n' });+ const { r, m } = runPassBin(repo);+ expect({ status: r.status, err: r.err }).toEqual({ status: EXIT.ok, err: '' });+ const mb = mergeBase(repo);+ const selection = Object.keys(files).filter(f => !f.startsWith('results/a/')).sort();+ const sliced = m!.readers.filter(x => x.slice && x.state === 'rendered');+ expect(sliced.length).toBeGreaterThan(1);+ const seen = new Map<string, string>();+ for (const x of sliced) for (const n of new Set(briefNames(repo, fs.readFileSync(x.file!, 'utf8'), mb).flat())) { expect(seen.get(n)).toBeUndefined(); seen.set(n, x.reader); }+ expect([...seen.keys()].sort()).toEqual(selection);+ expect(sliced.some(x => x.keep?.length)).toBe(true);+ collectAll(repo, m!);+ const v = verifyOut(repo, m!);+ expect(v.out).toMatch(new RegExp(`^SLICE specialist-batched MATCH slices=\\d files=${selection.length} `, 'm'));+ expect(v.out).toContain('VERIFY: clean');+ }, 300_000);++ // Value: protects=a PR at or under the ceiling gets exactly today's readers and briefs; fails_when=a normal pass gains a slice+ // reader, a slice field or slice wording; why_new=GST-4019 (zero change under the ceiling); seam=gstack-review-dispatch pass and verify+ test.skipIf(!POSIX)('a diff under the ceiling stays unsliced', () => {+ const repo = fixture({ 'alpha/a.ts': src('a', 300), 'beta/b.ts': src('b', 300) });+ const { r, m } = runPassBin(repo);+ expect({ status: r.status, err: r.err }).toEqual({ status: EXIT.ok, err: '' });+ expect(m!.readers.some(x => x.slice || x.reader.includes('#'))).toBe(false);+ for (const x of m!.readers.filter(y => y.file)) expect(fs.readFileSync(x.file!, 'utf8')).not.toContain('This review is slice');+ expect(fs.readFileSync(m!.ledger, 'utf8')).not.toContain('"slice"');+ collectAll(repo, m!);+ const v = verifyOut(repo, m!);+ expect(v.out).not.toContain('SLICE ');+ expect(v.out).toContain('VERIFY: clean');+ }, 300_000);+});++describe('a sliced reader is still one reviewer (R51)', () => {+ // Value: protects=slicing never multiplies review-log rows, start tokens or rounds; fails_when=Step 11 takes one+ // adversarial-review start per native slice, or a slice's reply is collected under the wrong reader; why_new=GST-4019;+ // seam=lib/capy-review-pass.js on a fake host with real bins, then verify+ test.skipIf(!POSIX)('Step 11 takes one start per voice however many slices its native reader has, and the pass verifies clean', async () => {+ const { dir, env } = harnessRepo();+ const sh = (c: string) => { const r = spawnSync('bash', ['-c', c], { cwd: dir, env, encoding: 'utf8', timeout: 120_000 }); if (r.status !== 0) throw new Error(r.stderr); };+ for (const d of ['alpha', 'beta', 'gamma']) for (let k = 0; k < 6; k++) { fs.mkdirSync(path.join(dir, d), { recursive: true }); fs.writeFileSync(path.join(dir, d, `m${k}.ts`), src(`${d}${k}`, 290)); }+ sh('git add -A && git commit -qm big');+ const out = path.join(dir, '.state/run/p1');+ const h = host(dir, env);+ const models = { 'outside-voice': { model_id: 'openai/gpt-6.2-sol' } };+ const base = { base: 'main', out, pass: 'x9p1', planFlags: ['--depth-floor', 'full'] };+ expect(await runPass(h, { ...base, logStart: ['review'] })).toContain('NEXT: judge (Phase 4)');+ const voices = await runPass(h, { ...base, stage: 'voices', models });+ expect(voices).toContain('NEXT: judge the voices');+ const m = JSON.parse(fs.readFileSync(path.join(out, 'pass-manifest.json'), 'utf8')) as Manifest;+ const native = m.readers.filter(r => r.role === 'adversarial-native');+ expect(native.map(r => r.reader)).toEqual(['adversarial-native#1/3', 'adversarial-native#2/3', 'adversarial-native#3/3']);+ expect(m.readers.filter(r => r.role === 'outside-voice').map(r => r.reader)).toEqual(['outside-voice']);+ expect(Object.keys(m.log_starts ?? {}).sort()).toEqual(['pass:review', 'voices:adversarial-review', 'voices:adversarial-review#2']);+ expect(m.readers.every(r => r.state === 'collected')).toBe(true);+ fs.writeFileSync(path.join(out, 'judged.jsonl'), '');+ expect(bin(dir, env, ['judge', '--ledger', m.ledger, '--merged', m.merged, '--judged', path.join(out, 'judged.jsonl')]).status).toBe(0);+ const v = bin(dir, env, ['verify', '--ledger', m.ledger]);+ expect(v.stdout).toMatch(/^SLICE adversarial-native MATCH slices=3 /m);+ expect(v.stdout).toContain('VERIFY: clean');+ }, 300_000);+});++describe.skipIf(!POSIX)('slice guards', () => {+ const three = () => fixture(Object.fromEntries(['alpha', 'beta', 'gamma'].flatMap(d => Array.from({ length: 6 }, (_, k) => [`${d}/m${k}.ts`, src(`${d}${k}`, 290)]))));++ // Value: protects=stage never renders slice briefs from a plan whose files moved; fails_when=a file added after pass reaches+ // no slice brief and the stage renders anyway; why_new=GST-4019 review (slicesMoved had no test); seam=pass, then stage+ test.skipIf(!POSIX)('stage refuses slice readers whose files changed after pass planned them', () => {+ const repo = three();+ const { m, file } = runPassBin(repo);+ expect(m!.readers.filter(x => x.role === 'adversarial-native' && x.state === 'planned').length).toBe(3);+ commit(repo, { 'alpha/new.ts': src('new', 10) });+ const s = runBin(repo, 'gstack-review-dispatch', ['stage', '--manifest', file, '--stage', 'voices']);+ expect(s.status).not.toBe(EXIT.ok);+ expect(s.err).toContain('planned its slices');+ const after = JSON.parse(fs.readFileSync(file, 'utf8')) as Manifest;+ expect(after.readers.filter(x => x.role === 'adversarial-native' && x.state === 'rendered')).toEqual([]);+ }, 300_000);++ // Value: protects=the targeted-reader record a receipt reads is done only when every slice was collected, and counts every+ // slice's findings; fails_when=a sliced targeted reader records done with a slice uncollected, or findings miss a slice;+ // why_new=GST-4019 review (targetedRecord's sliced path had no test); seam=pass, stage voices, collect, verify --targeted-out+ test.skipIf(!POSIX)('a sliced targeted reader records done only when every slice is collected, with findings summed', () => {+ const repo = fixture(Object.fromEntries(['billing', 'beta', 'gamma'].flatMap(d => Array.from({ length: 6 }, (_, k) => [`${d}/m${k}.ts`, `export const charge_limit_usd = ${k};\n` + src(`${d}${k}`, 290)]))));+ const { m, file } = runPassBin(repo);+ expect(runBin(repo, 'gstack-review-dispatch', ['stage', '--manifest', file, '--stage', 'voices']).status).toBe(EXIT.ok);+ const staged = JSON.parse(fs.readFileSync(file, 'utf8')) as Manifest;+ const targeted = staged.readers.filter(x => x.role === 'targeted');+ expect(targeted.length).toBeGreaterThan(1);+ expect(targeted.every(x => x.slice && x.state === 'rendered')).toBe(true);+ const last = targeted.at(-1)!.reader;+ const tree = `REVIEWED_TREE: ${repo.git('rev-parse', 'HEAD^{tree}')} ${fs.realpathSync(repo.work)}`;+ const finding = JSON.stringify({ severity: 'INFORMATIONAL', confidence: 6, path: 'billing/m0.ts', line: 1, category: 'money', summary: 'a note' });+ const send = (x: (typeof targeted)[number], reply: string) => {+ const role = ['--role', x.role!, ...(x.name ? ['--name', x.name] : []), '--slice', `${x.slice!.index}/${x.slice!.total}`];+ expect(runBin(repo, 'gstack-review-dispatch', ['sent', '--ledger', staged.ledger, ...role, '--sent', x.file!]).status).toBe(0);+ const f = path.join(staged.out, `${x.reader.replace(/[^a-z0-9]/gi, '_')}.reply.txt`);+ fs.writeFileSync(f, `${tree}\nREVIEW_VERDICT: blocking=0\n${reply}\n`);+ expect(runBin(repo, 'gstack-review-dispatch', ['collect', '--ledger', staged.ledger, ...role, '--output', f, '--merged', staged.merged]).status).toBe(0);+ };+ for (const x of targeted.slice(1, -1)) send(x, 'NO FINDINGS');+ send(targeted[0]!, finding);+ const record = () => runBin(repo, 'gstack-review-dispatch', ['verify', '--ledger', staged.ledger]).out.match(/^TARGETED_RECORD: .*$/m)?.[0];+ expect(record()).toContain('status=failed');+ send(targeted.find(x => x.reader === last)!, finding);+ expect(record()).toMatch(/status=done findings=2 /);+ }, 300_000);++ // Value: protects=a malformed --slice is a usage error before any ledger write; fails_when=3/2, 1/9, 0/1 or x is accepted;+ // why_new=GST-4019 review (the --slice usage path had no test); seam=gstack-review-dispatch collect and sent+ test.each(['3/2', '1/9', '0/1', 'x'])('--slice %s is a usage error for collect and sent', s => {+ const repo = fixture({ 'a.ts': 'export const a = 1;\n' });+ const ledger = path.join(repo.root, 'ledger.jsonl');+ for (const cmd of [['collect', '--output', ledger, '--merged', ledger], ['sent', '--sent', ledger]]) {+ const r = runBin(repo, 'gstack-review-dispatch', [cmd[0]!, '--ledger', ledger, '--role', 'specialist', '--name', 'testing', '--slice', s, ...cmd.slice(1)]);+ expect(r.status).toBe(EXIT.usage);+ expect(r.err).toContain('--slice takes');+ }+ expect(fs.existsSync(ledger)).toBe(false);+ });+});+++describe.skipIf(!POSIX)('slice readers in the fetch quarantine and the native test summary', () => {+ const reply = (repo: FixtureRepo, m: Manifest, x: Manifest['readers'][number], body: string) => {+ const role = ['--role', x.role!, ...(x.name ? ['--name', x.name] : []), '--slice', `${x.slice!.index}/${x.slice!.total}`];+ expect(runBin(repo, 'gstack-review-dispatch', ['sent', '--ledger', m.ledger, ...role, '--sent', x.file!]).status).toBe(0);+ const f = path.join(m.out, `${x.reader.replace(/[^a-z0-9]/gi, '_')}.reply.txt`);+ fs.writeFileSync(f, `REVIEWED_TREE: ${repo.git('rev-parse', 'HEAD^{tree}')} ${fs.realpathSync(repo.work)}\nREVIEW_VERDICT: blocking=0\n${body}\n`);+ expect(runBin(repo, 'gstack-review-dispatch', ['collect', '--ledger', m.ledger, ...role, '--output', f, '--merged', m.merged]).status).toBe(0);+ };++ // Value: protects=a slice reader that broke the fetch rule has its findings removed and its quarantine recorded under its+ // own key; fails_when=quarantineStage looks a slice reader up without its slice and removes nothing; why_new=GST-4019+ // final review (lib/review-sweep.ts:259); seam=pass, sent and collect, then quarantineStage and the ledger+ test('a quarantined slice reader loses its findings and its quarantine names the slice', () => {+ const repo = fixture(Object.fromEntries(['alpha', 'beta', 'gamma'].flatMap(d => Array.from({ length: 6 }, (_, k) => [`${d}/m${k}.ts`, src(`${d}${k}`, 290)]))));+ const { m } = runPassBin(repo);+ const first = m!.readers.find(x => x.reader === 'specialist-batched#1/3')!;+ reply(repo, m!, first, JSON.stringify({ severity: 'INFORMATIONAL', confidence: 6, path: 'alpha/m0.ts', line: 1, category: 'testing', summary: 'a note' }));+ const ids = () => fs.readFileSync(m!.merged, 'utf8').trim().split('\n').filter(Boolean).map(l => JSON.parse(l) as { id: string; reader: string });+ const mine = ids().filter(f => f.reader === first.reader).map(f => f.id);+ expect(mine.length).toBe(1);+ const { lines } = quarantineStage(m!, 'specialists', 1);+ expect(lines.find(l => l.startsWith(`QUARANTINED: reader=${first.reader} `))).toContain('findings_removed=1');+ expect(ids().map(f => f.id)).not.toContain(mine[0]);+ const events = readLedger(m!.ledger);+ expect([...quarantinedIds(events)]).toContain(mine[0]);+ expect(events.filter(e => e.event === 'quarantined').map(e => e.reader)).toContain(first.reader);+ }, 300_000);++ // Value: protects=a native slice's fixture summary command lists only that slice's test, fixture and spec files, and never+ // a file the base policy excludes; fails_when=the summary command reads the whole slice or an excluded output;+ // why_new=GST-4019 final review (lib/review-brief.ts:158); seam=pass and stage voices, the native briefs run by git+ test('a native slice summarizes only its own test and fixture files and no excluded output', () => {+ const files: Record<string, string> = {+ ...Object.fromEntries(['alpha', 'beta', 'gamma'].flatMap(d => Array.from({ length: 6 }, (_, k) => [`${d}/m${k}.ts`, src(`${d}${k}`, 290)]))),+ 'alpha/m0.test.ts': src('t0', 2), 'beta/fixtures/f.json': src('f', 2), 'gamma/x.spec.ts': src('s', 2), 'testkit/big.ts': src('kit', 1_200),+ 'results/a/test-out.json': src('out', 2),+ };+ const repo = fixture(files, { '.gstack/ship-policy.json': JSON.stringify({ review_exclude_paths: ['results/**'], min_gstack_version: REVIEW_EXCLUDE_KEY_VERSION }) + '\n' });+ const { r, file } = runPassBin(repo);+ expect({ status: r.status, err: r.err }).toEqual({ status: EXIT.ok, err: '' });+ expect(runBin(repo, 'gstack-review-dispatch', ['stage', '--manifest', file, '--stage', 'voices']).status).toBe(EXIT.ok);+ const m = JSON.parse(fs.readFileSync(file, 'utf8')) as Manifest;+ const mb = mergeBase(repo);+ const native = m.readers.filter(x => x.role === 'adversarial-native' && x.slice && x.state === 'rendered');+ expect(native.length).toBeGreaterThan(1);+ const summarized: string[] = [];+ for (const x of native) {+ const brief = fs.readFileSync(x.file!, 'utf8');+ const stat = [...brief.matchAll(/`(git diff --stat [^`]*)`/g)].map(c => c[1]!);+ expect(stat.length).toBe(1);+ const own = new Set(briefNames(repo, brief.replace(/`git diff --stat [^`]*`/, ''), mb).flat());+ const names = briefNames(repo, `\`${stat[0]}\``, mb).flat();+ for (const n of names) { expect(own.has(n)).toBe(true); expect(n).toMatch(/test|fixture|\.spec\./); expect(n.startsWith('results/')).toBe(false); }+ summarized.push(...names);+ }+ expect(summarized.sort()).toEqual(['alpha/m0.test.ts', 'beta/fixtures/f.json', 'gamma/x.spec.ts', 'testkit/big.ts']);+ }, 300_000);+});