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
fix(review-exclude): fixed git calls for the name scan and binary read; dispatch names a plan timeout (GST-1442) (#4040)
Garry Tan713c672d2824
diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.shindex fc9f2e2a1..c6c2b9437 100644--- a/bin/gstack-doctor-components.sh+++ b/bin/gstack-doctor-components.sh@@ -360,6 +360,7 @@ gstack_result_anchor() {PREGATE_HEAD_POLICY_LOOSENS) printf '%s' 'pregate-head-policy-loosens' ;;REVIEW_DIFF_TOO_LARGE) printf '%s' 'review-diff-too-large' ;;REVIEW_DIFF_UNREADABLE) printf '%s' 'review-diff-unreadable' ;;+ REVIEW_PLAN_STOPPED) printf '%s' 'review-plan-stopped' ;;REVIEW_EXCLUDE_REFERENCE) printf '%s' 'review-exclude-reference' ;;FETCH_VIOLATION) printf '%s' 'fetch-violation' ;;FETCH_RERUN_BLOCKED) printf '%s' 'fetch-rerun-blocked' ;;diff --git a/bin/gstack-review-dispatch b/bin/gstack-review-dispatchindex 11495c06f..16bf2fbc6 100755--- a/bin/gstack-review-dispatch+++ b/bin/gstack-review-dispatch@@ -26,6 +26,8 @@ import { BRIEF_ROLES, BriefError, briefFile, checkReviewedTree, checkoutRoot, chimport { cleanMarkers, collect, fixableRaises, mayBeUnavailable, parseFindings, readJsonl, readLedger, readerKey, recordJudgment, recordSent, appendEvent, verify, type JudgedLine, type MergedLine, type VerifyRow } from '../lib/review-ledger';import { buildManifest, chunkCount, chunkOf, manifestPath, markReader, readManifest, renderStage, withAuditModel, writeManifest, STAGES, type Extra, type Manifest, type PassReader, type ReaderState, type Stage } from '../lib/review-pass';import type { Dispatch } from '../lib/review-depth';+import { REVIEW_PLAN_TIMEOUT_MS } from '../lib/review-collect';+import { resultLine } from '../lib/result-codes';import { runScriptSync } from '../lib/script-invocation';import { TARGETED_RULES, parseClassList, targetedBriefSha, targetedRead } from '../lib/review-targeted';import { resolveBaseBranch } from '../lib/ship-policy';@@ -332,10 +334,20 @@ function pass(): number {process.stdout.write([...m.plan_lines, `MANIFEST: file=${file} pass=${id} readers=${m.readers.length} audit-only`, ...m.readers.map(r => readerLine(m, r))].join('\n') + '\n');return EXIT.ok;}- const plan = (json: boolean) => runScriptSync(path.join(ROOT, 'bin', 'gstack-review-plan'), ['--base', base, ...planArgs, ...(json ? ['--json'] : [])], { encoding: 'utf8', timeout: 180_000, maxBuffer: 64 * 1024 * 1024 });+ const limit = Number(process.env.GSTACK_REVIEW_PLAN_TIMEOUT_MS);+ const timeoutMs = Number.isFinite(limit) && limit >= 1 ? Math.floor(limit) : REVIEW_PLAN_TIMEOUT_MS;+ const plan = (json: boolean) => runScriptSync(path.join(ROOT, 'bin', 'gstack-review-plan'), ['--base', base, ...planArgs, ...(json ? ['--json'] : [])], { encoding: 'utf8', timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 });+ const stopped = (r: ReturnType<typeof plan>, json: boolean) => {+ if (r.status !== null || (!r.signal && !r.error)) return false;+ const reason = (r.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT' ? 'timeout' : r.signal ? 'signal' : 'spawn';+ process.stderr.write(`${r.stderr ?? ''}${resultLine('gstack-review-dispatch pass', 'REVIEW_PLAN_STOPPED', `step="gstack-review-plan --base ${base}${json ? ' --json' : ''}" reason=${reason} timeout_ms=${timeoutMs} signal=${r.signal ?? 'none'}`)}\n`);+ return true;+ };const text = plan(false);+ if (stopped(text, false)) return EXIT.fail;if (text.status !== 0) { process.stdout.write(text.stdout ?? ''); process.stderr.write(text.stderr ?? ''); return EXIT.fail; }const j = plan(true);+ if (stopped(j, true)) return EXIT.fail;if (j.status !== 0) { process.stderr.write(j.stderr ?? ''); return EXIT.fail; }const p = JSON.parse(j.stdout) as { next: { step: string }; dispatches: Dispatch[]; targeted?: { classes: string[] }; fix_range?: { base: string } | null; review_exclude?: Record<string, unknown> & { state: string; excluded?: number; kept_files?: unknown; references?: unknown }; readers?: EffectiveReaders };const step = p.next.step;diff --git a/changelog.d/gst-1442-review-plan-git-calls.md b/changelog.d/gst-1442-review-plan-git-calls.mdnew file mode 100644index 000000000..86c517e29--- /dev/null+++ b/changelog.d/gst-1442-review-plan-git-calls.md@@ -0,0 +1 @@+- **The review plan finishes in about 35 seconds on a 195,000-file results tree, and the pass says so when the plan runs out of time.** The `review_exclude_paths` name scan now writes the code and test files into a scratch index and runs one `git grep` per tree, and the binary check reads small blobs through one `git cat-file --batch` per 64 MB instead of one git call per file. The number of git calls no longer grows with the size of the tree or the PR. On harness-evals #269 the plan went from 2 min 38 s and 432 git calls to 32 s and 76 calls; on #279 it went from 206 s to 35 s, with the same output. When `gstack-review-plan` still runs past the pass's 180-second limit (`GSTACK_REVIEW_PLAN_TIMEOUT_MS` changes it), `gstack-review-dispatch pass` now prints a `REVIEW_PLAN_STOPPED` line naming the step, the reason and the limit instead of exiting with no output. (GST-1442)diff --git a/docs/review-policy.md b/docs/review-policy.mdindex 7413792c4..d1fd82dce 100644--- a/docs/review-policy.md+++ b/docs/review-policy.md@@ -284,7 +284,9 @@ costs one cheap pass. Each scan gets one 120-second deadline, set in millisecond256 MB, is also `consumer_scan_failed`, and its detail says what stopped it and namesthe deadline. One scan fits a minute inside the 180 seconds /ship gives`gstack-review-plan`; a plan that also scans a fix range runs two scans, and if they-pass that limit the plan fails, which also leads to a full review. Only `classifyDiff` applies the rule (`lib/review-collect.ts`+pass that limit `gstack-review-dispatch pass` stops with+[`REVIEW_PLAN_STOPPED`](troubleshooting.md#review-plan-stopped) before any reader+runs (`GSTACK_REVIEW_PLAN_TIMEOUT_MS` sets the pass's limit in milliseconds). Only `classifyDiff` applies the rule (`lib/review-collect.ts`finds the consumers, `gstack-ship-preflight`'s `RUNTIME_LINES` reads the samefunction); every path-only caller (the receipt's gate-scan decision, the Step 16post-review route, /autoplan's docs-only scope) keeps data files code. A numeric claimdiff --git a/docs/ship-policy.md b/docs/ship-policy.mdindex 19d019222..b7f7bc172 100644--- a/docs/ship-policy.md+++ b/docs/ship-policy.md@@ -1427,9 +1427,10 @@ informational `REVIEW_EXCLUDE_REFERENCE:` line naming the code that reads thefolder. A data file never keeps another file: a results manifest such as`docs/receipts-manifest.json` lists every receipt by full path, and it iscontent, not a program that reads them. The name scan is an uncapped `git grep -F -f` of the candidates'-paths over the consumer files alone (the head's and the merge base's trees filtered to code and tests, passed as literal-pathspecs in 24,000-byte chunks), never the data under the patterns, so its cost follows the code a results PR-can be read by and not the receipts it adds (GST-1435); it is not the collector's capped consumer scan.+paths over the consumer files alone (the head's and the merge base's trees filtered to code and tests and written into a+scratch index that one `git grep` per tree reads), never the data under the patterns, so its cost follows the code a results PR+can be read by and not the receipts it adds (GST-1435), and its git calls stay the same however many files the tree holds+(GST-1442); it is not the collector's capped consumer scan.**What readers run.** Every reader's `DIFF_CMD:` gains one`':(top,exclude,glob)<pattern>'` item per applied pattern, and the fixturediff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex e466012be..db65ad2f1 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -3549,6 +3549,21 @@ exclude its largest data folders on the base; git exit 128 (a missing object oran unfetched base), `git fetch origin <base>` and rerun once; anything else, stopand ask a person with the log file.+<a id="review-plan-stopped"></a>+### `REVIEW_PLAN_STOPPED`++**Meaning.** `gstack-review-dispatch pass` runs `gstack-review-plan` before it+writes a manifest, and that run did not finish, so the pass stopped (exit 1)+without dispatching a reader. The line names the step (the plan command),+`reason=timeout` with `timeout_ms` (180,000 ms; `GSTACK_REVIEW_PLAN_TIMEOUT_MS`+sets it in milliseconds), `reason=signal` with the signal when something else+killed it, or `reason=spawn` when it could not start. Before this line existed, a+plan that ran past the limit was killed with no output (GST-1442).++**Fix.** Rerun the pass once unchanged. If it stops again, report the line and the+repository's file count (`git ls-files | wc -l`) to your Captain. For+`reason=signal`, check the machine's free memory first.+<a id="review-exclude-reference"></a>### `REVIEW_EXCLUDE_REFERENCE`diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.tsindex 1f1c0e6e6..5ab1356ed 100644--- a/lib/result-codes-release.ts+++ b/lib/result-codes-release.ts@@ -541,6 +541,11 @@ export const RELEASE_RESULT_CODES = {summary: 'git could not read a reviewer\'s diff (reason=timeout after timeout_ms, or reason=git-exit with git\'s exit code), so /ship stopped; the full stderr, with remote URLs redacted, is in the log= file',fix: 'timeout: rerun once unchanged, then split the PR or exclude its largest data folders on the base; git exit 128: git fetch origin <base>, then rerun once; anything else: stop and ask a person',},+ REVIEW_PLAN_STOPPED: {+ anchor: 'review-plan-stopped',+ summary: 'gstack-review-plan did not finish inside the pass (reason=timeout after timeout_ms, reason=signal when something killed it, reason=spawn when it could not start), so gstack-review-dispatch pass stopped before writing a manifest or dispatching a reader',+ fix: 'rerun the pass once unchanged; if it stops again, report this line and the repository\'s file count (git ls-files | wc -l) to your Captain; reason=signal: check the machine\'s free memory first',+ },REVIEW_EXCLUDE_REFERENCE: {anchor: 'review-exclude-reference',summary: 'informational: a kept code file names an excluded folder (a directory reference, not a full file path), so its files stay excluded and readers see that code without the files it reads',diff --git a/lib/review-collect.ts b/lib/review-collect.tsindex 087059a65..95c5545d7 100644--- a/lib/review-collect.ts+++ b/lib/review-collect.ts@@ -119,6 +119,8 @@ export const CONSUMER_SCAN_DEPTH = 4;* a plan that also scans a fix range (--range-base) runs a second scan and can still reach that limit, which fails the plan.*/export const CONSUMER_SCAN_TIMEOUT_MS = 120_000;+/** How long gstack-review-dispatch pass waits for each gstack-review-plan call (GSTACK_REVIEW_PLAN_TIMEOUT_MS overrides it); past it the pass stops with REVIEW_PLAN_STOPPED. */+export const REVIEW_PLAN_TIMEOUT_MS = 180_000;/** Pathspec bytes per git grep call: a long list of files to search splits across calls instead of growing one command line. */export const CONSUMER_SCAN_PATHSPEC_BYTES = 16_000;/** Output bytes one consumer grep may return across all its calls, the buffer the single whole-tree call had; past it the scan fails closed. */diff --git a/lib/review-exclude.ts b/lib/review-exclude.tsindex ede914888..360a8c23e 100644--- a/lib/review-exclude.ts+++ b/lib/review-exclude.ts@@ -37,6 +37,8 @@ export const KEEP_ARG_MAX_BYTES = 24_000;/** How long one reader's `git diff` may run. */export const REVIEW_DIFF_TIMEOUT_MS = 120_000;const MAX_BUFFER = 256 * 1024 * 1024;+const BLOB_BATCH_MAX_BYTES = 1024 * 1024;+const BLOB_BATCH_BYTES = 64 * 1024 * 1024;export const KEPT_REASONS = ['policy-dir', 'gate-path', 'executable', 'agent-prose', 'config', 'gate-tagged', 'code', 'secret-line', 'named-by-code', 'consumer-scan-unavailable', 'gate-scan-unavailable', 'link'] as const;export type KeptReason = (typeof KEPT_REASONS)[number];@@ -92,8 +94,8 @@ function argChunks(paths: readonly string[]): string[][] {return chunks;}-function git(root: string, args: string[], input?: string): { ok: boolean; status: number | null; out: string; err: string } {- const r = spawnSync('git', ['-c', 'core.quotePath=false', ...args], { cwd: root, input, encoding: 'utf8', timeout: 120_000, maxBuffer: MAX_BUFFER });+function git(root: string, args: string[], input?: string, env?: NodeJS.ProcessEnv): { ok: boolean; status: number | null; out: string; err: string } {+ const r = spawnSync('git', ['-c', 'core.quotePath=false', ...args], { cwd: root, input, env, encoding: 'utf8', timeout: 120_000, maxBuffer: MAX_BUFFER });return { ok: r.status === 0, status: r.status, out: r.stdout ?? '', err: (r.stderr ?? '').trim() };}@@ -160,6 +162,8 @@ const nativeImage = (b: Buffer) => NATIVE_MAGIC.some(m => m.every((x, k) => b[k]* The claimed paths (git calls them binary under the branch's attributes or under none: bytesBinary) whose bytes hold a NUL* in their first 8,000 (git's own test), read from the head blob, the file on a live tree, or the old blob for a deletion.* A branch's .gitattributes can make git call a text file binary; only real bytes make it binary content here. A binary file that starts with executable image magic also goes in `native`.+ * Blobs up to BLOB_BATCH_MAX_BYTES come through `git cat-file --batch` in groups of up to BLOB_BATCH_BYTES, so the git calls+ * follow the bytes and not the file count; a larger blob, or one a batch did not return, is read alone (its first 8,000 bytes).*/function binaryContent(i: ExcludeInput, files: ReadonlyMap<string, Matched>, claimed: ReadonlySet<string>, unread: Set<string>, native: Set<string>): Set<string> {const out = new Set<string>();@@ -176,10 +180,29 @@ function binaryContent(i: ExcludeInput, files: ReadonlyMap<string, Matched>, claconst sha = real(m.newSha) ? m.newSha : real(m.oldSha) ? m.oldSha : '';if (sha) bySha.set(sha, [...(bySha.get(sha) ?? []), p]);}+ const heads = new Map<string, Buffer>();+ const sizes = bySha.size ? git(i.root, ['cat-file', '--batch-check=%(objectname) %(objectsize)'], [...bySha.keys()].join('\n') + '\n') : null;+ const small = (sizes?.ok ? sizes.out.split('\n') : []).map(l => l.split(' ')).filter(([s, n]) => bySha.has(s ?? '') && Number(n) <= BLOB_BATCH_MAX_BYTES).map(([s, n]) => [s!, Number(n)] as const);+ for (let k = 0; k < small.length;) {+ const group: string[] = [];+ let bytes = 0;+ while (k < small.length && (!group.length || bytes + small[k]![1] <= BLOB_BATCH_BYTES)) { group.push(small[k]![0]); bytes += small[k]![1]; k++; }+ const r = spawnSync('git', ['cat-file', '--batch'], { cwd: i.root, input: group.join('\n') + '\n', timeout: 120_000, maxBuffer: bytes + group.length * 200 });+ if (r.status !== 0) continue;+ let at = 0;+ for (const sha of group) {+ const nl = r.stdout.indexOf(10, at);+ const [name, type, size] = nl < 0 ? [] : r.stdout.subarray(at, nl).toString().split(' ');+ if (name !== sha || type !== 'blob' || size === undefined) break;+ heads.set(sha, Buffer.from(r.stdout.subarray(nl + 1, nl + 1 + Math.min(Number(size), 8000))));+ at = nl + 1 + Number(size) + 1;+ }+ }for (const [sha, paths] of bySha) {- const r = spawnSync('git', ['cat-file', 'blob', sha], { cwd: i.root, timeout: 30_000, maxBuffer: 8000 });- const read = r.status === 0 || (r.error as NodeJS.ErrnoException | undefined)?.code === 'ENOBUFS';- const head = (r.stdout ?? Buffer.alloc(0)).subarray(0, 8000);+ const batched = heads.get(sha);+ const r = batched ? null : spawnSync('git', ['cat-file', 'blob', sha], { cwd: i.root, timeout: 30_000, maxBuffer: 8000 });+ const read = !r || r.status === 0 || (r.error as NodeJS.ErrnoException | undefined)?.code === 'ENOBUFS';+ const head = batched ?? (r?.stdout ?? Buffer.alloc(0)).subarray(0, 8000);for (const p of paths) if (!read) unread.add(p); else sniff(p, head);}return out;@@ -242,10 +265,12 @@ const consumer = (i: ExcludeInput, f: string, candidates: ReadonlySet<string>) =/*** An uncapped `git grep -F -o -f` of fixed strings at the head (or the working tree) and `revs`: string -> the consumer files- * holding it; null when git could not list a tree, a consumer's name did not survive UTF-8 decoding (its literal pathspec would- * match nothing), or git grep failed (a timeout included). Each tree's file list is filtered to- * consumers first and grepped through literal pathspecs, so the data under the patterns is never read (GST-1435: a whole-tree- * grep for 4,354 candidate paths through 30 MB of receipts ran 278 s).+ * holding it; null when git could not list a tree, a consumer's name did not survive UTF-8 decoding, or git could not build+ * the scratch index or grep it (a timeout included). Each tree's file list is filtered to consumers first, so the data under+ * the patterns is never read (GST-1435: a whole-tree grep for 4,354 candidate paths through 30 MB of receipts ran 278 s), and+ * the consumers go into a scratch index that one git grep reads, so the git calls stay fixed however many files there are+ * (GST-1442: 363 chunked greps over a 192k-file tree ran 132 s). On a live tree, an entry git reads from its blob+ * (skip-worktree or assume-unchanged) goes into a second index grepped with --cached, as git grep itself would read it.*/function grepFixed(i: ExcludeInput, strings: readonly string[], candidates: ReadonlySet<string>, revs: readonly string[]): Map<string, Set<string>> | null {const found = new Map<string, Set<string>>();@@ -254,20 +279,33 @@ function grepFixed(i: ExcludeInput, strings: readonly string[], candidates: Readtry {const list = path.join(dir, 'patterns');fs.writeFileSync(list, strings.join('\n') + '\n');+ let n = 0;for (const at of [i.head ?? '', ...revs]) {- const ls = git(i.root, at ? ['ls-tree', '-r', '-z', '--name-only', at] : ['ls-files', '-z']);+ const ls = git(i.root, at ? ['ls-tree', '-r', '-z', at] : ['ls-files', '-s', '-v', '-z']);if (!ls.ok) return null;- const files = [...new Set(ls.out.split('\0'))].filter(f => f && consumer(i, f, candidates));- if (files.some(f => f.includes('\uFFFD'))) return null;- for (const chunk of argChunks(files)) {- const r = git(i.root, ['grep', '-I', '-F', '-o', '--null', '--no-line-number', '--no-column', '--no-color', '-f', list, ...(at ? [at] : []), '--', ...chunk.map(literal)]);+ const worktree: string[] = [];+ const cached: string[] = [];+ for (const entry of ls.out.split('\0')) {+ const tab = entry.indexOf('\t');+ const f = entry.slice(tab + 1);+ if (tab < 0 || !consumer(i, f, candidates)) continue;+ if (f.includes('\uFFFD')) return null;+ const meta = entry.slice(0, tab).split(' ');+ if (at) { if (meta[1] === 'blob') cached.push(`${meta[0]} ${meta[2]}\t${f}`); continue; }+ const [tag = '', mode, sha, stage] = meta;+ (tag === 'S' || tag !== tag.toUpperCase() ? cached : worktree).push(`${mode} ${sha} ${stage}\t${f}`);+ }+ for (const [entries, flags] of [[worktree, []], [cached, ['--cached']]] as const) {+ if (!entries.length) continue;+ const env = { ...process.env, GIT_INDEX_FILE: path.join(dir, `index-${n++}`) };+ if (!git(i.root, ['update-index', '-z', '--index-info'], entries.join('\0') + '\0', env).ok) return null;+ const r = git(i.root, ['grep', ...flags, '-I', '-F', '-o', '--null', '--no-line-number', '--no-column', '--no-color', '-f', list], undefined, env);if (r.status !== 0 && r.status !== 1) return null;for (const line of r.out.split('\n')) {const parts = line.split('\0');- const where = parts[0];+ const file = parts[0];const match = parts.length > 1 ? parts[parts.length - 1] : undefined;- if (!where || !match) continue;- const file = at ? where.slice(at.length + 1) : where;+ if (!file || !match) continue;(found.get(match) ?? found.set(match, new Set()).get(match)!).add(file);}}diff --git a/test/review-collect.test.ts b/test/review-collect.test.tsindex 74440e333..915566768 100644--- a/test/review-collect.test.ts+++ b/test/review-collect.test.ts@@ -3,7 +3,7 @@ import { spawnSync } from 'node:child_process';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';-import { collectCommit, collectLive, CONSUMER_SCAN_CAP, CONSUMER_SCAN_TIMEOUT_MS, consumerScanTimeoutMs, grepConsumers, loadRegistryAt, scanConsumers } from '../lib/review-collect';+import { collectCommit, collectLive, CONSUMER_SCAN_CAP, CONSUMER_SCAN_TIMEOUT_MS, consumerScanTimeoutMs, grepConsumers, loadRegistryAt, REVIEW_PLAN_TIMEOUT_MS, scanConsumers } from '../lib/review-collect';import { depthOfCommitInput } from '../lib/review-depth';const dirs: string[] = [];@@ -352,8 +352,10 @@ describe('GST-544: the consumer scan reads only files that can match, under one// Value: protects=a slow scan ends in its own fail-closed consumer_scan_failed, not in the parent killing gstack-review-plan;// fails_when=the scan deadline reaches the timeout the dispatch and preflight callers give the whole plan; seam=caller sourcetest('the default scan deadline leaves a minute of the plan timeout its callers set', () => {- const callers = ['bin/gstack-review-dispatch', 'lib/ship-preflight.ts'].map(f => fs.readFileSync(path.join(import.meta.dir, '..', f), 'utf8'));- const limits = callers.flatMap(src => [...src.matchAll(/gstack-review-plan'[^\n]*?(?:timeout: |\], )(\d[\d_]+)/g)].map(m => Number(m[1]!.replace(/_/g, ''))));+ const callers = ['lib/ship-preflight.ts'].map(f => fs.readFileSync(path.join(import.meta.dir, '..', f), 'utf8'));+ const dispatch = fs.readFileSync(path.join(import.meta.dir, '..', 'bin/gstack-review-dispatch'), 'utf8');+ expect(dispatch).toMatch(/import \{ REVIEW_PLAN_TIMEOUT_MS \} from '\.\.\/lib\/review-collect'/);+ const limits = [REVIEW_PLAN_TIMEOUT_MS, ...callers.flatMap(src => [...src.matchAll(/gstack-review-plan'[^\n]*?(?:timeout: |\], )(\d[\d_]+)/g)].map(m => Number(m[1]!.replace(/_/g, ''))))];expect(limits.length).toBeGreaterThanOrEqual(2);expect(CONSUMER_SCAN_TIMEOUT_MS).toBeLessThanOrEqual(Math.min(...limits) - 60_000);});diff --git a/test/review-dispatch-plan-timeout.test.ts b/test/review-dispatch-plan-timeout.test.tsnew file mode 100644index 000000000..d880803b6--- /dev/null+++ b/test/review-dispatch-plan-timeout.test.ts@@ -0,0 +1,37 @@+/**+ * gstack-review-dispatch pass stops with a REVIEW_PLAN_STOPPED line when gstack-review-plan runs past its limit (GST-1442):+ * on harness-evals #279 the plan took about 214 s against the pass's 180 s, and the pass was killed with no output at all.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++const DISPATCH = path.join(import.meta.dir, '..', 'bin', 'gstack-review-dispatch');+const dirs: string[] = [];+afterEach(() => { while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); });++describe('pass names the plan step and its limit when the plan does not finish (GST-1442)', () => {+ // Value: protects=a plan past the pass's limit ends in a line naming the step, the reason and the limit, with no manifest;+ // fails_when=the pass treats the killed plan like any failed plan and exits 1 with empty output (the #279 silent kill);+ // why_new=GST-1442; seam=gstack-review-dispatch pass with GSTACK_REVIEW_PLAN_TIMEOUT_MS=1; no_claim=the 180 s default+ test('a plan that runs past the limit prints REVIEW_PLAN_STOPPED with reason=timeout and writes no manifest', () => {+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'rd-plan-timeout-')));+ dirs.push(root);+ const work = path.join(root, 'work');+ const env = { ...process.env, GSTACK_STATE_ROOT: path.join(root, 'state'), GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t', GIT_CONFIG_GLOBAL: path.join(root, 'gitconfig') };+ fs.writeFileSync(path.join(root, 'gitconfig'), '[commit]\n\tgpgsign = false\n');+ const sh = (cwd: string, c: string) => { const r = spawnSync('bash', ['-c', c], { cwd, env, encoding: 'utf8', timeout: 60_000 }); if (r.status !== 0) throw new Error(`${c}: ${r.stderr}`); };+ sh(root, 'git init -q --bare -b main origin.git && git clone -q origin.git work 2>/dev/null');+ sh(work, "mkdir src && echo 'export const a = 1;' > src/a.ts && git add -A && git commit -qm base && git push -q origin main && git checkout -qb feat && echo 'export const b = 2;' >> src/a.ts && git commit -qam feat");+ const out = path.join(root, 'run');+ const r = spawnSync(DISPATCH, ['pass', '--base', 'main', '--out', out, '--pass', 'timeout-p1'], { cwd: work, env: { ...env, GSTACK_REVIEW_PLAN_TIMEOUT_MS: '1' }, encoding: 'utf8', timeout: 120_000 });+ expect(r.status, r.stdout + r.stderr).toBe(1);+ expect(r.stderr).toContain('gstack-review-dispatch pass: gstack-review-plan did not finish inside the pass');+ expect(r.stderr).toContain('step="gstack-review-plan --base main" reason=timeout timeout_ms=1 signal=SIGTERM');+ expect(r.stderr.trimEnd().endsWith('(REVIEW_PLAN_STOPPED)')).toBe(true);+ expect(r.stdout).not.toContain('MANIFEST:');+ expect(fs.existsSync(path.join(out, 'pass-manifest.json'))).toBe(false);+ }, 180_000);+});diff --git a/test/review-exclude.test.ts b/test/review-exclude.test.tsindex 6ad1e1657..80d5b4e53 100644--- a/test/review-exclude.test.ts+++ b/test/review-exclude.test.ts@@ -773,13 +773,43 @@ describe('a branch cannot hide code under a base pattern', () => {expect(x.excluded.has('receipts/bulk/7/result.json')).toBe(true);const greps = fs.readFileSync(trace, 'utf8').split('\n').filter(l => /built-in: git( -c \S+)* grep /.test(l));expect(greps.length).toBeGreaterThan(0);- const read = greps.map(l => [...(l.split(' -- ')[1] ?? '').matchAll(/:\(top,literal\)([^' ]+)/g)].map(m => m[1]!));- expect(read.every(paths => paths.length > 0)).toBe(true);- const all = new Set(read.flat());- expect(['lib/reader.js', 'test/d.test.js'].every(p => all.has(p))).toBe(true);- expect([...all].filter(p => p.startsWith('receipts/') && p !== 'receipts/run.sh')).toEqual([]);+ expect(greps.filter(l => / -- /.test(l))).toEqual([]);}, 120_000);+ // Value: protects=the plan's consumer scan and binary read finish in a fixed number of git calls however many files the tree+ // and the PR hold, so a results PR cannot push the plan past gstack-review-dispatch's 180 s limit; fails_when=the scan greps+ // in pathspec chunks (one call per 24 KB of consumer names) or reads one blob per git call, so the count grows with the+ // tree; why_new=GST-1442 (harness-evals #269: 363 greps over a 192k-file tree, 2 min 38 s on a Capy machine);+ // seam=reviewExclude in head and live mode, git processes counted through GIT_TRACE; no_claim=wall-clock time+ test('the consumer scan and the binary read take the same git calls for 20 or 1,200 files', () => {+ const calls = (n: number, live: boolean) => {+ const repo = census();+ const files: Record<string, string> = {};+ for (let k = 0; k < n; k++) {+ files[`receipts/many/${k}/result.json`] = `{"k": ${k}}\n`;+ files[`lib/generated/a-consumer-module-with-a-long-enough-name-${k}.ts`] = `export const k${k} = ${k};\n`;+ }+ files['lib/generated/reads.ts'] = "export const p = 'receipts/many/3/result.json';\n";+ for (let k = 0; k < n; k++) write(repo.work, `receipts/shots/${k}.png`, `\x89PNG\0${k}`);+ commit(repo, files, 'many receipts');+ const baseSha = repo.git('rev-parse', 'origin/main');+ const head = repo.git('rev-parse', 'HEAD');+ const c = live ? collectLive(repo.work, 'origin/main') : collectCommit(repo.work, baseSha, head);+ const trace = path.join(repo.root, 'git-trace.log');+ const prior = process.env.GIT_TRACE;+ process.env.GIT_TRACE = trace;+ let x: ReturnType<typeof reviewExclude>;+ try { x = reviewExclude({ root: repo.work, baseSha, ref: 'origin/main', mergeBase: c.mergeBase!, ...(live ? {} : { head }), perPath: c.perPath, added: c.added, classRoot: live ? repo.work : c.root ?? [], gateTagged: new Set(), context: 'test' }); }+ finally { if (prior === undefined) delete process.env.GIT_TRACE; else process.env.GIT_TRACE = prior; }+ expect(x.state).toBe('active');+ if (x.state !== 'active') return -1;+ expect(x.kept).toContainEqual({ path: 'receipts/many/3/result.json', reason: 'named-by-code' });+ expect([`receipts/many/${n - 1}/result.json`, `receipts/shots/${n - 1}.png`].every(p => x.excluded.has(p))).toBe(true);+ return fs.readFileSync(trace, 'utf8').split('\n').filter(l => /trace: built-in: git /.test(l)).length;+ };+ for (const live of [false, true]) expect({ live, calls: calls(1200, live) }).toEqual({ live, calls: calls(20, live) });+ }, 240_000);+// GST-1435 review (outside-voice#1): a consumer whose name is not valid UTF-8 comes back from ls-tree as U+FFFD, so its literal// pathspec matches nothing; fails_when=the scan treats that as no match and excludes the data the file names instead of keeping// every candidate; seam=reviewExclude in head mode