Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

fix(checks): find source readers across lines, file by file [D1,C7]

Corey Olson7eafbe1ce748
diff --git a/bin/checks/test-inputs.js b/bin/checks/test-inputs.js
index 95be16ca..00dc00f8 100644
--- a/bin/checks/test-inputs.js
+++ b/bin/checks/test-inputs.js
@@ -3,25 +3,36 @@
* Rigor check: a test that reads source files declares it [D1,C7,V4].
*
* Submit selects the tests a change affects through import edges (src/affected-tests.js). A test
- * that reads source as data, rather than importing it, is invisible to that graph unless its file
- * opens with the header line the selection reads: `/** @pullboard-test-input source-tree *\/`,
+ * that reaches source by path, rather than importing it, is invisible to that graph unless its
+ * file opens with the header line the selection reads: `/** @pullboard-test-input source-tree *\/`,
* among the declaration lines at the very top of the file.
*
- * A test reads source files when one line of its code (outside strings and comments) calls a
- * node:fs read (readFileSync, readFile, readdirSync, readdir, opendirSync, opendir or
- * createReadStream), anchors a path at this checkout through `import.meta` or a `ROOT` constant,
- * and holds a string or template literal naming the source tree: `src` as a whole path segment,
- * as in '../src/seal.js' or join(ROOT, 'src'). The anchor keeps out fixtures, which copy src into
- * a temporary repo and read that copy. A test file is `*.test.js` or `*.spec.js`, also .mjs and
- * .cjs. One problem per undeclared test file, at its first such line.
+ * The rule is per file, because a path is often built on one line and read on another (a variable,
+ * a queue of files to walk). A test file reads source files when its code (outside strings and
+ * comments) has both of these anywhere:
+ * - a node:fs read or copy call: readFileSync, readFile, readdirSync, readdir, opendirSync,
+ * opendir, createReadStream, cpSync, cp, copyFileSync or copyFile;
+ * - an anchored source path: a string or template literal naming the source tree (`src` as a whole
+ * path segment; for a template, in its text before the first `${`) that is a direct argument of
+ * a call whose own arguments include `import.meta.url`, `import.meta.dirname`,
+ * `import.meta.filename` or a `ROOT` constant, as in new URL('../src/x.js', import.meta.url),
+ * resolve(import.meta.dirname, '../src') or join(ROOT, 'src', 'cockpit.js').
+ *
+ * Two kinds of path do not count. A fixture path, such as join(lane, 'src/board.js'), has no
+ * anchor: it names a copy inside a temporary repo, not this checkout. A module URL, which the
+ * code turns into `.href`, wraps in pathToFileURL(...) or passes to import(...), names a module to
+ * import, not a file to read. A test file is `*.test.js` or `*.spec.js`, also .mjs and .cjs. One
+ * problem per undeclared test file, at the line of its first anchored source path.
*/
-import { lex, readText, runCheck, TEST_FILE, walk } from './scan.js';
+import { lex, lineAt, readText, runCheck, TEST_FILE, walk } from './scan.js';
const SOURCE_TREE_INPUT = '/** @pullboard-test-input source-tree */';
const DECLARATIONS = new Set([SOURCE_TREE_INPUT, '/** @pullboard-test-input test-tree */', '/** @pullboard-test-input docs-tree */']);
-const READ = /\b(?:readFileSync|readFile|readdirSync|readdir|opendirSync|opendir|createReadStream)\s*\(/u;
-const ANCHOR = /\bimport\s*\.\s*meta\b|(?<![\w$.])ROOT\b/u;
+const READ = /(?<![\w$])(?:readFileSync|readFile|readdirSync|readdir|opendirSync|opendir|createReadStream|cpSync|cp|copyFileSync|copyFile)\s*\(/u;
+const ANCHOR = /(?<![\w$])import\s*\.\s*meta\s*\.\s*(?:url|dirname|filename)\b|(?<![\w$.])ROOT\b/u;
const SOURCE_PATH = /(?:^|\/)src(?:\/|$)/u;
+const OPENERS = '([{';
+const CLOSERS = ')]}';
/**
* True when the file's leading declaration lines include the source-tree input, read as the
@@ -38,6 +49,79 @@ export function declaresSource(source) {
return false;
}
+/** The offset of the innermost bracket that encloses `at` in blanked code, or -1. */
+function enclosing(code, at) {
+ let depth = 0;
+ for (let index = at - 1; index >= 0; index -= 1) {
+ if (CLOSERS.includes(code[index])) depth += 1;
+ else if (OPENERS.includes(code[index])) {
+ if (depth === 0) return index;
+ depth -= 1;
+ }
+ }
+ return -1;
+}
+
+/** The offset of the bracket that closes the one at `open`, or the end of the code. */
+function closing(code, open) {
+ let depth = 0;
+ for (let index = open + 1; index < code.length; index += 1) {
+ if (OPENERS.includes(code[index])) depth += 1;
+ else if (CLOSERS.includes(code[index])) {
+ if (depth === 0) return index;
+ depth -= 1;
+ }
+ }
+ return code.length;
+}
+
+/** The code between two brackets at their own depth, with anything nested deeper blanked. */
+function ownArguments(code, open, close) {
+ let text = '';
+ let depth = 0;
+ for (let index = open + 1; index < close; index += 1) {
+ const char = code[index];
+ if (OPENERS.includes(char)) depth += 1;
+ else if (CLOSERS.includes(char)) depth -= 1;
+ else text += depth === 0 ? char : ' ';
+ }
+ return text;
+}
+
+/**
+ * True when the call that opens at `open` names a module to import: it, or the call wrapping it,
+ * is followed by `.href`, is wrapped in pathToFileURL(...), or is the argument of import(...).
+ */
+function moduleUrl(code, open, close) {
+ const callee = code.slice(0, open).trimEnd();
+ if (/(?<![\w$.])import$/u.test(callee)) return true;
+ if (/^\s*\.\s*href\b/u.test(code.slice(close + 1))) return true;
+ const outer = enclosing(code, open);
+ if (outer === -1 || code[outer] !== '(') return false;
+ const wrapper = code.slice(0, outer).trimEnd();
+ return /(?<![\w$.])(?:pathToFileURL|import)$/u.test(wrapper) || /^\s*\.\s*href\b/u.test(code.slice(closing(code, outer) + 1));
+}
+
+/**
+ * The offset of the first anchored source path in a file's code, or -1.
+ *
+ * @param {string} source
+ * @param {ReturnType<typeof lex>} lexed
+ * @returns {number}
+ */
+function firstAnchoredSourcePath(source, { code, strings }) {
+ for (const literal of strings) {
+ const text = source[literal.start] === '`' ? literal.text.split('${')[0] : literal.text;
+ if (!SOURCE_PATH.test(text)) continue;
+ const open = enclosing(code, literal.start);
+ if (open === -1 || code[open] !== '(') continue;
+ const close = closing(code, open);
+ if (!ANCHOR.test(ownArguments(code, open, close)) || moduleUrl(code, open, close)) continue;
+ return literal.start;
+ }
+ return -1;
+}
+
/**
* One problem per test file that reads source files without the declaration.
*
@@ -49,13 +133,10 @@ export function testInputProblems(root) {
for (const path of walk(root, TEST_FILE)) {
const source = readText(root, path);
if (declaresSource(source)) continue;
- const { code, strings } = lex(source);
- const codeLines = code.split('\n');
- const lineStarts = [0];
- for (const line of codeLines) lineStarts.push(lineStarts[lineStarts.length - 1] + line.length + 1);
- const index = codeLines.findIndex((line, at) => READ.test(line) && ANCHOR.test(line)
- && strings.some((literal) => literal.start >= lineStarts[at] && literal.start < lineStarts[at + 1] && SOURCE_PATH.test(literal.text)));
- if (index !== -1) problems.push({ path, line: index + 1, text: `reads source files without ${SOURCE_TREE_INPUT} at the top` });
+ const lexed = lex(source);
+ if (!READ.test(lexed.code)) continue;
+ const at = firstAnchoredSourcePath(source, lexed);
+ if (at !== -1) problems.push({ path, line: lineAt(source, at), text: `reads source files without ${SOURCE_TREE_INPUT} at the top` });
}
return problems;
}
diff --git a/test/rigor-checks.test.js b/test/rigor-checks.test.js
index 2c465fb0..6a93decf 100644
--- a/test/rigor-checks.test.js
+++ b/test/rigor-checks.test.js
@@ -60,8 +60,11 @@ const PINNED_PROBLEMS = {
['test/land.test.js', 760], ['test/land.test.js', 762], ['test/land.test.js', 906], ['test/runners.test.js', 1250],
].map(([path, line]) => `${path}:${line}: ${BARE}`),
'test-inputs': [
- ['test/blueprint.test.js', 13], ['test/cockpit/layout.test.js', 146], ['test/cockpit/relay.test.js', 131],
- ['test/doctrine.test.js', 28], ['test/seal.test.js', 90],
+ ['test/api-http.test.js', 428], ['test/blueprint.test.js', 13], ['test/cockpit/layout.test.js', 146],
+ ['test/cockpit/relay.test.js', 131], ['test/doctrine.test.js', 28], ['test/e2e-private-checks.test.js', 113],
+ ['test/gate-profile.test.js', 16], ['test/gate.test.js', 13], ['test/help.test.js', 33], ['test/resources.test.js', 131],
+ ['test/resume-flow.test.js', 27], ['test/run-tests.test.js', 119], ['test/seal.test.js', 90], ['test/settings.test.js', 11],
+ ['test/test-resources.test.js', 86], ['test/test-runner.test.js', 108],
].map(([path, line]) => `${path}:${line}: ${UNDECLARED}`),
};
@@ -139,7 +142,7 @@ test('Pullboard\'s four checks count what main has [D1, C7]', async (t) => {
assert.deepEqual(runCheck(name, { cwd: dir, root: pinned }).lines, expected[name], `${name} scans its argument the same`);
}
assert.deepEqual(Object.fromEntries(CHECKS.map((name) => [name, expected[name].length])),
- { 'file-size': 70, 'test-names': 15, 'empty-catch': 13, 'test-inputs': 5 }, 'today\'s counts');
+ { 'file-size': 70, 'test-names': 15, 'empty-catch': 13, 'test-inputs': 16 }, 'today\'s counts');
});
await t.test('on this checkout each check prints sorted path:line: text lines, exits 0 or 1, in under 10s [D1, C7]', () => {
@@ -249,17 +252,48 @@ test('Pullboard\'s four checks count what main has [D1, C7]', async (t) => {
"test('reads the seal source [S1]', () => readFileSync(new URL('../src/seal.js', import.meta.url), 'utf8'));",
'',
].join('\n');
+ const splitVariable = [
+ "import { readFileSync } from 'node:fs';",
+ "const source = new URL('../src/x.js', import.meta.url);",
+ 'export const text = readFileSync(source, \'utf8\');',
+ '',
+ ].join('\n');
+ const queuedWalk = [
+ "import { readFileSync } from 'node:fs';",
+ "import { resolve } from 'node:path';",
+ "const ROOT = resolve(import.meta.dirname, '..');",
+ "const pending = [[resolve(ROOT, 'src/help.js')]];",
+ 'for (const file of pending.pop()) readFileSync(file, \'utf8\');',
+ '',
+ ].join('\n');
put(root, 'test/declared.test.js', `/** @pullboard-test-input test-tree */\n/** @pullboard-test-input source-tree */\n${reader}`);
put(root, 'test/fixture-copy.test.js', "import { readFileSync } from 'node:fs';\nconst copy = (lane) => readFileSync(join(lane, 'src/board.js'), 'utf8');\n");
put(root, 'test/imports.test.js', "import { seal } from '../src/seal.js';\nconst note = \"readFileSync(new URL('../src/a.js', import.meta.url))\";\n");
+ put(root, 'test/module-url.test.js', [
+ "import { readFileSync } from 'node:fs';",
+ "const board = new URL('../src/board.js', import.meta.url).href;",
+ "const cli = pathToFileURL(resolve(import.meta.dirname, '../src/cli.js')).href;",
+ "const api = await import(new URL('../src/api.js', import.meta.url));",
+ "export const config = readFileSync('pullboard.json', 'utf8');",
+ '',
+ ].join('\n'));
+ put(root, 'test/no-read.test.js', "export const worker = resolve(import.meta.dirname, '../src/worker.js');\n");
const clean = runCheck('test-inputs', { root });
- assert.deepEqual([clean.status, clean.lines], [0, []], 'a declared reader, a fixture copy and an import print nothing');
+ assert.deepEqual([clean.status, clean.lines], [0, []], 'a declared reader, a fixture copy, an import, module URLs and a path never read print nothing');
put(root, 'test/undeclared.test.js', reader);
const undeclared = runCheck('test-inputs', { root });
assert.deepEqual(undeclared.lines, [`test/undeclared.test.js:3: ${UNDECLARED}`], 'one undeclared reader is one line');
assert.equal(undeclared.status, 1);
+ rmSync(join(root, 'test/undeclared.test.js'));
+ put(root, 'test/split-variable.test.js', splitVariable);
+ assert.deepEqual(runCheck('test-inputs', { root }).lines, [`test/split-variable.test.js:2: ${UNDECLARED}`],
+ 'a source path built on one line and read on the next is one line');
+ rmSync(join(root, 'test/split-variable.test.js'));
+ put(root, 'test/queued-walk.test.js', queuedWalk);
+ assert.deepEqual(runCheck('test-inputs', { root }).lines, [`test/queued-walk.test.js:4: ${UNDECLARED}`],
+ 'a ROOT-anchored path queued and read later, as help.test.js does, is one line');
put(root, 'test/late.test.js', `import { readFileSync } from 'node:fs';\n/** @pullboard-test-input source-tree */\n${reader.split('\n').slice(1).join('\n')}`);
assert.deepEqual(runCheck('test-inputs', { root }).lines.map((line) => line.slice(0, line.indexOf(':'))),
- ['test/late.test.js', 'test/undeclared.test.js'], 'a declaration below the first code line is not read, as the selection reads it');
+ ['test/late.test.js', 'test/queued-walk.test.js'], 'a declaration below the first code line is not read, as the selection reads it');
});
});