From 79f3052f3589563d92e4bef12a5a68be936ddd8c Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Sun, 22 Nov 2026 15:36:37 -0800 Subject: [PATCH] The stale-test-value check matches tests by resolved import, not file name (GST-3563) (#4723) The check that flags tests still holding a changed constant's old value now matches tests by the import that resolves to the changed file, not by file name. Why: when two files share a name (two `config.ts`), it flagged tests of the wrong file and a JSON golden nobody could waive, and a list that only gained an item flagged every test still naming the kept item. What you do: nothing. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team Review-Finding: lib/pregate/checks/literals.ts:197:core reader=core --- ...stale-test-value-check-resolves-imports.md | 4 + docs/pregate.md | 28 +++++ docs/troubleshooting.md | 4 +- lib/pregate/checks/literals.ts | 113 +++++++++++++++--- lib/pregate/import-graph.ts | 2 +- test/pregate-literals-consumers.test.ts | 113 ++++++++++++++++++ test/retired-skills.test.ts | 26 ++-- 7 files changed, 261 insertions(+), 29 deletions(-) create mode 100644 changelog.d/stale-test-value-check-resolves-imports.md create mode 100644 test/pregate-literals-consumers.test.ts diff --git a/changelog.d/stale-test-value-check-resolves-imports.md b/changelog.d/stale-test-value-check-resolves-imports.md new file mode 100644 index 000000000..d96b56a54 --- /dev/null +++ b/changelog.d/stale-test-value-check-resolves-imports.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +**The stale-test-value check no longer flags tests of a different file with the same name.** When two files share a name (two `config.ts`), a test now counts as using the changed file only if one of its imports or paths resolves to it, tsconfig path aliases included. JSON goldens count only where a value sits under the changed constant's name, and a one-item list that only gained items (`"investigate"` → `"investigate verify"`) no longer flags tests that still use the kept item, while an assertion on the whole old value still fails. diff --git a/docs/pregate.md b/docs/pregate.md index 70d8c2fed..cd92f1852 100644 --- a/docs/pregate.md +++ b/docs/pregate.md @@ -280,6 +280,34 @@ Two stages with separate clocks, both printed: or `limit` is an ordinary word, so for it the file must also name the changed module, whatever the old value's length: a test that only uses the word is not a consumer, and a test that imports the module still is. + When another file in the repository has the module's name (two `config.ts` + files), a path fragment or file name alone is ambiguous, so a file counts + through the module only when one of its references resolves to the changed + file: a relative import, a tsconfig/jsconfig `paths` alias or `baseUrl` + import, a quoted repository path or a `join()` of segments, the same + resolution lane selection uses. A test importing the other `config.ts` is not + a consumer (gbrain#10078: 17 false hits). An alias import counts even when the + name is unique. A test that reaches the module only through another module + (a barrel or a caller) is not found this way; it needs the constant's name. + A JSON file has no comments, so it can't carry a waiver; instead, an old value + in it counts only where the JSON ties it to the constant: the value of a key + named after the constant, or anything inside a record whose string value is + the constant's name (`{ "name": "LIMIT_MS", "signature": ["2000"] }`). An equal + value under another name in a golden is not a consumer; a golden that pins the + changed constant still is. A JSON file that doesn't parse counts only on lines + that name the constant. + A quoted one-item list that keeps its item and gains more + (`"investigate"` → `"investigate verify"`, every item a bare word) leaves its + member valid, so a line holding the old item counts only when it asserts the + whole old value: as the whole argument of `toBe`, `toEqual`, `toStrictEqual` + or an `equal`/`strictEqual`/`deepEqual` style assert (alone or as a one-item + array), beside `==`/`===`/`!=`/`!==`, or as an assignment's value; or in a + statement that names the constant or a binding taken from the module or the + constant (an alias such as `modes`), unless that line only checks membership + (`toContain`, `includes`, `indexOf`, `has`, `in`). Words inside strings + don't make a binding. A list that had several items, or a value that is prose + (`"file not found"`), keeps the ordinary rule, because its quoted old value is + the whole value wherever it appears. A test that keeps the old value on purpose, such as the refused input after a minimum version goes up, marks that one line with a comment on it or on the comment line directly above it: diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index e556cce11..e0ea65b6b 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -4848,7 +4848,9 @@ keeps the old value on purpose (the refused input after a minimum version goes up), mark that line: `// pregate-literal: NAME= ` on the line or on the comment line directly above it. The marker waives only that line, and the check lists it as `waived:`. Don't use `warn: ["literals"]` for this, since -that turns the check off for every constant. +that turns the check off for every constant. A JSON file can't hold a marker, +so the check only counts JSON values tied to the constant's name; a listed JSON +line really pins the old value, so update the golden. ### `PREGATE_ENVIRONMENT` with `environment: arg-limit — E2BIG` (or `Argument list too long`) diff --git a/lib/pregate/checks/literals.ts b/lib/pregate/checks/literals.ts index 5eab67786..7e6e1da60 100644 --- a/lib/pregate/checks/literals.ts +++ b/lib/pregate/checks/literals.ts @@ -10,7 +10,7 @@ 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, scansLiterals } from '../import-graph'; +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 } @@ -82,6 +82,58 @@ export function changedLiterals(file: string, oldText: string, newText: string): 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 | 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(); + 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 @@ -118,8 +170,16 @@ function unquote(v: string): string { return /^['"`]/.test(v) ? v.slice(1, -1) : * A consumer line is waived by a `pregate-literal: NAME= ` 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[]): string[] { +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(`(? new RegExp(`^[ \\t]*\\[[ \\t]*${/^['"`]/.test(raw) ? `['"\`]${escape(unquote(raw))}['"\`]` : escape(raw)}[ \\t]*,`, 'm'); @@ -136,22 +196,40 @@ export function consumersOf(repoRoot: string, testFiles: readonly string[], chan 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(); + 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*(?:\/\/|#|\*|\/\*|\n\nMY LOCAL EDITS\n'; - fs.writeFileSync(path.join(skills, 'investigate', 'SKILL.md'), edited); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired - fs.writeFileSync(path.join(skills, 'investigate', 'notes.md'), 'mine\n'); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired + fs.writeFileSync(path.join(skills, 'investigate', 'SKILL.md'), edited); + fs.writeFileSync(path.join(skills, 'investigate', 'notes.md'), 'mine\n'); const r = relink(); expect(r.status, r.stderr).toBe(0); - expect(fs.existsSync(path.join(skills, 'investigate', 'SKILL.md'))).toBe(false); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired - expect(fs.readFileSync(path.join(skills, 'investigate', 'notes.md'), 'utf8')).toBe('mine\n'); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired + expect(fs.existsSync(path.join(skills, 'investigate', 'SKILL.md'))).toBe(false); + expect(fs.readFileSync(path.join(skills, 'investigate', 'notes.md'), 'utf8')).toBe('mine\n'); const root = path.join(tmp, 'state', 'backups', 'skills'); - const backups = fs.readdirSync(root).map(stamp => path.join(root, stamp, 'investigate', 'SKILL.md')).filter(f => fs.existsSync(f)); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired + const backups = fs.readdirSync(root).map(stamp => path.join(root, stamp, 'investigate', 'SKILL.md')).filter(f => fs.existsSync(f)); expect(backups.map(f => fs.readFileSync(f, 'utf8'))).toEqual([edited]); });