Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: compare server import growth to the merge base instead of a fixed ceiling (#7993)

[._.]/ Adam Eivye0d4a937e44e
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.js
index 9349b3b1bb..05d1c6a509 100644
--- a/scripts/ci-test-plan.js
+++ b/scripts/ci-test-plan.js
@@ -236,6 +236,15 @@ export const ALWAYS_RUN_TESTS = [
// `.env.example` itself is not a scope the selector routes to a runner.
'server/envExampleDrift.test.js',
'server/lib/generatedManifests.test.js',
+ // Base-relative server import-growth guard (#7993). A new eager edge in a
+ // widely reached module multiplies across suites this file does not import,
+ // so impact selection would not reach it unless the diff touched this file.
+ // Docs-only plans and rebases onto a moved base still need the comparison. It reads
+ // CI_BASE_SHA — the same variable main() requires for a pull request that
+ // is not forced full — and fails closed when that commit cannot be read.
+ // Pregate copies the sha into the test process so the local run uses this
+ // plan's base, not a second guess.
+ 'server/lib/importScoping.test.js',
// Whole-tree scanner: any server/client file can add a hardcoded "Models →"
// breadcrumb, with no import edge back to this file.
'server/lib/localProviderRuntime.test.js',
diff --git a/scripts/lib/importGrowth.js b/scripts/lib/importGrowth.js
new file mode 100644
index 0000000000..c7b24f70ac
--- /dev/null
+++ b/scripts/lib/importGrowth.js
@@ -0,0 +1,581 @@
+/**
+ * Base-relative server import-growth guard (#7993).
+ *
+ * The number this module reports is a static proxy, not a count of runtime
+ * module instantiations. For each server `*.test.js` file it is the size of
+ * that file's static import closure (the file included). Shared modules are
+ * counted once per test that reaches them, because that is how the suite pays
+ * import cost: every worker re-evaluates the closure. Dynamic `import()` is
+ * invisible here, on purpose — the same rule `staticImportGraph.js` uses.
+ *
+ * An absolute ceiling on the sum made ordinary growth fail. A new leaf on a
+ * widely reached module, or a new suite's own closure, inched the repository
+ * total until the next unrelated change crossed a fixed line (#7993: CI
+ * reported 116,920 against a 116,900 ceiling). This guard compares one
+ * analyzer against the merge base and the working tree instead.
+ *
+ * The gated quantity is existing-suite growth: the sum, over test files that
+ * exist on both sides, of how many modules each closure gained. New test
+ * files are reported as new-suite contribution and do not spend the
+ * allowance, so adding tests cannot by itself exhaust a repository-wide
+ * budget. Shrinkage on one suite does not cancel growth on another.
+ *
+ * Threshold. The heavy edges this repository already measured:
+ * #6009 removed 19,286 (115,519 → 96,233) by cutting widely reached barrels.
+ * #6156 removed 12,794 (96,233 → 83,439) by deferring boot/run-only imports.
+ * At the time this guard replaced the ceiling, `services/settings.js` was in
+ * 331 suite closures and `services/userActions.js` (one of the #6156
+ * deferrals) had a 23-module closure — on the order of 331×23 of proxy count
+ * for that single edge. `lib/editorial/checkRegistry.js` (a #6009 barrel) was
+ * 69 modules, and `lib/validation.js` was reached by 224 suites. A new
+ * zero-dependency leaf on the widest owner, `lib/providerVendors.js` (376
+ * suites), costs a few hundred. `EXISTING_SUITE_GROWTH_LIMIT` sits above that
+ * ordinary band and below half of the smaller heavy regression, so a limit
+ * bump large enough to admit a #6156-class edge fails the pin test.
+ *
+ * Missing history fails closed. An unresolvable base commit, a base tree
+ * with too few test files to be the real suite, or a base blob git cannot
+ * read throws `ImportGrowthBaseError`. None of those become a zero delta.
+ *
+ * Wall-clock is not a gate. `benchmarkProxySplit` reports a synthetic
+ * collection walk and a synthetic execution loop as separate numbers so the
+ * two costs stay distinguishable; the live report's collect timings are the
+ * same kind of evidence. Neither is compared to a threshold.
+ */
+
+import { spawnSync } from 'child_process';
+import { existsSync, readFileSync, statSync } from 'fs';
+import { join, isAbsolute, posix, relative } from 'path';
+import { staticImportSpecifiersFromSource } from '../../server/lib/staticImportGraph.js';
+
+/** Proxy counts recorded for the heavy edges this guard is calibrated against. */
+export const HISTORICAL_PROXY_TOTALS = Object.freeze({
+ before6009: 115_519,
+ after6009: 96_233,
+ after6156: 83_439,
+});
+
+export const REGRESSION_6009 = HISTORICAL_PROXY_TOTALS.before6009 - HISTORICAL_PROXY_TOTALS.after6009;
+export const REGRESSION_6156 = HISTORICAL_PROXY_TOTALS.after6009 - HISTORICAL_PROXY_TOTALS.after6156;
+
+/**
+ * Existing-suite proxy growth that fails the guard.
+ * Above ordinary wide-leaf growth (~1,500 in the retired ceiling's own
+ * notes; a few hundred for one leaf on `providerVendors.js`) and below half
+ * of #6156's 12,794 so that regression cannot be waived by raising this.
+ */
+export const EXISTING_SUITE_GROWTH_LIMIT = 2_500;
+
+/** Half of the smaller known heavy regression. The pin test keeps the limit under this. */
+export const HEAVY_REGRESSION_BAND = Math.floor(REGRESSION_6156 / 2);
+
+/** Below this, a measurement is not the server suite — passing would be vacuous. */
+export const MIN_SERVER_TESTS = 1_000;
+
+const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
+const SOURCE_EXT = /\.(?:[cm]?js|jsx|tsx?)$/;
+
+const PROXY_NOTE = 'Static closure sizes are a proxy for import cost, not a count of observed module instantiations.';
+
+export function importGrowthBaseError(message) {
+ const error = new Error(message);
+ error.name = 'ImportGrowthBaseError';
+ error.code = 'IMPORT_GROWTH_BASE_UNAVAILABLE';
+ return error;
+}
+
+/** Repo-relative POSIX path for a specifier, or null when it leaves the repo. */
+export function resolveRepoSpecifier(fromRel, spec) {
+ if (!spec.startsWith('.')) return null;
+ const next = posix.normalize(posix.join(posix.dirname(fromRel), spec));
+ if (next === '..' || next.startsWith('../') || next.startsWith('/')) return null;
+ return next;
+}
+
+function closureOf(entry, resolved) {
+ const files = new Set();
+ const stack = [entry];
+ while (stack.length) {
+ const file = stack.pop();
+ if (files.has(file)) continue;
+ files.add(file);
+ for (const dep of resolved(file)) if (!files.has(dep)) stack.push(dep);
+ }
+ return files;
+}
+
+/**
+ * Closure sizes for `testFiles`, using `readText` for every file.
+ * Both the working tree and a git commit go through this function — base and
+ * head never run different analyzers. `readText` returns null when the path
+ * is absent. A throw from `readText` is a failed read, not an empty closure.
+ *
+ * @returns {{ tests: Map<string, Set<string>>, deps: Map<string, string[]>, testCount: number, total: number }}
+ */
+export function measureClosures(testFiles, readText) {
+ const textCache = new Map();
+ const read = (rel) => {
+ if (textCache.has(rel)) return textCache.get(rel);
+ const text = readText(rel);
+ textCache.set(rel, text);
+ return text;
+ };
+ const deps = new Map();
+ const resolved = (rel) => {
+ const cached = deps.get(rel);
+ if (cached) return cached;
+ const text = read(rel);
+ if (text == null) {
+ deps.set(rel, []);
+ return [];
+ }
+ const next = [];
+ const seen = new Set();
+ for (const spec of staticImportSpecifiersFromSource(text)) {
+ const target = resolveRepoSpecifier(rel, spec);
+ if (!target || seen.has(target)) continue;
+ if (read(target) == null) continue;
+ seen.add(target);
+ next.push(target);
+ }
+ deps.set(rel, next);
+ return next;
+ };
+
+ const tests = new Map();
+ let total = 0;
+ for (const file of testFiles) {
+ if (read(file) == null) continue;
+ const closure = closureOf(file, resolved);
+ tests.set(file, closure);
+ total += closure.size;
+ }
+ return { tests, deps, testCount: tests.size, total };
+}
+
+export function closureSizeFromDeps(entry, deps) {
+ return closureOf(entry, (rel) => deps.get(rel) || []).size;
+}
+
+function isServerTest(rel) {
+ if (!rel.startsWith('server/') || !rel.endsWith('.test.js')) return false;
+ return rel.split('/').every((part) => part && !part.startsWith('.') && !SKIP_DIRS.has(part));
+}
+
+/**
+ * Compare two measurements from `measureClosures`.
+ * `existingSuiteGrowth` sums per-file closure growth. A suite that shrinks
+ * does not pay down a suite that grew. New test files contribute only to
+ * `newSuiteContribution`.
+ */
+export function compareImportGrowth(base, head, { limit = EXISTING_SUITE_GROWTH_LIMIT } = {}) {
+ let existingSuiteGrowth = 0;
+ let existingSuiteShrink = 0;
+ let comparedSuites = 0;
+ let newSuiteContribution = 0;
+ let newSuiteCount = 0;
+ let removedSuiteContribution = 0;
+ let removedSuiteCount = 0;
+ const suiteDeltas = [];
+ const newReach = new Map();
+
+ for (const [file, headClosure] of head.tests) {
+ const baseClosure = base.tests.get(file);
+ if (!baseClosure) {
+ newSuiteCount += 1;
+ newSuiteContribution += headClosure.size;
+ continue;
+ }
+ comparedSuites += 1;
+ const growth = Math.max(0, headClosure.size - baseClosure.size);
+ const shrink = Math.max(0, baseClosure.size - headClosure.size);
+ existingSuiteGrowth += growth;
+ existingSuiteShrink += shrink;
+ if (growth === 0) continue;
+ const added = [];
+ for (const mod of headClosure) {
+ if (baseClosure.has(mod)) continue;
+ added.push(mod);
+ newReach.set(mod, (newReach.get(mod) || 0) + 1);
+ }
+ suiteDeltas.push({
+ file,
+ base: baseClosure.size,
+ head: headClosure.size,
+ growth,
+ added: added.sort(),
+ });
+ }
+
+ for (const [file, baseClosure] of base.tests) {
+ if (head.tests.has(file)) continue;
+ removedSuiteCount += 1;
+ removedSuiteContribution += baseClosure.size;
+ }
+
+ suiteDeltas.sort((a, b) => b.growth - a.growth || a.file.localeCompare(b.file));
+
+ const largestNewDependencies = [...newReach.entries()]
+ .map(([module, reach]) => ({
+ module,
+ newReach: reach,
+ closureSize: closureSizeFromDeps(module, head.deps),
+ }))
+ .sort((a, b) => (b.newReach * b.closureSize) - (a.newReach * a.closureSize) || a.module.localeCompare(b.module))
+ .slice(0, 8);
+
+ return {
+ ok: existingSuiteGrowth <= limit,
+ limit,
+ proxyNote: PROXY_NOTE,
+ baseTotal: base.total,
+ headTotal: head.total,
+ baseTestCount: base.testCount,
+ headTestCount: head.testCount,
+ comparedSuites,
+ existingSuiteGrowth,
+ existingSuiteShrink,
+ newSuiteContribution,
+ newSuiteCount,
+ removedSuiteContribution,
+ removedSuiteCount,
+ largestSuiteDeltas: suiteDeltas.slice(0, 8),
+ largestNewDependencies,
+ };
+}
+
+export function formatImportGrowthReport(report) {
+ const lines = [
+ PROXY_NOTE,
+ `Base ${report.baseTestCount} suites, proxy total ${report.baseTotal}.`,
+ `Head ${report.headTestCount} suites, proxy total ${report.headTotal}.`,
+ `Existing-suite growth ${report.existingSuiteGrowth} (limit ${report.limit}); shrinkage elsewhere ${report.existingSuiteShrink}.`,
+ `New-suite contribution ${report.newSuiteContribution} across ${report.newSuiteCount} new test file(s) — not part of the limit.`,
+ `Removed-suite proxy ${report.removedSuiteContribution} across ${report.removedSuiteCount} deleted test file(s).`,
+ ];
+ if (report.baseSha) lines.splice(1, 0, `Compared with ${report.baseSource || 'base'} ${report.baseSha}.`);
+ if (report.largestSuiteDeltas.length > 0) {
+ lines.push('Largest existing-suite increases:');
+ for (const row of report.largestSuiteDeltas) {
+ const sample = row.added.slice(0, 6).join(', ');
+ lines.push(` ${row.file} ${row.base} → ${row.head} (+${row.growth})${sample ? ` added ${sample}` : ''}`);
+ }
+ }
+ if (report.largestNewDependencies.length > 0) {
+ lines.push('Largest new dependency closures (new reachers × that module\'s closure):');
+ for (const row of report.largestNewDependencies) {
+ lines.push(` ${row.module} closure ${row.closureSize}, newly reached by ${row.newReach} existing suite(s)`);
+ }
+ }
+ if (!report.ok) {
+ lines.push(
+ 'A widely reached module gained an eager dependency whose closure is too large to be ordinary leaf growth.',
+ 'Narrow it, or defer it with await import() on the path that actually uses it.',
+ 'New test files do not spend this allowance — do not delete a suite to get under the limit.',
+ 'Raising EXISTING_SUITE_GROWTH_LIMIT is the intentional-regression path: do it in the same change, name the module that cannot be deferred, and keep the limit below the #6156 band (the pin test enforces that). See server/AGENTS.md, Import scoping.',
+ );
+ }
+ if (report.timings) {
+ lines.push(
+ `Measurement timings (not a threshold): base collect ${report.timings.baseCollectMs}ms, head collect ${report.timings.headCollectMs}ms, compare ${report.timings.compareMs}ms.`,
+ 'Those timings are the guard reading source. They are not Vitest collection time and not test-execution time.',
+ );
+ }
+ return lines.join('\n');
+}
+
+/**
+ * Synthetic collection-versus-execution split.
+ * Collection is the static closure walk. Execution is a separate loop over
+ * the measured result. Both are returned so a caller can report them apart;
+ * nothing here decides pass/fail from either number.
+ */
+export function benchmarkProxySplit({ modules = 30 } = {}) {
+ const files = new Map();
+ for (let i = 0; i < modules; i += 1) {
+ const prev = i === 0 ? '' : `import './m${i - 1}.js';\n`;
+ files.set(`synth/m${i}.js`, `${prev}export const n = ${i};\n`);
+ }
+ files.set('synth/suite.test.js', `import './m${modules - 1}.js';\n`);
+ const readText = (rel) => files.get(rel) ?? null;
+ const collectStart = performance.now();
+ const measured = measureClosures(['synth/suite.test.js'], readText);
+ const collectionMs = performance.now() - collectStart;
+ const executeStart = performance.now();
+ let executed = 0;
+ for (const closure of measured.tests.values()) executed += closure.size;
+ const executionMs = performance.now() - executeStart;
+ return {
+ collectionMs,
+ executionMs,
+ executed,
+ environment: {
+ node: process.version,
+ platform: process.platform,
+ synthetic: true,
+ modules,
+ },
+ limitations: [
+ 'collectionMs times the static closure walk on an in-memory synthetic graph, not Vitest transforming the server suite',
+ 'executionMs times a loop over that walk\'s result, not test bodies',
+ 'neither number is a CI pass/fail threshold; the gate is existing-suite proxy growth',
+ PROXY_NOTE,
+ ],
+ };
+}
+
+function git(repoRoot, args, { input, encoding = 'utf8', maxBuffer = 64 * 1024 * 1024 } = {}) {
+ const result = spawnSync('git', args, {
+ cwd: repoRoot,
+ input,
+ encoding,
+ maxBuffer,
+ });
+ return result;
+}
+
+function gitOk(repoRoot, args, options) {
+ const result = git(repoRoot, args, options);
+ if (result.error || result.status !== 0) return null;
+ return typeof result.stdout === 'string' ? result.stdout.trim() : result.stdout;
+}
+
+export function gitRevParse(repoRoot, rev) {
+ return gitOk(repoRoot, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`]);
+}
+
+function gitMergeBase(repoRoot, ref) {
+ return gitOk(repoRoot, ['merge-base', ref, 'HEAD']);
+}
+
+function defaultBaseRef(repoRoot) {
+ const head = git(repoRoot, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']);
+ if (head.status === 0 && head.stdout.trim()) return head.stdout.trim();
+ return 'origin/main';
+}
+
+/**
+ * The commit head is compared against.
+ * `CI_BASE_SHA` wins when it is set (CI pull requests and pregate, which
+ * forwards the same sha the planner used). It must resolve; a present but
+ * unreadable value does not fall through to a self-comparison.
+ * On GitHub Actions without that variable (nightly, workflow dispatch) the
+ * parent commit is the base — a depth-2 checkout has it — and a missing
+ * parent fails. Locally, the merge-base with the remote default branch is
+ * the base, and a missing ref fails the same way.
+ */
+export function resolveImportGrowthBase({
+ repoRoot,
+ env = process.env,
+ revParse = gitRevParse,
+ mergeBase = gitMergeBase,
+ defaultRef,
+} = {}) {
+ const explicit = typeof env.CI_BASE_SHA === 'string' ? env.CI_BASE_SHA.trim() : '';
+ if (explicit) {
+ const sha = revParse(repoRoot, explicit);
+ if (!sha) {
+ throw importGrowthBaseError(
+ `CI_BASE_SHA does not resolve to a commit. The import-growth guard does not pass when the base commit is unavailable.`,
+ );
+ }
+ return { sha, source: 'CI_BASE_SHA' };
+ }
+ if (env.GITHUB_ACTIONS === 'true') {
+ const sha = revParse(repoRoot, 'HEAD^1');
+ if (!sha) {
+ throw importGrowthBaseError(
+ 'GitHub Actions did not provide CI_BASE_SHA and HEAD^1 does not resolve. The import-growth guard does not pass without a base commit.',
+ );
+ }
+ return { sha, source: 'HEAD^1' };
+ }
+ const ref = defaultRef || defaultBaseRef(repoRoot);
+ const sha = mergeBase(repoRoot, ref);
+ if (!sha) {
+ throw importGrowthBaseError(
+ `Cannot resolve a merge-base with ${ref}. Fetch it (git fetch origin). The import-growth guard does not pass without a base commit.`,
+ );
+ }
+ return { sha, source: `merge-base ${ref}` };
+}
+
+function gitPaths(repoRoot, args) {
+ const result = git(repoRoot, args);
+ if (result.error || result.status !== 0) {
+ throw importGrowthBaseError(`git ${args[0]} failed (exit ${result.status ?? 'spawn'}). The import-growth guard does not pass when the file list cannot be read.`);
+ }
+ return result.stdout.split('\0').filter(Boolean);
+}
+
+/**
+ * Files the head measurement may read: tracked blobs plus untracked files.
+ * Submodule contents are neither, so base (parent tree) and head agree on
+ * them instead of the working tree inventing a closure the base commit
+ * cannot see. Untracked server tests still count — that is new-suite growth.
+ */
+function listHeadPaths(repoRoot) {
+ const tracked = gitPaths(repoRoot, ['ls-files', '-z']);
+ const untracked = gitPaths(repoRoot, ['ls-files', '-z', '--others', '--exclude-standard']);
+ return new Set([...tracked, ...untracked]);
+}
+
+function diskRead(repoRoot) {
+ return (rel) => {
+ if (!rel || rel.includes('\0') || rel.startsWith('/') || rel.split('/').includes('..')) return null;
+ const abs = join(repoRoot, ...rel.split('/'));
+ const back = relative(repoRoot, abs);
+ if (back.startsWith('..') || isAbsolute(back)) return null;
+ if (!existsSync(abs)) return null;
+ const stat = statSync(abs);
+ if (!stat.isFile()) return null;
+ return readFileSync(abs, 'utf8');
+ };
+}
+
+export function measureWorkingTree(repoRoot) {
+ const paths = listHeadPaths(repoRoot);
+ const readDisk = diskRead(repoRoot);
+ const testFiles = [...paths].filter(isServerTest).sort();
+ return measureClosures(testFiles, (rel) => (paths.has(rel) ? readDisk(rel) : null));
+}
+
+/**
+ * Paths at `sha` whose blob must be read from git because the worktree copy
+ * is not that commit's bytes (edits, deletions, renames). Added paths are
+ * omitted: they are not in the base tree.
+ */
+export function basePathsToReadFromGit(nameStatusZ) {
+ const parts = nameStatusZ.split('\0').filter((part) => part !== '');
+ const paths = [];
+ for (let i = 0; i < parts.length;) {
+ const status = parts[i];
+ i += 1;
+ if (!status) break;
+ const code = status[0];
+ const path = parts[i];
+ i += 1;
+ if (path == null) {
+ throw importGrowthBaseError('git diff --name-status output ended mid-record.');
+ }
+ if (code === 'R' || code === 'C') {
+ const renamed = parts[i];
+ i += 1;
+ if (renamed == null) throw importGrowthBaseError('git diff --name-status rename record is missing its destination.');
+ paths.push(path);
+ continue;
+ }
+ if (code !== 'A') paths.push(path);
+ }
+ return paths;
+}
+
+function listTree(repoRoot, sha) {
+ const result = git(repoRoot, ['ls-tree', '-r', '-z', '--name-only', sha]);
+ if (result.status !== 0) {
+ throw importGrowthBaseError(`Cannot list the tree of ${String(sha).slice(0, 12)}. The import-growth guard does not pass when base history is unreadable.`);
+ }
+ return new Set(result.stdout.split('\0').filter(Boolean));
+}
+
+function readBlobs(repoRoot, sha, paths) {
+ const wanted = paths.filter((rel) => SOURCE_EXT.test(rel) && !rel.includes('\0') && !rel.includes('\n'));
+ const blobs = new Map();
+ if (wanted.length === 0) return blobs;
+ const input = Buffer.from(wanted.map((rel) => `${sha}:${rel}`).join('\n') + '\n');
+ const result = git(repoRoot, ['cat-file', '--batch'], { input, encoding: 'buffer', maxBuffer: 256 * 1024 * 1024 });
+ if (result.error || result.status !== 0) {
+ throw importGrowthBaseError(`git cat-file failed while reading ${String(sha).slice(0, 12)} (exit ${result.status ?? 'spawn'}).`);
+ }
+ const stdout = result.stdout;
+ let offset = 0;
+ const decodeLine = () => {
+ const end = stdout.indexOf(0x0a, offset);
+ if (end === -1) return null;
+ const line = stdout.toString('utf8', offset, end);
+ offset = end + 1;
+ return line;
+ };
+ for (let n = 0; n < wanted.length; n += 1) {
+ const header = decodeLine();
+ if (header == null) {
+ throw importGrowthBaseError(`git cat-file ended early while reading ${String(sha).slice(0, 12)}.`);
+ }
+ if (header.endsWith(' missing')) {
+ throw importGrowthBaseError(`Base commit ${String(sha).slice(0, 12)} has no blob for ${wanted[n]}. The import-growth guard does not pass when a base file is missing.`);
+ }
+ const match = header.match(/^([0-9a-f]+) blob (\d+)$/);
+ if (!match) {
+ throw importGrowthBaseError(`git cat-file returned an unexpected header while reading ${String(sha).slice(0, 12)}.`);
+ }
+ const size = Number(match[2]);
+ const body = stdout.toString('utf8', offset, offset + size);
+ offset += size;
+ if (stdout[offset] === 0x0a) offset += 1;
+ blobs.set(wanted[n], body);
+ }
+ return blobs;
+}
+
+export function measureGitTree(repoRoot, sha) {
+ const tree = listTree(repoRoot, sha);
+ const testFiles = [...tree].filter(isServerTest).sort();
+ // git diff exits 1 when the trees differ and 0 when they do not. Above 1 is a real failure.
+ const diff = git(repoRoot, ['diff', '-z', '--name-status', '--find-renames', sha]);
+ if (diff.error || diff.status > 1) {
+ throw importGrowthBaseError(`Cannot diff the worktree against ${String(sha).slice(0, 12)}. The import-growth guard does not pass when the base diff is unreadable.`);
+ }
+ const dirty = new Set(basePathsToReadFromGit(diff.stdout).filter((rel) => tree.has(rel)));
+ const blobs = readBlobs(repoRoot, sha, [...dirty]);
+ const fromDisk = diskRead(repoRoot);
+ const readText = (rel) => {
+ if (!tree.has(rel)) return null;
+ if (blobs.has(rel)) return blobs.get(rel);
+ if (dirty.has(rel)) {
+ throw importGrowthBaseError(`Base file ${rel} differs from the worktree but its blob was not loaded from ${String(sha).slice(0, 12)}.`);
+ }
+ const abs = join(repoRoot, ...rel.split('/'));
+ if (!existsSync(abs)) {
+ throw importGrowthBaseError(`Base file ${rel} is unchanged from ${String(sha).slice(0, 12)} but missing from the worktree.`);
+ }
+ return fromDisk(rel);
+ };
+ return measureClosures(testFiles, readText);
+}
+
+/**
+ * Measure the working tree and the resolved base with the same analyzer.
+ * Throws `ImportGrowthBaseError` when the base cannot be read or either side
+ * is too small to be the server suite. A thrown error is not a passing delta.
+ */
+export function evaluateWorkingTreeImportGrowth({
+ repoRoot,
+ env = process.env,
+ limit = EXISTING_SUITE_GROWTH_LIMIT,
+ now = () => performance.now(),
+} = {}) {
+ const baseRef = resolveImportGrowthBase({ repoRoot, env });
+ const headStart = now();
+ const head = measureWorkingTree(repoRoot);
+ const headCollectMs = Math.round(now() - headStart);
+ if (head.testCount < MIN_SERVER_TESTS) {
+ throw importGrowthBaseError(
+ `Found ${head.testCount} server test files. The import-growth guard does not pass on a walk that cannot see the suite.`,
+ );
+ }
+ const baseStart = now();
+ const base = measureGitTree(repoRoot, baseRef.sha);
+ const baseCollectMs = Math.round(now() - baseStart);
+ if (base.testCount < MIN_SERVER_TESTS) {
+ throw importGrowthBaseError(
+ `Base ${baseRef.sha.slice(0, 12)} has ${base.testCount} server test files. The import-growth guard does not treat a partial history read as zero growth.`,
+ );
+ }
+ const compareStart = now();
+ const report = compareImportGrowth(base, head, { limit });
+ const compareMs = Math.round(now() - compareStart);
+ report.baseSha = baseRef.sha;
+ report.baseSource = baseRef.source;
+ report.timings = { baseCollectMs, headCollectMs, compareMs };
+ return report;
+}
diff --git a/scripts/lib/importGrowth.test.js b/scripts/lib/importGrowth.test.js
new file mode 100644
index 0000000000..9d671c63d4
--- /dev/null
+++ b/scripts/lib/importGrowth.test.js
@@ -0,0 +1,359 @@
+/**
+ * Base-relative import-growth contract (#7993).
+ *
+ * The live server suite is measured from importScoping.test.js. This file
+ * pins the decision that measurement makes: ordinary leaf and new-suite
+ * growth pass, the #6009 / #6156 heavy shapes fail, base and head share one
+ * analyzer, and a missing base is an error rather than a zero delta.
+ */
+
+import { execFileSync } from 'child_process';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { dirname, join } from 'path';
+import { afterEach, describe, expect, it } from 'vitest';
+import { fileURLToPath } from 'url';
+import { staticImportClosure, staticImportSpecifiers, staticImportSpecifiersFromSource } from '../../server/lib/staticImportGraph.js';
+import {
+ EXISTING_SUITE_GROWTH_LIMIT,
+ HEAVY_REGRESSION_BAND,
+ HISTORICAL_PROXY_TOTALS,
+ REGRESSION_6009,
+ REGRESSION_6156,
+ basePathsToReadFromGit,
+ benchmarkProxySplit,
+ compareImportGrowth,
+ evaluateWorkingTreeImportGrowth,
+ formatImportGrowthReport,
+ measureClosures,
+ measureGitTree,
+ measureWorkingTree,
+ resolveImportGrowthBase,
+ resolveRepoSpecifier,
+} from './importGrowth.js';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+function sourceMap(files) {
+ const map = new Map(Object.entries(files));
+ return (rel) => map.get(rel) ?? null;
+}
+
+function measure(files) {
+ const tests = Object.keys(files).filter((rel) => rel.endsWith('.test.js')).sort();
+ return measureClosures(tests, sourceMap(files));
+}
+
+/** `suites` existing tests each gain `extra` modules behind one heavy root. */
+function fanOut({ suites, extra }) {
+ const baseFiles = {};
+ const headFiles = {};
+ const children = [];
+ for (let i = 0; i < extra; i += 1) {
+ const name = `server/heavy/m${i}.js`;
+ children.push(name);
+ const prev = i === 0 ? '' : `import './m${i - 1}.js';\n`;
+ baseFiles[name] = 'export const untouched = true;\n';
+ headFiles[name] = `${prev}export const n = ${i};\n`;
+ }
+ const heavyImports = extra === 0 ? '' : `import './heavy/m${extra - 1}.js';\n`;
+ baseFiles['server/wide.js'] = 'export const wide = 1;\n';
+ headFiles['server/wide.js'] = `${heavyImports}export const wide = 1;\n`;
+ for (let s = 0; s < suites; s += 1) {
+ const file = `server/suite${s}.test.js`;
+ const body = "import './wide.js';\n";
+ baseFiles[file] = body;
+ headFiles[file] = body;
+ }
+ return { base: measure(baseFiles), head: measure(headFiles) };
+}
+
+describe('import-growth threshold (#6009, #6156)', () => {
+ it('keeps the limit above ordinary leaf growth and below the known heavy regressions', () => {
+ expect(REGRESSION_6009).toBe(HISTORICAL_PROXY_TOTALS.before6009 - HISTORICAL_PROXY_TOTALS.after6009);
+ expect(REGRESSION_6156).toBe(HISTORICAL_PROXY_TOTALS.after6009 - HISTORICAL_PROXY_TOTALS.after6156);
+ expect(REGRESSION_6009).toBe(19_286);
+ expect(REGRESSION_6156).toBe(12_794);
+ expect(EXISTING_SUITE_GROWTH_LIMIT).toBeGreaterThan(1_500);
+ expect(EXISTING_SUITE_GROWTH_LIMIT).toBeLessThan(HEAVY_REGRESSION_BAND);
+ });
+
+ it('passes a wide leaf and a large new suite, and fails the heavy fan-out shapes', () => {
+ // providerVendors.js was reached by 376 suites when this limit was chosen.
+ // One new module in each of those closures is the ordinary shape.
+ const leaf = fanOut({ suites: 376, extra: 1 });
+ const leafReport = compareImportGrowth(leaf.base, leaf.head);
+ expect(leafReport.ok).toBe(true);
+ expect(leafReport.existingSuiteGrowth).toBe(376);
+
+ const added = measure({ 'server/new.test.js': "import './paid.js';\n", 'server/paid.js': 'export const paid = 1;\n' });
+ const empty = measure({});
+ const addedReport = compareImportGrowth(empty, added);
+ expect(addedReport.ok).toBe(true);
+ expect(addedReport.existingSuiteGrowth).toBe(0);
+ expect(addedReport.newSuiteContribution).toBe(2);
+ expect(addedReport.newSuiteCount).toBe(1);
+
+ // settings.js × userActions.js: 331 suites, 23-module closure, one #6156 edge.
+ const settingsEdge = compareImportGrowth(...Object.values(fanOut({ suites: 331, extra: 23 })));
+ expect(settingsEdge.ok).toBe(false);
+ expect(settingsEdge.existingSuiteGrowth).toBe(331 * 23);
+ expect(settingsEdge.largestNewDependencies[0].module).toBe('server/heavy/m22.js');
+ expect(settingsEdge.largestNewDependencies[0].newReach).toBe(331);
+ expect(settingsEdge.largestNewDependencies[0].closureSize).toBe(23);
+ expect(settingsEdge.largestSuiteDeltas[0].growth).toBe(23);
+
+ // validation.js reach × checkRegistry.js closure, the #6009 barrel shape.
+ const barrel = compareImportGrowth(...Object.values(fanOut({ suites: 224, extra: 69 })));
+ expect(barrel.ok).toBe(false);
+ expect(barrel.existingSuiteGrowth).toBe(224 * 69);
+ });
+
+ it('does not let shrinkage on one suite cancel growth on another', () => {
+ const base = measure({
+ 'server/a.test.js': "import './wide.js';\n",
+ 'server/b.test.js': "import './wide.js';\nimport './gone.js';\n",
+ 'server/wide.js': 'export const w = 1;\n',
+ 'server/gone.js': 'export const g = 1;\n',
+ });
+ const head = measure({
+ 'server/a.test.js': "import './wide.js';\nimport './heavy.js';\n",
+ 'server/b.test.js': "import './wide.js';\n",
+ 'server/wide.js': 'export const w = 1;\n',
+ 'server/heavy.js': `${Array.from({ length: 20 }, (_, i) => `import './h${i}.js';`).join('\n')}\n`,
+ ...Object.fromEntries(Array.from({ length: 20 }, (_, i) => [`server/h${i}.js`, `export const n = ${i};\n`])),
+ });
+ const report = compareImportGrowth(base, head, { limit: 10 });
+ expect(report.existingSuiteShrink).toBeGreaterThan(0);
+ expect(report.existingSuiteGrowth).toBeGreaterThan(10);
+ expect(report.ok).toBe(false);
+ });
+
+ it('describes a failure as a proxy and names the suites and dependencies', () => {
+ const report = compareImportGrowth(...Object.values(fanOut({ suites: 4, extra: 3 })), { limit: 1 });
+ const text = formatImportGrowthReport(report);
+ expect(text).toMatch(/proxy/);
+ expect(text).toMatch(/not a count of observed module instantiations/);
+ expect(text).toMatch(/server\/suite0\.test\.js/);
+ expect(text).toMatch(/server\/heavy\/m2\.js/);
+ expect(text).toMatch(/New-suite contribution/);
+ expect(text).toMatch(/intentional-regression/);
+ expect(report.timings).toBeUndefined();
+ });
+});
+
+describe('one analyzer for base and head', () => {
+ it('reports zero growth when both sides read the same sources', () => {
+ const files = {
+ 'server/a.test.js': "import './leaf.js';\n",
+ 'server/leaf.js': 'export const leaf = 1;\n',
+ };
+ const report = compareImportGrowth(measure(files), measure(files));
+ expect(report.ok).toBe(true);
+ expect(report.existingSuiteGrowth).toBe(0);
+ expect(report.baseTotal).toBe(report.headTotal);
+ });
+
+ it('attributes a head-only edge to growth rather than to the analyzer', () => {
+ const base = measure({ 'server/a.test.js': 'export const t = 1;\n' });
+ const head = measure({
+ 'server/a.test.js': "import './added.js';\n",
+ 'server/added.js': 'export const a = 1;\n',
+ });
+ const report = compareImportGrowth(base, head);
+ expect(report.existingSuiteGrowth).toBe(1);
+ expect(report.newSuiteContribution).toBe(0);
+ });
+
+ it('resolves specifiers the same way staticImportClosure walks them', () => {
+ const root = mkdtempSync(join(tmpdir(), 'portos-import-walk-'));
+ try {
+ mkdirSync(join(root, 'server', 'nested'), { recursive: true });
+ writeFileSync(join(root, 'server', 'a.test.js'), "import './nested/b.js';\n");
+ writeFileSync(join(root, 'server', 'nested', 'b.js'), "import '../c.js';\n");
+ writeFileSync(join(root, 'server', 'c.js'), 'export const c = 1;\n');
+ const read = (rel) => {
+ try { return readFileSync(join(root, ...rel.split('/')), 'utf8'); } catch { return null; }
+ };
+ const measured = measureClosures(['server/a.test.js'], read);
+ expect([...measured.tests.get('server/a.test.js')].sort()).toEqual([
+ 'server/a.test.js', 'server/c.js', 'server/nested/b.js',
+ ]);
+ expect(measured.total).toBe(staticImportClosure(join(root, 'server', 'a.test.js')).files.size);
+ const source = readFileSync(join(root, 'server', 'nested', 'b.js'), 'utf8');
+ expect(staticImportSpecifiersFromSource(source)).toEqual(staticImportSpecifiers(join(root, 'server', 'nested', 'b.js')));
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('missing base history', () => {
+ it('does not fall through when CI_BASE_SHA is set and does not resolve', () => {
+ expect(() => resolveImportGrowthBase({
+ repoRoot: REPO_ROOT,
+ env: { CI_BASE_SHA: 'not-a-commit' },
+ revParse: () => null,
+ mergeBase: () => 'should-not-be-used',
+ })).toThrow(/does not pass/);
+ });
+
+ it('does not replace a missing Actions base with the remote default branch', () => {
+ expect(() => resolveImportGrowthBase({
+ repoRoot: REPO_ROOT,
+ env: { GITHUB_ACTIONS: 'true' },
+ revParse: () => null,
+ mergeBase: () => 'origin-main',
+ })).toThrow(/HEAD\^1/);
+ });
+
+ it('fails a local run whose merge-base cannot be resolved', () => {
+ expect(() => resolveImportGrowthBase({
+ repoRoot: REPO_ROOT,
+ env: {},
+ revParse: () => null,
+ mergeBase: () => null,
+ defaultRef: 'origin/main',
+ })).toThrow(/merge-base/);
+ });
+
+ it('uses CI_BASE_SHA when it resolves, including on Actions', () => {
+ expect(resolveImportGrowthBase({
+ repoRoot: REPO_ROOT,
+ env: { CI_BASE_SHA: 'abc', GITHUB_ACTIONS: 'true' },
+ revParse: (_root, rev) => (rev === 'abc' ? 'abcabc' : null),
+ mergeBase: () => null,
+ })).toEqual({ sha: 'abcabc', source: 'CI_BASE_SHA' });
+ });
+});
+
+describe('git base versus worktree head', () => {
+ const roots = [];
+ afterEach(() => {
+ while (roots.length) rmSync(roots.pop(), { recursive: true, force: true });
+ });
+
+ function repo() {
+ const root = mkdtempSync(join(tmpdir(), 'portos-import-git-'));
+ roots.push(root);
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' });
+ git('init', '-q');
+ mkdirSync(join(root, 'empty-hooks'));
+ git('config', 'core.hooksPath', join(root, 'empty-hooks'));
+ git('config', 'user.email', '[email protected]');
+ git('config', 'user.name', 'Example Agent');
+ git('config', 'commit.gpgsign', 'false');
+ const write = (rel, body) => {
+ mkdirSync(join(root, dirname(rel)), { recursive: true });
+ writeFileSync(join(root, rel), body);
+ };
+ const commit = () => {
+ git('add', '-A');
+ git('commit', '-qm', 'fixture');
+ return git('rev-parse', 'HEAD').trim();
+ };
+ return { root, git, write, commit };
+ }
+
+ it('reads the base blob for a dirty file and counts a new test file separately', () => {
+ const { root, write, commit } = repo();
+ write('server/wide.js', 'export const wide = 1;\n');
+ write('server/keep.test.js', "import './wide.js';\n");
+ const sha = commit();
+
+ write('server/wide.js', "import './heavy.js';\nexport const wide = 1;\n");
+ write('server/heavy.js', 'export const heavy = 1;\n');
+ write('server/new.test.js', "import './heavy.js';\n");
+
+ const base = measureGitTree(root, sha);
+ const head = measureWorkingTree(root);
+ expect(base.tests.get('server/keep.test.js').has('server/heavy.js')).toBe(false);
+ expect(head.tests.get('server/keep.test.js').has('server/heavy.js')).toBe(true);
+ const report = compareImportGrowth(base, head);
+ expect(report.existingSuiteGrowth).toBe(1);
+ expect(report.newSuiteCount).toBe(1);
+ expect(report.newSuiteContribution).toBe(2);
+ expect(report.ok).toBe(true);
+ expect(report.largestNewDependencies[0]).toMatchObject({ module: 'server/heavy.js', newReach: 1, closureSize: 1 });
+ });
+
+ it('fails closed when the base commit cannot be listed', () => {
+ const { root, write, commit } = repo();
+ write('server/a.test.js', 'export const a = 1;\n');
+ commit();
+ expect(() => measureGitTree(root, 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef')).toThrow(/does not pass/);
+ });
+
+ it('treats a rename as a wash when the closure does not gain modules', () => {
+ const { root, git, write, commit } = repo();
+ write('server/old.js', 'export const leaf = 1;\n');
+ write('server/keep.test.js', "import './old.js';\n");
+ const sha = commit();
+ git('mv', 'server/old.js', 'server/renamed.js');
+ write('server/keep.test.js', "import './renamed.js';\n");
+ const report = compareImportGrowth(measureGitTree(root, sha), measureWorkingTree(root));
+ expect(report.existingSuiteGrowth).toBe(0);
+ expect(report.ok).toBe(true);
+ });
+});
+
+describe('benchmark timings stay out of the gate', () => {
+ it('reports collection and execution separately on synthetic data', () => {
+ const benchmark = benchmarkProxySplit({ modules: 12 });
+ expect(benchmark.collectionMs).toEqual(expect.any(Number));
+ expect(benchmark.executionMs).toEqual(expect.any(Number));
+ expect(benchmark.executed).toBe(13);
+ expect(benchmark.environment.synthetic).toBe(true);
+ expect(benchmark.limitations.join('\n')).toMatch(/CI pass\/fail threshold/);
+ expect(benchmark.limitations.join('\n')).toMatch(/not Vitest transforming/);
+ expect(benchmark.limitations.join('\n')).toMatch(/not test bodies/);
+ const passing = compareImportGrowth(...Object.values(fanOut({ suites: 2, extra: 1 })));
+ expect(passing.ok).toBe(true);
+ expect(passing.timings).toBeUndefined();
+ });
+});
+
+describe('name-status parsing', () => {
+ it('asks git for the pre-image of edits, deletions, and renames, not additions', () => {
+ expect(basePathsToReadFromGit('M\0server/a.js\0A\0server/new.js\0D\0server/gone.js\0R100\0server/old.js\0server/renamed.js\0')).toEqual([
+ 'server/a.js', 'server/gone.js', 'server/old.js',
+ ]);
+ });
+
+ it('rejects a truncated rename record instead of guessing a path', () => {
+ expect(() => basePathsToReadFromGit('R90\0server/old.js')).toThrow(/rename/);
+ });
+});
+
+describe('specifier resolution', () => {
+ it('keeps in-repo relative specifiers and drops ones that leave the repo', () => {
+ expect(resolveRepoSpecifier('server/lib/a.js', '../services/b.js')).toBe('server/services/b.js');
+ expect(resolveRepoSpecifier('server/a.js', '../../outside.js')).toBeNull();
+ expect(resolveRepoSpecifier('server/a.js', 'vitest')).toBeNull();
+ });
+});
+
+describe('evaluateWorkingTreeImportGrowth on a repo that is not the suite', () => {
+ it('refuses a partial measurement instead of reporting success', () => {
+ const root = mkdtempSync(join(tmpdir(), 'portos-import-partial-'));
+ try {
+ execFileSync('git', ['init', '-q'], { cwd: root });
+ mkdirSync(join(root, 'empty-hooks'));
+ execFileSync('git', ['config', 'core.hooksPath', join(root, 'empty-hooks')], { cwd: root });
+ execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: root });
+ execFileSync('git', ['config', 'user.name', 'Example Agent'], { cwd: root });
+ execFileSync('git', ['config', 'commit.gpgsign', 'false'], { cwd: root });
+ mkdirSync(join(root, 'server'));
+ writeFileSync(join(root, 'server', 'a.test.js'), 'export const a = 1;\n');
+ execFileSync('git', ['add', '-A'], { cwd: root });
+ execFileSync('git', ['commit', '-qm', 'fixture'], { cwd: root });
+ const sha = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim();
+ expect(() => evaluateWorkingTreeImportGrowth({
+ repoRoot: root,
+ env: { CI_BASE_SHA: sha },
+ })).toThrow(/does not pass/);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/scripts/pregate.js b/scripts/pregate.js
index 33164fc3f8..9fcf825d7b 100644
--- a/scripts/pregate.js
+++ b/scripts/pregate.js
@@ -89,6 +89,10 @@ export function resolvePlanStages(plan, { skipLint = false, baseSha } = {}) {
CI_TEST_MODE: scoped.mode,
CI_TEST_FILES: JSON.stringify(scoped.files),
CI_TEST_SOURCES: JSON.stringify(scoped.sources),
+ // Same base the planner just used. The import-growth guard fails
+ // closed without it; omitting it here would make pregate compare
+ // against a different ref than CI.
+ ...(baseSha ? { CI_BASE_SHA: baseSha } : {}),
},
});
});
diff --git a/scripts/pregate.test.js b/scripts/pregate.test.js
index c515f7687c..2f769f52d1 100644
--- a/scripts/pregate.test.js
+++ b/scripts/pregate.test.js
@@ -72,6 +72,9 @@ describe('resolvePlanStages', () => {
args: ['--base', 'resolved-base', '--worktree'], env: {},
});
expect(stages[1].env).toEqual({ CI_LINT_MODE: 'files', CI_LINT_FILES: '["client/src/App.jsx"]' });
+ for (const stage of stages.filter((item) => item.script === 'run-ci-tests.js')) {
+ expect(stage.env.CI_BASE_SHA).toBe('resolved-base');
+ }
});
it('drops the lint stage under --skip-lint but keeps the test stages', () => {
diff --git a/server/AGENTS.md b/server/AGENTS.md
index 4c024d957d..68011e4f0e 100644
--- a/server/AGENTS.md
+++ b/server/AGENTS.md
@@ -31,7 +31,7 @@ These apply to Express/service/model code. Universal constraints (no try/catch o
- **A widely-reached module must not drag a subtree it only needs a constant from.** The Linux CI server suite spends more wall time importing modules than running assertions, because import cost multiplies: every test file that transitively reaches module `X` re-instantiates all of `X`'s closure in its own worker. So one convenient barrel import inside a module 400 suites reach is worth thousands of module instantiations. `server/lib/importScoping.test.js` pins the narrowings made in #6009 (which cut the suite from ~115.5k static module instantiations to ~94.5k) as negative reachability assertions over `staticImportClosure`; add a row there when you narrow another one. The two shapes worth looking for: a constant re-exported through a heavy barrel (import it from the module that *declares* it — `CHECK_SCOPES` from `editorial/checkInfra/taxonomy.js`, not from `editorial/checkRegistry.js` and its 13 check-definition modules), and a dependency only a boot/rare path uses (`await import()` it inside that path — `ensureSchemaImpl()` composes the DDL that way, keeping `lib/db/schema/**` out of the ~400 suites that reach `lib/db.js` through `pgFileFacade.js`).
- **In a non-async scope, defer with `.then()` rather than giving up.** The lazy shape is not limited to `async` functions: a `new Promise` executor or a fire-and-forget branch takes `import('./x.js').then(({ fn }) => fn(…)).catch(handler)`, which also routes an import failure into the error path the call already had. That is how the TUI branch in `services/promptRunner.js` defers `tuiPromptRunner.js` (and with it `node-pty`). Prefer putting the `import()` INSIDE an existing predicate gate when there is one — `runner.js` defers `ollamaAgentContext.js` inside the `isOllamaBackedProvider` ternary, so a cloud-provider run pays neither the hop nor the subtree.
-- **The tree-wide budget is the backstop the per-edge rows can't be.** `importScoping.test.js` also asserts a ceiling on the sum, over every server test file, of `staticImportClosure(file).files.size` — the one assertion that catches a NEW heavy edge somewhere nobody thought to add a row for. It carries headroom for ordinary growth; when it fails, narrow or defer the import before raising the number, and lower it after a change that drops the total. History: 115,519 (before #6009) → 96,233 (#6009) → 83,439 (#6156).
+- **The tree-wide backstop is a base-relative growth guard, not an absolute ceiling.** `importScoping.test.js` compares every server `*.test.js` file's static import closure against the merge base, using one analyzer for both sides (`scripts/lib/importGrowth.js`). The count is a **proxy**: closure size summed across suites, shared modules counted once per suite that reaches them, not a count of runtime instantiations or a wall-clock. New test files are reported as new-suite contribution and do not spend the allowance, so ordinary additions cannot fail the guard just because the repository total grew. The gated number is the sum, over suites that exist on both sides, of how much each closure grew (shrinkage elsewhere does not cancel it). The limit is 2,500, above the old ceiling's ~1,500 ordinary-growth note and below half of the smaller heavy regression this file already records: #6009 removed 19,286 (115,519 → 96,233) and #6156 removed 12,794 (96,233 → 83,439). A failure names the largest suite increases and the largest newly reached dependency closures. Narrow the import, or defer it with `await import()` on the path that uses it. Raising `EXISTING_SUITE_GROWTH_LIMIT` is the intentional-regression path: do it in the same change, name the module that cannot be deferred, and keep the limit under that #6156 band — the pin test rejects a limit high enough to admit those edges. A missing or unreadable base fails the guard; it is not treated as zero growth. `benchmarkProxySplit` reports synthetic collection time and execution time separately and neither is a per-PR threshold. CI and `npm run pregate` run this comparison: the test is on `ALWAYS_RUN_TESTS`, and pregate forwards the same `CI_BASE_SHA` the planner used.
- **Narrowing an import must not step around a barrel a suite mocks.** `vi.mock('./cos.js')` intercepts the specifier, not the function — so re-pointing a caller from `./cos.js` to the `./cosTaskStore.js` that declares `addTask` makes production code reach the REAL implementation while the suite still believes it is doubled. The failure lands in an unrelated test file with no obvious link to the import you changed. Before narrowing, grep the tree for `vi.mock` against the module you are leaving; if any suite that reaches the caller mocks it, leave the import on the barrel. A lazy `await import()` has no such hazard — vitest's mock registry covers dynamic imports too.
## Generated manifests
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 464cb8c506..d8404148d9 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -15,7 +15,8 @@
* module instantiations to CI. So each narrowing is pinned here as a negative
* reachability assertion, paired with a positive control (per the contract in
* `staticImportGraph.js`: a resolver gap must not be able to make the walk look
- * clean).
+ * clean). The aggregate backstop is no longer a fixed total: the growth
+ * describe below compares this same closure walk to the merge base.
*
* BEFORE narrowing one of these — or any other production import — read the
* "Import scoping" section of `server/AGENTS.md`. Bypassing a barrel that a
@@ -24,10 +25,16 @@
*/
import { describe, it, expect } from 'vitest';
-import { existsSync, readdirSync, readFileSync } from 'fs';
-import { dirname, join, relative, resolve, sep } from 'path';
+import { readFileSync } from 'fs';
+import { dirname, join, relative, sep } from 'path';
import { fileURLToPath } from 'url';
-import { staticImportClosure, staticImportSpecifiers } from './staticImportGraph.js';
+import { staticImportClosure } from './staticImportGraph.js';
+import {
+ evaluateWorkingTreeImportGrowth,
+ formatImportGrowthReport,
+ measureClosures,
+ measureWorkingTree,
+} from '../../scripts/lib/importGrowth.js';
const SERVER_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -398,626 +405,41 @@ describe('heavy test imports stay hoisted to file scope (#7951)', () => {
});
});
-/**
- * The trend metric, as a budget.
- *
- * The rows above are exact: each defends one edge. This defends the property
- * they exist for — that the suite as a whole does not drift back toward
- * importing what it never runs — and it is the only assertion here that catches
- * a NEW heavy edge somewhere nobody has thought to add a row for.
- *
- * It is a budget, not a high-water mark. It sits ~1.5k above the measured total
- * so ordinary growth (a new service plus its suite) does not fail it, while the
- * shape this file exists to catch — one eager edge into a heavy subtree,
- * multiplied by every suite crossing it — moves the number by thousands.
- *
- * If a change pushes past it, first ask whether the new import belongs at module
- * scope at all. If it does, raise the number in the same commit and say what was
- * added. When a narrowing drops the total well below it, lower it — a budget
- * nobody tightens stops measuring anything.
- *
- * History, over the test files under `server/` only — the same denominator
- * #6009 reported, and what `serverTestFiles()` below walks:
- * 115,519 before #6009 · 96,233 after · 83,439 after #6156 · 85,105 after #5992 (orchestration profiles service & routes).
- *
- * Raised to 88,000 in #6305. The budget had drifted to within single digits of
- * the measured total, so the next ordinary addition was always going to trip it
- * — #6305's own share is ~43 (two new suites, plus one leaf service module,
- * `services/codexOssSupport.js`, reached by the 14 suites that cross
- * `services/providerPrerequisites.js`). That is the ordinary growth this budget
- * is documented to tolerate, not the shape it exists to catch, so the fix is to
- * restore the ~1.5k headroom the number is supposed to carry rather than to
- * inch it up by a hundred each time. It stays thousands below what ONE eager
- * edge into a heavy subtree costs, which is what actually has to fail here.
- */
-// #6350: Pi's vendor leaf is necessarily reached by the shared dispatcher.
-// Deferring catalog/version parsers removes 296 instantiations (88,360 →
-// 88,064). Restore the documented ~1.5k allowance for ordinary leaf growth;
-// keep the negative runtime-installer guard above so eager parsing cannot return.
-//
-// #6377 measures 89,889. Its share is ~389, and it is the tolerated shape, not
-// the one this budget exists to catch: two new LEAF vocabulary modules with no
-// subtree behind them — `lib/taskTargetScope.js` (four constants, zero imports)
-// and `lib/quotaBurnTaskRef.js` (pure shape + resolver, importing only
-// `objects.js`, which every reacher already had). They are reached by the ~200
-// suites that cross `lib/quotaBurnConfig.js`, so a leaf costs ~200 apiece with
-// nothing to defer. Restore the ~1.5k allowance again rather than inching the
-// number up by a few hundred per PR.
-//
-// #6368 adds `lib/callerModePolicy.js`, another zero-dependency leaf reached by
-// the routing boundary and the lib barrel (~92 instantiations). Same tolerated
-// shape; it fits inside the allowance above.
-//
-// #6375 adds `lib/autonomousJobIntervals.js` — the autonomous-job cadence
-// vocabulary `cosValidation.js` validates against, so ~194 suites reach it. It is
-// a zero-import leaf (its time units are declared locally precisely so it drags
-// nothing); the alternative is re-declaring the cadence list at the Zod boundary,
-// which is the drift that issue exists to close. Fits inside the allowance above.
-//
-// #6364 retires the server/client copy convention, splitting four pure leaves
-// out of modules the client now imports (`bibleLimits.js` out of `storyBible.js`,
-// `portosUrls.js` out of `ports.js`, `youtubeUrlAssert.js` out of `youtubeUrl.js`,
-// `avatarStyles.js` in from the client tree). Each is one extra NODE on a path
-// that already existed — a flatter graph, not a new eager edge into a heavy
-// subtree. Fits inside the allowance above.
-//
-// #6380 measures 91,710 — the ~1.5k allowance restored at #6377 is spent, so
-// re-measure and restore it rather than inching. The +371 is ONE new suite,
-// `services/cosTaskGenerator.auditMode.test.js`, and its cost IS its point: it
-// generates a real audit task through `cosTaskGenerator.js` (274) and renders
-// the final agent prompt from it through `agentPromptBuilder.js` (+94
-// marginal), because the file-issues mode is enforced across exactly that seam
-// and neither half alone can prove an issues-only run cannot acquire
-// commit/push/PR instructions. No new eager edge into a heavy subtree: the
-// production change adds only `lib/auditCatalog.js` (a zero-import leaf) to
-// `autonomousJobs/skillTemplates.js`, worth 2.
-// #6434: after deferring the private sandbox at all three CoS call sites,
-// this branch measures 93,722 versus 93,229 on its current main base. The
-// remaining +493 is the shared policy/provenance leaves and two boundary
-// suites, not an eager sandbox/runtime subtree. Main already exceeded the
-// previous ceiling; restore the documented ~1.5k ordinary-growth allowance.
-// The DEFERRED row above prevents the avoidable sandbox edge from returning.
-//
-// #6442 adds 344 on top of that base (94,066), which fits inside the allowance
-// #6434 restored — so the ceiling stays put. All 344 is three NEW suites and
-// none of it a new eager edge; the production change adds no import its module
-// did not already reach. The largest,
-// services/pipeline/editorial/reviewStaleness.test.js (198), earns its reach:
-// only the real SOURCE_RESOLVERS table can prove the evolution lens has its own
-// fingerprint token, so a lens edit stales a review while a want/need edit does
-// not. services/pipeline/arcPlanner/context.test.js (78) and
-// lib/editorial/checks/characterArcEvolution.test.js (68) are boundary tests
-// over modules those trees already instantiate.
-// #6532: same-origin Eidoverse proxy (`eidoverseProxy.js` + route allowlist)
-// loaded via the host mount at boot. Measured 95,246 on this branch (+46 over
-// the prior ceiling) — ordinary growth for an intentional main-server edge,
-// not an eager heavy subtree. Raise the ceiling to keep the ~1.5k allowance.
-//
-// Replacing five client hand-copies of server constants (the component and page
-// mirrors the earlier sweeps left) with imports added two pure leaves the
-// browser bundle reads: `lib/characterIntegrityVocabulary.js`
-// (split out of `characterIntegrity.js`, which reaches `crypto`) and
-// `lib/creativeBriefLimits.js` (the caps both creative validation modules
-// enforce). Measured 95,470 (+223 over main's 95,247): `creativeBriefLimits.js`
-// +206 (every suite that reaches `creativeCommissionValidation.js` through
-// `validation.js`'s flat re-export), `uuid.js` +56 (newly reached through
-// `seriesCharacterArc.js`), the vocabulary leaf +24, less the five deleted
-// mirror suites — leaves with nothing behind them to defer, the tolerated shape,
-// not an eager edge. Restore the ~1.5k allowance.
-//
-// #6590 is the same shape again: the image-gen capability literals the client
-// hand-copied (input-image caps, the prompt rule, the shipped default
-// models/effort, the aspect-ratio alphabets) moved out of three
-// `services/imageGen/*` modules — unreachable from the browser bundle because
-// they import `errorHandler.js` — into one dependency-free leaf,
-// `lib/imageGenCapabilities.js`. Measured 96,975 (+108 over main's 96,867): the
-// leaf is +1 in each of the 108 closures that already reached `imageGen/modes.js`,
-// and it pulls in nothing new (its only import, `generationModes.js`, was
-// already in every one of them). A leaf with nothing behind it to defer is the
-// tolerated shape. The allowance had drifted to ~30 again, so restore the ~1.5k.
-//
-// #6617 is that shape once more: collapsing `runAgentSpawn`'s eight hand-copied
-// block-and-bail epilogues into one helper meant lifting the steps they were
-// tangled with out of the orchestrator — `lib/publicReviewSpawnGate.js`,
-// `lib/agentRegistrationRecord.js`, `lib/taskGenerationOverrides.js` and
-// `services/publicReviewSpawnInput.js`. Measured 98,642 (+142 over main's
-// 98,500): four modules appearing as +1 each in the closures that already
-// reached `agentLifecycle.js`, pulling in nothing those closures lacked. The
-// one edge that WOULD have been new — `agentRegistrationRecord.js` reaching
-// `normalizeReviewers` through the 123-module `validation.js` catch-all — is
-// narrowed to its declaring leaf, `reviewerConfig.js`, so it contributes
-// nothing. Restore the ~1.5k allowance.
-// Beeper adds 22 server suites (1,045 instantiations) and 933 instantiations
-// across existing suites, primarily dependency-free validation/attachment
-// leaves. Measured against current main: 99,794 -> 101,772. No new heavy eager
-// subtree is introduced; retain the standard roughly 1,500 allowance.
-//
-// #6816 is the #6590/#6617 shape again: `creativeCommissionValidation.js`'s
-// generation-key spec (GENERATION_KEY_DEFS / ABILITY_GENERATION_SPEC and the
-// quality/aspect-ratio/backend enums) moved into a new dependency-free leaf,
-// `creativeCommissionSpec.js`, so the client form can import it directly
-// instead of hand-copying it. Its only imports (`generationModes.js`,
-// `renderTargets.js`) were already reached by every closure that reaches
-// `creativeCommissionValidation.js` (itself widely reached through
-// `validation.js`'s flat re-export, per the #6617 note above), so the new leaf
-// contributes +1 to each of those ~230 closures and pulls in nothing new.
-// Measured against current main: 103,076 -> 103,308. Restore the ~1.5k allowance.
-//
-// #6836 is the opposite shape — a DECREASE, not a new leaf's small additive
-// cost: this install's federation identity (UNKNOWN_INSTANCE_ID, ensureSelf,
-// getSelf, getInstanceId, ensureInstanceId, updateSelf, the data/instances.json
-// file I/O + mutex) moved out of services/instances.js into the dependency-free
-// services/instanceIdentity.js leaf above. The 22 callers that only needed an
-// id read no longer statically load instances.js's peer-orchestration closure
-// (the Tailscale status parser, the federated-media probe, the socket relay,
-// ~30 modules). Measured against current main: 103,462 -> 101,702 (-1,760);
-// suites whose closure reaches services/instances.js: 181 -> 33. Lower the
-// ceiling to the new measured total plus the standard ~1.5k allowance.
-// #6992 adds the existing hostShutdown latch to GitHub command completion and
-// branch reconciliation. Its dependencies were already in these callers'
-// closures; the measured baseline 103,190 -> 103,228 is the shutdown module
-// itself in 38 additional suite closures, not a new heavy subtree. Preserve
-// the existing headroom by accounting for exactly that additive lifecycle edge.
-// #7239 points cosValidation.js, peerSyncValidation.js and taskBlockCategories.js
-// at the task vocabularies declared in lib/taskParser.js, so the HTTP enum, the
-// peer wire enum and the block-category set cannot drift from what TASKS.md can
-// actually represent. taskParser.js is a zero-import leaf, so each edge costs
-// exactly one module in a suite that did not already reach it: this branch's own
-// delta is +92 — 60 such suites plus the new lib/peerSyncValidation.test.js
-// closure (32). There is nothing to narrow — the leaf IS the narrow form — so
-// raise by exactly that delta and keep the existing headroom. The measured total
-// is 103,356 after rebasing onto a main that grew by 36 on its own.
-// The yt-dlp update path adds services/ytdlpUpdate.js (closure 22 — 17 of them
-// lib/bufferedSpawn.js, which the Video Downloader route already reached) and
-// its own test file. The measured whole-tree delta is +16: nearly everything
-// ytdlpUpdate.js reaches was already in some suite's closure, so the cost is
-// the new modules themselves rather than a new heavy subtree. There is nothing
-// to narrow — bufferedSpawn IS how this tree captures a subprocess's output —
-// so raise by exactly that delta and keep the existing headroom.
-// The preflight task card (#7258) adds lib/preflightPlan.js — a zero-import
-// leaf — and services/preflightTaskCard.js, which reaches only cosTaskStore.js
-// (already in every closure that drains on-demand requests). Nearly all of the
-// measured +136 is the barrel: registering the leaf in lib/index.js, which the
-// module-organization rule requires, instantiates one more module in every
-// closure that reaches the barrel. There is nothing to narrow — the leaf pulls
-// nothing — so raise by exactly that delta and keep the existing headroom.
-// The idle-review steal's card hand-off measures +1: one new test file, which
-// reaches cosTaskGenerator.js through `await import()` (after its vi.mocks, as
-// that suite must), so its static closure is itself alone. Its one new module
-// edge — preflightTaskCard.js → taskScheduleConstants.js, for the "only a USER
-// origin is carded" policy — is free: onDemandDrain.js already reached that
-// leaf directly, and gave up its own edge to the same shared helper. Nothing to
-// narrow — a deferred import IS the narrow form.
-// The Codex quota-freshness fix measures +4: providerUsage.js and
-// providerQuotaShare.js stop hand-rolling "which reading is newer" and reach for
-// lwwTimestamp.js (the canonical LWW polarity) plus singleFlight.js. Both are
-// dependency-free leaves, so the delta is the two modules themselves across the
-// handful of closures that reach these services — there is no subtree behind
-// them to narrow, and deferring a compare used on every passive quota read
-// would trade the whole point of the shared rule for four instantiations.
-// Decks (Create → Decks) measures +393 after narrowing everything that could
-// be: the route module, the boot-time hook, the render service and the prompt
-// services all defer their heavy subtrees (DB, prompt runner, media queue,
-// image-gen dispatcher) to the request that needs them. What remains is the
-// closures of the six new suites themselves — the DB-backed route suite reaches
-// db.js, the hook suite reaches the media queue, the prompt/render suites reach
-// the modules they mock — plus the two pure leaves the lib barrel gains and the
-// schema composer's decks.js, counted by the suites that load those barrels.
-// Pinning the shipped image-gen model defaults to the seeded provider catalog
-// measures +7, all of it ONE new test file's own closure: imageGenCapabilities.js
-// and the generationModes.js leaf behind it, plus providerModels.js and its
-// three leaves, reached so the guard can assert the agy pin is the tier
-// pickAntigravityRelayModel would choose rather than a second hand-maintained
-// opinion. It reads data.reference/providers.json as JSON rather than importing
-// the toolkit's own catalog module precisely to avoid dragging that subtree in,
-// and no production module gained an edge — so raise by exactly that delta and
-// keep the headroom.
-// Federating card decks (record kind `deck`) measures +30: `services/decks.js`
-// becomes a static edge of the four peer-sync modules a new federated kind must
-// register in (recordKinds.js, peerSync.js, tombstoneGc.js,
-// conflictJournalResolver.js), dragging the one subtree it owns that those
-// modules did not already reach — `lib/deckTemplates.js` and the deck
-// validation/prompt leaves beside it. Everything else it imports (db.js,
-// conflictJournal.js, recordEvents.js, renderTargets.js) those four already
-// had. There is no narrowing available: the descriptor table needs the getter
-// and merger at module scope, by construction. The federation suite that
-// covers it (services/decksSync.db.test.js) measures a further +40, all of it
-// that one new test file's own closure — decks.js plus the syncWire/db-gate
-// leaves it asserts against, no production edge. Raise by exactly those deltas.
-// Surfacing stored model pins the provider catalog has retired (#7315) measures
-// +38. 11 are the modelPinReconcile leaf suite's own closure: the leaf plus
-// providerModels.js and its leaves, plus localProviderRuntime.js — the leaf
-// delegates its base membership rule to that module's `modelPinIsOffered`
-// rather than re-deriving it, which is what gives the audit the local-daemon
-// carve-out (an Ollama-backed provider's stored `models` is a stale snapshot,
-// so judging a pin against it reports a serving model as retired). 4 are the
-// route suite, which reaches the route through a dynamic import and statically
-// pulls only express and two error/test leaves. The audit suite adds nothing —
-// it reaches everything through vi.mock + await import. The rest is
-// routes/providers.js gaining services/modelPinAudit.js, whose own closure is
-// 34 light files: settings.js (already reached), imageGenCapabilities.js, and
-// dependency-free leaves. Its three HEAVY stores — apps.js, taskSchedule.js,
-// providers.js — stay behind memoized call-site `await import()`, without which
-// that one edge alone measured +449.
-// Giving the screened pull-request surface ONE definition (#7323) measures +68.
-// All of it is the new pure leaf `lib/prReviewContent.js` landing in the closure
-// of the 68 files that already reach `services/issueWatcher.js`,
-// `services/prReviewerSecurity.js`, or the `lib/` barrel — +1 file each. Its own
-// closure adds nothing: it imports only `lib/modelAbuseGuard.js`, which every one
-// of those already had. There is no narrowing available, and deferring it would
-// defeat the point — the preflight STAMPS a content fingerprint that the
-// coordinator RECOMPUTES before it acts, the check fails closed, and two builders
-// that drift apart disable review, CI approval, and merge for every external PR.
-// Putting both halves in one pure leaf is what keeps the contract test out of the
-// coordinator's service subtree entirely.
-// Splitting the model-pin membership rule out of `localProviderRuntime.js` into
-// the browser-safe leaf `modelPinMembership.js` (#7327) measures +297. Almost
-// all of it is one extra module NODE, not a new subtree: `localProviderRuntime`
-// is reached from a great many suites and now instantiates the leaf beside it,
-// so each of those closures grows by one. The rest is the leaf's own suite —
-// the leaf plus `providerModels.js`, `localEndpoint.js` and `ports.js`, all of
-// which that suite's predecessor already pulled. Nothing gained an edge into a
-// heavy subtree, and the split REMOVES one for the browser, which is its point:
-// `localProviderRuntime` reaches `opencodeConfig.js` → `zod` to resolve
-// ENDPOINTS, a question no picker asks. Raise by exactly that delta.
-// #7328 raised this by a further 2: the retired-pin notifier's new suite and the
-// module it statically imports, lib/mirrorParity.js (dependency-free), for the
-// bootstrap source contract. Both the notifier and the audit behind it are
-// reached through `await import()`, so neither is in that closure — and
-// bootstrap.js gaining a static import of the notifier cost nothing, because no
-// server test file statically reaches bootstrap.js.
-// +80 for services/agentSentinelSweep.test.js: a new leaf suite whose closure is
-// the sweep, lib/agentSentinel.js and the fileUtils chain those two already
-// share with the rest of the suite. No new edge into a heavy subtree — a new
-// test file simply costs its own closure once.
-// #7326 extends the audit to the per-record `imageModelId` pins: +7 on top of
-// that (104,487), raised by exactly the delta the way #7327 did. All 7 is the two new
-// suites' OWN closures — modelPinRecords.test.js and modelPinRecords.db.test.js
-// each reach `services/modelPinRecords.js` plus its three light leaves (db.js,
-// renderTargets.js, runtimeEnv.js). Neither statically imports a record service:
-// the DB suite seeds and reads with raw SQL and lets `clearRecordPin` pull
-// decks.js the way production does, which is worth ~41 on its own. The production
-// change adds NO import to any module — the collector sits behind the same
-// memoized call-site `await import()` as the audit's other three stores, and the
-// mode -> provider map stays in modelPinAudit.js rather than moving to a shared
-// leaf, which would have cost ~54 (one more file in the static closure of every
-// suite reaching routes/providers.js).
-// Making the local image runtime describe itself the same way everywhere
-// measures +65, and every one of those is the module-catalog rule rather than a
-// heavy edge. The vocabulary the layers share — the status probe, the renderer's
-// pre-flight refusal, regen.js, and the client, which re-exports it through
-// imageGenModes.js so no component hand-copies a remedy kind — has to be a
-// leaf under lib/ (it imports only runners.js), and registering a new lib/ file
-// in index.js is mandatory (lib/index.test.js fails without it), which puts
-// imageRuntimeRemedies.js into the closure of the ~57 suites that reach the
-// barrel; the rest reach it through services/imageGen/local.js and regen.js,
-// which classify a model's runtime with the same helper, plus the new suite's
-// own closure. The diagnosis module itself (localRuntime.js, which pulls the
-// model registry and the setup-check cache) measured a further +111 from the
-// image-gen dispatcher and is NOT in this number: checkConnection reaches it
-// through a memoized call-site await import(), so the ~110 suites that never
-// probe a local runtime do not pay for it.
-// The managed-app `.quality.json` publisher raises this by a further 38, all of
-// it in two new suites, none of it a new edge into a widely-reached module:
-// `services/git.commit.test.js` pays git.js's closure (~34) to pin that an
-// automated commit is scoped to literal pathspecs, and
-// `services/appQualitySnapshotFile.test.js` plus crud.js's static import of that
-// dependency-free module account for the rest. The publisher itself reaches
-// git.js and appQualityFederation.js through `await import()`, and the audit
-// hook reaches the publisher the same way, so neither is in any closure.
-// `lib/terminalReplay.js` raises this by a further 37 — one instantiation per
-// test file whose closure reaches the `lib/index.js` barrel, and nothing more.
-// It cannot be narrowed away: the catalog rule (root AGENTS.md) requires every
-// new `server/lib/` module to be re-exported from the barrel, and
-// `lib/index.test.js` fails without it. The module is deliberately
-// dependency-free (a few regexes over a string), so it adds no edge into any
-// subtree — its only consumer, `services/shell.js`, deep-imports it directly.
-// Auditing reviewer and task-template model pins (#7339) measures +41, and none
-// of it is a new edge into a heavy subtree. The shared reviewer -> provider-record
-// table is a pure leaf (`lib/reviewerProviderMatchers.js`) importing only
-// `providerModels.js`, `providerTypes.js` and `arrayUtils.js`, which every module
-// that can reach it already instantiates; registering it in the `lib/` barrel is
-// mandatory (`lib/index.test.js`) and costs one node in each barrel reacher's
-// closure, and its own suite pulls those leaves plus `reviewerConfig.js`. The
-// remaining ~22 is `services/modelPinAuditNotifier.js` taking its ONE static
-// import — `lib/modelPinReconcile.js`, so the card and the panel name a pin's
-// provider records with the same function — which lands in that module's own
-// suite and in `bootstrap.js`'s closure; no server test file statically reaches
-// `bootstrap.js`, so the production edge costs nothing. The two stores the new
-// collectors read stay behind the audit's memoized call-site `await import()`
-// (`services/taskTemplates.js` is never in a static closure), and
-// `modelPinAudit.js` gaining `reviewerConfig.js` / `goalFidelity.js` cost
-// nothing — `routes/providers.js` already reaches both through
-// `lib/validation.js`.
-// Fixing the sibling-process port mis-attribution (#7357) measures +37, all of
-// it a new boundary test file plus one dependency-free leaf. The attribution
-// rules live in `lib/ecosystemProcessPorts.js`, which imports nothing, so the
-// ~13 existing closures that reach the two services now sharing it each gain one
-// node. `services/appPortConfig.test.js` has to go through the real filesystem
-// (the regression is "the config file must come back byte-identical", which the
-// route suite's mocked writer cannot observe), so it pays its own closure. That
-// closure is 24 rather than 83 because the same change moved `deriveUiPort` —
-// three pure lines the write-back path was importing the whole 81-module
-// `services/appListEnrichment.js` for — down into that leaf, which
-// re-exports it for its existing callers.
-//
-// Raised to 106,200 for the Persistent Mind forge-issue capability, and to
-// restore the documented ~1.5k of headroom. The capability's own net share is
-// +34, because the new suite's closure (~94) is most of the way offset by the
-// managed-app roster it shares with the task capability, which replaced a second
-// app/tracker reader. The headroom is the larger half of this raise: #7357 above
-// had already landed the number at EXACTLY the measured total, so any addition
-// at all failed it — the same zero-headroom state #6305 raised it out of, and
-// that is what makes this a budget rather than a high-water mark. Measured after
-// both changes: 104,739.
-//
-// Raised to 107,700 for the Eidoverse foundation promote gate (#7455).
-// Measured after the change: 106,329, so its own cost is +132. Most of that is
-// ONE node on each of the ~60 closures that reach `services/userActions.js`,
-// which now imports the extracted leaf `lib/secretKeys.js` instead of
-// declaring `isSecretKey` inline — the extraction is what lets the federation
-// gate ask the same question, and the leaf has no imports of its own, so the
-// alternative was a second copy of the table. The rest is four small new
-// suites and the mandatory `lib/` barrel rows. Nothing heavy gained an edge:
-// the promote path's assay dependency is reached only from the ledger service,
-// which only `routes/eidoverseWorldRoutes.js` imports. The remainder of the
-// raise restores the ~1.5k of headroom this is meant to carry — the previous
-// number had drifted back to three above the measured total, the same
-// zero-headroom state #6305 raised it out of, where any addition at all fails.
-//
-// Raised to 109,200 for the Kilo Code and OpenChamber harnesses. Measured after
-// the change: 107,699, so their own cost is +816 against the 106,883 this stood
-// at beforehand. There is no new edge into a heavy subtree: `lib/kilo.js` and
-// `lib/openchamber.js` are browser-safe leaves whose whole closure is
-// `providerModels.js`, and almost all of the cost is those two nodes appearing
-// on each of the ~375 closures that already reach `lib/providerVendors.js` —
-// adding a vendor to that registry is what makes it one row instead of N call
-// sites, and this is the price of the row. The rest is three new suites
-// (`lib/kilo.test.js`, `lib/openchamber.test.js`, `lib/providerHarnesses.test.js`)
-// and the mandatory `lib/` barrel rows. Two leaves rather than one is
-// deliberate: OpenChamber is not a fork of Kilo or of OpenCode's argv — it is a
-// control plane with a different prompt-delivery contract — and the "one file
-// per vendor" split is what has kept each of these readable.
-// The remainder of the raise restores the ~1.5k of headroom this is meant to
-// carry: the previous number had drifted to ONE above the measured total, the
-// zero-headroom state #6305 raised it out of, where any addition at all fails.
-//
-// Raised to 110,700 for the stale git lock fix (#7513). Measured after the
-// change: 109,282, so its own cost is +82 — one new test file
-// (`services/git.staleLock.test.js`) reaching `services/git.js`'s existing
-// closure to cover `pull`/`syncBranch`/`ensureLatest`'s lock-clearing paths.
-// No new heavy edge: `git.js` was already reached by a dozen other server
-// test files. The remainder restores headroom the previous number had worn
-// down to zero.
-//
-// Raised to 111,500 for `lib/jobFormFields.js`, the per-job configuration-form
-// vocabulary + schemas: a NEW leaf on `lib/cosValidation.js` — one node on each
-// of the ~131 closures that already reach the job schema, dragging no subtree
-// with it (its only import is `zod`, which every one of those closures already
-// carries). That is the shape this budget is meant to allow: the cost is one
-// module, not a new heavy edge.
-//
-// This raise and the #7513 one above landed on INDEPENDENT branches, so the
-// ceiling is re-measured against the combined tree rather than resolved by
-// taking the larger of the two competing numbers — that would bank headroom
-// neither branch ever verified. Measured after both: 109,991 (so jobFormFields
-// costs +709 over #7513's 109,282), and the ceiling keeps the ~1.5k of real
-// headroom this budget exists to carry rather than being pinned to the
-// measurement.
-// 111,500 → 111,700 (#7563): `routes/providers.js` gained `providerServices.js`
-// and `providerGraph.js` gained `providerServiceInstances.js`, each one file
-// deep, plus two new suites.
-// 111,700 → 112,900 (#7564): the composite provider-id grammar is ONE
-// dependency-free leaf (`lib/providerRef.js`) reached through `zodCompat.js`
-// by every suite that validates a selection field, and its mirror
-// (`aiToolkit/internal/providerRef.js`) by every suite that reaches the
-// toolkit's provider service or validation — one node each on ~700 closures,
-// no subtree. The resolver itself (`services/compositeProviders.js`) is
-// reached only by `await import()` from the run paths and the routes, so its
-// graph-store closure stays off every suite that does not test it. Measured
-// after the change: 112,576, with five new suites; the ceiling keeps the same
-// ~300 of headroom the previous number carried.
-// 112,900 → 113,300 (#7567 rebase): three suites merged in parallel — the
-// SWE-bench and LiveCodeBench benchmark sources (#7590, 154-module closures
-// each, self-contained) and the CoS activity calendar (#7591, 44) — each fit
-// under the ceiling alone and overshot it together by 82. No widely-reached
-// module gained an eager import (the per-module closure diff against the
-// pre-merge tree shows only those three new entries growing). Measured after
-// the merge: 112,982; the ceiling keeps the same ~300 of headroom.
-// 113,300 → 113,700 (CoS spawn-window settlement): `lib/cosSpawnWindow.js` is a
-// dependency-free leaf, so it adds one node per closure that reaches it — six
-// server modules (`routes/cosTaskRoutes.js`, `routes/cosInsightRoutes.js`,
-// `routes/systemHealth.js`, `services/cos.js`, `services/activeProcessing.js`,
-// `services/systemResources.js`) plus its own suite. No subtree. Measured after
-// the change: 113,350 — the pre-change tree had already eroded to within single
-// digits of the old ceiling, so this restores the ~350 of headroom the recent
-// entries carry rather than leaving the next unrelated commit to trip it.
-// 113,700 → 114,200 (#7609 catalog extraction lens): `lib/catalogSourceKinds.js`
-// is a dependency-free leaf — the scrap source-kind vocabulary plus the
-// extraction lens each kind implies — so it adds one node per closure that
-// reaches it: `lib/catalogValidation.js` (which builds its ingest enum from
-// the ids), `services/catalogExtraction.js`, the lib barrel, and its own
-// suite. No subtree, and no widely-reached module gained an edge into one.
-// Measured before 113,568, after 113,814; its whole share is 246. The
-// alternative is what this issue exists to close: the lens re-declared as a
-// private Set inside the extractor, parallel to the source-kind list at the
-// Zod boundary, where a new ingest source silently reads a memoir through the
-// fiction lens. Restores the ~390 of headroom the recent entries carry.
-// 114,200 → 114,650 (agent loopback API token): two dependency-free-by-design
-// leaves and one small service. `lib/agentApiToken.js` (the env-var name plus the
-// `curl` argument that spends it) adds one node to the 22 closures that reach a
-// prompt builder; `lib/localReviewBridge.js` (the review-bridge script path,
-// over `fileUtils`, which those closures already carry) adds one to 75, most of
-// them via `services/cosTaskPrompts.js` — it replaces the same `join(PATHS.root,
-// …)` that builder open-coded. `services/agentApiAuth.js` reaches the auth/session
-// subtree, so the widely-reached direct-CLI spawner takes it through an
-// `await import()` instead; the TUI and runner spawn sites keep the static edge,
-// which 12 closures pay. No existing widely-reached module gained an eager edge
-// into a subtree. Measured before 114,119, after 114,253; its whole share is 134.
-// Restores the ~400 of headroom the recent entries carry — main had eroded to 81,
-// which is why an unrelated parallel merge kept tripping this.
-// 114,650 → 115,100 (#7664 Brain threads): a new record type with a route, a
-// ref registry and four suites. `lib/threadRefKinds.js` is a dependency-free
-// leaf (the (kind, id) vocabulary plus its URL builder) and adds one node to
-// the 35 closures reaching `lib/brainValidation.js`, plus the lib barrel.
-// `services/threadRefs.js` keeps its single-kind lookups behind
-// `await import()`, so the only static edges it adds are `lib/db.js` and
-// `services/brainStorage.js` — both already carried by `routes/brain.js`, the
-// one closure that reaches the new route. The rest is the suites themselves:
-// `routes/brainThreads.test.js` is 162 of the 206, which is what ANY route test
-// costs (express + the route under test), and the drift guard reaches the
-// resolver through `await import()` so it costs 2 instead of 27. Measured
-// before 114,486, after 114,692; its whole share is 206. Restores the ~400 of
-// headroom the recent entries carry — main had eroded to 164 again.
-// 115,100 → 115,300 (#7662 quota staleness): `lib/fleetQuotas.js` and
-// `services/providerUsage.js` gain a new edge into `lib/quotaWindows.js`, a
-// dependency-free leaf (staleness now needs the same window-period classifier
-// the quota-burn gate already used) — so every closure that reaches either
-// module without already reaching `quotaWindows.js` through `quotaBurn.js`
-// pays one node for it. No subtree. Measured before 114,692, after 114,853;
-// restores the ~400 of headroom the recent entries carry.
-// 115,300 → 115,900 (#7643 scope adherence): three new lib leaves
-// (`prdClauses.js`, `scopeAdherence.js`, `scopeAdherenceReasons.js`) and four
-// suites. The leaves are cheap and the barrel rows they add cost 3 in total —
-// `bm25.js`, `memoryQuery.js`, `textUtils.js`, `markdownText.js` and `jev.js`
-// are all already reachable from `lib/index.js`. The whole share is 196, and
-// 180 of it is `routes/apps/scopeAdherence.test.js` alone, which is what ANY
-// route test using `validateRequest` costs (express + the route + the
-// validation barrel): its siblings in that directory run 93 to 600, so it sits
-// mid-pack. `services/scopeAdherence.test.js` costs 1, because the service
-// reaches `jevRouter.js`, `untrustedContent.js` and `jev.js` only through
-// `await import()`. Measured before 115,283, after 115,479; restores the ~400
-// of headroom the recent entries carry — main had eroded to 17.
-// 116,500 → 116,900 (post-fleet host import growth): the current server suite
-// measures 116,547 static instantiations. This restores the established ~400
-// headroom while the import graph remains unchanged by this PR.
-// 116,100 → 116,500 (fleet host inbound usage): one new lib leaf,
-// `fleetHostUsage.js`, one new service (`fleetLlmUsage.js`) and their two
-// suites. The leaf's only edge is `openAiChatStream.js` for `normalizeUsage`,
-// which `lib/index.js` already re-exports, so nothing gains a subtree — the
-// whole share is the two new nodes once per reaching suite plus the two new
-// test files' own closures. Measured before 116,066, after 116,111 (+45);
-// restores the ~400 of headroom the recent entries carry — main had eroded
-// to 34.
-// The current tree also carries three avoidable operational edges: the review
-// queue's feedback store, its action adapters, and H3 weight provisioning were
-// imported at module scope even though each runs only from an explicit queue,
-// mutation, forwarding, or H3-render path. Keep those boundaries deferred so
-// unrelated server suites do not pay their subtrees.
-// 116,500 -> 116,600 (reviewer configuration health): the health route's
-// code-review mock adds 47 measured static instantiations across the suite;
-// the production route keeps the service import dynamic to avoid that graph.
-// 116,900 -> 117,300 (parallel-merge drift, unrelated to any single PR): main
-// itself measures 116,920, already 20 over the prior ceiling before this
-// change adds anything — see #7993 for the base-relative guard that would
-// make this fixed number unnecessary. Restores the ~400 headroom convention.
-const MAX_STATIC_INSTANTIATIONS = 117300;
-
-
-const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
-const serverTestFiles = (dir = SERVER_DIR, out = []) => {
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name) || entry.name.startsWith('.')) continue;
- serverTestFiles(join(dir, entry.name), out);
- } else if (entry.name.endsWith('.test.js')) {
- out.push(join(dir, entry.name));
- }
- }
- return out;
-};
-
-/**
- * `staticImportClosure` re-reads and re-parses every module it walks, so calling
- * it once per suite re-parses widely-shared modules thousands of times. That is
- * fine for the handful of single-entry assertions above and far too slow here:
- * ~1,600 entries took 18s on a CI runner and blew the 10s testTimeout.
- *
- * Same walk, with the per-file specifier list memoized across entries. The
- * agreement test below pins it to the shared implementation so the two cannot
- * drift into measuring different things.
- */
-const depsCache = new Map();
-const resolvedDeps = (file) => {
- const cached = depsCache.get(file);
- if (cached) return cached;
- const deps = [...new Set(
- staticImportSpecifiers(file)
- .filter((spec) => spec.startsWith('.'))
- .map((spec) => resolve(dirname(file), spec))
- .filter((path) => existsSync(path)),
- )];
- depsCache.set(file, deps);
- return deps;
-};
+const REPO_ROOT = dirname(SERVER_DIR);
-const closureSize = (entry) => {
- const seen = new Set();
- const stack = [entry];
- while (stack.length) {
- const file = stack.pop();
- if (seen.has(file)) continue;
- seen.add(file);
- for (const dep of resolvedDeps(file)) if (!seen.has(dep)) stack.push(dep);
- }
- return seen.size;
-};
-
-// Same memoized walk as closureSize, but stops the moment it finds `target`
-// instead of counting the whole closure — used by the #6836 reach-count test
-// below, which only needs a yes/no per file, not a total.
-const closureReaches = (entry, target) => {
- const seen = new Set();
- const stack = [entry];
- while (stack.length) {
- const file = stack.pop();
- if (file === target) return true;
- if (seen.has(file)) continue;
- seen.add(file);
- for (const dep of resolvedDeps(file)) if (!seen.has(dep)) stack.push(dep);
- }
- return false;
-};
-
-describe('server suite import budget (#6156)', () => {
+describe('server suite import growth (#7993)', () => {
it('memoized closure walk agrees with staticImportClosure', () => {
- // A spread of entry points: two modules this PR touched, one heavy suite,
- // and a leaf. If the shared parser gains a specifier shape this walk does
- // not follow (or vice versa), these diverge.
- for (const sample of ['lib/db.js', 'lib/pipelineValidation.js', 'services/agentManagement.test.js', 'lib/editorial/checkInfra/taxonomy.js']) {
- expect(closureSize(abs(sample)), sample).toBe(staticImportClosure(abs(sample)).files.size);
+ const read = (rel) => {
+ try {
+ return readFileSync(join(REPO_ROOT, ...rel.split('/')), 'utf8');
+ } catch {
+ return null;
+ }
+ };
+ for (const sample of ['server/lib/db.js', 'server/lib/pipelineValidation.js', 'server/services/agentManagement.test.js', 'server/lib/editorial/checkInfra/taxonomy.js']) {
+ const measured = measureClosures([sample], read);
+ expect(measured.total, sample).toBe(staticImportClosure(join(REPO_ROOT, ...sample.split('/'))).files.size);
}
});
- // Explicit timeout: this walks every server test file, which is inherently
- // more work than a unit test and runs on a shared CI runner. The memoized
- // walk brings it to ~1s locally, but the default 10s leaves no margin for a
- // slow or contended runner — and a timeout here reads as a budget failure,
- // which is exactly the wrong diagnosis.
- it(`stays under ${MAX_STATIC_INSTANTIATIONS.toLocaleString()} static module instantiations`, () => {
- const files = serverTestFiles();
- // Guards the walk itself: an empty or tiny list would make the budget pass
- // vacuously, the same failure mode the positive controls above defend.
- expect(files.length, 'found almost no test files — the walk above is broken').toBeGreaterThan(1000);
-
- const total = files.reduce((sum, file) => sum + closureSize(file), 0);
- expect(
- total,
- `Static module instantiations across the server suite rose to ${total.toLocaleString()}. Something added an eager import into a heavy subtree from a widely-reached module — narrow it, defer it with a call-site await import(), or raise the budget deliberately. See the "Import scoping" section of server/AGENTS.md.`,
- ).toBeLessThanOrEqual(MAX_STATIC_INSTANTIATIONS);
+ // The absolute ceiling this replaced failed ordinary growth: shared modules
+ // are counted once per reaching suite, so the repository total climbs even
+ // when no heavy edge was added. The comparison below is the backstop the
+ // per-edge rows cannot be. It fails closed when the base commit cannot be
+ // read — a timeout or a throw here is a guard failure, not a pass.
+ it('does not fan a heavy subtree into existing suites relative to the merge base', () => {
+ const report = evaluateWorkingTreeImportGrowth({ repoRoot: REPO_ROOT });
+ expect(report.ok, formatImportGrowthReport(report)).toBe(true);
}, 60_000);
// #6836: before the identity leaf split, 181 of these files' closures reached
- // services/instances.js — for most of them (the 22 direct identity-only
- // callers plus everything downstream of the 46 test doubles) only because a
- // static id-read reachability chain touched it, not because the suite
- // actually exercises peer orchestration. Reuses the same memoized dep cache
- // as the instantiation-count walk above, so the extra pass costs a graph
- // traversal, not re-parsing.
+ // services/instances.js. Most of them only needed an id read. The targeted
+ // row above pins the direct callers; this counts the whole suite so a new
+ // widely reached edge back onto instances.js is visible.
it('keeps fewer than 60 server test files statically reaching services/instances.js', () => {
- const files = serverTestFiles();
- const target = abs('services/instances.js');
- const reachingCount = files.filter((file) => closureReaches(file, target)).length;
+ const measured = measureWorkingTree(REPO_ROOT);
+ const target = 'server/services/instances.js';
+ const reachingCount = [...measured.tests.values()].filter((closure) => closure.has(target)).length;
expect(
reachingCount,
`${reachingCount} server test files still statically reach services/instances.js (was 181 before #6836's instanceIdentity.js leaf split). If this crept back up, check for a caller that only needs identity (getInstanceId/ensureInstanceId/getSelf/ensureSelf/updateSelf/UNKNOWN_INSTANCE_ID) re-widening its import back onto instances.js instead of instanceIdentity.js.`,
diff --git a/server/lib/staticImportGraph.js b/server/lib/staticImportGraph.js
index 35353526a2..94ce968384 100644
--- a/server/lib/staticImportGraph.js
+++ b/server/lib/staticImportGraph.js
@@ -30,13 +30,13 @@ const STATIC_FROM = /^\s*(?:import|export)\b[^;]*?from\s*['"]([^'"]+)['"]/gm;
const STATIC_BARE = /^\s*import\s*['"]([^'"]+)['"]/gm;
/**
- * Every module specifier `file` statically imports, in source order, verbatim
- * (relative specifiers keep their `./` / `../` prefix; bare package specifiers
- * come through as written). Duplicates are preserved — callers that want a set
- * build one.
+ * Every module specifier in `src`, in source order, verbatim (relative
+ * specifiers keep their `./` / `../` prefix; bare package specifiers come
+ * through as written). Duplicates are preserved — callers that want a set
+ * build one. The file reader and the base/head import-growth guard both call
+ * this so a specifier-shape fix cannot land in only one walker.
*/
-export function staticImportSpecifiers(file) {
- const src = readFileSync(file, 'utf-8');
+export function staticImportSpecifiersFromSource(src) {
const out = [];
for (const re of [STATIC_FROM, STATIC_BARE]) {
re.lastIndex = 0;
@@ -46,6 +46,11 @@ export function staticImportSpecifiers(file) {
return out;
}
+/** `staticImportSpecifiersFromSource` for a file on disk. */
+export function staticImportSpecifiers(file) {
+ return staticImportSpecifiersFromSource(readFileSync(file, 'utf-8'));
+}
+
/**
* Walk the static import graph from `entry`, following relative specifiers that
* resolve to a file on disk.