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
/**
* pregate check `literals` (tier 1, preflight): for every exported constant,
* timeout, retry or delay literal the branch changed, grep the whole test
* tree, nightly-only and Heavy-only files included, for the old value next to
* the constant's name or its module. Incident p0-4-heavy-old-constant: a
* nightly-only test still asserted the old number and went red a week after
* the merge.
*/
import { spawnSync } from '../../spawn-sync';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { baseInputs, sha256 } from '../context';
import { isTestFile, listRepoFiles, pathAliasResolver, referencesIn, scansLiterals } from '../import-graph';
import type { CheckDef, CheckResult, PregateContext } from '../types';
export interface ChangedLiteral { name: string; old: string; new: string; file: string }
/** A consumer line a `pregate-literal:` marker waived; `added` when the merge-base file lacks the marker. */
export interface LiteralWaiver { at: string; reason: string; added: boolean }
const MARKER = /pregate-literal:[ \t]*([A-Za-z_]\w*)=(\S+)[ \t]+([^\s*].*?)[ \t]*(?:\*+\/[ \t]*)?$/;
/** The marker in this line's trailing comment (`//`, `#` or `/*` outside a string), or null. */
function markerIn(line: string): { marker: string; name: string; value: string; reason: string } | null {
const at = line.indexOf('pregate-literal:');
if (at < 0) return null;
const before = line.slice(0, at);
const open = /(?:\/\/|#|\/\*)[ \t]*$/.exec(before);
if (!open) return null;
const code = before.slice(0, open.index);
if (['\'', '"', '`'].some(q => code.split(q).length % 2 === 0)) return null;
const m = MARKER.exec(line.slice(at));
return m ? { marker: line.slice(at).trim(), name: m[1]!, value: m[2]!, reason: m[3]! } : null;
}
const CONST_PATTERNS: RegExp[] = [
/^\s*export\s+(?:const|let|var)\s+([A-Z][A-Z0-9_]{1,})\s*(?::\s*[^=]+?)?\s*=\s*(.+?);?\s*$/,
/^\s*(?:module\.)?exports\.([A-Z][A-Z0-9_]{1,})\s*=\s*(.+?);?\s*$/,
/^\s*(?:export\s+)?(?:static\s+)?readonly\s+([A-Z][A-Z0-9_]{1,})\s*(?::\s*[^=]+?)?\s*=\s*(.+?);?\s*$/,
/^([A-Z][A-Z0-9_]{2,})\s*=\s*(.+?)\s*$/,
/^(?:export\s+|readonly\s+)?([A-Z][A-Z0-9_]{2,})=(\S+)\s*$/,
];
const CALL_PATTERN = /\b(timeout(?:Ms|_ms)?|retries|maxRetries|max_retries|attempts|maxAttempts|delay(?:Ms)?|interval(?:Ms)?|budget|cap|limit)\s*[:=]\s*(\d+(?:_\d+)*)\b/g;
const LITERAL = /^(?:-?\d+(?:_\d+)*(?:\.\d+)?|'[^']*'|"[^"]*"|`[^`$]*`|true|false|null|\[[^\]]*\])$/;
/** `NAME → literal` for one source text; only literal right-hand sides count. */
export function constantsIn(text: string): Map<string, string> {
const out = new Map<string, string>();
for (const line of text.split('\n')) {
for (const re of CONST_PATTERNS) {
const m = re.exec(line);
if (!m) continue;
const value = m[2]!.trim();
if (LITERAL.test(value)) out.set(m[1]!, value);
break;
}
}
return out;
}
/** Named numeric call sites (`timeout: 5000`) keyed by name, every value in source order. */
export function callLiteralsIn(text: string): Map<string, string[]> {
const out = new Map<string, string[]>();
for (const m of text.matchAll(CALL_PATTERN)) out.set(m[1]!, [...(out.get(m[1]!) ?? []), m[2]!]);
return out;
}
export function changedLiterals(file: string, oldText: string, newText: string): ChangedLiteral[] {
const out: ChangedLiteral[] = [];
const oldC = constantsIn(oldText); const newC = constantsIn(newText);
for (const [name, old] of oldC) { const now = newC.get(name); if (now !== undefined && now !== old) out.push({ name, old, new: now, file }); }
const oldCall = callLiteralsIn(oldText); const newCall = callLiteralsIn(newText);
for (const [name, olds] of oldCall) {
if (oldC.has(name)) continue;
const added = [...(newCall.get(name) ?? [])];
const removed = olds.filter(v => { const i = added.indexOf(v); if (i >= 0) added.splice(i, 1); return i < 0; });
if (!added.length) continue;
const seen = new Set<string>();
removed.forEach((old, i) => { if (!seen.has(old)) { seen.add(old); out.push({ name, old, new: added[Math.min(i, added.length - 1)]!, file }); } });
}
return out;
}
function escape(s: string): string { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
function unquote(v: string): string { return /^['"`]/.test(v) ? v.slice(1, -1) : v; }
/** The text with each string emptied (a template literal keeps its `${…}` parts), so a word inside a string is not code. */
function blankStrings(s: string): string {
return s.replace(/'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|`(?:[^`\\]|\\.)*`/g, q => q.startsWith('`') ? [...q.matchAll(/\$\{[^}]*\}/g)].map(m => m[0]).join(' ') : "''");
}
/** A quoted one-item list that kept its item and gained more (`"investigate"` → `"investigate verify"`), every item a bare token. */
function onlyGrew(old: string, now: string): boolean {
const token = /^[\w.@/:-]+$/;
const items = unquote(now).split(/\s+/).filter(Boolean);
return /^['"`]/.test(old) && /^['"`]/.test(now) && token.test(unquote(old)) && items.length > 1 && items.includes(unquote(old)) && items.every(t => token.test(t));
}
/** 0-based lines of the JSON scalars tied to `name`: the value of a `name` key, or anything inside a record holding the string `name`; null when the text is not JSON. */
function jsonLinesTiedTo(text: string, name: string): Set<number> | null {
type Node = { line: number; scalar?: string; entries?: Array<[string, Node]>; items?: Node[] };
const tokens: Array<{ t: string; line: number }> = [];
let line = 0; let at = 0;
for (const m of text.matchAll(/"(?:[^"\\\n]|\\.)*"|[{}[\]:,]|[^\s{}[\]:,"]+|\s+/g)) {
if (m.index !== at) return null;
at += m[0].length;
if (m[0].trim()) tokens.push({ t: m[0], line });
line += m[0].split('\n').length - 1;
}
if (at !== text.length) return null;
let k = 0;
const parse = (): Node => {
const tok = tokens[k++];
if (!tok || '}]:,'.includes(tok.t)) throw new Error('json');
if (tok.t !== '{' && tok.t !== '[') return { line: tok.line, scalar: tok.t.startsWith('"') ? JSON.parse(tok.t) as string : tok.t };
const close = tok.t === '{' ? '}' : ']';
const entries: Array<[string, Node]> = [];
if (tokens[k]?.t === close) k++;
else for (;;) {
let key = '';
if (close === '}') { const kt = tokens[k++]; if (!kt?.t.startsWith('"') || tokens[k++]?.t !== ':') throw new Error('json'); key = JSON.parse(kt.t) as string; }
entries.push([key, parse()]);
const sep = tokens[k++]?.t;
if (sep === close) break;
if (sep !== ',') throw new Error('json');
}
return close === '}' ? { line: tok.line, entries } : { line: tok.line, items: entries.map(e => e[1]) };
};
const out = new Set<number>();
const walk = (n: Node, tied: boolean): void => {
if (n.scalar !== undefined) { if (tied) out.add(n.line); return; }
if (n.items) { for (const c of n.items) walk(c, tied); return; }
const record = tied || n.entries!.some(([, v]) => v.scalar === name);
for (const [key, v] of n.entries!) walk(v, record || key === name);
};
try { walk(parse(), false); } catch { return null; }
return k === tokens.length ? out : null;
}
/**
* Test files that still carry the old literal beside the constant's name or
* its module. The module counts as its full file name (`install.sh`, not
* `install.sh.tmpl`) or as a path fragment (`/retry.js`, `/retry'`) whose stem is
* followed by the module's own extension (for a JS/TS module also any JS/TS
* extension or `.d.ts`), a sentence-ending `.`, or anything but a word
* character, `.` or `-`, so a sibling `/retry.txt`, `/retry-v2.ts` or
* `/retry.ts.snap`, or `lib/install.ts` for `install.sh`, is not the module (GST-820): a bare stem such as `install` or `retry` is an
* English word in half the test tree, and a one-character old value (`2`)
* sits in every test, so that value needs the constant's name (a wrapper
* version 2 → 3 flagged 575 consumers through the stem alone), and counts only
* in a statement that names it: on the name's line, or on a line that
* continues it (the line before ends open, `(` `,` `.` `=`, or the line
* starts with `.` `)` `]`), comments excluded (#3492: `$2`, "from revision 2",
* `export default 2`). A one- or two-digit integer (`12`, `-10`) is nearly as
* common, so through the module it counts only in a statement that names the
* constant or a binding the file takes from the module: an import of it
* (`import { shards } from '…/arms'`, type-only imports excluded) or a variable
* a line naming it declares (`const out = run('…/arms.ts')`). A comment that
* names the module beside an unrelated `10` is not a consumer (#4312), while
* `expect(shards()).toBe(12)` still is (GST-820). A call-site name (`attempts`, `limit`) is an ordinary
* word, so for it the file must also name the module whatever the value's
* length (gstack-evals#97, #4478).
*
* A version-history row (`[45, "<digest>"]`, the old value first in a
* bracketed row) is skipped when the same table, a run of consecutive
* `[…` lines, holds a new-value row and `baseText` (the file at the merge
* base; null for a file the base lacks, undefined when it cannot be read)
* has no new-value row: the branch extended the table. A table it did not
* extend, a file that already held a new-value row, and an unreadable base
* still count, and the scan goes on past skipped rows to the first real consumer.
*
* A consumer line is waived by a `pregate-literal: NAME=<old value> <reason>` comment on that line or
* on the comment line directly above it, naming this constant and its old value (#3490: the refused
* input after a minimum-version bump). Each waiver goes to `waived`; the scan goes on to the next line.
*
* With `repoFiles`, a module name another repo file shares (two `config.ts`) is ambiguous, so the file
* counts through the module only when one of its references (import, tsconfig/jsconfig alias, quoted
* repo path, `join()` segments) resolves to the changed file; an alias import counts even when the name
* is unique (gbrain#10078: 17 tests of the other config.ts). A JSON file, which cannot carry a marker,
* counts only on values tied to the constant (its key, or a record whose string value is the name). A
* quoted one-item list that kept its item and gained more counts only where a line asserts the whole old
* value or a statement uses the constant or a module binding for anything but a membership check (#4714).
*/
export function consumersOf(repoRoot: string, testFiles: readonly string[], change: ChangedLiteral, baseText?: (rel: string) => string | null | undefined, waived?: LiteralWaiver[], repoFiles?: readonly string[]): string[] {
const value = unquote(change.old);
const valueRe = /^-?\d/.test(value) ? new RegExp(`(?<![\\w.])${escape(value)}(?![\\w.])`) : new RegExp(`['"\`]${escape(value)}['"\`]`);
const row = (raw: string) => new RegExp(`^[ \\t]*\\[[ \\t]*${/^['"`]/.test(raw) ? `['"\`]${escape(unquote(raw))}['"\`]` : escape(raw)}[ \\t]*,`, 'm');
const oldRowRe = row(change.old);
const newRowRe = row(change.new);
const base = path.basename(change.file);
const stem = base.replace(/\.[^.]+$/, '');
const own = base.slice(stem.length + 1);
const jsLike = /^[cm]?[jt]sx?$/.test(own);
const exts = (jsLike ? [...new Set([own, 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'mts', 'cts'])] : [own]).map(escape).join('|');
const dts = jsLike ? '(?:d\\.)?' : '';
const moduleRe = new RegExp(`(?:^|[/\\\\])${escape(stem)}(?=[^\\w.-]|$|\\.${dts}(?:${exts})(?![\\w.-])|\\.(?!\\w))|(?<![\\w-])${escape(base)}(?![\\w-]|\\.\\w)`, 'm');
const nameRe = new RegExp(`\\b${escape(change.name)}\\b`);
const nameRequired = value.length < 2;
const shortNumber = !nameRequired && /^-?\d{1,2}$/.test(value);
const callSite = !/^[A-Z]/.test(change.name);
const grew = onlyGrew(change.old, change.new);
const quoted = `['"\`]${escape(value)}['"\`]`;
const wholeRe = new RegExp(`\\.(?:toBe|toEqual|toStrictEqual)\\(\\s*\\[?\\s*${quoted}\\s*\\]?\\s*\\)|\\b(?:is|equal|strictEqual|deepEqual|deepStrictEqual|assertEqual|assert_equal|assertEquals)\\((?:.*,)?\\s*\\[?\\s*${quoted}\\s*\\]?\\s*[,)]|(?:[!=]==?|(?<![=!<>])=)\\s*\\[?\\s*${quoted}|${quoted}\\s*\\]?\\s*[!=]==?`);
const memberRe = new RegExp(`\\.(?:toContain|toContainEqual|includes|indexOf|has|contains)\\(\\s*${quoted}|${quoted}\\s+(?:not\\s+)?in\\b`);
const files = new Set(repoFiles ?? []);
const twinned = [...files].some(f => f !== change.file && moduleRe.test(path.posix.basename(f)));
const dirs = new Set<string>();
for (const f of files) for (let d = path.posix.dirname(f); d !== '.'; d = path.posix.dirname(d)) dirs.add(d);
const aliasesFor = repoFiles ? pathAliasResolver(repoRoot, repoFiles).aliasesFor : null;
const isModule = (rel: string, source: string, fragment = source): boolean => {
if (!twinned && moduleRe.test(fragment)) return true;
if (!aliasesFor || (!twinned && !aliasesFor(rel).aliases.length)) return false;
const exact = aliasesFor(rel).aliases.filter(a => !a.wildcard && a.targets.some(t => change.file.startsWith(t.replace(/\.[cm]?[jt]sx?$/, ''))));
if (!source.includes(stem) && !exact.some(a => source.includes(a.prefix))) return false;
return referencesIn(files, dirs, rel, source, aliasesFor(rel)).some(r => r.target === change.file);
};
const comment = (l: string) => /^\s*(?:\/\/|#|\*|\/\*|<!--)/.test(l);
const continues = (prev: string, cur: string) => /[([{,.=+\-*/&|?:\\]\s*$/.test(prev) || /^\s*[.)\]}?:&|+]/.test(cur);
const hits: string[] = [];
for (const rel of testFiles) {
let text: string;
try { text = fs.readFileSync(path.join(repoRoot, rel), 'utf8'); } catch { continue; }
const json = rel.endsWith('.json');
if (json ? !(nameRe.test(text) && (!callSite || isModule(rel, text))) : !((nameRequired ? nameRe.test(text) : nameRe.test(text) || isModule(rel, text)) && (!callSite || isModule(rel, text)))) continue;
const lines = text.split('\n');
const tied = json ? jsonLinesTiedTo(text, change.name) : null;
const bindings = !json && (shortNumber || grew) ? moduleBindings(lines, (s, fragment) => isModule(rel, s, fragment), change.name, comment, continues) : [];
if (shortNumber && !bindings.length && !nameRe.test(text)) continue;
const statementRe = bindings.length ? new RegExp(`(?<![\\w$])(?:${[change.name, ...bindings].map(escape).join('|')})(?![\\w$])`) : nameRe;
const named = (i: number, code = false) => {
if (comment(lines[i]!)) return false;
for (let j = i; j >= 0 && i - j < 4; j--) {
if (j < i && (comment(lines[j]!) || !continues(lines[j]!, lines[j + 1]!))) return false;
if (statementRe.test(code ? blankStrings(lines[j]!) : lines[j]!)) return true;
}
return false;
};
const table: number[] = [];
const tableHasNew: boolean[] = [];
for (let i = 0; i < lines.length; i++) {
if (!/^[ \t]*\[/.test(lines[i]!)) { table.push(-1); continue; }
if (table[i - 1] === undefined || table[i - 1] === -1) tableHasNew.push(false);
table.push(tableHasNew.length - 1);
if (newRowRe.test(lines[i]!)) tableHasNew[tableHasNew.length - 1] = true;
}
let extended: boolean | undefined;
const skip = (i: number) => {
const line = lines[i]!;
if (!oldRowRe.test(line) || !tableHasNew[table[i]!] || valueRe.test(line.slice(line.indexOf(']') + 1))) return false;
if (extended === undefined) { const base = baseText?.(rel); extended = base === null || (base !== undefined && !newRowRe.test(base)); }
return extended;
};
const waiver = (i: number) => {
const m = [markerIn(lines[i]!), i > 0 && comment(lines[i - 1]!) ? markerIn(lines[i - 1]!) : null].find(c => c && c.name === change.name && unquote(c.value) === value);
if (!m) return false;
const before = baseText?.(rel);
waived?.push({ at: `${rel}:${i + 1}`, reason: m.reason, added: typeof before !== 'string' || !before.includes(m.marker) });
return true;
};
const carries = (i: number) => { const m = markerIn(lines[i]!); return valueRe.test(m ? lines[i]!.slice(0, lines[i]!.indexOf('pregate-literal:')) : lines[i]!); };
const counts = (i: number) => {
const line = lines[i]!;
if (json) return tied ? tied.has(i) : nameRe.test(line);
if (grew) return !comment(line) && wholeRe.test(line) || named(i, true) && !memberRe.test(line);
return !(nameRequired || shortNumber) || oldRowRe.test(line) || named(i);
};
for (let i = 0; i < lines.length; i++) if (carries(i) && counts(i) && !skip(i) && !waiver(i)) { hits.push(`${rel}:${i + 1}`); break; }
}
return hits;
}
/** The names a file takes from the module: the bindings of a JS/TS import whose specifier is the module (type-only ones excluded), and the variables a non-comment statement (a line plus the lines that continue it) declares or assigns from the module or from such a name (`const items = listItems()`, `out = run('bin/x.sh')` in a hook). */
function moduleBindings(lines: readonly string[], isModule: (source: string, fragment?: string) => boolean, name: string, comment: (l: string) => boolean, continues: (prev: string, cur: string) => boolean): string[] {
const code = lines.filter(l => !comment(l)).join('\n');
const out = new Set<string>([name]);
const names = (list: string) => list.split(',').map(s => s.trim()).filter(s => s && !/^type\s/.test(s)).map(s => s.split(/\s+as\s+|:/).pop()!.replace(/^\.\.\./, '').trim());
for (const m of code.matchAll(/\bimport\s+(?!type\b)([^'"`;]*?)\s*\bfrom\s*['"]([^'"]+)['"]/g)) {
if (!isModule(m[0], m[2]!)) continue;
const braces = /\{([^}]*)\}/.exec(m[1]!);
if (braces) for (const n of names(braces[1]!)) out.add(n);
for (const n of m[1]!.replace(/\{[^}]*\}/, '').split(',').map(s => s.trim().replace(/^\*\s+as\s+/, ''))) out.add(n);
}
const codeLines = code.split('\n');
const statements = codeLines.map((line, i) => {
let s = line;
for (let j = i + 1; j < codeLines.length && j - i < 4 && continues(codeLines[j - 1]!, codeLines[j]!); j++) s += '\n' + codeLines[j];
return s;
});
const declRe = /(?:\b(?:const|let|var)\s+(\{[^}]*\}|[\w$]+)|(?<![\w$.])([\w$]+))\s*=(?![=>])/;
for (let grew = true, round = 0; grew && round < 4; round++) {
grew = false;
const known = [...out].filter(n => /^[\w$]+$/.test(n));
const knownRe = known.length ? new RegExp(`(?<![\\w$])(?:${known.map(escape).join('|')})(?![\\w$])`) : null;
for (const s of statements) {
const m = declRe.exec(s);
if (!m || !(isModule(s) || knownRe?.test(blankStrings(s.slice(m.index + m[0].length))))) continue;
for (const n of m[1]?.startsWith('{') ? names(m[1].slice(1, -1)) : [m[1] ?? m[2]!]) if (!out.has(n)) { out.add(n); grew = true; }
}
}
return [...out].filter(n => n !== name && /^[\w$]+$/.test(n));
}
function run(ctx: PregateContext): CheckResult {
const candidates = ctx.touched.filter(t => (t.status === 'M' || t.status === 'R') && !isTestFile(t.path) && /\.(?:[cm]?[jt]sx?|py|rb|sh|bash)$/.test(t.path));
const changes: ChangedLiteral[] = [];
for (const t of candidates) {
const old = spawnSync('git', ['show', `${ctx.mergeBase}:${t.renamedFrom ?? t.path}`], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024 * 1024, env: ctx.env });
if (old.status !== 0) continue;
let now = '';
try { now = fs.readFileSync(path.join(ctx.repoRoot, t.path), 'utf8'); } catch { continue; }
changes.push(...changedLiterals(t.path, old.stdout, now));
}
const inputs = baseInputs(ctx, { changes: sha256(changes.map(c => `${c.file}:${c.name}:${c.old}→${c.new}`).join('\n')) });
if (!changes.length) return { id: 'literals', stage: 'preflight', status: 'pass', inputs, detail: `no exported constant or named timeout literal changed in ${candidates.length} modified source file(s)` };
const repoFiles = listRepoFiles(ctx.repoRoot);
const testFiles = repoFiles.filter(f => scansLiterals(f) && !f.startsWith('bin/'));
const lines: string[] = [];
const notes: string[] = [];
for (const c of changes) {
const waived: LiteralWaiver[] = [];
const hits = consumersOf(ctx.repoRoot, testFiles, c, rel => {
const from = ctx.touched.find(t => t.path === rel)?.renamedFrom ?? rel;
const r = spawnSync('git', ['show', `${ctx.mergeBase}:${from}`], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024 * 1024, env: ctx.env });
if (r.status === 0) return r.stdout;
const ls = spawnSync('git', ['ls-tree', ctx.mergeBase, '--', from], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 30_000, env: ctx.env });
return ls.status === 0 && !ls.stdout.trim() ? null : undefined;
}, waived, repoFiles);
for (const w of waived) notes.push(`waived: ${w.at}: ${c.name} ${c.old} (${w.reason}${w.added ? '; marker added on this branch' : ''})`);
ctx.explain.push(`literals: ${c.file} ${c.name} ${c.old} → ${c.new}: ${hits.length} test file(s) still carry ${c.old}`);
for (const h of hits) lines.push(`${h}: ${c.name} still ${c.old} (now ${c.new} in ${c.file})`);
}
const waivers = notes.length ? `; ${notes.length} line(s) waived by pregate-literal markers` : '';
if (lines.length) return { id: 'literals', stage: 'preflight', status: 'fail', inputs, lines: [...lines, ...notes], code: 'PREGATE_LITERALS', detail: `${lines.length} test location(s) still carry an old literal${waivers}`, fix: "update each listed test to the new value (nightly- and Heavy-only files included), keep the old constant, or, when the old value is the test's input on purpose, mark that line with `// pregate-literal: NAME=<old value> <reason>`" };
return { id: 'literals', stage: 'preflight', status: 'pass', inputs, ...(notes.length ? { lines: notes } : {}), detail: `${changes.length} changed literal(s), no test still carries an old value (${testFiles.length} test-tree files scanned)${waivers}` };
}
export const literalsCheck: CheckDef = { id: 'literals', stage: 'preflight', tier: 1, downgradable: true, needsRepoCommands: false, run };