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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
perf(tests): narrow server import graphs so CI stops importing what it never runs (#6009)
Adam Eivyf8701bb0a09a
diff --git a/server/AGENTS.md b/server/AGENTS.mdindex 8cc90f6c0a..0b5bc83a3d 100644--- a/server/AGENTS.md+++ b/server/AGENTS.md@@ -23,6 +23,11 @@ These apply to Express/service/model code. Universal constraints (no try/catch o- **Record-creating tests and peer fan-out.** Record create/update paths reach peer-sync only through the subscription adapter in `server/services/sharing/recordEvents.js` (`autoSubscribeRecordToAllPeers` etc.) — a silent no-op until `peerSync.js` registers the real implementation at module load. A suite that never loads `peerSync.js` therefore gets no fan-out without mocking anything. Suites that DO load the peer-sync graph (importing `peerSync.js` or `sharing/index.js`, directly or transitively) must still mock `services/instances.js` with `mockNoPeers()` from `server/lib/mockPathsDataRoot.js` and `services/sharing/peerSync.js` with `mockNoPeerSync()` — the mock keeps the real module's registration side effect from wiring live fan-out into the adapter. To assert auto-subscribe behavior in a domain test, register a test double via `registerSubscriptionAdapter({...})` and clean up with `__resetSubscriptionAdapter()`.+## Import scoping++- **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`).+- **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- **A checked-in generated manifest is addressed by CONTENT, never by POSITION.** `server/lib/*.generated.json` files are derived from source and kept honest by a drift test that regenerates and compares. That only works if the manifest changes when the thing it describes changes — and *only* then. A record that says "declared at `foo.js:412`" is rewritten by any edit that inserts a line above 412 (a rename, a comment, an unrelated handler), so the drift test fires on commits that change no route/stage/event at all, each parallel branch regenerates the file differently, and every rebase conflicts on it. `apiRouteCatalog.generated.json` shipped 30 changed lines per no-op refactor this way, and `main` still ended up carrying a stale `stats.declarations` whose route graph was byte-identical.diff --git a/server/lib/db.js b/server/lib/db.jsindex dc116c1951..63866f9589 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -6,7 +6,6 @@*/import pg from 'pg';-import { buildUpgradeDdl, buildCatalogDdl } from './db/schema/index.js';const { Pool } = pg;@@ -359,6 +358,18 @@ export async function ensureSchema() {}async function ensureSchemaImpl() {+ // The DDL composer is imported lazily, not at module load. `db.js` is reached+ // by ~400 server test files through pgFileFacade.js, and eagerly importing+ // ./db/schema/index.js pulled its 17 per-domain DDL modules into every one of+ // those import graphs — ~7k module instantiations per suite run, for+ // statement arrays only this function ever reads (#6009). Resolved BEFORE the+ // advisory lock below, so no other booting process waits on a module load,+ // and once per boot inside a path already awaiting Postgres, so it costs+ // nothing at runtime. vi.mock('./db/schema/index.js') still intercepts it —+ // the mock registry covers dynamic imports too, which is what+ // lib/db.test.js's bad-DDL injection relies on.+ const { buildUpgradeDdl, buildCatalogDdl } = await import('./db/schema/index.js');+// ⚠️ Boot CREATE INDEX lock window. Every `CREATE INDEX IF NOT EXISTS` below// (and in the catalogDDL block, incl. the HNSW vector index on catalog_scraps)// runs as a plain, non-CONCURRENT build. The FIRST time an index materializesdiff --git a/server/lib/editorial/severityConfig.js b/server/lib/editorial/severityConfig.jsindex 423615872f..95dfd6a6f9 100644--- a/server/lib/editorial/severityConfig.js+++ b/server/lib/editorial/severityConfig.js@@ -23,7 +23,7 @@* checked first, before any emptiness check.*/-import { CHECK_SEVERITIES } from './checkRegistry.js';+import { CHECK_SEVERITIES } from './checkInfra/taxonomy.js';// Transparent severity penalty weights (mirrors editorialScore.SEVERITY_WEIGHTS,// which now re-exports this). A draft starts at 100 and loses points per OPENdiff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsnew file mode 100644index 0000000000..cacb70a012--- /dev/null+++ b/server/lib/importScoping.test.js@@ -0,0 +1,86 @@+/**+ * Import-scoping guards (#6009).+ *+ * The Linux CI server suite spends more wall time importing modules than+ * running assertions, and almost none of that is any one test's fault: a+ * handful of widely-reached modules each pulled a subtree they only needed a+ * constant (or a boot-time function) from, and every test file downstream paid+ * for the whole thing. Narrowing those imports cut the suite's static module+ * instantiations — the sum, over all 1,588 server test files, of the modules in+ * each one's import closure — from ~115.5k to ~94.5k (-18%).+ *+ * That is a property nothing else in the tree defends, and it regresses+ * silently: re-pointing one of these imports back at the convenient barrel+ * still passes every behavioral test, it just quietly re-adds thousands of+ * 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).+ *+ * BEFORE narrowing one of these — or any other production import — read the+ * "Import scoping" section of `server/AGENTS.md`. Bypassing a barrel that a+ * suite `vi.mock()`s reaches the real implementation instead of the double, and+ * the failure surfaces in an unrelated test file.+ */++import { describe, it, expect } from 'vitest';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import { staticImportClosure } from './staticImportGraph.js';++const SERVER_DIR = dirname(dirname(fileURLToPath(import.meta.url)));++// Server-relative POSIX paths, so a failure names `lib/db.js` rather than the+// absolute path of whoever's checkout is running the suite.+const abs = (relative) => join(SERVER_DIR, ...relative.split('/'));+const reaches = (entry, target) => staticImportClosure(abs(entry)).files.has(abs(target));++// Each row: the entry that was narrowed, the module it must no longer+// statically reach, and why the entry only ever needed a slice of it.+const NARROWED = [+ ['lib/db.js', 'lib/db/schema/index.js',+ 'the DDL composer is boot-only — ensureSchemaImpl() imports it lazily'],+ ['lib/pipelineValidation.js', 'lib/editorial/checkRegistry.js',+ 'needs CHECK_SCOPES/CHECK_SEVERITIES, not the 13 check-definition modules'],+ ['lib/editorial/severityConfig.js', 'lib/editorial/checkRegistry.js',+ 'needs CHECK_SEVERITIES only'],+ ['services/pipeline/series.js', 'lib/editorial/checkRegistry.js',+ 'needs CHECK_SEVERITIES only'],+ ['services/pipeline/applyCuts.js', 'lib/editorial/checkRegistry.js',+ 'needs CUT_TYPES/SAFE_CUT_TYPES only'],+ ['services/apps.js', 'lib/validation.js',+ 'needs sanitizeTaskMetadata, which cosValidation.js declares'],+ ['services/memoryEmbeddings.js', 'services/memoryBackend.js',+ 'needs DEFAULT_MEMORY_CONFIG, which memoryConfig.js declares'],+ ['lib/llmRoutePin.js', 'lib/storyBible.js',+ 'needs trimTo, which textUtils.js declares'],+ ['lib/slashdoInvocation.js', 'lib/tuiHandshake.js',+ 'needs inferTuiCommand, which providerVendors.js declares'],+ ['services/voice/tools/pipeline.js', 'services/pipeline/issues.js',+ 'needs NAVIGABLE_STAGE_IDS, which issuesShared.js declares'],+];++describe('narrowed imports stay narrow (#6009)', () => {+ it.each(NARROWED)('%s no longer statically reaches %s — it %s', (entry, target) => {+ expect(reaches(entry, target)).toBe(false);+ });++ // Positive controls. Without these the negatives above would also pass if+ // `staticImportClosure` stopped resolving these files at all.+ it('still sees the modules the narrowed entries were pointed AT', () => {+ expect(reaches('lib/pipelineValidation.js', 'lib/editorial/checkInfra/taxonomy.js')).toBe(true);+ expect(reaches('services/apps.js', 'lib/cosValidation.js')).toBe(true);+ expect(reaches('services/memoryEmbeddings.js', 'services/memoryConfig.js')).toBe(true);+ expect(reaches('lib/llmRoutePin.js', 'lib/textUtils.js')).toBe(true);+ expect(reaches('lib/slashdoInvocation.js', 'lib/providerVendors.js')).toBe(true);+ expect(reaches('services/voice/tools/pipeline.js', 'services/pipeline/issuesShared.js')).toBe(true);+ });++ // And a control on the other side: the barrels themselves still reach what+ // they re-export, so "nobody reaches checkRegistry" is a statement about the+ // narrowed callers, not about a broken registry.+ it('leaves the editorial barrel and the schema composer intact', () => {+ expect(reaches('lib/editorial/checkRegistry.js', 'lib/editorial/checks/proseStyle.js')).toBe(true);+ expect(reaches('lib/db/schema/index.js', 'lib/db/schema/catalog.js')).toBe(true);+ });+});diff --git a/server/lib/llmRoutePin.js b/server/lib/llmRoutePin.jsindex 4f9e6fa5c8..34aaf8a13b 100644--- a/server/lib/llmRoutePin.js+++ b/server/lib/llmRoutePin.js@@ -30,7 +30,7 @@import { z } from 'zod';import { EFFORT_LEVELS } from './providerModels.js';-import { trimTo } from './storyBible.js';+import { trimTo } from './textUtils.js';/** Field caps for a pin — the one source of truth for both the door check* (`llmRoutePinSchema`) and the sanitizer, so they can never drift. */diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.jsindex 1a3899a8f3..da7c06d512 100644--- a/server/lib/pipelineValidation.js+++ b/server/lib/pipelineValidation.js@@ -19,7 +19,7 @@ import {} from './storyBible.js';import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';import { EFFORT_LEVELS } from './providerModels.js';-import { CHECK_SCOPES, CHECK_SEVERITIES } from './editorial/checkRegistry.js';+import { CHECK_SCOPES, CHECK_SEVERITIES } from './editorial/checkInfra/taxonomy.js';import { SHOT_TYPES, SCREEN_DIRECTIONS } from './shotGrammar.js';// =============================================================================diff --git a/server/lib/slashdoInvocation.js b/server/lib/slashdoInvocation.jsindex db1548f591..7d52b469bb 100644--- a/server/lib/slashdoInvocation.js+++ b/server/lib/slashdoInvocation.js@@ -28,7 +28,7 @@* resolved copy on disk rather than pasted (`buildSlashdoSection`'s `bodyPath`).*/import { isClaudeProvider, isOpencodeProvider } from './providerModels.js';-import { inferTuiCommand } from './tuiHandshake.js';+import { inferTuiCommand } from './providerVendors.js';import { PROVIDER_TYPES } from './aiToolkit/constants.js';/** slashdo's command namespace — `commands/do/<cmd>.md` in the submodule. */diff --git a/server/services/apps.js b/server/services/apps.jsindex 126bd31809..d832c13573 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -6,7 +6,7 @@ import { PORTOS_APP_ID } from '../lib/appIdentity.js';import { NON_PM2_TYPES, usesPm2, isDesktopType } from './streamingDetect.js';import { listProcessesStrict } from './pm2.js';import { SELF_IMPROVEMENT_TASK_TYPES } from './taskScheduleRegistry.js';-import { sanitizeTaskMetadata } from '../lib/validation.js';+import { sanitizeTaskMetadata } from '../lib/cosValidation.js';import { isPlainObject } from '../lib/objects.js';import { resolveAppWorkTracker } from '../lib/workTracker.js';import { PORTS } from '../lib/ports.js';diff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.jsindex df79db0973..0e0ef4dd13 100644--- a/server/services/memoryEmbeddings.js+++ b/server/services/memoryEmbeddings.js@@ -5,7 +5,7 @@* Provides semantic search capabilities for the memory system.*/-import { DEFAULT_MEMORY_CONFIG } from './memoryBackend.js';+import { DEFAULT_MEMORY_CONFIG } from './memoryConfig.js';import { getProviderById } from './providers.js';import { getConfig as getCosConfig } from './cosState.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';diff --git a/server/services/pipeline/applyCuts.js b/server/services/pipeline/applyCuts.jsindex 59cf265695..c0297bbd51 100644--- a/server/services/pipeline/applyCuts.js+++ b/server/services/pipeline/applyCuts.js@@ -19,7 +19,7 @@import { randomUUID } from 'crypto';import { updateStagesWithLatest } from './issues.js';import { collectManuscriptSections } from './arcPlanner.js';-import { SAFE_CUT_TYPES, CUT_TYPES } from '../../lib/editorial/checkRegistry.js';+import { SAFE_CUT_TYPES, CUT_TYPES } from '../../lib/editorial/checkInfra/craftStages.js';import {MIN_ANCHOR_CHARS,locateCutSpan,diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 2e6c5f35a9..2f8b82c506 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -19,7 +19,7 @@ import { sanitizeCharacterArcList } from '../../lib/seriesCharacterArc.js';import { sanitizeStyleGuide } from '../../lib/styleGuide.js';import { sanitizeProseExportSettings } from '../../lib/proseExportSettings.js';import { sanitizeSeverityWeights, sanitizeBlockingSeverities } from '../../lib/editorial/severityConfig.js';-import { CHECK_SEVERITIES } from '../../lib/editorial/checkRegistry.js';+import { CHECK_SEVERITIES } from '../../lib/editorial/checkInfra/taxonomy.js';import { sanitizeOrigin } from '../../lib/sharingOrigin.js';import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';import { persistedRenderPinFields } from '../../lib/renderTargets.js';diff --git a/server/services/voice/tools/pipeline.js b/server/services/voice/tools/pipeline.jsindex 2a985ae590..d9190a6ee7 100644--- a/server/services/voice/tools/pipeline.js+++ b/server/services/voice/tools/pipeline.js@@ -2,7 +2,7 @@// named stage of the current pipeline issue. These only work on a// /pipeline/issues/... page; off-page calls return a friendly error.-import { NAVIGABLE_STAGE_IDS as PIPELINE_STAGE_IDS } from '../../pipeline/issues.js';+import { NAVIGABLE_STAGE_IDS as PIPELINE_STAGE_IDS } from '../../pipeline/issuesShared.js';// Pipeline stage navigation — fires on "next stage", "previous stage",// "back to prose", "open the storyboards", "open prose", "open teleplay",