Review leaves out copied open-source files that match their upstream byte for byte (GST-3298) (#4665)

Files a repo copies unchanged from an allowlisted open-source project,
and that gstack verifies byte for byte against the pinned upstream
commit, can now be left out of `/ship`'s review under
`review_exclude_paths`.

Why: verified upstream code doesn't need a reviewer, so its bytes no
longer count toward the 2 MB reader limit, while every other keep rule
still applies.

Nothing to do for repos without `review_vendored`: their review
selection is unchanged (216 of 216 replayed commits identical).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/specialist-batched#1 reader=specialist-batched
Review-Finding: p1/specialist-batched#2 reader=specialist-batched
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: s11/outside-voice#1 reader=outside-voice
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-22 05:58:38 +00:00
1 parent 7c0659a69f
commit 9cfbbb94fd
8 files changed
+334 -22

No files matched your search

+42 -14
View File
@@ -44,6 +44,8 @@ import { secretExcerpt } from './review-secret-excerpt';
import { cmpVersion, parseVersion } from './version-source';
import { REVIEW_EXCLUDE_KEY_VERSION, SHIP_POLICY_PATH, isUnavailable, policyUnavailableLine } from './ship-policy';
import { loadPolicyAt } from './ship-policy-at';
import { resolveStateRoot } from './state-root';
import { vendoredCacheRoot, vendoredPolicy, vendoredSelection, type VendoredSelection } from './review-vendored';
/** The most diff bytes one reader is handed (about 500K tokens); above it the pass stops instead of truncating. */
export const REVIEW_DIFF_MAX_BYTES = 2_000_000;
@@ -61,12 +63,16 @@ export type KeptReason = (typeof KEPT_REASONS)[number];
export interface ExcludeRecord {
source: string; patterns: string[]; applied: string[]; unmatched: string[];
excluded: number; excluded_bytes: number; kept: number; gate_tagged: string[]; patterns_sha256: string; list_sha256: string; digest: string;
/** Excluded files that are verified vendored upstream files (docs/vendored-code.md); absent when none are. */
vendored?: number;
}
export interface ActiveExclusion {
state: 'active'; record: ExcludeRecord; excluded: Set<string>; specs: string[]; keep: string[];
/** The kept files (a subset of keep, as `:(top,literal)` items) whose only reason is a secret line, or gate tags on data lines: pass readers get an excerpt. */
excerpt: string[];
kept: Array<{ path: string; reason: KeptReason }>; content: Record<ContentKind, number>; references: Array<{ prefix: string; files: string[] }>;
/** The base policy's review_vendored check over the matched files; absent when the base declares none. */
vendored?: VendoredSelection | { error: string };
}
export type Exclusion =
| { state: 'none' }
@@ -89,6 +95,8 @@ export interface ExcludeInput {
gateTagged?: ReadonlySet<string> | null;
/** The command name the refusal lines start with. */
context: string;
/** Fetch review_vendored upstreams into the cache first (gstack-review-plan); every other caller reads the cache offline. */
vendoredFetch?: boolean;
}
const sha256 = (s: string) => createHash('sha256').update(s).digest('hex');
@@ -300,13 +308,13 @@ function attributeBinaryLines(i: ExcludeInput, paths: readonly string[], unread:
}
/** The kind of content a path holds when the policy may exclude it, or null for code (tests included). */
export type ContentKind = 'binary' | 'data' | 'docs' | 'log' | 'declared';
export type ContentKind = 'binary' | 'data' | 'docs' | 'log' | 'declared' | 'vendored';
/**
* One range's input with the matched files a pattern names by their file name (its last segment, with no glob character): a
* config name there is data; and the files a review_exclude_paths and a review_content_patterns pattern both match, which
* the base policy declares content.
*/
type Scope = ExcludeInput & { named?: ReadonlySet<string>; declared?: ReadonlySet<string>; keptDeclared?: ReadonlySet<string> };
type Scope = ExcludeInput & { named?: ReadonlySet<string>; declared?: ReadonlySet<string>; keptDeclared?: ReadonlySet<string>; vendored?: ReadonlySet<string> };
const config = (i: Scope, p: string) => isDataConfig(p) && !i.named?.has(p);
/** Source code by its name, in any letter case: a program extension, or a build or task file name. A declared file with one stays code. */
const SOURCE = /(?:\.(?:[cm]?[jt]sx?|py[iw]?|pyx|rb|erb|rake|sh|bash|zsh|fish|ksh|csh|ps1|psm1|psd1|bat|cmd|vbs|go|rs|dart|java|kt|kts|scala|sc|groovy|gradle|clj[sc]?|swift|m|mm|c|h|cc|cpp|cxx|hpp|hh|hxx|ino|cs|fs|fsx|vb|php|phtml|pl|pm|lua|r|jl|ex|exs|erl|hrl|hs|ml|mli|elm|zig|nim|v|sol|sql|vue|svelte|astro|html?|xhtml|css|scss|sass|less|wasm|wat|tf|hcl|nix|mk|cmake|bzl|star|awk|sed|asm|s|applescript|jsonnet|tmpl|ejs|hbs|jinja2?|j2|mdx)|(?:^|\/)(?:Makefile|GNUmakefile|Dockerfile|Containerfile|Rakefile|Gemfile|Brewfile|Justfile|Procfile|Vagrantfile|Jenkinsfile|Earthfile|Tiltfile|BUILD|WORKSPACE|CMakeLists\.txt|meson\.build)(?:\.[^/]*)?)$/i;
@@ -317,6 +325,7 @@ function contentKind(i: Scope, p: string, binary: ReadonlySet<string>): ContentK
if (DATA_PATH.test(p) && !config(i, p)) return 'data';
if (/\.log$/i.test(p)) return 'log';
if (classifyPath(p, i.classRoot) === 'docs' && !SOURCE.test(p)) return 'docs';
if (i.vendored?.has(p)) return 'vendored';
return declaredData(i, p) ? 'declared' : null;
}
@@ -367,11 +376,15 @@ function pathReason(i: Scope, p: string, m: Matched, binary: ReadonlySet<string>
/**
* A file whose full-path reference keeps excluded content: a code or test file (not docs, data, a .log or binary) outside the
* would-be-excluded set, or a declared file that stays in review (kept in this range, or an executable or link at `mode`).
* would-be-excluded set, or a declared file that stays in review (kept in this range, or an executable or link at `mode`). A
* verified vendored file counts as the code it is, excluded or not, so the files it names keep the selection they had before.
*/
const consumer = (i: Scope, f: string, candidates: ReadonlySet<string>, mode?: string) =>
!candidates.has(f) && !f.startsWith('.gstack/tmp/') && (contentKind(i, f, new Set()) === null
|| (!!i.declared?.has(f) && (!!i.keptDeclared?.has(f) || mode === '100755' || mode === '120000')));
const consumer = (i: Scope, f: string, candidates: ReadonlySet<string>, mode?: string) => {
if (f.startsWith('.gstack/tmp/')) return false;
const kind = contentKind(i, f, new Set());
if (kind === 'vendored' && !declaredData(i, f)) return true;
return !candidates.has(f) && (kind === null || (!!i.declared?.has(f) && (!!i.keptDeclared?.has(f) || mode === '100755' || mode === '120000')));
};
/**
* An uncapped search for fixed strings at the head (or the working tree) and `revs`: string -> the consumer files
@@ -469,8 +482,12 @@ export function reviewExclude(i: ExcludeInput): Exclusion {
const native = new Set<string>();
const claimed = i.perPath.filter(e => e.binary && sel.files.has(e.path)).map(e => e.path);
const binary = binaryContent(i, sel.files, new Set([...claimed, ...(bytesBinary(i, patterns) ?? sel.files.keys())]), unread, native);
const vpol = vendoredPolicy(load.policy);
const hiddenManifest = vpol?.manifests.find(m => sel.files.has(m));
const vsel = hiddenManifest ? { error: `${hiddenManifest} matches review_exclude_paths, so readers would not see its pins` } : vpol ? vendoredSelection({ root: i.root, policy: vpol, head: i.head, mergeBase: i.mergeBase, changed: new Set(sel.files.keys()), fetch: !!i.vendoredFetch, cacheRoot: vendoredCacheRoot(resolveStateRoot()) }) : undefined;
const vendored = vsel && !('error' in vsel) ? new Set(vsel.verified) : undefined;
const fileName = (s: string) => s.slice(s.lastIndexOf('/') + 1);
const x: Scope = { ...i, declared, named: new Set(patterns.flatMap(q => /[*?[\\]/.test(fileName(q)) ? [] : (sel.byPattern.get(q) ?? []).filter(f => fileName(f) === fileName(q)))) };
const x: Scope = { ...i, declared, vendored, named: new Set(patterns.flatMap(q => /[*?[\\]/.test(fileName(q)) ? [] : (sel.byPattern.get(q) ?? []).filter(f => fileName(f) === fileName(q)))) };
const text = { ...x, added: { ...i.added, ...attributeBinaryLines(i, claimed.filter(p => !binary.has(p) && !unread.has(p)), unread) } };
const collected = new Map(i.perPath.map(e => [e.path, e]));
const unseen = (p: string) => { const e = collected.get(p); return !e || (!e.binary && e.lines > 0 && !(p in text.added)); };
@@ -478,7 +495,7 @@ export function reviewExclude(i: ExcludeInput): Exclusion {
for (const [p, m] of sel.files) reasons.set(p, unread.has(p) ? 'consumer-scan-unavailable' : pathReason(text, p, m, binary, native) ?? (unseen(p) ? 'consumer-scan-unavailable' : null));
const candidates = new Set([...reasons].filter(([, r]) => r === null).map(([p]) => p));
const secretOnly = [...reasons].filter(([p, r]) => r === 'secret-line' && !p.includes('\n')).map(([p]) => p);
const tagOnly = [...reasons].filter(([p, r]) => r === 'gate-tagged' && !p.includes('\n') && (GATE_DATA.test(p) || (/\.json$/i.test(p) && RESULTS_TREE.test(p)))
const tagOnly = [...reasons].filter(([p, r]) => r === 'gate-tagged' && !p.includes('\n') && (GATE_DATA.test(p) || (/\.json$/i.test(p) && RESULTS_TREE.test(p)) || !!vendored?.has(p))
&& !binary.has(p) && !unseen(p) && pathReason({ ...text, gateTagged: null }, p, sel.files.get(p)!, binary, native) === null).map(([p]) => p);
const renamed = tagOnly.length ? renamedPaths(i) : null;
const floorCtx = { project: parseGateIntegrityBlock(readClaudeMd(i.root)), specIsTestPath: true };
@@ -504,7 +521,9 @@ export function reviewExclude(i: ExcludeInput): Exclusion {
const why = new Map<string, number>();
for (const f of kept) why.set(reasons.get(f)!, (why.get(reasons.get(f)!) ?? 0) + 1);
const top = [...why].sort((a, b) => b[1] - a[1]).map(([r, n]) => `${r}:${n}`).join(',');
return { state: 'refused', code: 'REVIEW_EXCLUDE_KEEP_TOO_LARGE', lines: [`${i.context}: review_exclude_paths pattern ${p} on ${source} keeps ${kept.length} matched files in review (${top}), and the command readers run to read them would need ${bytes} argument bytes (more than ${KEEP_ARG_MAX_BYTES}), so the pattern cannot be applied and is not dropped either; fix: when those files are published data, add a review_content_patterns entry for them beside the pattern on ${base} as its own PR (docs/ship-policy.md#review-content-patterns), else narrow the pattern or split the PR; nothing was planned (REVIEW_EXCLUDE_KEEP_TOO_LARGE)`] };
const unverified = vsel ? ('error' in vsel ? kept.length : vsel.failed.filter(e => kept.includes(e.path)).length) : 0;
const vfix = unverified ? `${unverified} of them are vendored files that did not verify (gstack-review-plan lists them as REVIEW_VENDORED_KEPT); run gstack-vendored-verify --base ${base} and fix what it names, then rerun once; ` : '';
return { state: 'refused', code: 'REVIEW_EXCLUDE_KEEP_TOO_LARGE', lines: [`${i.context}: review_exclude_paths pattern ${p} on ${source} keeps ${kept.length} matched files in review (${top}), and the command readers run to read them would need ${bytes} argument bytes (more than ${KEEP_ARG_MAX_BYTES}), so the pattern cannot be applied and is not dropped either; fix: ${vfix}when those files are published data, add a review_content_patterns entry for them beside the pattern on ${base} as its own PR (docs/ship-policy.md#review-content-patterns), else narrow the pattern or split the PR; nothing was planned (REVIEW_EXCLUDE_KEEP_TOO_LARGE)`] };
}
applied.push(p);
for (const f of kept) keep.add(f);
@@ -513,20 +532,21 @@ export function reviewExclude(i: ExcludeInput): Exclusion {
const excerpt = [...excerptable].filter(p => keep.has(p)).sort();
const keptList = [...reasons].filter(([, r]) => r !== null).map(([p, r]) => ({ path: p, reason: r! })).sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
const sortedExcluded = [...excluded].sort();
const content: Record<ContentKind, number> = { binary: 0, data: 0, docs: 0, log: 0, declared: 0 };
const content: Record<ContentKind, number> = { binary: 0, data: 0, docs: 0, log: 0, declared: 0, vendored: 0 };
for (const p of sortedExcluded) content[contentKind(x, p, binary)!]++;
const prefixes = [...new Set(applied.map(literalPrefix).filter(Boolean))];
const refs = grepFixed(y, prefixes, excluded, []) ?? new Map<string, Set<string>>();
const patterns_sha256 = sha256(JSON.stringify(patterns));
const list_sha256 = sha256(JSON.stringify({ applied, excluded: sortedExcluded, kept: keptList.map(k => [k.path, k.reason]) }));
const list_sha256 = sha256(JSON.stringify({ applied, excluded: sortedExcluded, kept: keptList.map(k => [k.path, k.reason]), ...(vendored?.size ? { vendored: (vsel as VendoredSelection).digest } : {}) }));
const record: ExcludeRecord = {
source, patterns: [...patterns], applied, unmatched: patterns.filter(p => !(sel.byPattern.get(p) ?? []).length),
excluded: excluded.size, excluded_bytes: excludedBytes(i, sortedExcluded, sel.files), kept: keptList.length,
gate_tagged: keptList.filter(k => k.reason === 'gate-tagged').map(k => k.path), patterns_sha256, list_sha256, digest: sha256(`${patterns_sha256}\n${list_sha256}`),
...(content.vendored ? { vendored: content.vendored } : {}),
};
return {
state: 'active', record, excluded, specs: applied.map(p => `:(top,exclude,glob)${p}`), keep: [...keep].sort().map(literal), excerpt: excerpt.map(literal), kept: keptList, content,
references: prefixes.filter(p => refs.has(p)).map(p => ({ prefix: p, files: [...refs.get(p)!].sort() })),
references: prefixes.filter(p => refs.has(p)).map(p => ({ prefix: p, files: [...refs.get(p)!].sort() })), ...(vsel ? { vendored: vsel } : {}),
};
}
@@ -551,6 +571,14 @@ export function excludeLines(x: Exclusion, base: string): string[] {
if (x.state === 'fallback') return [fallbackLine(x, base)];
const r = x.record;
const out = [`REVIEW_EXCLUDE: patterns=${r.applied.length}/${r.patterns.length} excluded=${r.excluded} bytes=${r.excluded_bytes} kept=${r.kept} content=${Object.entries(x.content).filter(([, n]) => n).map(([k, n]) => `${k}:${n}`).join(',') || 'none'} source=${r.source} digest=${r.digest}${r.unmatched.length ? ` unmatched=${r.unmatched.join(',')}` : ''}`];
const v = x.vendored;
if (v && 'error' in v) out.push(`REVIEW_VENDORED: unavailable (${v.error}); no vendored file is treated as verified; fix: gstack-vendored-verify --base ${base} (docs/vendored-code.md)`);
else if (v) {
out.push(`REVIEW_VENDORED: verified=${v.verified.length} unverified=${v.failed.length} pins=${v.pins.length} digest=${v.digest}`);
for (const p of v.pins) out.push(`REVIEW_VENDORED_PIN: ${p.upstream}@${p.commit.slice(0, 12)} reachable_from=${p.reachable_from ?? 'none'} files=${p.files} verified=${p.verified}`);
for (const f of v.failed.slice(0, 20)) out.push(`REVIEW_VENDORED_KEPT: ${f.verdict} ${f.path}${f.detail ? ` (${f.detail})` : ''}`);
if (v.failed.length > 20) out.push(`REVIEW_VENDORED_KEPT: +${v.failed.length - 20} more (gstack-vendored-verify --base ${base} --json lists every one)`);
}
for (const k of x.kept.slice(0, 20)) out.push(`REVIEW_EXCLUDE_KEPT: ${k.reason} ${k.path}`);
if (x.kept.length > 20) out.push(`REVIEW_EXCLUDE_KEPT: +${x.kept.length - 20} more (gstack-review-plan --json lists every kept file)`);
const gated = x.excerpt.filter(s => x.kept.some(k => k.reason === 'gate-tagged' && literal(k.path) === s)).length;
@@ -560,8 +588,8 @@ export function excludeLines(x: Exclusion, base: string): string[] {
}
/** The one line every brief gets under an active exclusion; it names the selection digest the receipt binds (verify's REVIEW_EXCLUDE_RECORD). */
export function disclosureLine(r: Pick<ExcludeRecord, 'source' | 'excluded' | 'excluded_bytes' | 'applied' | 'kept' | 'digest'>): string {
return `Excluded by base policy ${r.source} (selection ${r.digest}): ${r.excluded} files, ${r.excluded_bytes} bytes on this branch matching ${r.applied.join(' ') || 'no applied pattern'}. They are not in your diff; do not report on their absence. Kept despite a match: ${r.kept} files (listed in the plan).`;
export function disclosureLine(r: Pick<ExcludeRecord, 'source' | 'excluded' | 'excluded_bytes' | 'applied' | 'kept' | 'digest' | 'vendored'>): string {
return `Excluded by base policy ${r.source} (selection ${r.digest}): ${r.excluded} files, ${r.excluded_bytes} bytes on this branch matching ${r.applied.join(' ') || 'no applied pattern'}. They are not in your diff; do not report on their absence. Kept despite a match: ${r.kept} files (listed in the plan).${r.vendored ? ` ${r.vendored} of the excluded files are vendored upstream files gstack verified byte for byte against the pins the base allowlists; the manifest that pins them is in your diff.` : ''}`;
}
/** The selection digest a disclosure line names, or undefined. */
export const disclosureDigest = (line: string | undefined) => line?.match(/^Excluded by base policy \S+ \(selection ([0-9a-f]{64})\)/)?.[1];
+48
View File
@@ -204,6 +204,7 @@ function fetchUpstream(cacheRoot: string, up: VendoredUpstream, pins: Map<string
if (!head.ok || !def) { fail(`could not read the default branch (${head.err.split('\n').pop() || 'no HEAD'})`); return; }
const heads = new Set(head.out.split('\n').map(l => l.split('\t')[1]).filter(Boolean));
const named = up.branches.filter(b => b.includes('*') || heads.has(`refs/heads/${b}`));
for (const b of up.branches) if (!b.includes('*') && !heads.has(`refs/heads/${b}`)) git(refs, ['update-ref', '-d', `refs/vendored/heads/${b}`], genv);
const specs = [`+refs/heads/${def}:refs/vendored/heads/${def}`, '+refs/tags/*:refs/vendored/tags/*', ...named.map(b => `+refs/heads/${b}:refs/vendored/heads/${b}`)];
const f = git(refs, [...flags, 'fetch', '--quiet', '--no-tags', '--prune', '--filter=tree:0', url, ...specs], genv, t);
if (!f.ok) { fail(`could not fetch its branches and tags (${f.err.split('\n').pop()})`); return; }
@@ -289,3 +290,50 @@ export function resolveVendored(i: ResolveInput): { entries: EntryResult[]; pins
/** The cache directory under a state root. */
export const vendoredCacheRoot = (stateRoot: string) => path.join(stateRoot, 'vendored-cache');
/** What a review range may treat as vendored (lib/review-exclude.ts): sorted verified paths, the entries that did not verify, the pins, and a digest of the verified list. */
export interface VendoredSelection { verified: string[]; failed: EntryResult[]; pins: PinResult[]; digest: string }
/**
* The verified vendored files among `changed`: entries of the head's manifests, checked at the head, and files the range
* deletes that the merge base's manifests list, checked at the merge base (a re-pin's old files). With no head (a live
* tree) the manifests and blobs come from HEAD, and a file the working tree or index changes is not verified. A manifest
* that is missing at the head, does not parse, or pins one path twice gives { error } and nothing is verified.
*/
export function vendoredSelection(i: { root: string; policy: VendoredPolicy; head?: string; mergeBase: string; changed: ReadonlySet<string>; fetch: boolean; cacheRoot: string; env?: NodeJS.ProcessEnv }): VendoredSelection | { error: string } {
const show = (rev: string, f: string) => { const r = spawnSync('git', ['show', `${rev}:${f}`], { cwd: i.root, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); return r.status === 0 ? r.stdout ?? '' : null; };
const rev = i.head ?? 'HEAD';
const now: VendoredEntry[] = [];
const old: VendoredEntry[] = [];
for (const m of i.policy.manifests) {
const text = show(rev, m);
if (text === null) return { error: `${m} is not in ${i.head ? i.head.slice(0, 12) : 'HEAD'}` };
const parsed = parseManifest(text, m);
if (parsed.errors.length) return { error: parsed.errors[0]! };
now.push(...parsed.entries);
const before = show(i.mergeBase, m);
if (before !== null) old.push(...parseManifest(before, m).entries);
}
const lower = new Set<string>();
for (const e of now) { if (lower.has(e.path.toLowerCase())) return { error: `${e.path} is pinned more than once` }; lower.add(e.path.toLowerCase()); }
const atHead = now.filter(e => i.changed.has(e.path));
const dropped = old.filter(e => i.changed.has(e.path) && !lower.has(e.path.toLowerCase()) && !e.path.includes('\n'));
const probe = dropped.length ? spawnSync('git', ['cat-file', '--batch-check=%(objectname)'], { cwd: i.root, input: dropped.map(e => `${rev}:${e.path}\n`).join(''), encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }) : null;
if (probe && probe.status !== 0) return { error: 'git could not check which vendored files the range deletes' };
const probed = (probe?.stdout ?? '').split('\n');
const gone = dropped.filter((e, k) => probed[k] === `${rev}:${e.path} missing` && (i.head || !fs.existsSync(path.join(i.root, e.path))));
const head = resolveVendored({ root: i.root, rev, policy: i.policy, entries: atHead, fetch: i.fetch, cacheRoot: i.cacheRoot, env: i.env });
const base = gone.length ? resolveVendored({ root: i.root, rev: i.mergeBase, policy: i.policy, entries: gone, fetch: i.fetch, cacheRoot: i.cacheRoot, env: i.env }) : { entries: [], pins: [], digest: '' };
if (!head || !base) return { error: 'git could not list the vendored files' };
const dirty = new Set<string>();
if (!i.head) {
const d = spawnSync('git', ['-c', 'core.quotePath=false', 'diff', '--name-only', '-z', '--no-renames', 'HEAD'], { cwd: i.root, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });
if (d.status !== 0) return { error: 'git could not list the working tree changes' };
for (const f of (d.stdout ?? '').split('\0')) if (f) dirty.add(f);
}
const all = [...head.entries, ...base.entries];
const verified = all.filter(e => e.verdict === 'verified' && !dirty.has(e.path)).map(e => e.path).sort();
const failed = all.filter(e => e.verdict !== 'verified' || dirty.has(e.path)).map(e => (e.verdict === 'verified' ? { ...e, verdict: 'mismatched' as const, detail: 'changed in the working tree' } : e));
return { verified, failed, pins: [...head.pins, ...base.pins], digest: createHash('sha256').update(JSON.stringify(verified)).digest('hex') };
}