mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-23 08:31:44 +01:00
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
This commit is contained in:
1 parent
50cc296700
commit
79f3052f35
7 files changed
+261
-29
No files matched your search
@@ -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.
|
||||
@@ -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:
|
||||
|
||||
@@ -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=<old value> <reason>` 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.
|
||||
|
||||
<a id="arg-limit"></a>
|
||||
### `PREGATE_ENVIRONMENT` with `environment: arg-limit — E2BIG` (or `Argument list too long`)
|
||||
|
||||
@@ -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<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
|
||||
@@ -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=<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[]): 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(`(?<![\\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');
|
||||
@@ -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<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; }
|
||||
if (!((nameRequired ? nameRe.test(text) : nameRe.test(text) || moduleRe.test(text)) && (!callSite || moduleRe.test(text)))) 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 bindings = shortNumber ? moduleBindings(lines, moduleRe, comment, continues) : [];
|
||||
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) => {
|
||||
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(lines[j]!)) return true;
|
||||
if (statementRe.test(code ? blankStrings(lines[j]!) : lines[j]!)) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
@@ -178,18 +256,24 @@ export function consumersOf(repoRoot: string, testFiles: readonly string[], chan
|
||||
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]!); };
|
||||
for (let i = 0; i < lines.length; i++) if (carries(i) && (!(nameRequired || shortNumber) || oldRowRe.test(lines[i]!) || named(i)) && !skip(i) && !waiver(i)) { hits.push(`${rel}:${i + 1}`); break; }
|
||||
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[], moduleRe: RegExp, comment: (l: string) => boolean, continues: (prev: string, cur: string) => boolean): string[] {
|
||||
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>();
|
||||
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 (!moduleRe.test(m[2]!)) continue;
|
||||
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);
|
||||
@@ -207,11 +291,11 @@ function moduleBindings(lines: readonly string[], moduleRe: RegExp, comment: (l:
|
||||
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 || !(moduleRe.test(s) || knownRe?.test(s.slice(m.index + m[0].length)))) continue;
|
||||
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 => /^[\w$]+$/.test(n));
|
||||
return [...out].filter(n => n !== name && /^[\w$]+$/.test(n));
|
||||
}
|
||||
|
||||
function run(ctx: PregateContext): CheckResult {
|
||||
@@ -226,7 +310,8 @@ function run(ctx: PregateContext): CheckResult {
|
||||
}
|
||||
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 testFiles = listRepoFiles(ctx.repoRoot).filter(f => scansLiterals(f) && !f.startsWith('bin/'));
|
||||
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) {
|
||||
@@ -237,7 +322,7 @@ function run(ctx: PregateContext): CheckResult {
|
||||
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);
|
||||
}, 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})`);
|
||||
|
||||
@@ -279,7 +279,7 @@ const NO_ALIASES: PathAliases = { aliases: [], baseUrl: null, notes: [] };
|
||||
* config that declares neither defers upward, so a file never loses an alias
|
||||
* the root gives it. With no nested config every file gets the root's.
|
||||
*/
|
||||
function pathAliasResolver(repoRoot: string, files: readonly string[]): { aliasesFor: (rel: string) => PathAliases; notes: string[] } {
|
||||
export function pathAliasResolver(repoRoot: string, files: readonly string[]): { aliasesFor: (rel: string) => PathAliases; notes: string[] } {
|
||||
const root = readPathAliases(repoRoot);
|
||||
const notes = [...root.notes];
|
||||
const read = new Set<string>();
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { consumersOf } from '../lib/pregate/checks/literals';
|
||||
|
||||
const nl = String.fromCharCode(10);
|
||||
function fixture(prefix: string, files: Record<string, string>): string {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
for (const [rel, text] of Object.entries(files)) { fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true }); fs.writeFileSync(path.join(root, rel), text); }
|
||||
return root;
|
||||
}
|
||||
const tests = (files: Record<string, string>) => Object.keys(files).filter(f => f.startsWith('test/'));
|
||||
|
||||
describe('literals: consumers by resolved reference (GBRA-739)', () => {
|
||||
// Value: protects=when another repo file shares the changed module's file name, a test counts as its consumer only through a
|
||||
// reference that resolves to it (a relative import, a tsconfig paths alias, a quoted repo path), so tests importing the other
|
||||
// config.ts are not flagged while the real consumer is; fails_when=a path fragment such as `/config'` makes a file a consumer
|
||||
// again (gbrain#10078: DEFAULT_SESSION_TOKEN_BUDGET 2000 -> 8000 in src/core/skills/resolver/config.ts flagged 17 tests of
|
||||
// src/core/config.ts); why_new=fixtures never held a second file with the module's name; seam=none; no_claim=a module name
|
||||
// unique in the repo keeps the fragment rule (previous tests)
|
||||
test('a test importing a same-named module elsewhere is not a consumer; one importing the changed file still is', () => {
|
||||
const files: Record<string, string> = {
|
||||
'src/core/config.ts': "export const LOCK_WAIT_MS = 2000;" + nl,
|
||||
'src/core/skills/resolver/config.ts': "export const DEFAULT_SESSION_TOKEN_BUDGET = 8000;" + nl,
|
||||
'tsconfig.json': JSON.stringify({ compilerOptions: { baseUrl: '.', paths: { '@/*': ['src/*'] } } }),
|
||||
'test/config.test.ts': ["import { loadConfig } from '../src/core/config';", "expect(loadConfig({ since: '2000-01-01' }).lockWaitMs).toBe(2000);", ''].join(nl),
|
||||
'test/retry-after.test.ts': ["import { parseRetryAfterMs } from '../src/core/config.ts';", "expect(parseRetryAfterMs('2')).toBe(2000);", ''].join(nl),
|
||||
'test/alias-other.test.ts': ["import { loadConfig } from '@/core/config';", 'expect(loadConfig().lockWaitMs).toBe(2000);', ''].join(nl),
|
||||
'test/budget.test.ts': ["import { sessionBudget } from '../src/core/skills/resolver/config';", 'expect(sessionBudget()).toBe(2000);', ''].join(nl),
|
||||
'test/alias-budget.test.ts': ["import { sessionBudget } from '@/core/skills/resolver/config';", 'expect(sessionBudget()).toBe(2000);', ''].join(nl),
|
||||
'test/named.test.ts': ['expect(DEFAULT_SESSION_TOKEN_BUDGET).toBe(2000);', ''].join(nl),
|
||||
};
|
||||
const root = fixture('gstack-literals-twin-', files);
|
||||
const change = { name: 'DEFAULT_SESSION_TOKEN_BUDGET', old: '2000', new: '8000', file: 'src/core/skills/resolver/config.ts' };
|
||||
expect(consumersOf(root, tests(files), change, undefined, undefined, Object.keys(files))).toEqual(['test/budget.test.ts:2', 'test/alias-budget.test.ts:2', 'test/named.test.ts:1']);
|
||||
const unique = ['tsconfig.json', 'src/core/skills/resolver/config.ts', 'src/core/config/README.md', 'test/alias-budget.test.ts', 'test/config.test.ts'];
|
||||
expect(consumersOf(root, ['test/alias-budget.test.ts', 'test/config.test.ts'], change, undefined, undefined, unique)).toEqual(['test/alias-budget.test.ts:2', 'test/config.test.ts:2']);
|
||||
fs.writeFileSync(path.join(root, 'tsconfig.json'), JSON.stringify({ compilerOptions: { baseUrl: '.', paths: { '#budget': ['src/core/skills/resolver/config.ts'] } } }));
|
||||
fs.writeFileSync(path.join(root, 'test/exact-alias.test.ts'), ["import { sessionBudget } from '#budget';", 'expect(sessionBudget()).toBe(2000);', ''].join(nl));
|
||||
expect(consumersOf(root, ['test/exact-alias.test.ts'], change, undefined, undefined, [...unique, 'test/exact-alias.test.ts'])).toEqual(['test/exact-alias.test.ts:2']);
|
||||
expect(consumersOf(root, ['test/exact-alias.test.ts'], change)).toEqual([]);
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// Value: protects=a JSON file cannot carry a pregate-literal marker, so an old value in it counts only where JSON ties it to the
|
||||
// constant: the value of a key named after the constant, or a record whose string value is the constant's name; fails_when=an
|
||||
// unrelated equal value in a golden is reported again (gbrain#10078: "2000" for LONG_PAGE_DEADLINE_MS in an exports golden),
|
||||
// or a golden that pins the changed constant stops being reported; why_new=JSON hits were unwaivable; seam=none; no_claim=JSON
|
||||
// that pins a derived value under another key
|
||||
test('a JSON golden counts only where it ties the old value to the changed constant', () => {
|
||||
const record = (name: string, value: string) => [' {', ' "kind": "variable",', ` "name": "${name}",`, ' "signature": [', ` "${value}"`, ' ]', ' }'];
|
||||
const files: Record<string, string> = {
|
||||
'test/fixtures/goldens/unrelated.json': ['{', ' "src/core/skills/resolver/config.ts": [', ...record('LONG_PAGE_DEADLINE_MS', '2000'), ' ]', '}', ''].join(nl),
|
||||
'test/fixtures/goldens/pinned.json': ['{', ' "src/core/skills/resolver/config.ts": [', ...record('LONG_PAGE_DEADLINE_MS', '2000') .map((l, i) => i === 6 ? l + ',' : l), ...record('DEFAULT_SESSION_TOKEN_BUDGET', '2000'), ' ]', '}', ''].join(nl),
|
||||
'test/fixtures/goldens/keyed.json': JSON.stringify({ other: 2000, DEFAULT_SESSION_TOKEN_BUDGET: 2000 }, null, 2) + nl,
|
||||
'test/fixtures/goldens/sibling.json': JSON.stringify({ DEFAULT_SESSION_TOKEN_BUDGET: 8000, LONG_PAGE_DEADLINE_MS: 2000 }, null, 2) + nl,
|
||||
};
|
||||
const root = fixture('gstack-literals-json-', files);
|
||||
const change = { name: 'DEFAULT_SESSION_TOKEN_BUDGET', old: '2000', new: '8000', file: 'src/core/skills/resolver/config.ts' };
|
||||
expect(consumersOf(root, Object.keys(files), change)).toEqual(['test/fixtures/goldens/pinned.json:14', 'test/fixtures/goldens/keyed.json:3']);
|
||||
fs.writeFileSync(path.join(root, 'test/fixtures/goldens/broken.json'), ['{', ' "LONG_PAGE_DEADLINE_MS": 2000,', ' "DEFAULT_SESSION_TOKEN_BUDGET": 2000,', ''].join(nl));
|
||||
expect(consumersOf(root, ['test/fixtures/goldens/broken.json'], change)).toEqual(['test/fixtures/goldens/broken.json:3']);
|
||||
fs.writeFileSync(path.join(root, 'test/fixtures/run.json'), JSON.stringify({ timeout: 30000 }, null, 2) + nl);
|
||||
fs.writeFileSync(path.join(root, 'test/fixtures/runner-run.json'), JSON.stringify({ module: 'lib/runner.ts', timeout: 30000 }, null, 2) + nl);
|
||||
expect(consumersOf(root, ['test/fixtures/run.json', 'test/fixtures/runner-run.json'], { name: 'timeout', old: '30000', new: '60000', file: 'lib/runner.ts' })).toEqual(['test/fixtures/runner-run.json:3']);
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('literals: a one-item list that only gained items (#4714, #4719)', () => {
|
||||
// Value: protects=when a one-item list constant only gains items ("investigate" -> "investigate verify"), a test that still names
|
||||
// the unchanged member (a path, a fixture, a membership check) is not a consumer, while an assertion that the whole value is the
|
||||
// old one still is, directly (toBe, toEqual, ===, an assert call, an assignment) or through a binding taken from the module or
|
||||
// the constant; fails_when=member lines are reported again (#4714 carried 13 markers in test/retired-skills.test.ts), or a
|
||||
// whole-value assertion through an alias such as `modes` is missed (#4719's review); why_new=list growth had no rule;
|
||||
// seam=none; no_claim=multi-item old lists, whose quoted old value is the whole value wherever it appears
|
||||
test('member uses are not consumers; whole-value assertions, aliases included, still are', () => {
|
||||
const files: Record<string, string> = {
|
||||
'test/member.test.ts': ["const REGISTRY = path.join(ROOT, 'bin', 'registry.sh');", "fs.mkdirSync(path.join(skills, 'investigate'));", "expect(fs.existsSync(path.join(skills, 'investigate', 'SKILL.md'))).toBe(false);", ''].join(nl),
|
||||
'test/contains.test.ts': ["const out = run('bin/registry.sh');", "expect(out.split(' ')).toContain('investigate');", "expect(out.includes('investigate')).toBe(true);", ''].join(nl),
|
||||
'test/exact.test.ts': ["const out = run('bin/registry.sh');", "expect(names(out)).toBe('investigate');", ''].join(nl),
|
||||
'test/array.test.ts': ["const out = run('bin/registry.sh');", "expect(list(out)).toEqual(['investigate']);", ''].join(nl),
|
||||
'test/strict.test.ts': ["const out = run('bin/registry.sh');", "assert.strictEqual(read(out), 'investigate');", ''].join(nl),
|
||||
'test/compare.test.ts': ["const out = run('bin/registry.sh');", "if (read(out) !== 'investigate') throw new Error('x');", ''].join(nl),
|
||||
'test/assign.test.ts': ["const out = run('bin/registry.sh');", "const expected = 'investigate';", 'expect(read(out)).toBe(expected);', ''].join(nl),
|
||||
'test/alias.test.ts': ["import { RETIRED_DEMO_SKILLS as modes } from '../bin/registry.sh';", "expect(check(modes, 'investigate')).toBe(true);", ''].join(nl),
|
||||
'test/alias-member.test.ts': ["import { RETIRED_DEMO_SKILLS as modes } from '../bin/registry.sh';", "expect(modes.split(' ')).toContain('investigate');", ''].join(nl),
|
||||
'test/derived.test.ts': ["import { RETIRED_DEMO_SKILLS } from '../bin/registry.sh';", 'const modes = RETIRED_DEMO_SKILLS;', "expect(same(modes, 'investigate')).toBe(true);", ''].join(nl),
|
||||
};
|
||||
const root = fixture('gstack-literals-grew-', files);
|
||||
const change = { name: 'RETIRED_DEMO_SKILLS', old: '"investigate"', new: '"investigate verify"', file: 'bin/registry.sh' };
|
||||
expect(consumersOf(root, Object.keys(files), change)).toEqual([
|
||||
'test/exact.test.ts:2', 'test/array.test.ts:2', 'test/strict.test.ts:2', 'test/compare.test.ts:2', 'test/assign.test.ts:2', 'test/alias.test.ts:2', 'test/derived.test.ts:3',
|
||||
]);
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test('only a one-item list that kept its item and gained more gets the rule; prose and multi-item lists keep the old one', () => {
|
||||
const files: Record<string, string> = {
|
||||
'test/prose.test.ts': ["import { ERR } from '../src/errors';", "expect(log('file not found')).toBe(1);", ''].join(nl),
|
||||
'test/modes.test.ts': ["import { MODES as modes } from '../src/modes';", "expect(log('read write')).toBe(1);", "expect(modes.split(' ')).toContain('read');", ''].join(nl),
|
||||
'test/swap.test.ts': ["import { MODE } from '../src/mode';", "fs.mkdirSync(path.join(dir, 'fast'));", ''].join(nl),
|
||||
};
|
||||
const root = fixture('gstack-literals-grew-not-', files);
|
||||
expect(consumersOf(root, ['test/prose.test.ts'], { name: 'ERR', old: '"file not found"', new: '"file not found here"', file: 'src/errors.ts' })).toEqual(['test/prose.test.ts:2']);
|
||||
expect(consumersOf(root, ['test/modes.test.ts'], { name: 'MODES', old: "'read write'", new: "'read write admin'", file: 'src/modes.ts' })).toEqual(['test/modes.test.ts:2']);
|
||||
expect(consumersOf(root, ['test/swap.test.ts'], { name: 'MODE', old: "'fast'", new: "'slow fast'", file: 'src/mode.ts' })).toEqual([]);
|
||||
expect(consumersOf(root, ['test/swap.test.ts'], { name: 'MODE', old: "'fast'", new: "'slow'", file: 'src/mode.ts' })).toEqual(['test/swap.test.ts:2']);
|
||||
expect(consumersOf(root, ['test/swap.test.ts'], { name: 'MODE', old: "'fast'", new: "'fast!'", file: 'src/mode.ts' })).toEqual(['test/swap.test.ts:2']);
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
+13
-13
@@ -56,36 +56,36 @@ describe('gstack-relink after an upgrade removed /investigate (GST-1717)', () =>
|
||||
afterEach(() => fs.rmSync(tmp, { recursive: true, force: true }));
|
||||
|
||||
test('the dangling investigate and gstack-investigate entries are removed', () => {
|
||||
fs.mkdirSync(path.join(skills, 'investigate')); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired
|
||||
fs.symlinkSync(path.join(install, 'investigate', 'SKILL.md'), path.join(skills, 'investigate', 'SKILL.md')); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired
|
||||
fs.symlinkSync(path.join(install, 'investigate'), path.join(skills, 'gstack-investigate')); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired
|
||||
fs.mkdirSync(path.join(skills, 'investigate'));
|
||||
fs.symlinkSync(path.join(install, 'investigate', 'SKILL.md'), path.join(skills, 'investigate', 'SKILL.md'));
|
||||
fs.symlinkSync(path.join(install, 'investigate'), path.join(skills, 'gstack-investigate'));
|
||||
const r = relink();
|
||||
expect(r.status, r.stderr).toBe(0);
|
||||
expect(fs.lstatSync(path.join(skills, 'investigate'), { throwIfNoEntry: false })).toBeUndefined(); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired
|
||||
expect(fs.lstatSync(path.join(skills, 'investigate'), { throwIfNoEntry: false })).toBeUndefined();
|
||||
expect(fs.lstatSync(path.join(skills, 'gstack-investigate'), { throwIfNoEntry: false })).toBeUndefined();
|
||||
expect(fs.existsSync(path.join(skills, 'ship', 'SKILL.md'))).toBe(true);
|
||||
});
|
||||
|
||||
test("a user's own investigate skill is left alone", () => {
|
||||
fs.mkdirSync(path.join(skills, 'investigate')); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired
|
||||
fs.mkdirSync(path.join(skills, 'investigate'));
|
||||
const own = '---\nname: investigate\ndescription: mine\n---\nmy own debugger\n';
|
||||
fs.writeFileSync(path.join(skills, 'investigate', 'SKILL.md'), own); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired
|
||||
fs.writeFileSync(path.join(skills, 'investigate', 'SKILL.md'), own);
|
||||
const r = relink();
|
||||
expect(r.status, r.stderr).toBe(0);
|
||||
expect(fs.readFileSync(path.join(skills, 'investigate', 'SKILL.md'), 'utf8')).toBe(own); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired
|
||||
expect(fs.readFileSync(path.join(skills, 'investigate', 'SKILL.md'), 'utf8')).toBe(own);
|
||||
});
|
||||
|
||||
test('an edited gstack-generated investigate copy moves to the backup root instead of being deleted', () => {
|
||||
fs.mkdirSync(path.join(skills, 'investigate')); // pregate-literal: GSTACK_RETIRED_SKILLS="investigate" retired list only gained verify; investigate stays retired
|
||||
fs.mkdirSync(path.join(skills, 'investigate'));
|
||||
const edited = '---\nname: investigate\ndescription: test\n---\n<!-- AUTO-GENERATED from SKILL.md.tmpl — do not edit directly -->\n<!-- Regenerate: bun run gen:skill-docs -->\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]);
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user