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(test): run test entries without standalone helpers [C7]

Corey Olson5cc8089ba71f
diff --git a/bin/run-tests.js b/bin/run-tests.js
index 2166ff40..019edcee 100644
--- a/bin/run-tests.js
+++ b/bin/run-tests.js
@@ -297,35 +297,11 @@ function explicitTestFiles(args) {
return files;
}
-/** Match Node's default test-file patterns against a Git path for this runtime. */
-function isDefaultTestFile(path, includeTypeScript) {
+/** Select repository test entry files while keeping imported helpers out of direct discovery. */
+function isDefaultTestFile(path) {
const normalized = path.replaceAll('\\', '/');
- const parts = normalized.split('/');
- if (parts.some(part => part === 'node_modules' || part.startsWith('.'))) return false;
- const basename = parts.at(-1);
- const extension = includeTypeScript ? /\.(?:cjs|mjs|js|cts|mts|ts)$/u : /\.(?:cjs|mjs|js)$/u;
- if (!extension.test(basename)) return false;
- return parts.slice(0, -1).includes('test') ||
- /^test(?:-|\.)/u.test(basename) ||
- (includeTypeScript
- ? /(?:\.test|-test|_test)\.(?:cjs|mjs|js|cts|mts|ts)$/u
- : /(?:\.test|-test|_test)\.(?:cjs|mjs|js)$/u).test(basename);
-}
-
-/** Probe the effective TypeScript mode of the Node child that will execute tests. */
-function typeScriptTestDiscovery(args, env) {
- const typeFlags = args.filter(argument => [
- '--experimental-strip-types', '--strip-types', '--experimental-transform-types',
- '--no-experimental-strip-types', '--no-strip-types',
- ].includes(argument));
- const result = spawnSync(process.execPath, [...typeFlags, '-p', 'String(process.features?.typescript ?? false)'], {
- cwd: process.cwd(), encoding: 'utf8', env, timeout: 5_000,
- });
- if (result.error) throw result.error;
- if (result.status !== 0) {
- throw new Error(`Node could not report TypeScript test discovery mode (status ${result.status}, signal ${result.signal ?? 'none'}): ${result.stderr.trim()}`);
- }
- return !['false', 'undefined', ''].includes(result.stdout.trim());
+ if (normalized.split('/').some(part => part === 'node_modules' || part.startsWith('.'))) return false;
+ return /^(?:test|docs)\/.+\.test\.(?:js|mjs)$/u.test(normalized);
}
/** Preserve native discovery outside Git, but never hide a repository access failure. */
@@ -339,10 +315,10 @@ function isGitWorkTree(cwd, env) {
throw new Error(result.stderr.trim() || `git rev-parse failed (status ${result.status})`);
}
-/** List tracked files matching Node's runtime default patterns, excluding worktree copies. */
-function trackedDefaultTestFiles(cwd, includeTypeScript, env) {
+/** List tracked repository test entry files, excluding helpers and worktree-only copies. */
+function trackedDefaultTestFiles(cwd, env) {
const output = execFileSync('git', ['ls-files', '-z'], { cwd, env, encoding: 'utf8' });
- return output.split('\0').filter(path => path && isDefaultTestFile(path, includeTypeScript)).sort()
+ return output.split('\0').filter(path => path && isDefaultTestFile(path)).sort()
.map(path => `./${path}`);
}
@@ -382,7 +358,7 @@ function executeTests(args, sandbox, gateMarkers, fullSuite) {
let files;
try {
files = isGitWorkTree(process.cwd(), env)
- ? trackedDefaultTestFiles(process.cwd(), typeScriptTestDiscovery(args, env), env)
+ ? trackedDefaultTestFiles(process.cwd(), env)
: null;
}
catch (error) {
diff --git a/src/affected-tests.js b/src/affected-tests.js
index b8cf8d89..9f3a837a 100644
--- a/src/affected-tests.js
+++ b/src/affected-tests.js
@@ -7,6 +7,7 @@ import { importsIn } from './module-imports.js';
const MODULE = /\.[cm]?js$/u;
const TEST = /\.(?:test|spec)\.[cm]?js$/u;
const DOC = /^docs\/.+\.md$/u;
+const TEST_README = /^test\/(?:.*\/)?README\.md$/u;
// A scanner declares this header rather than executing code while the graph is read.
const TEST_TREE_INPUT = '/** @pullboard-test-input test-tree */';
const SOURCE_TREE_INPUT = '/** @pullboard-test-input source-tree */';
@@ -138,7 +139,7 @@ function documentationInputs(path, source, imports, changedDocs = []) {
}
/** Compile this tree's import edges, plus the literal child-CLI dependency used by fixture modules. */
-function graphAt(root, commit, changedDocs = []) {
+function graphAt(root, commit, changedDocs = [], changedReadmes = []) {
const modules = modulesAt(root, commit);
const paths = [...modules.keys()];
const imports = importsIn([...modules.values()]);
@@ -149,7 +150,14 @@ function graphAt(root, commit, changedDocs = []) {
const sourceTreeReaders = new Set();
const docInputs = new Map();
paths.forEach((path, index) => {
- if (changedDocs.length) docInputs.set(path, documentationInputs(path, modules.get(path), imports[index], changedDocs));
+ if (changedDocs.length || changedReadmes.length) {
+ const inputs = documentationInputs(path, modules.get(path), imports[index], changedDocs);
+ // Literal test README references are real inputs; a test-tree marker alone is not a reader.
+ for (const readme of changedReadmes) {
+ if (modules.get(path).includes(readme) || modules.get(path).includes(posix.relative(posix.dirname(path), readme))) inputs.add(readme);
+ }
+ docInputs.set(path, inputs);
+ }
if (TEST.test(path)) {
for (const line of modules.get(path).split(/\r?\n/u)) {
if (line === TEST_TREE_INPUT) testTreeReaders.add(path);
@@ -205,17 +213,18 @@ export function selectAffectedTests(root, { base, trunk, commit = 'HEAD', change
}
changed ??= selectionGit(root, ['diff', '--no-renames', '--name-only', '-z', base, commit]).split('\0').filter(Boolean);
const changedDocs = changed.filter(path => DOC.test(path));
- const after = graphAt(root, commit, changedDocs);
+ const changedReadmes = changed.filter(path => TEST_README.test(path));
+ const after = graphAt(root, commit, changedDocs, changedReadmes);
files = after.paths.filter(path => TEST.test(path)).sort();
const fallback = changed.find(path => GLOBAL.has(path) || path.startsWith('.githooks/'));
if (fallback) return { full: true, reason: `${fallback} controls the gate or dependency selection`, files };
if (!files.length) return { full: true, reason: 'no committed Node test files can be selected', files };
- const unsupported = changed.find(path => !MODULE.test(path) && !DOC.test(path));
+ const unsupported = changed.find(path => !MODULE.test(path) && !DOC.test(path) && !TEST_README.test(path));
if (unsupported) return { full: true, reason: `import selection cannot compute the effect of ${unsupported}`, files };
- const before = graphAt(root, base, changedDocs);
+ const before = graphAt(root, base, changedDocs, changedReadmes);
const reached = new Set(changed);
const queue = [...changed];
- for (const doc of changed.filter(path => DOC.test(path))) {
+ for (const doc of [...changedDocs, ...changedReadmes]) {
for (const graph of [before, after]) {
for (const [reader, inputs] of graph.docInputs) {
if ([...inputs].some(input => input === doc || doc.startsWith(input + '/'))) {
@@ -233,7 +242,7 @@ export function selectAffectedTests(root, { base, trunk, commit = 'HEAD', change
}
}
}
- const changedTestInput = changed.some(path => path.startsWith('test/') || TEST.test(path) || /^test\.[cm]?js$/u.test(path));
+ const changedTestInput = changed.some(path => !TEST_README.test(path) && (path.startsWith('test/') || TEST.test(path) || /^test\.[cm]?js$/u.test(path)));
const changedSourceInput = changed.some(path => path.startsWith('src/') || path.startsWith('bin/'));
const selected = files.filter(path => reached.has(path) || before.always.has(path) || after.always.has(path)
|| (changedTestInput && (before.testTreeReaders.has(path) || after.testTreeReaders.has(path)))
diff --git a/test/run-tests.test.js b/test/run-tests.test.js
index 7a446166..e7cfda7c 100644
--- a/test/run-tests.test.js
+++ b/test/run-tests.test.js
@@ -3,11 +3,12 @@ import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { test } from 'node:test';
-import { startFixtureChild, runFixtureChild } from './fixture-child.js';
+import { startFixtureChild, runFixtureChild, runFixtureGit } from './fixture-child.js';
import { listResources } from '../src/resources.js';
+import { selectAffectedTests } from '../src/affected-tests.js';
const runner = fileURLToPath(new URL('../bin/run-tests.js', import.meta.url));
const shardFileCount = 9;
@@ -59,10 +60,11 @@ function makeTrackedSelectionFixture(t) {
const source = join(root, 'src');
const tests = join(root, 'test');
const scratch = join(root, 'scratch');
- const expected = ['tracked', 'dot-suffix', 'dash-suffix', 'underscore-suffix', 'test-prefix', 'test-name'];
+ const expected = ['tracked', 'docs-esm'];
mkdirSync(bin);
mkdirSync(tests);
mkdirSync(scratch);
+ mkdirSync(join(root, 'docs'));
writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'module' }));
writeFileSync(join(root, '.gitignore'), 'scratch/\n');
copyFileSync(runner, join(bin, 'run-tests.js'));
@@ -70,6 +72,7 @@ function makeTrackedSelectionFixture(t) {
const capture = join(root, 'selected-files.txt');
const trackedSources = new Map([
['test/tracked.test.js', trackedFixtureSource('tracked')],
+ ['docs/guide.test.mjs', trackedFixtureSource('docs-esm')],
['prefix.test.js', trackedFixtureSource('dot-suffix')],
['prefix-test.cjs', trackedFixtureSource('dash-suffix')],
['prefix_test.mjs', trackedFixtureSource('underscore-suffix')],
@@ -127,7 +130,7 @@ function trackedSelectionTest(t) {
'the failing scratch test is actually ignored by Git');
const tracked = execFileSync('git', ['ls-files'], { cwd: fixture.root, encoding: 'utf8' }).trim().split(/\r?\n/u);
assert.ok(tracked.includes('.gitignore') && tracked.includes('tracked.spec.js'), 'the non-default and ignore control files are tracked');
- assert.equal(tracked.length, fixture.expected.length + 2, 'all pattern cases and non-default controls are tracked');
+ assert.equal(tracked.length, 9, 'all pattern cases and non-default controls are tracked');
const result = runFixtureChild(process.execPath, [fixture.runner], {
cwd: fixture.root,
encoding: 'utf8',
@@ -138,19 +141,19 @@ function trackedSelectionTest(t) {
for (const label of fixture.expected) assert.match(result.stdout, new RegExp(`ok [0-9]+ - tracked .*${label}.* pattern ran \\[C7\\]`, 'u'));
assert.doesNotMatch(`${result.stdout}\n${result.stderr ?? ''}`, /ignored test was executed|untracked test was executed|non-default test was executed/u);
assert.deepEqual(readFileSync(fixture.capture, 'utf8').trim().split(/\r?\n/u).sort(),
- ['tracked', 'dot-suffix', 'dash-suffix', 'underscore-suffix', 'test-prefix', 'test-name'].sort(),
- 'every default filename pattern runs exactly once');
+ fixture.expected.toSorted(),
+ 'only repository test entry names run exactly once');
writeFileSync(fixture.capture, '');
- const filtered = runFixtureChild(process.execPath, [fixture.runner, '--test-name-pattern', 'dot-suffix'], {
+ const filtered = runFixtureChild(process.execPath, [fixture.runner, '--test-name-pattern', 'docs-esm'], {
cwd: fixture.root,
encoding: 'utf8',
env: { ...process.env, PULLBOARD_TRACKED_CAPTURE: fixture.capture },
});
assert.equal(filtered.status, 0, filtered.context);
- assert.match(filtered.stdout, /ok [0-9]+ - tracked dot-suffix pattern ran \[C7\]/u,
+ assert.match(filtered.stdout, /ok [0-9]+ - tracked docs-esm pattern ran \[C7\]/u,
'name filters still apply to the tracked default list');
- assert.equal(readFileSync(fixture.capture, 'utf8'), 'dot-suffix\n');
+ assert.equal(readFileSync(fixture.capture, 'utf8'), 'docs-esm\n');
const explicit = runFixtureChild(process.execPath, [fixture.runner, 'test/untracked.test.js'], {
cwd: fixture.root,
@@ -164,6 +167,88 @@ function trackedSelectionTest(t) {
test('the runner skips test files git does not track [C7]', trackedSelectionTest);
+/** Keep perf-shaped helpers importable without launching their standalone entry points. */
+function onlyTestEntriesTest(t) {
+ const fixture = makeShardFixture(t);
+ const env = { ...process.env, PULLBOARD_SHARD_CAPTURE: fixture.capture,
+ GIT_AUTHOR_NAME: 'Test Agent', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Test Agent', GIT_COMMITTER_EMAIL: '[email protected]' };
+ /** Write one tracked fixture input with its real repository-relative path. */
+ const put = (path, body) => {
+ mkdirSync(dirname(join(fixture.root, path)), { recursive: true });
+ writeFileSync(join(fixture.root, path), body);
+ };
+ /** Commit the fixture graph so the selector reads immutable Git objects. */
+ const commit = () => {
+ runFixtureGit(['add', '-A'], { cwd: fixture.root, env });
+ runFixtureGit(['commit', '-qm', 'chore: discovery fixture'], { cwd: fixture.root, env });
+ return runFixtureGit(['rev-parse', 'HEAD'], { cwd: fixture.root, env }).trim();
+ };
+ const helpers = ['test/cockpit/perf/run.mjs', 'test/cockpit/perf/generate.mjs',
+ 'test/cockpit/fixture.js', 'test/view-link-fixture.js'];
+ put('.gitignore', 'selected-files.txt\n');
+ for (const path of helpers) put(path, `import { fileURLToPath } from 'node:url';
+export const value = 42;
+if (process.argv[1] === fileURLToPath(import.meta.url)) throw new Error('standalone helper: ${path}');
+`);
+ put('test/cockpit/perf.test.js', `import assert from 'node:assert/strict';
+import { appendFileSync } from 'node:fs';
+import { test } from 'node:test';
+import { value as run } from './perf/run.mjs';
+import { value as generate } from './perf/generate.mjs';
+import { value as fixture } from './fixture.js';
+import { value as link } from '../view-link-fixture.js';
+/** Exercise every imported helper without its standalone workload. */
+function importedHelpersWork() { assert.deepEqual([run, generate, fixture, link], [42,42,42,42]); appendFileSync(process.env.PULLBOARD_SHARD_CAPTURE, 'cockpit/perf.test.js\\n'); }
+test('perf helpers remain importable [C7]', importedHelpersWork);
+`);
+ put('docs/guide.test.mjs', "import { test } from 'node:test';\nimport { appendFileSync } from 'node:fs';\n/** Exercise a named documentation test entry. */\nfunction guide() { appendFileSync(process.env.PULLBOARD_SHARD_CAPTURE, 'docs/guide.test.mjs\\n'); }\ntest('documentation test entry [C7]', guide);\n");
+ put('test/tree-reader.test.js', "/** @pullboard-test-input test-tree */\nimport { appendFileSync } from 'node:fs';\nappendFileSync(process.env.PULLBOARD_SHARD_CAPTURE, 'tree-reader.test.js\\n');\n");
+ put('test/cockpit/perf/README.md', '# Perf harness\n');
+ const base = commit();
+ const discovered = runFixtureChild(process.execPath, [fixture.runner], {
+ cwd: fixture.root, encoding: 'utf8', env,
+ });
+ assert.equal(discovered.status, 0, `${discovered.context}\n${discovered.stdout}`);
+ assert.doesNotMatch(discovered.stdout + discovered.stderr, /standalone helper:/u);
+ assert.match(discovered.stdout, /ok [0-9]+ - perf helpers remain importable/u);
+ assert.match(discovered.stdout, /ok [0-9]+ - documentation test entry/u);
+ assert.deepEqual(readFileSync(fixture.capture, 'utf8').trim().split('\n').sort(),
+ [...fixture.expected, 'cockpit/perf.test.js', 'docs/guide.test.mjs', 'tree-reader.test.js'].sort(),
+ 'each expected test entry executes once, including a file with only a tree-reader declaration');
+ const entries = [...fixture.expected.map(name => `test/${name}`),
+ 'test/cockpit/perf.test.js', 'docs/guide.test.mjs', 'test/tree-reader.test.js'];
+ const explicit = runFixtureChild(process.execPath, [fixture.runner, ...entries], {
+ cwd: fixture.root, encoding: 'utf8', env,
+ });
+ assert.equal(explicit.status, 0, `${explicit.context}\n${explicit.stdout}`);
+ assert.equal(discovered.stdout.match(/^# tests (\d+)$/mu)?.[1],
+ explicit.stdout.match(/^# tests (\d+)$/mu)?.[1],
+ 'discovery runs exactly the same test cases as the explicit test-entry list');
+ put('test/cockpit/perf/README.md', '# Updated harness instructions\n');
+ const head = commit();
+ const readme = selectAffectedTests(fixture.root, { base, commit: head });
+ assert.equal(readme.full, false, 'an unread test README does not force the full gate');
+ assert.deepEqual(readme.files, [], 'an unread README does not activate the test-tree scanner');
+ assert.equal(selectAffectedTests(fixture.root, {
+ base, commit: head, changed: ['test/cockpit/perf/unknown.json'],
+ }).full, true, 'unknown test assets still require the full gate');
+ put('test/cockpit/readme-helper.js', "import { readFileSync } from 'node:fs';\nexport const instructions = readFileSync(new URL('./perf/README.md', import.meta.url), 'utf8');\n");
+ put('test/cockpit/readme-reader.test.js', "import './readme-helper.js';\n");
+ const readerBase = commit();
+ put('test/cockpit/readme-helper.js', "export const instructions = 'reader removed';\n");
+ put('test/cockpit/perf/README.md', '# Instructions after reader removal\n');
+ const readerHead = commit();
+ const readers = selectAffectedTests(fixture.root, {
+ base: readerBase, commit: readerHead, changed: ['test/cockpit/perf/README.md'],
+ });
+ assert.equal(readers.full, false);
+ assert.deepEqual(readers.files, ['test/cockpit/readme-reader.test.js'],
+ 'a real README reader remains selected through its old helper edge, without test-tree-wide widening');
+}
+
+test('the suite runs only test files, not helpers or the perf harness [C7]', onlyTestEntriesTest);
+
/** Run the copied production runner and return the test filenames it actually executed. */
function runShardFixture(fixture, shard) {
writeFileSync(fixture.capture, '');