Skip to content

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

Stop /ship stalling on branches that merged in thousands of data files (GST-1855) (#4149)

Garry Tan1bdb1644d844
diff --git a/bin/gstack-review-dispatch b/bin/gstack-review-dispatch
index 777480e11..6172bff23 100755
--- a/bin/gstack-review-dispatch
+++ b/bin/gstack-review-dispatch
@@ -28,6 +28,7 @@ import { buildManifest, chunkCount, chunkOf, manifestPath, markReader, readManif
import { diffCommand, type Dispatch } from '../lib/review-depth';
import { mayExclude, policySelection, selectFor } from '../lib/review-selection';
import { REVIEW_PLAN_TIMEOUT_MS } from '../lib/review-collect';
+import { reviewPlanTimeoutMs } 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';
@@ -349,7 +350,7 @@ function standaloneSelection(reader: string, base: string, diffBase: string, rea
let x: (Record<string, unknown> & { state: string }) | null = null;
if (mayExclude(process.cwd(), base)) {
const tail = args.includes('--') ? args.slice(args.indexOf('--') + 1) : [];
- const p = runScriptSync(path.join(ROOT, 'bin', 'gstack-review-plan'), ['--base', base, ...tail, '--json'], { encoding: 'utf8', timeout: REVIEW_PLAN_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 });
+ const p = runScriptSync(path.join(ROOT, 'bin', 'gstack-review-plan'), ['--base', base, ...tail, '--json'], { encoding: 'utf8', timeout: REVIEW_PLAN_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024, env: { ...process.env, GSTACK_REVIEW_PLAN_BOUNDED: '1' } });
if (p.status !== 0) throw new BriefError(`gstack-review-plan --base ${base} --json exited ${p.status ?? p.signal}, so the base policy's review selection is unknown and no brief is rendered without it: ${(p.stderr ?? '').trim().slice(-400)}`);
x = (JSON.parse(p.stdout) as { review_exclude?: Record<string, unknown> & { state: string } }).review_exclude ?? null;
}
@@ -387,9 +388,8 @@ 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 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 timeoutMs = reviewPlanTimeoutMs();
+ 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, env: { ...process.env, GSTACK_REVIEW_PLAN_BOUNDED: '1' } });
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';
diff --git a/bin/gstack-review-plan b/bin/gstack-review-plan
index 29a6ebe02..868009292 100755
--- a/bin/gstack-review-plan
+++ b/bin/gstack-review-plan
@@ -29,7 +29,7 @@ import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
import { resultLine } from '../lib/result-codes';
import { runScriptSync } from '../lib/script-invocation';
import { baseNote } from '../lib/gate-diff/git';
-import { collectCommit, collectLive } from '../lib/review-collect';
+import { collectCommit, collectLive, reviewPlanTimeoutMs } from '../lib/review-collect';
import { excludeLines, reviewExclude, type Exclusion } from '../lib/review-exclude';
import { isUnavailable } from '../lib/ship-policy';
import { reviewPolicy } from '../lib/ship-policy-review';
@@ -235,7 +235,7 @@ function main(): number {
else {
const commit = collectCommit(root, resolved, 'HEAD');
const range = classifyDiff({ ...commit, registry, scope: scopeOf([resolved, '--head', 'HEAD']), gateTagged: gateTagsOf([resolved]), ...riskPaths, ...(active ? { excluded: active.excluded } : {}) });
- fixRange = range.errors.length ? unread(range.errors.map(e => `${e.code} ${e.input}`).join('; '))
+ fixRange = range.errors.length ? unread([...range.errors.slice(0, 5).map(e => `${e.code} ${e.input}`), ...(range.errors.length > 5 ? [`+${range.errors.length - 5} more`] : [])].join('; '))
: !commit.paths.length ? unread('the fix range is empty: commit the fix after the range base')
: { base: rangeBase, runtime_lines: range.runtimeLines, ...(range.class === 'gate' ? { touched_gate: true as const } : {}) };
}
@@ -298,4 +298,20 @@ function main(): number {
return EXIT.ok;
}
-process.exitCode = main();
+/**
+ * One plan's bound (GST-1855): the plan runs in a child under reviewPlanTimeoutMs, and a child that does not finish prints
+ * REVIEW_PLAN_STOPPED and exits 1 with no plan, so /ship stops on a named line instead of waiting for minutes. A caller that
+ * bounds the run itself (gstack-review-dispatch pass) sets GSTACK_REVIEW_PLAN_BOUNDED=1 and the plan runs in place.
+ */
+function bounded(): number {
+ if (process.env.GSTACK_REVIEW_PLAN_BOUNDED === '1') return main();
+ const timeoutMs = reviewPlanTimeoutMs();
+ const args = process.argv.slice(2);
+ const r = runScriptSync(Bun.fileURLToPath(import.meta.url), args, { stdio: 'inherit', timeout: timeoutMs, env: { ...process.env, GSTACK_REVIEW_PLAN_BOUNDED: '1' } });
+ if (r.status !== null) return r.status;
+ const reason = (r.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT' ? 'timeout' : r.signal ? 'signal' : 'spawn';
+ process.stderr.write(`${resultLine('gstack-review-plan', 'REVIEW_PLAN_STOPPED', `step="gstack-review-plan ${args.join(' ')}" reason=${reason} timeout_ms=${timeoutMs} signal=${r.signal ?? 'none'}`)}\n`);
+ return EXIT.fail;
+}
+
+process.exitCode = bounded();
diff --git a/bin/gstack-review-scope b/bin/gstack-review-scope
index 170510084..1a8a7b53c 100755
--- a/bin/gstack-review-scope
+++ b/bin/gstack-review-scope
@@ -20,7 +20,9 @@
*/
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 { StringDecoder } from 'node:string_decoder';
import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
import { resultLineWithDocs } from '../lib/result-codes';
import { runScriptSync } from '../lib/script-invocation';
@@ -66,6 +68,36 @@ function git(args: string[], cwd: string): { ok: boolean; out: string; err: stri
const r = spawnSync('git', ['-c', 'core.quotePath=false', ...args], { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });
return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr ?? '').trim() };
}
+const HUNK_LINE = /^(diff --git |--- |\+\+\+ |@@)/;
+/**
+ * `git diff <from>` reduced to the lines parseHunks reads (file headers and @@ lines). git writes the diff to a scratch file that
+ * is read back a megabyte at a time, so no pipe buffer bounds the diff's size (GST-1855: harness-evals #320's 67 MB results diff
+ * passed the 64 MB buffer and classify refused with an empty reason). A failure names git's stderr, its error code or the timeout.
+ */
+function diffHunkLines(from: string, cwd: string): { ok: boolean; out: string; err: string } {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-review-scope-'));
+ try {
+ const file = path.join(dir, 'diff');
+ const r = spawnSync('git', ['-c', 'core.quotePath=false', 'diff', ...DIFF_ARGS, `--output=${file}`, from], { cwd, encoding: 'utf8', timeout: 120_000 });
+ const code = (r.error as NodeJS.ErrnoException | undefined)?.code;
+ if (r.status !== 0) return { ok: false, out: '', err: (r.stderr ?? '').trim() || (code === 'ETIMEDOUT' ? 'timed out after 120 s' : code ?? `exit ${r.status ?? r.signal}`) };
+ const keep: string[] = [];
+ const decoder = new StringDecoder('utf8');
+ const buf = Buffer.alloc(1024 * 1024);
+ const fd = fs.openSync(file, 'r');
+ let rest = '';
+ try {
+ for (let n = fs.readSync(fd, buf); n > 0; n = fs.readSync(fd, buf)) {
+ const lines = (rest + decoder.write(buf.subarray(0, n))).split('\n');
+ rest = lines.pop()!;
+ for (const l of lines) if (HUNK_LINE.test(l)) keep.push(l);
+ }
+ } finally { fs.closeSync(fd); }
+ rest += decoder.end();
+ if (HUNK_LINE.test(rest)) keep.push(rest);
+ return { ok: true, out: keep.join('\n'), err: '' };
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+}
function gh(args: string[], cwd: string): { ok: boolean; out: string; err: string } {
const r = spawnSync('gh', args, { cwd, encoding: 'utf8', timeout: 120_000, maxBuffer: 16 * 1024 * 1024 });
if (r.error) return { ok: false, out: '', err: (r.error as NodeJS.ErrnoException).code === 'ENOENT' ? 'gh is not installed' : r.error.message };
@@ -151,7 +183,7 @@ function cmdClassify(rest: string[], json: boolean): number {
const mergeBase = git(['merge-base', baseRef, 'HEAD'], repoRoot);
if (!mergeBase.ok) return refuse('classify', 'REVIEW_SCOPE_RANGE', `cannot resolve the merge base of ${baseRef} and HEAD: ${mergeBase.err}`);
// Prefixes pinned as lib/pregate/checks/secrets.ts pins them: diff.mnemonicPrefix would print c/ and w/ and nothing would match a finding.
- const diff = git(['diff', ...DIFF_ARGS, mergeBase.out.trim()], repoRoot);
+ const diff = diffHunkLines(mergeBase.out.trim(), repoRoot);
if (!diff.ok) return refuse('classify', 'REVIEW_SCOPE_RANGE', `git diff ${mergeBase.out.trim()} failed: ${diff.err}`);
const untracked = git(['ls-files', '--others', '--exclude-standard'], repoRoot).out.split('\n').filter(Boolean);
const diffHunks = parseHunks(diff.out, untracked);
@@ -162,7 +194,7 @@ function cmdClassify(rest: string[], json: boolean): number {
if (!rangeBase) return refuse('classify', 'REVIEW_SCOPE_INPUT', '--range-base <sha> (HEAD at the start of the previous pass) is required from pass 2 on');
const ancestor = git(['merge-base', '--is-ancestor', rangeBase, 'HEAD'], repoRoot);
if (!ancestor.ok) return refuse('classify', 'REVIEW_SCOPE_RANGE', `--range-base ${rangeBase.slice(0, 12)} is not an ancestor of HEAD (rewritten history? start a full pass)`);
- const range = git(['diff', ...DIFF_ARGS, rangeBase], repoRoot);
+ const range = diffHunkLines(rangeBase, repoRoot);
if (!range.ok) return refuse('classify', 'REVIEW_SCOPE_RANGE', `git diff ${rangeBase.slice(0, 12)} failed: ${range.err}`);
rangeHunks = parseHunks(range.out, untracked);
}
diff --git a/changelog.d/review-plan-and-classify-on-big-results-prs.md b/changelog.d/review-plan-and-classify-on-big-results-prs.md
new file mode 100644
index 000000000..3b9982d7c
--- /dev/null
+++ b/changelog.d/review-plan-and-classify-on-big-results-prs.md
@@ -0,0 +1 @@
+- **/ship no longer stalls planning review on a branch that merged in thousands of data files, and `gstack-review-scope classify` reads a branch diff of any size.** `gstack-review-plan` checked each changed data or docs file for a leading `#!` with its own git call, so a fix range that took in another run's 11,749 trial files spent about 200 s per read of that range on a Capy machine (harness-evals #320 waited 25 to 58 minutes); it now finds those files in a few batched git calls. A plan run by itself now stops at the same 180 s limit `gstack-review-dispatch pass` gives it (`GSTACK_REVIEW_PLAN_TIMEOUT_MS` sets it), printing `REVIEW_PLAN_STOPPED` and no plan, and an unreadable fix range lists its first five problems and a count instead of every file. `classify` failed with an empty reason once the branch diff passed 64 MB; it now reads git's diff from a file, and a failure names git's error or the timeout.
diff --git a/docs/review-policy.md b/docs/review-policy.md
index 0c3f48420..182f955ae 100644
--- a/docs/review-policy.md
+++ b/docs/review-policy.md
@@ -305,9 +305,9 @@ costs one cheap pass. Each scan gets one 120-second deadline, set in millisecond
256 MB, is also `consumer_scan_failed`, and its detail says what stopped it and names
the 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 `gstack-review-dispatch pass` stops with
+pass that limit the plan, run by itself or under `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`
+runs (`GSTACK_REVIEW_PLAN_TIMEOUT_MS` sets the limit in milliseconds). Only `classifyDiff` applies the rule (`lib/review-collect.ts`
finds the consumers, `gstack-ship-preflight`'s `RUNTIME_LINES` reads the same
function); every path-only caller (the receipt's gate-scan decision, the Step 16
post-review route, /autoplan's docs-only scope) keeps data files code. A numeric claim
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 435f6ea84..276a13813 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -3761,15 +3761,15 @@ and 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
+**Meaning.** `gstack-review-plan` did not finish inside its limit, so it printed
+no plan, or `gstack-review-dispatch pass`, which runs it before it writes a
+manifest, stopped without dispatching a reader (exit 1 either way). 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
+**Fix.** Rerun 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.
@@ -6568,7 +6568,8 @@ record's start time and that each pass was finished with `via:"ship"`.
**Meaning.** `gstack-review-scope classify` could not read the diff it scopes
findings against: `origin/<base>` or `--range-base` does not resolve, or the
range base is not an ancestor of HEAD (history was rewritten since the previous
-pass).
+pass), or `git diff` over that range failed, and the line names git's error or
+the 120-second timeout.
**Fix.** Fetch `origin/<base>`, check `--range-base` against the pass heads in
the invocation record, and start a full pass (`--pass 1`) when the branch was
diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.ts
index 22f748e7d..0cdfbca0b 100644
--- a/lib/result-codes-release.ts
+++ b/lib/result-codes-release.ts
@@ -558,8 +558,8 @@ export const RELEASE_RESULT_CODES = {
},
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',
+ 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 the review stopped before any reader ran: gstack-review-dispatch pass writes no manifest, and a plan run by itself prints no plan',
+ fix: 'rerun 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',
diff --git a/lib/review-collect.ts b/lib/review-collect.ts
index 95c5545d7..65b43184c 100644
--- a/lib/review-collect.ts
+++ b/lib/review-collect.ts
@@ -119,13 +119,18 @@ 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. */
+/** How long one gstack-review-plan run may take, by itself or under gstack-review-dispatch pass (GSTACK_REVIEW_PLAN_TIMEOUT_MS overrides it); past it the run 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. */
export const CONSUMER_SCAN_OUTPUT_BYTES = 256 * 1024 * 1024;
+export function reviewPlanTimeoutMs(): number {
+ const v = Number(process.env.GSTACK_REVIEW_PLAN_TIMEOUT_MS);
+ return Number.isFinite(v) && v >= 1 ? Math.floor(v) : REVIEW_PLAN_TIMEOUT_MS;
+}
+
export function consumerScanTimeoutMs(): number {
const v = Number(process.env.GSTACK_CONSUMER_SCAN_TIMEOUT_MS);
return Number.isFinite(v) && v >= 1 ? Math.floor(v) : CONSUMER_SCAN_TIMEOUT_MS;
@@ -239,23 +244,49 @@ function drawingsAmong(perPath: readonly PathLines[], classRoot: string | readon
* The changed paths a docs, data or run-log rule could move out of code that are executables: the exec bit, a symlink, or text
* that starts with "#!" (GSTA-258 L7). `isExec` answers for one path and fails closed (true) when it cannot read it.
*/
+const movable = (e: PathLines, classRoot: string | readonly string[]) => (BINARY_DATA_PATH.test(e.path) && classifyPath(e.path, classRoot) === 'code') || dataCandidate(e.path, classRoot) || svgCandidate(e.path, classRoot) || classifyPath(e.path, classRoot) === 'docs';
function executablesAmong(perPath: readonly PathLines[], classRoot: string | readonly string[], isExec: (e: PathLines) => boolean): string[] {
- return perPath.filter(e => (BINARY_DATA_PATH.test(e.path) && classifyPath(e.path, classRoot) === 'code') || dataCandidate(e.path, classRoot) || svgCandidate(e.path, classRoot) || classifyPath(e.path, classRoot) === 'docs').filter(isExec).map(e => e.path).sort();
+ return perPath.filter(e => movable(e, classRoot)).filter(isExec).map(e => e.path).sort();
+}
+
+/**
+ * The paths among `paths` whose blob at `rev` holds a line that starts with "#!", a superset of those whose text starts with it:
+ * one git grep per CONSUMER_SCAN_PATHSPEC_BYTES of literal pathspecs, so the git calls follow the pathspec bytes and not the file
+ * count (a results PR's thousands of trial files cost one blob read each before). Null when git fails or a name does not decode.
+ */
+function shebangCandidates(root: string, rev: string, paths: readonly string[]): Set<string> | null {
+ const found = new Set<string>();
+ for (let i = 0; i < paths.length;) {
+ const chunk: string[] = [];
+ for (let bytes = 0; i < paths.length && (!chunk.length || bytes + paths[i]!.length <= CONSUMER_SCAN_PATHSPEC_BYTES); i++) { chunk.push(paths[i]!); bytes += paths[i]!.length; }
+ const r = git(root, ['--literal-pathspecs', 'grep', '-a', '-G', '-l', '-z', '--no-color', '-e', '^#!', rev, '--', ...chunk]);
+ if (r.status !== 0 && r.status !== 1) return null;
+ for (const f of r.out.split('\0')) {
+ if (!f) continue;
+ if (f.includes('\uFFFD')) return null;
+ found.add(f.slice(rev.length + 1));
+ }
+ }
+ return found;
}
/**
* The executables among the changed paths at `headSha`: tree mode 100755 or 120000 (a symlink, as collectLive sees it), or a text
- * blob whose first two bytes are "#!". A path the head tree lacks is a deletion, never an executable; an unreadable tree or blob counts as one.
+ * blob whose first two bytes are "#!" (read only for a blob shebangCandidates names, or for every one when it fails). A path the head
+ * tree lacks is a deletion, never an executable; an unreadable tree or blob counts as one.
*/
function executablesAt(root: string, headSha: string, perPath: readonly PathLines[], classRoot: readonly string[]): string[] {
const tree = git(root, ['ls-tree', '-r', '-z', headSha]);
const entries = new Map(tree.out.split('\0').flatMap(rec => { const m = /^(\d+) blob ([0-9a-f]+)\t(.*)$/s.exec(rec); return m ? [[m[3]!, { mode: m[1]!, sha: m[2]! }] as const] : []; }));
+ const plain = (e: PathLines) => { const mode = entries.get(e.path)?.mode; return !!mode && mode !== '100755' && mode !== '120000'; };
+ const shebang = tree.ok ? shebangCandidates(root, headSha, perPath.filter(e => !e.binary && plain(e) && movable(e, classRoot)).map(e => e.path)) : null;
return executablesAmong(perPath, classRoot, e => {
if (!tree.ok) return true;
const t = entries.get(e.path);
if (!t) return false;
if (t.mode === '100755' || t.mode === '120000') return true;
if (e.binary) return false;
+ if (shebang && !shebang.has(e.path)) return false;
const r = spawnSync('git', ['cat-file', 'blob', t.sha], { cwd: root, timeout: 30_000, maxBuffer: 2 });
const read = r.status === 0 || (r.error as NodeJS.ErrnoException | undefined)?.code === 'ENOBUFS';
return !read || (r.stdout ?? Buffer.alloc(0)).subarray(0, 2).toString('latin1') === '#!';
diff --git a/test/review-collect.test.ts b/test/review-collect.test.ts
index 915566768..56f4d6e24 100644
--- a/test/review-collect.test.ts
+++ b/test/review-collect.test.ts
@@ -360,3 +360,32 @@ describe('GST-544: the consumer scan reads only files that can match, under one
expect(CONSUMER_SCAN_TIMEOUT_MS).toBeLessThanOrEqual(Math.min(...limits) - 60_000);
});
});
+
+describe('executables at a commit cost a few git calls, not one per data file (GST-1855)', () => {
+ // Value: protects=a results PR's thousands of data files cost a few git calls in collectCommit, not one blob read each
+ // (harness-evals #320's fix range: 10,914 reads, about 200 s per collect); fails_when=executablesAt reads every candidate
+ // blob with its own git process again; seam=collectCommit with a git shim on PATH that logs each call
+ test.skipIf(process.platform === 'win32')('only blobs with a line starting "#!" are read, and a shebang still lists the path', () => {
+ const r = repo({});
+ const trials = Object.fromEntries(Array.from({ length: 200 }, (_, i) => [`results/t${i}/trial.json`, `{"i":${i}}\n`]));
+ const head = r.commit({ ...trials, 'results/run.log': 'ok\n#!/bin/sh quoted in a log\n', 'results/logs/prune': '#!/bin/sh\nrm -rf "$1"\n' });
+ const shim = fs.mkdtempSync(path.join(os.tmpdir(), 'review-collect-shim-'));
+ dirs.push(shim);
+ const log = path.join(shim, 'calls');
+ fs.writeFileSync(path.join(shim, 'git'), `#!/bin/sh\nprintf '%s\\n' "$*" >> '${log}'\nexec '${Bun.which('git')}' "$@"\n`, { mode: 0o755 });
+ const before = process.env.PATH;
+ process.env.PATH = `${shim}${path.delimiter}${before}`;
+ let c: ReturnType<typeof collectCommit>;
+ try { c = collectCommit(r.dir, r.baseSha, head); } finally { process.env.PATH = before; }
+ expect(c.executables).toEqual(['results/logs/prune']);
+ expect(fs.readFileSync(log, 'utf8').split('\n').filter(l => / cat-file blob /.test(` ${l}`)).length).toBe(2);
+ });
+ // Value: protects=a "#!" script under results/ stays code when the repository's git config sets grep.patternType=fixed;
+ // fails_when=the shebang scan's git grep takes its pattern type from config again; seam=collectCommit on a fixture repo
+ test('a fixed-string grep.patternType in the repository config still finds the shebang', () => {
+ const r = repo({});
+ r.git('config', 'grep.patternType', 'fixed');
+ const head = r.commit({ 'results/t.json': '{"i":1}\n', 'results/logs/prune': '#!/bin/sh\nrm -rf "$1"\n' });
+ expect(collectCommit(r.dir, r.baseSha, head).executables).toEqual(['results/logs/prune']);
+ });
+});
diff --git a/test/review-dispatch-plan-timeout.test.ts b/test/review-dispatch-plan-timeout.test.ts
index d880803b6..3af1a69fd 100644
--- a/test/review-dispatch-plan-timeout.test.ts
+++ b/test/review-dispatch-plan-timeout.test.ts
@@ -35,3 +35,28 @@ describe('pass names the plan step and its limit when the plan does not finish (
expect(fs.existsSync(path.join(out, 'pass-manifest.json'))).toBe(false);
}, 180_000);
});
+
+describe('gstack-review-plan run by itself stops at its own limit (GST-1855)', () => {
+ // Value: protects=a plan /ship runs directly ends at the limit in a named line with no plan, instead of holding the run for
+ // 25 to 58 minutes as harness-evals #320's did; fails_when=a standalone plan ignores GSTACK_REVIEW_PLAN_TIMEOUT_MS again;
+ // seam=gstack-review-plan with GSTACK_REVIEW_PLAN_TIMEOUT_MS=1; no_claim=the 180 s default
+ test('a plan past the limit prints REVIEW_PLAN_STOPPED with reason=timeout and no plan lines', () => {
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'rp-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 PLAN = path.join(import.meta.dir, '..', 'bin', 'gstack-review-plan');
+ const r = spawnSync(PLAN, ['--base', 'main'], { 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('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('REVIEW_PLAN:');
+ const ok = spawnSync(PLAN, ['--base', 'main'], { cwd: work, env, encoding: 'utf8', timeout: 120_000 });
+ expect(ok.status, ok.stderr).toBe(0);
+ expect(ok.stdout).toContain('REVIEW_PLAN:');
+ }, 180_000);
+});
diff --git a/test/review-scope.test.ts b/test/review-scope.test.ts
index b166db1e7..1bf9e53a5 100644
--- a/test/review-scope.test.ts
+++ b/test/review-scope.test.ts
@@ -524,3 +524,32 @@ describe('GSTA-167 part 4b: untested state-matrix cells map below the floor per
expect(fs.readFileSync(path.join(ROOT, 'review', 'specialists', 'state-machines.md'), 'utf8')).toContain('- **Untested cell (CRITICAL; this rule\'s High tier).**');
});
});
+
+describe('gstack-review-scope classify on a diff past 64 MB (GST-1855)', () => {
+ // Value: protects=a results PR whose branch diff passes 64 MB still gets its findings placed; fails_when=classify reads git diff
+ // through a bounded pipe again and refuses harness-evals #320's 67 MB diff with an empty reason; seam=gstack-review-scope classify
+ test('classify places findings in a 70 MB branch diff', () => {
+ const repo = fixture();
+ const src = path.join(repo.work, 'src');
+ fs.mkdirSync(src, { recursive: true });
+ fs.writeFileSync(path.join(src, 'auth.ts'), Array.from({ length: 30 }, (_, i) => `line ${i + 1}`).join('\n') + '\n');
+ repo.git('add', '.'); repo.git('commit', '-qm', 'seed'); repo.git('push', '-q', 'origin', 'main');
+ repo.git('checkout', '-qb', 'feat');
+ fs.mkdirSync(path.join(repo.work, 'results'));
+ fs.writeFileSync(path.join(repo.work, 'results', 'trials.jsonl'), `{"trial":"${'x'.repeat(1010)}"}\n`.repeat(70_000));
+ const lines = fs.readFileSync(path.join(src, 'auth.ts'), 'utf8').split('\n');
+ lines[9] = 'line 10 changed';
+ fs.writeFileSync(path.join(src, 'auth.ts'), lines.join('\n'));
+ repo.git('add', '.'); repo.git('commit', '-qm', 'results and a fix');
+ const f = path.join(repo.root, 'findings.json');
+ fs.writeFileSync(f, JSON.stringify([
+ { fingerprint: 'src/auth.ts:10:logic', path: 'src/auth.ts', line: 10, severity: 'CRITICAL', category: 'logic', summary: 'wrong' },
+ { fingerprint: 'src/auth.ts:25:logic', path: 'src/auth.ts', line: 25, severity: 'CRITICAL', category: 'logic', summary: 'neighbour' },
+ { fingerprint: 'results/trials.jsonl:3:data', path: 'results/trials.jsonl', line: 3, severity: 'INFORMATIONAL', category: 'data', summary: 'row' },
+ ]));
+ const p1 = runBin(repo, 'gstack-review-scope', ['classify', '--base', 'main', '--pass', '1', '--findings', f, '--json']);
+ expect(p1.status, p1.err).toBe(EXIT.ok);
+ expect(JSON.parse(p1.out).findings.map((x: ScopedFinding) => `${x.fingerprint}=${x.locus}`)).toEqual([
+ 'src/auth.ts:10:logic=diff', 'src/auth.ts:25:logic=outside', 'results/trials.jsonl:3:data=diff']);
+ }, 120_000);
+});