mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-25 09:31:43 +01:00
/ship's review plan no longer runs out of time on results repositories whose trial files name many data files. On harness-evals #551 the scan now takes about 40 s instead of running past its limit. Why: harness-evals #551 is blocked on it. git's `grep -o` with about 80 file names took 220 s on one 16 MB trials file, and the plan timed out at 1,703 s. Nothing to do. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=testing Review-Finding: p1/red-team#1 reader=red-team Review-Finding: v1/outside-voice#1 reader=outside-voice
518 lines
35 KiB
TypeScript
518 lines
35 KiB
TypeScript
/**
|
|
* review-collect — the git reads behind a review depth (docs/review-policy.md#review-depth),
|
|
* kept out of lib/review-depth.ts so the policy stays pure. collectCommit reads git
|
|
* objects only (a range between two commits, from any checkout, dirty or not);
|
|
* collectLive reads the working tree as /ship reviews it (committed, tracked
|
|
* uncommitted edits and untracked files). Both return a ClassInput with per-path
|
|
* line counts, the base commit's generated-output registry and collector errors;
|
|
* the caller adds the gate-scan result.
|
|
*/
|
|
import { spawnSync } from './spawn-sync';
|
|
import * as fs from 'node:fs';
|
|
import * as path from 'node:path';
|
|
import { resolveBase, type ResolvedBase } from './gate-diff/git';
|
|
import { GENERATED_PATH, parseRegistry } from './regen';
|
|
import { RESULT_CODES } from './result-codes';
|
|
import { BINARY_DATA_PATH, classifyPath, dataCandidate, svgCandidate, svgDrawing, type ClassInput, type DepthError, type PathLines, type RegistryInfo } from './review-depth';
|
|
|
|
export interface Collected extends ClassInput {
|
|
perPath: PathLines[];
|
|
registry: RegistryInfo;
|
|
errors: DepthError[];
|
|
deleted: string[];
|
|
stampOnly: string[];
|
|
/** Paths the diff creates (untracked files included): their added lines are the whole file. */
|
|
created: string[];
|
|
/** Added lines per path, for scanNumbers. */
|
|
added: Record<string, string[]>;
|
|
/** Deleted lines per path, for the targeted classes (lib/review-targeted.ts). */
|
|
removed: Record<string, string[]>;
|
|
diffLines: number;
|
|
mergeBase: string | null;
|
|
untracked: string[];
|
|
consumed: string[] | 'all';
|
|
drawings: string[];
|
|
executables: string[];
|
|
/** collectLive only: the ref resolveBase read for the base name (GST-1036), null when nothing resolved. */
|
|
base?: ResolvedBase | null;
|
|
}
|
|
|
|
function git(root: string, args: string[]): { ok: boolean; status: number | null; out: string; err: string } {
|
|
const r = spawnSync('git', ['-c', 'core.quotePath=false', ...args], { cwd: root, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 });
|
|
return { ok: r.status === 0, status: r.status, out: r.stdout ?? '', err: (r.stderr ?? '').trim() };
|
|
}
|
|
/** git with what is left of an overall deadline (epoch ms) as its timeout, for a read that may take minutes. */
|
|
function gitUntil(root: string, args: string[], deadline: number): { status: number | null; out: string; err: string; timedOut: boolean } {
|
|
const left = deadline - Date.now();
|
|
if (left <= 0) return { status: null, out: '', err: '', timedOut: true };
|
|
const r = spawnSync('git', ['-c', 'core.quotePath=false', ...args], { cwd: root, encoding: 'utf8', timeout: left, maxBuffer: 256 * 1024 * 1024 });
|
|
const status = r.status ?? null;
|
|
return { status, out: r.stdout ?? '', err: (r.stderr ?? '').trim() || ((r.error as NodeJS.ErrnoException | undefined)?.code ?? ''), timedOut: status === null && Date.now() >= deadline };
|
|
}
|
|
const scratch = (p: string) => p.startsWith('.gstack/tmp/');
|
|
const oneLine = (s: string) => s.replace(/[\0-\x1f]+/g, ' ').trim().slice(0, 200);
|
|
const unavailable = (input: string, detail: string): RegistryInfo => ({ sha: null, outputs: [], error: { code: 'registry_unavailable', detail: oneLine(detail), input, repair: 'fetch the base branch (git fetch origin <base>) so its commit and registry resolve' } });
|
|
|
|
/** The registry as committed at `sha`: outputs of entries with a command (a `command: null` entry never excludes); a missing file is an empty registry. */
|
|
export function loadRegistryAt(root: string, sha: string): RegistryInfo {
|
|
const commit = git(root, ['rev-parse', '--verify', '--quiet', `${sha}^{commit}`]);
|
|
if (!commit.ok) return unavailable(`${sha}:${GENERATED_PATH}`, `${sha} is not a commit in this repository`);
|
|
const resolved = commit.out.trim();
|
|
const input = `${resolved.slice(0, 12)}:${GENERATED_PATH}`;
|
|
if (!git(root, ['cat-file', '-e', `${resolved}:${GENERATED_PATH}`]).ok) return { sha: resolved, outputs: [] };
|
|
const show = git(root, ['show', `${resolved}:${GENERATED_PATH}`]);
|
|
if (!show.ok) return unavailable(input, show.err || 'git show failed');
|
|
const { registry, errors } = parseRegistry(show.out);
|
|
const e = errors[0];
|
|
if (e) return { sha: resolved, outputs: [], error: { code: 'registry_invalid', detail: oneLine(`${e.path || GENERATED_PATH}: ${e.message}`), input, repair: RESULT_CODES[e.code].fix, result: e.code } };
|
|
return { sha: resolved, outputs: registry.entries.filter(x => x.command !== null).flatMap(x => x.outputs) };
|
|
}
|
|
|
|
const C_ESCAPES: Record<string, number> = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 };
|
|
/**
|
|
* A patch header's path (the text after "--- " or "+++ ") without its a/ or b/ prefix. core.quotePath=false stops git
|
|
* escaping non-ASCII bytes, but a name holding a quote, a backslash or a control byte is still C-quoted in patch headers
|
|
* (-z does not change patch output), so a quoted name is decoded byte by byte: octal escapes, \" \\ \t and the rest. git
|
|
* adds a tab after an unquoted name holding a space (GST-1451).
|
|
*/
|
|
function headerPath(rest: string): string {
|
|
if (!rest.startsWith('"')) return rest.replace(/\t$/, '').slice(2);
|
|
const src = Buffer.from(rest, 'utf8');
|
|
const out: number[] = [];
|
|
for (let k = 1; k < src.length && src[k] !== 0x22; k++) {
|
|
if (src[k] !== 0x5c) { out.push(src[k]!); continue; }
|
|
const c = String.fromCharCode(src[++k] ?? 0);
|
|
if (/[0-7]/.test(c)) { out.push(parseInt(src.subarray(k, k + 3).toString('latin1'), 8) & 0xff); k += 2; }
|
|
else out.push(C_ESCAPES[c] ?? src[k]!);
|
|
}
|
|
return Buffer.from(out).toString('utf8').slice(2);
|
|
}
|
|
|
|
/** Numstat, deletions and the -U0 patch for `range` (`[mergeBase, head]` or `[mergeBase]` for the working tree). */
|
|
function readDiff(root: string, range: string[], errors: DepthError[]): Pick<Collected, 'perPath' | 'deleted' | 'stampOnly' | 'created' | 'added' | 'removed'> {
|
|
const numstat = git(root, ['diff', '--numstat', '-z', '--no-renames', ...range]);
|
|
const status = git(root, ['diff', '--name-status', '-z', '--no-renames', '--diff-filter=D', ...range]);
|
|
const patch = git(root, ['diff', '-U0', '--no-color', '--no-ext-diff', '--no-renames', '--src-prefix=a/', '--dst-prefix=b/', ...range]);
|
|
const empty = { perPath: [], deleted: [], stampOnly: [], created: [], added: {}, removed: {} };
|
|
for (const [r, what] of [[numstat, '--numstat'], [status, '--name-status'], [patch, '-U0']] as const) {
|
|
if (!r.ok) { errors.push({ code: 'numstat_failed', detail: oneLine(r.err || 'git diff failed'), input: `git diff ${what} ${range.join(' ')}`, repair: 'check that both commits exist locally (git fetch origin <base>) and rerun' }); return empty; }
|
|
}
|
|
const perPath: PathLines[] = [];
|
|
for (const rec of numstat.out.split('\0').filter(Boolean)) {
|
|
const [a, d, ...rest] = rec.split('\t');
|
|
const p = rest.join('\t');
|
|
if (!scratch(p)) perPath.push({ path: p, lines: (Number(a) || 0) + (Number(d) || 0), binary: a === '-' && d === '-' });
|
|
}
|
|
const statusParts = status.out.split('\0');
|
|
const deleted = statusParts.flatMap((s, k) => (s === 'D' && statusParts[k + 1] ? [statusParts[k + 1]!] : [])).filter(p => !scratch(p));
|
|
const added: Record<string, string[]> = {};
|
|
const removed: Record<string, string[]> = {};
|
|
const changed: Record<string, string[]> = {};
|
|
const created: string[] = [];
|
|
let cur = '';
|
|
let minus = '';
|
|
let inHunk = false;
|
|
for (const line of patch.out.split('\n')) {
|
|
if (line.startsWith('diff --git ')) { inHunk = false; cur = ''; minus = ''; continue; }
|
|
if (!inHunk) {
|
|
if (line.startsWith('--- ')) minus = line === '--- /dev/null' ? '' : headerPath(line.slice(4));
|
|
else if (line.startsWith('+++ ')) {
|
|
cur = line === '+++ /dev/null' ? minus : headerPath(line.slice(4));
|
|
if (cur && !scratch(cur)) { added[cur] ??= []; if (!minus) created.push(cur); }
|
|
}
|
|
else if (line.startsWith('@@')) inHunk = true;
|
|
continue;
|
|
}
|
|
if (!cur || scratch(cur) || line.startsWith('@@')) continue;
|
|
if (line[0] === '+') (added[cur] ??= []).push(line.slice(1));
|
|
if (line[0] === '-') (removed[cur] ??= []).push(line.slice(1));
|
|
if (line[0] === '+' || line[0] === '-') (changed[cur] ??= []).push(line);
|
|
}
|
|
const stampOnly = perPath.map(e => e.path).filter(p => p.endsWith('package.json') && !!changed[p]?.length && changed[p]!.every(l => /^[+-]\s*"version"\s*:\s*"[^"]*"\s*,?\s*$/.test(l)));
|
|
return { perPath, deleted, stampOnly, created, added, removed };
|
|
}
|
|
|
|
/** More data candidates than this keep every data file code: the consumer scan is not run. */
|
|
export const CONSUMER_SCAN_CAP = 2000;
|
|
/** How many data files deep a chain of data naming data is followed (a manifest naming a data file) before the rest count as consumed. */
|
|
export const CONSUMER_SCAN_DEPTH = 4;
|
|
/**
|
|
* One consumer scan's whole budget, every git grep in it (GSTACK_CONSUMER_SCAN_TIMEOUT_MS overrides it); past it the scan fails
|
|
* closed. One scan stays a minute under the default 180 s (REVIEW_PLAN_TIMEOUT_MS) every caller gives all of gstack-review-plan;
|
|
* 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 one gstack-review-plan run may take, by itself or under gstack-review-dispatch pass and render or gstack-ship-preflight (GSTACK_REVIEW_PLAN_TIMEOUT_MS overrides it through reviewPlanTimeoutMs, which every caller reads); 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;
|
|
/** Blob bytes one `git cat-file --batch` call reads for the consumer scan, so a commit's hit files are held a batch at a time. */
|
|
const CONSUMER_SCAN_BLOB_BATCH_BYTES = 64 * 1024 * 1024;
|
|
|
|
/** A whole number of at least 1 from the environment variable `name`, rounded down; anything else (unset, empty, zero, negative, not a number) is `fallback`. */
|
|
function positiveEnv(name: string, fallback: number): number {
|
|
const v = Number(process.env[name]);
|
|
return Number.isFinite(v) && v >= 1 ? Math.floor(v) : fallback;
|
|
}
|
|
|
|
export const reviewPlanTimeoutMs = (): number => positiveEnv('GSTACK_REVIEW_PLAN_TIMEOUT_MS', REVIEW_PLAN_TIMEOUT_MS);
|
|
export const consumerScanTimeoutMs = (): number => positiveEnv('GSTACK_CONSUMER_SCAN_TIMEOUT_MS', CONSUMER_SCAN_TIMEOUT_MS);
|
|
/** CONSUMER_SCAN_CAP, or GSTACK_REVIEW_CONSUMER_SCAN_CAP: more data candidates than this skip the scan and count every one as consumed (code). */
|
|
export const consumerScanCap = (): number => positiveEnv('GSTACK_REVIEW_CONSUMER_SCAN_CAP', CONSUMER_SCAN_CAP);
|
|
|
|
export type GrepFailure = { timedOut: boolean; status: number | null; err: string };
|
|
/** What one scan has listed at a rev ('' for the working tree): the extensions its -l passes covered and the kept files holding one, as scratch-index entries (`blob`: read from its object; `disk`: from the working tree) or names left to git (`git`). */
|
|
export type ScanMemo = { exts: Set<string>; blob: string[]; disk: string[]; git: string[]; listing?: string[] };
|
|
|
|
type Hit = { name: string; sha?: string };
|
|
|
|
/** One `git grep -l` of `patterns` over a scratch index holding `entries` (`--cached` reads their blobs, otherwise the working tree), kept under the git dir as patch-id diffs are, so an unwritable TMPDIR cannot fail the scan; a spot it cannot write is a named scan failure. */
|
|
function grepIndex(root: string, entries: readonly string[], each: readonly string[], cached: boolean, deadline: number): string[] | GrepFailure {
|
|
if (!entries.length) return [];
|
|
const at = path.resolve(root, gitUntil(root, ['rev-parse', '--git-path', 'gstack-consumers'], deadline).out.trim() || '.git/gstack-consumers');
|
|
let dir: string;
|
|
try { fs.mkdirSync(at, { recursive: true }); dir = fs.mkdtempSync(path.join(at, 'scan-')); } catch (e) { return { status: null, err: `cannot create a scratch index under ${at} (${(e as Error).message.split('\n')[0]}); make that directory writable`, timedOut: false }; }
|
|
try {
|
|
const env = { ...process.env, GIT_INDEX_FILE: path.join(dir, 'index') };
|
|
const run = (args: string[], input?: string) => spawnSync('git', args, { cwd: root, env, input, encoding: 'utf8', timeout: Math.max(1, deadline - Date.now()), maxBuffer: CONSUMER_SCAN_OUTPUT_BYTES });
|
|
const failed = (r: ReturnType<typeof run>): GrepFailure => ({ status: r.status ?? null, err: (r.stderr ?? '').trim() || ((r.error as NodeJS.ErrnoException | undefined)?.code ?? ''), timedOut: r.status === null && Date.now() >= deadline });
|
|
const index = run(['update-index', '-z', '--index-info'], entries.join('\0') + '\0');
|
|
if (index.status !== 0) return failed(index);
|
|
const hit = run(['-c', 'core.quotePath=false', 'grep', ...(cached ? ['--cached'] : []), '-I', '-F', '-l', '-z', '--no-color', ...each]);
|
|
if (hit.status !== 0 && hit.status !== 1) return failed(hit);
|
|
return hit.stdout.split('\0').filter(Boolean);
|
|
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
|
}
|
|
|
|
/**
|
|
* The lines `git grep -I -F -o --null` prints for `patterns` at `rev` ('' is the working tree with untracked files), for
|
|
* the files `keep` accepts, in some order. git's own -o retries every pattern after each match, so its time grew with patterns
|
|
* times matches per line (HARN-98: 80 basenames over one 16 MB trials file of harness-evals#551 took 220 s, and the plan timed out
|
|
* at 1,703 s). Every pattern holds its own extension, so one `-l` pass for the extensions per scan (`memo`) lists every file
|
|
* that can match; the kept ones go into scratch indexes that `git grep -l` reads per pattern list without walking the whole
|
|
* tree, and only the files that hold a pattern are read, one at a time from disk or in `git cat-file --batch` calls of at most
|
|
* CONSUMER_SCAN_BLOB_BATCH_BYTES (a file larger than the output cap goes to git's -o by pathspec instead), and their matches listed here the way git's -o picks them: the earliest start, the longest pattern there,
|
|
* then on from its end. In the working tree every tracked file is read from disk, as `git grep --untracked` reads it even when
|
|
* it is skip-worktree or assume-unchanged, and an untracked, unmerged or non-regular file goes back to git by pathspec under --literal-pathspecs (an inherited
|
|
* GIT_GLOB_PATHSPECS makes git refuse, which fails closed), as does any hit that is not a plain file when read.
|
|
* CONSUMER_SCAN_OUTPUT_BYTES of lines in all; past it the scan fails closed. A listed name that is not valid UTF-8, or a pattern
|
|
* holding a newline (several patterns to git), sends the whole tree through one -o grep, as the scan did before GST-544. Each
|
|
* call gets what is left of `deadline` (epoch ms).
|
|
*/
|
|
export function grepConsumers(root: string, patterns: readonly string[], rev: string, keep: (file: string) => boolean, deadline: number, chunkBytes = CONSUMER_SCAN_PATHSPEC_BYTES, outputBytes = CONSUMER_SCAN_OUTPUT_BYTES, memo: Map<string, ScanMemo> = new Map()): string[] | GrepFailure {
|
|
const where = rev ? [rev, '--'] : ['--untracked', '--'];
|
|
const each = patterns.flatMap(b => ['-e', b]);
|
|
const flags = ['--literal-pathspecs', 'grep', '-I', '-F', '-o', '--null', '--no-line-number', '--no-column', '--no-color', ...each, ...where];
|
|
const whole = () => { const w = gitUntil(root, flags, deadline); return w.status !== 0 && w.status !== 1 ? w : w.out.split('\n'); };
|
|
if (patterns.some(b => b.includes('\n'))) return whole();
|
|
const seen = memo.get(rev) ?? memo.set(rev, { exts: new Set(), blob: [], disk: [], git: [] }).get(rev)!;
|
|
const exts = [...new Set(patterns.map(b => b.slice(b.lastIndexOf('.'))))].filter(e => !seen.exts.has(e));
|
|
if (exts.length) {
|
|
const listed = gitUntil(root, ['grep', '-I', '-F', '-l', '-z', '--no-color', ...exts.flatMap(e => ['-e', e]), ...where], deadline);
|
|
if (listed.status !== 0 && listed.status !== 1) return listed;
|
|
const names = new Set(listed.out.split('\0').filter(Boolean).map(f => (rev ? f.slice(rev.length + 1) : f)));
|
|
if ([...names].some(f => f.includes('\uFFFD'))) return whole();
|
|
if (!seen.listing) {
|
|
const ls = gitUntil(root, rev ? ['ls-tree', '-r', '-z', '--full-tree', rev] : ['ls-files', '-s', '-z'], deadline);
|
|
if (ls.status !== 0) return ls;
|
|
seen.listing = ls.out.split('\0').filter(Boolean);
|
|
}
|
|
const have = new Set([...seen.blob, ...seen.disk].map(e => e.slice(e.indexOf('\t') + 1)).concat(seen.git));
|
|
const tracked = new Set<string>();
|
|
for (const e of seen.listing) {
|
|
const tab = e.indexOf('\t');
|
|
const file = e.slice(tab + 1);
|
|
if (tab < 0 || !names.has(file)) continue;
|
|
tracked.add(file);
|
|
if (have.has(file) || !keep(file)) continue;
|
|
have.add(file);
|
|
const meta = e.slice(0, tab).split(' ');
|
|
if (rev) { if (meta[1] === 'blob') seen.blob.push(`${meta[0]} ${meta[2]}\t${file}`); continue; }
|
|
const [mode, sha, stage] = meta;
|
|
if (stage !== '0' || (mode !== '100644' && mode !== '100755')) seen.git.push(file);
|
|
else seen.disk.push(`${mode} ${sha} ${stage}\t${file}`);
|
|
}
|
|
if (!rev) for (const file of names) if (!tracked.has(file) && !have.has(file) && keep(file)) { have.add(file); seen.git.push(file); }
|
|
for (const e of exts) seen.exts.add(e);
|
|
}
|
|
const found: Hit[] = [];
|
|
const shas = new Map(seen.blob.map(e => [e.slice(e.indexOf('\t') + 1), e.slice(e.indexOf(' ') + 1).split(/[ \t]/)[0]!]));
|
|
for (const [entries, cached] of [[seen.blob, true], [seen.disk, false]] as const) {
|
|
const hits = grepIndex(root, entries, each, cached, deadline);
|
|
if (!Array.isArray(hits)) return hits;
|
|
for (const name of hits) found.push(cached ? { name, sha: shas.get(name) } : { name });
|
|
}
|
|
for (let i = 0; i < seen.git.length;) {
|
|
const chunk: string[] = [];
|
|
for (let bytes = 0; i < seen.git.length && (!chunk.length || bytes + seen.git[i]!.length <= chunkBytes); i++) { chunk.push(seen.git[i]!); bytes += seen.git[i]!.length; }
|
|
const hit = gitUntil(root, ['--literal-pathspecs', 'grep', '-I', '-F', '-l', '-z', '--no-color', ...each, ...where, ...chunk], deadline);
|
|
if (hit.status !== 0 && hit.status !== 1) return hit;
|
|
for (const name of hit.out.split('\0').filter(Boolean)) found.push({ name: rev ? name.slice(rev.length + 1) : name });
|
|
}
|
|
const needles = patterns.map(b => Buffer.from(b));
|
|
const lines: string[] = [];
|
|
let total = 0;
|
|
const enobufs: GrepFailure = { status: null, err: 'ENOBUFS', timedOut: false };
|
|
for (let i = 0; i < found.length;) {
|
|
const chunk: Hit[] = [];
|
|
for (let bytes = 0; i < found.length; i++) {
|
|
if (chunk.length && bytes + found[i]!.name.length > chunkBytes) break;
|
|
chunk.push(found[i]!);
|
|
bytes += found[i]!.name.length;
|
|
}
|
|
let over = false;
|
|
const add = (line: string) => { total += Buffer.byteLength(line) + 1; if (total > outputBytes) over = true; else lines.push(line); return !over; };
|
|
const unread: string[] = [];
|
|
const blobs: Hit[] = [];
|
|
const match = (body: Buffer, h: Hit) => {
|
|
const at: Array<[number, number]> = [];
|
|
needles.forEach((needle, k) => { for (let x = body.indexOf(needle); x >= 0; x = body.indexOf(needle, x + 1)) at.push([x, k]); });
|
|
at.sort((x, y) => x[0] - y[0] || needles[y[1]]!.length - needles[x[1]]!.length);
|
|
const shown = rev ? `${rev}:${h.name}` : h.name;
|
|
for (let cur = 0, j = 0; j < at.length; j++) if (at[j]![0] >= cur) { if (!add(`${shown}\0${patterns[at[j]![1]]}`)) return; cur = at[j]![0] + needles[at[j]![1]]!.length; }
|
|
};
|
|
for (const h of chunk) {
|
|
if (rev || h.sha) { blobs.push(h); continue; }
|
|
let body: Buffer | null = null;
|
|
try { const st = fs.lstatSync(path.join(root, h.name)); if (st.isFile() && st.size <= outputBytes) body = fs.readFileSync(path.join(root, h.name)); } catch { body = null; }
|
|
if (body) match(body, h); else unread.push(h.name);
|
|
if (over) return enobufs;
|
|
}
|
|
if (blobs.length) {
|
|
const want = blobs.map(h => h.sha ?? `${rev}:${h.name}`);
|
|
if (want.some(w => !w || w.includes('\n'))) return whole();
|
|
const cat = (mode: string, specs: string[], maxBuffer: number) => spawnSync('git', ['cat-file', mode], { cwd: root, input: specs.join('\n') + '\n', timeout: Math.max(1, deadline - Date.now()), maxBuffer });
|
|
const failed = (c: ReturnType<typeof cat>): GrepFailure => ({ status: c.status ?? null, err: (c.stderr?.toString() ?? '').trim() || ((c.error as NodeJS.ErrnoException | undefined)?.code ?? ''), timedOut: c.status === null && Date.now() >= deadline });
|
|
const check = cat('--batch-check', want, CONSUMER_SCAN_OUTPUT_BYTES);
|
|
if (check.status !== 0 || !Buffer.isBuffer(check.stdout)) return failed(check);
|
|
const sizes = check.stdout.toString().split('\n').slice(0, want.length).map(l => l.split(' '));
|
|
const bad = sizes.findIndex(s => s[1] !== 'blob' || !/^\d+$/.test(s[2] ?? ''));
|
|
if (sizes.length < want.length || bad >= 0) return { status: null, err: `git cat-file --batch-check could not read ${blobs[bad < 0 ? sizes.length : bad]!.name}`, timedOut: false };
|
|
const size = (k: number) => Number(sizes[k]![2]);
|
|
for (let k = 0; k < blobs.length;) {
|
|
if (size(k) > outputBytes) { unread.push(blobs[k++]!.name); continue; }
|
|
const batch: number[] = [];
|
|
for (let bytes = 0; k < blobs.length && size(k) <= outputBytes && (!batch.length || bytes + size(k) <= Math.min(outputBytes, CONSUMER_SCAN_BLOB_BATCH_BYTES)); k++) { batch.push(k); bytes += size(k); }
|
|
const b = cat('--batch', batch.map(n => want[n]!), batch.reduce((s, n) => s + size(n) + 128, 0));
|
|
if (b.status !== 0 || !Buffer.isBuffer(b.stdout)) return failed(b);
|
|
for (let at = 0, j = 0; j < batch.length; j++) {
|
|
const nl = b.stdout.indexOf(10, at);
|
|
const [, type, got] = b.stdout.subarray(at, nl < 0 ? at : nl).toString().split(' ');
|
|
if (nl < 0 || type !== 'blob' || got !== String(size(batch[j]!))) return { status: null, err: `git cat-file --batch could not read ${blobs[batch[j]!]!.name}`, timedOut: false };
|
|
match(b.stdout.subarray(nl + 1, nl + 1 + size(batch[j]!)), blobs[batch[j]!]!);
|
|
if (over) return enobufs;
|
|
at = nl + 2 + size(batch[j]!);
|
|
}
|
|
}
|
|
}
|
|
if (unread.length) {
|
|
const r = gitUntil(root, [...flags, ...unread], deadline);
|
|
if (r.status !== 0 && r.status !== 1) return r;
|
|
for (const line of r.out.split('\n')) if (line && !add(line)) break;
|
|
}
|
|
if (Date.now() >= deadline) return { status: null, err: '', timedOut: true };
|
|
if (over) return enobufs;
|
|
}
|
|
return lines;
|
|
}
|
|
|
|
/**
|
|
* The data candidates (lib/review-depth.ts dataCandidate) among the changed and deleted paths that a non-docs file names
|
|
* by basename, at each rev and, with `live`, in the working tree with untracked files. The merge base is one of the revs,
|
|
* so a consumer the change removes still counts. A data file named only by another data file is consumed when that one
|
|
* is, followed CONSUMER_SCAN_DEPTH files deep; anything still open after that counts as consumed. A git grep failure, or
|
|
* a scan that outlives `timeoutMs`, is a collector error, which fails the depth closed.
|
|
*/
|
|
export function scanConsumers(root: string, paths: readonly string[], revs: readonly string[], live: boolean, classRoot: string | readonly string[], errors: DepthError[], timeoutMs = consumerScanTimeoutMs()): string[] | 'all' {
|
|
const candidates = [...new Set(paths)].filter(p => dataCandidate(p, classRoot) || svgCandidate(p, classRoot)).sort();
|
|
if (candidates.length > consumerScanCap()) return 'all';
|
|
const deadline = Date.now() + timeoutMs;
|
|
const base = (p: string) => p.slice(p.lastIndexOf('/') + 1);
|
|
const read = (file: string) => !scratch(file) && classifyPath(file, classRoot) !== 'docs';
|
|
const named = new Map<string, Set<string>>();
|
|
const direct = new Set<string>();
|
|
const probed = new Set<string>();
|
|
const readable = new Map<string, boolean>();
|
|
const memo = new Map<string, ScanMemo>();
|
|
let probe = candidates;
|
|
for (let depth = 0; probe.length && depth < CONSUMER_SCAN_DEPTH; depth++) {
|
|
const patterns = [...new Set(probe.map(base))];
|
|
const next = new Set<string>();
|
|
const probing = new Set(probe);
|
|
const credits = new Map<string, string[]>();
|
|
for (const at of [...revs, ...(live ? [''] : [])]) {
|
|
const r = grepConsumers(root, patterns, at, read, deadline, CONSUMER_SCAN_PATHSPEC_BYTES, CONSUMER_SCAN_OUTPUT_BYTES, memo);
|
|
if (!Array.isArray(r)) {
|
|
const detail = r.timedOut ? `timed out: the scan's ${timeoutMs / 1000} s deadline passed (GSTACK_CONSUMER_SCAN_TIMEOUT_MS)` : `git grep exited ${r.status}${r.err ? `: ${r.err}` : ''} (deadline ${timeoutMs / 1000} s)`;
|
|
errors.push({ code: 'consumer_scan_failed', detail: oneLine(detail), input: `git grep -F <data basenames> ${at || '--untracked'}`, repair: r.timedOut ? 'raise GSTACK_CONSUMER_SCAN_TIMEOUT_MS (milliseconds) or run the git grep by hand to see why it is slow' : 'run the git grep by hand and fix what git reports' });
|
|
return 'all';
|
|
}
|
|
for (const line of r) {
|
|
const parts = line.split('\0');
|
|
const where = 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 (!(readable.get(file) ?? readable.set(file, read(file)).get(file))) continue;
|
|
const credited = credits.get(match) ?? credits.set(match, probe.filter(p => match.includes(base(p)))).get(match)!;
|
|
if (!credited.length) continue;
|
|
const data = dataCandidate(file, classRoot);
|
|
for (const p of credited) {
|
|
if (file === p) continue;
|
|
if (!data) { direct.add(p); continue; }
|
|
(named.get(file) ?? named.set(file, new Set()).get(file)!).add(p);
|
|
if (!probed.has(file) && !probing.has(file)) next.add(file);
|
|
}
|
|
}
|
|
}
|
|
for (const p of probe) probed.add(p);
|
|
probe = [...next];
|
|
}
|
|
const consumed = new Set([...direct, ...probe]);
|
|
for (let grew = true; grew;) {
|
|
grew = false;
|
|
for (const [file, targets] of named) if (consumed.has(file)) for (const p of targets) if (!consumed.has(p)) { consumed.add(p); grew = true; }
|
|
}
|
|
return candidates.filter(p => consumed.has(p));
|
|
}
|
|
|
|
/** The largest SVG whose text is read for the drawing check; a larger one stays code. */
|
|
export const DRAWING_READ_CAP = 8 * 1024 * 1024;
|
|
|
|
/** The changed SVG candidates whose whole text, read by `read` (null when it cannot be read), is a drawing (lib/review-depth.ts svgDrawing). */
|
|
function drawingsAmong(perPath: readonly PathLines[], classRoot: string | readonly string[], read: (p: string) => Buffer | null): string[] {
|
|
return perPath.filter(e => !e.binary && svgCandidate(e.path, classRoot)).map(e => e.path).filter(p => {
|
|
const buf = read(p);
|
|
return !!buf && buf.length <= DRAWING_READ_CAP && !buf.includes(0) && svgDrawing(buf.toString('utf8'));
|
|
}).sort();
|
|
}
|
|
|
|
/**
|
|
* 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 => 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 "#!" (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') === '#!';
|
|
});
|
|
}
|
|
|
|
function result(diff: ReturnType<typeof readDiff>, extra: Pick<Collected, 'root' | 'registry' | 'errors' | 'mergeBase' | 'untracked' | 'consumed'> & { drawings?: string[]; executables?: string[] }): Collected {
|
|
const paths = diff.perPath.map(e => e.path).sort();
|
|
return { ...diff, drawings: [], executables: [], ...extra, paths, gateTagged: null, diffLines: diff.perPath.reduce((n, e) => n + e.lines, 0) };
|
|
}
|
|
|
|
/** The range `baseSha`...`headSha` from git objects alone; the registry is the base commit's, never the head's. */
|
|
export function collectCommit(root: string, baseSha: string, headSha: string): Collected {
|
|
const errors: DepthError[] = [];
|
|
const registry = loadRegistryAt(root, baseSha);
|
|
const mb = git(root, ['merge-base', baseSha, headSha]);
|
|
if (!mb.ok) {
|
|
errors.push({ code: 'numstat_failed', detail: oneLine(mb.err || 'no merge base'), input: `git merge-base ${baseSha} ${headSha}`, repair: 'check that both commits exist locally (git fetch origin <base>) and rerun' });
|
|
return result({ perPath: [], deleted: [], stampOnly: [], created: [], added: {}, removed: {} }, { root: [], registry, errors, mergeBase: null, untracked: [], consumed: 'all' });
|
|
}
|
|
const mergeBase = mb.out.trim();
|
|
const diff = readDiff(root, [mergeBase, headSha], errors);
|
|
const tree = git(root, ['ls-tree', '-r', '--name-only', '-z', headSha]);
|
|
const skillDirs = [...new Set(tree.out.split('\0').flatMap(p => /^([^/]+)\/SKILL\.md(\.tmpl)?$/.exec(p)?.[1] ?? []))].sort();
|
|
const consumed = scanConsumers(root, [...diff.perPath.map(e => e.path), ...diff.deleted], [headSha, mergeBase], false, skillDirs, errors);
|
|
const drawings = drawingsAmong(diff.perPath, skillDirs, p => {
|
|
const blob = spawnSync('git', ['cat-file', 'blob', `${headSha}:${p}`], { cwd: root, timeout: 60_000, maxBuffer: DRAWING_READ_CAP + 1 });
|
|
return blob.status === 0 && !blob.error ? blob.stdout : null;
|
|
});
|
|
return result(diff, { root: skillDirs, registry, errors, mergeBase, untracked: [], consumed, drawings, executables: executablesAt(root, headSha, diff.perPath, skillDirs) });
|
|
}
|
|
|
|
/**
|
|
* The working tree against the merge base with the base resolveBase reads (lib/gate-diff/git.ts: a bare name is
|
|
* origin/<base> when it shares history with HEAD, else the local branch; a remote-qualified base reads
|
|
* refs/remotes/<base> only), untracked files counted per path; the registry is the base ref's commit.
|
|
*/
|
|
export function collectLive(root: string, base: string): Collected {
|
|
const errors: DepthError[] = [];
|
|
const resolved = resolveBase(base, root, 'HEAD');
|
|
const ref = resolved?.sha ?? base;
|
|
const registry = loadRegistryAt(root, ref);
|
|
const mb = git(root, ['merge-base', ref, 'HEAD']);
|
|
if (!mb.ok) {
|
|
errors.push({ code: 'numstat_failed', detail: oneLine(mb.err || `no merge base with ${ref}`), input: `git merge-base ${ref} HEAD`, repair: `fetch the base first (git fetch origin ${base})` });
|
|
return { ...result({ perPath: [], deleted: [], stampOnly: [], created: [], added: {}, removed: {} }, { root, registry, errors, mergeBase: null, untracked: [], consumed: 'all' }), base: resolved };
|
|
}
|
|
const mergeBase = mb.out.trim();
|
|
const diff = readDiff(root, [mergeBase], errors);
|
|
const others = git(root, ['ls-files', '--others', '--exclude-standard', '-z']);
|
|
if (!others.ok) errors.push({ code: 'numstat_failed', detail: oneLine(others.err || 'git ls-files failed'), input: 'git ls-files --others --exclude-standard', repair: 'run the command by hand and fix what git reports' });
|
|
const untracked = others.out.split('\0').filter(p => p && !scratch(p)).sort();
|
|
for (const p of untracked) {
|
|
let buf: Buffer;
|
|
try { buf = fs.readFileSync(path.join(root, p)); } catch { diff.perPath.push({ path: p, lines: 0, binary: true }); continue; }
|
|
const binary = buf.subarray(0, 8000).includes(0);
|
|
const text = binary ? '' : buf.toString('utf8');
|
|
const lines = text ? text.split('\n').length - (text.endsWith('\n') ? 1 : 0) : 0;
|
|
diff.perPath.push({ path: p, lines, binary });
|
|
if (!binary) { diff.added[p] = text.split('\n'); diff.created.push(p); }
|
|
}
|
|
const consumed = scanConsumers(root, [...diff.perPath.map(e => e.path), ...diff.deleted], [mergeBase], true, root, errors);
|
|
const drawings = drawingsAmong(diff.perPath, root, p => {
|
|
try { const st = fs.lstatSync(path.join(root, p)); return st.isFile() && st.size <= DRAWING_READ_CAP ? fs.readFileSync(path.join(root, p)) : null; } catch { return null; }
|
|
});
|
|
const executables = executablesAmong(diff.perPath, root, e => {
|
|
try {
|
|
const f = path.join(root, e.path);
|
|
const st = fs.lstatSync(f);
|
|
if (!st.isFile() || st.mode & 0o111) return true;
|
|
if (e.binary) return false;
|
|
const fd = fs.openSync(f, 'r');
|
|
const buf = Buffer.alloc(2);
|
|
try { fs.readSync(fd, buf, 0, 2, 0); } finally { fs.closeSync(fd); }
|
|
return buf.toString('latin1') === '#!';
|
|
} catch (err) { return (err as NodeJS.ErrnoException).code !== 'ENOENT'; }
|
|
});
|
|
return { ...result(diff, { root, registry, errors, mergeBase, untracked, consumed, drawings, executables }), base: resolved };
|
|
}
|