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

test: guard every static import cycle in server/services with a shrinking baseline (#5693)

[._.]/ Adam Eivy5bce086067e4
diff --git a/server/lib/README.md b/server/lib/README.md
index bc0a4cd5e8..97013d2303 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -484,7 +484,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `slashdoLoader.js` | Loads bundled slashdo command/lib markdown (`lib/slashdo/` submodule) and resolves it the way slashdo's own per-environment installer would, since PortOS inlines these bodies into CoS-agent prompts WITHOUT running that installer. `loadSlashdoFile(cmd, {stripFrontmatter, skipIncludes})` / `loadSlashdoLib(name, {teams})` resolve the `` !`cat ~/.claude/lib/…` `` includes + `if:teams` conditionals, with `skipIncludes` pruning lib includes the run can never reach (each leaves a one-line "not applicable" marker — #3110); `writeResolvedSlashdoBody(cmd, body, {skipIncludes})` → absolute path, writing the already-loaded body under `PATHS.slashdoResolved` (`data/cos/slashdo-resolved/`, gitignored derived cache) at most once per (command, body) per process, so a file-tool host can be handed a path instead of a 250KB paste. Split out of `fileUtils.js` (a generic file-utilities module) as its own feature module — pairs with `slashdoInvocation.js`, which resolves how a workflow is TYPED per host CLI rather than how its body is loaded. |
| `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `services/promptRunner.js`'s fallback mark-and-pick. |
| `staleWhileRevalidate.js` | `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` / `clear(key?)` — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). `wait`: `'fresh'` bypasses and blocks, `'cached'` (default) blocks only on a cold cache, `'never'` returns the `PENDING` symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`. |
-| `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `buildStaticImportGraph(rootDir)` → `Map<relPath, relPath[]>` of one directory's internal static edges (recurses into subdirectories, skips `.test.js`); `findImportCycles(graph)` → each cycle rendered as `a.js -> b.js -> a.js`; `specifierMatchesPackage(spec, pkg)` matches a package or any subpath; `toModuleKey(relPath)` is the one graph-key mint — always `/`-separated, because the keys are built two ways (entry-name concatenation vs `path.relative`) and Windows spells the second one with `\`, which silently dropped every edge into a subdirectory module and made the acyclicity guards pass vacuously there (#5909). Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `agentImportCycles.test.js` and `twinImportCycles.test.js` (acyclicity) and `spriteAnimationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). |
+| `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `buildStaticImportGraph(rootDir)` → `Map<relPath, relPath[]>` of one directory's internal static edges (recurses into subdirectories, skips `.test.js`); `findImportCycles(graph)` → each cycle rendered as `a.js -> b.js -> a.js` (depth-first, so WHICH rings it names depends on where the walk enters a component — fine for an "is this empty?" assertion, unusable as a baseline); `findImportCycleComponents(graph)` → the cyclic strongly-connected components as sorted member lists, traversal-order invariant and therefore baselineable (#5693); `specifierMatchesPackage(spec, pkg)` matches a package or any subpath; `toModuleKey(relPath)` is the one graph-key mint — always `/`-separated, because the keys are built two ways (entry-name concatenation vs `path.relative`) and Windows spells the second one with `\`, which silently dropped every edge into a subdirectory module and made the acyclicity guards pass vacuously there (#5909). Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `serviceImportCycles.test.js` (the tree-wide cycle ratchet), `agentImportCycles.test.js` and `twinImportCycles.test.js` (per-cluster acyclicity) and `spriteAnimationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. |
| `streamAttachment.js` | `streamAttachment(res,stream,{filename,contentType,failure,label})` — pipe a readable to a response as a file download. Sets the attachment headers plus `X-Content-Type-Options:nosniff`, and owns the teardown every attachment route needs: a pre-stream failure drops the download headers and returns `failure` via `sendErrorResponse`, a mid-stream failure destroys the socket (the envelope no-ops once headers are sent), and a client disconnect calls `stream.abort?.()` so an upstream child process is torn down. Shared by `routes/imageTo3d.js` (GLB, full-mesh) and `routes/backup.js` (snapshot tarball). |
| `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |
diff --git a/server/lib/staticImportGraph.js b/server/lib/staticImportGraph.js
index 67c3d3b6d3..fbe568d218 100644
--- a/server/lib/staticImportGraph.js
+++ b/server/lib/staticImportGraph.js
@@ -10,8 +10,8 @@
* `exec` drain loop, which is exactly how a guard rots: a fix to one parser
* (multi-line import lists, `export * from`, a new specifier shape) lands in
* one copy while the other keeps silently under-reporting. `buildStaticImportGraph`
- * and `findImportCycles` live here for the same reason — `agentImportCycles` and
- * `twinImportCycles` both walk `server/services` for rings.
+ * and the cycle walks live here for the same reason — `serviceImportCycles`,
+ * `agentImportCycles` and `twinImportCycles` all walk `server/services` for rings.
*
* **Static imports only.** `await import('./x.js')` is deferred to call time,
* so it can neither produce a load-time cycle nor drag a native dependency into
@@ -170,3 +170,67 @@ export function findImportCycles(graph) {
for (const node of graph.keys()) if (!state.has(node)) visit(node);
return [...cycles];
}
+
+/**
+ * Every cyclic strongly-connected component of `graph`, as sorted member lists,
+ * themselves sorted — the traversal-order-INVARIANT form of "what is mutually
+ * import-dependent here". A component is returned when it holds more than one
+ * module, or when a single module imports itself.
+ *
+ * `findImportCycles` answers a different question and cannot be baselined. Its
+ * depth-first walk reports the rings it happens to close from whichever node it
+ * enters a component through, so the SAME graph yields a different set of rings
+ * depending on where the walk starts — and the walk starts wherever
+ * `readdirSync` put the first file, which is OS/filesystem order, not
+ * alphabetical. That is fine for an "is this empty?" assertion (emptiness is
+ * order-independent) and wrong for a baseline list, which would go red on
+ * another machine over a graph nobody touched.
+ *
+ * Tarjan's algorithm instead partitions the graph: the components are a
+ * property of the edges alone, so a baseline keyed on them means the same thing
+ * on every machine. Closing a NEW ring either mints a component or pulls
+ * modules into an existing one — both change this output. Removing one shrinks
+ * or deletes a component, which changes it too, so a stale baseline entry
+ * cannot survive the fix it was waiting for.
+ */
+export function findImportCycleComponents(graph) {
+ const index = new Map();
+ const lowlink = new Map();
+ const onStack = new Set();
+ const stack = [];
+ const components = [];
+ let counter = 0;
+
+ const visit = (node) => {
+ index.set(node, counter);
+ lowlink.set(node, counter);
+ counter += 1;
+ stack.push(node);
+ onStack.add(node);
+
+ for (const dep of graph.get(node) || []) {
+ if (!index.has(dep)) {
+ visit(dep);
+ lowlink.set(node, Math.min(lowlink.get(node), lowlink.get(dep)));
+ } else if (onStack.has(dep)) {
+ lowlink.set(node, Math.min(lowlink.get(node), index.get(dep)));
+ }
+ }
+
+ if (lowlink.get(node) !== index.get(node)) return;
+ const members = [];
+ let member;
+ do {
+ member = stack.pop();
+ onStack.delete(member);
+ members.push(member);
+ } while (member !== node);
+ // A one-module component is cyclic only when it imports itself; every
+ // acyclic module is also a one-module component, and those are not findings.
+ const selfImporting = members.length === 1 && (graph.get(node) || []).includes(node);
+ if (members.length > 1 || selfImporting) components.push(members.sort());
+ };
+
+ for (const node of graph.keys()) if (!index.has(node)) visit(node);
+ return components.sort((a, b) => (a.join() < b.join() ? -1 : 1));
+}
diff --git a/server/services/serviceImportCycles.test.js b/server/services/serviceImportCycles.test.js
new file mode 100644
index 0000000000..75583fca0e
--- /dev/null
+++ b/server/services/serviceImportCycles.test.js
@@ -0,0 +1,174 @@
+/**
+ * The tree-wide static-import-cycle ratchet for `server/services` (#5693).
+ *
+ * A static ESM cycle is a boot-order hazard: whichever member evaluates first
+ * sees `undefined` for the others' bindings, so a top-level `const` derived from
+ * an imported value anywhere in the ring is a TDZ crash that no behavior test
+ * notices until an unrelated import-order change surfaces it.
+ *
+ * Two guards already prove specific clusters acyclic — `agentImportCycles.test.js`
+ * (#2837/#3450) and `twinImportCycles.test.js` (#5687) — and both deliberately
+ * ignore a cycle that misses their cluster. That left the rest of a 1000-module
+ * directory unguarded: nothing stopped a new service from closing the next ring.
+ * This suite covers everything, and the cluster guards keep their own assertions
+ * (facade re-export rules, deferred-import bans) because those check properties a
+ * general acyclicity walk does not.
+ *
+ * **A shrinking baseline, not a hard zero.** Five cyclic components are live
+ * today; fixing them all in one PR would be un-reviewable, so each is recorded
+ * below against the issue that removes it, and the assertions run BOTH ways:
+ * a component that is not in the baseline fails (no new cycles from today), and
+ * a baseline entry that is no longer detected fails too (a fixed cycle must be
+ * deleted from the list, so the baseline can only shrink and cannot rot).
+ *
+ * **Why components and not rendered rings.** `findImportCycles` reports the
+ * rings its depth-first walk happens to close, which depends on where the walk
+ * enters a component — and it enters wherever `readdirSync` put the first file,
+ * i.e. filesystem order, not alphabetical. That is fine for the cluster guards,
+ * which only ask "is this empty?", and useless as a baseline: the same untouched
+ * graph would produce a different list on another machine. Strongly-connected
+ * components are a property of the edges alone, so this list means the same thing
+ * everywhere. It is also the truer picture — the DFS walk names 8 modules in the
+ * autopilot ring; the component is 22.
+ *
+ * Static edges only. `await import()` is deferred to call time and cannot
+ * produce a load-time cycle, so breaking a cycle by deferring an import does not
+ * count as a fix — see the deferred-import guards in `agentImportCycles.test.js`.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { fileURLToPath } from 'url';
+import { dirname } from 'path';
+import { buildStaticImportGraph, findImportCycles, findImportCycleComponents } from '../lib/staticImportGraph.js';
+
+const SERVICES_DIR = dirname(fileURLToPath(import.meta.url));
+
+// Every cyclic component still live in `server/services`, each against the issue
+// that removes it. Delete an entry the moment its cycle is broken — the second
+// assertion below fails while a fixed entry is still listed, which is what stops
+// this list from becoming a wish.
+const KNOWN_CYCLIC_COMPONENTS = [
+ // #5920 — the seriesAutopilot barrel and the creativeDirector completion hook
+ // each re-enter the other's half; 22 modules end up mutually reachable.
+ {
+ issue: 5920,
+ members: [
+ 'creative/toolRegistry.js',
+ 'creative/tools/pipeline.js',
+ 'creativeDirector/agentBridge.js',
+ 'creativeDirector/completionHook.js',
+ 'creativeDirector/planAdvance.js',
+ 'creativeDirector/sceneEvaluator.js',
+ 'creativeDirector/sceneRunner.js',
+ 'pipeline/autoRunner.js',
+ 'pipeline/episodeVideo.js',
+ 'pipeline/seriesAutopilot.js',
+ 'pipeline/seriesAutopilot/arcSteps.js',
+ 'pipeline/seriesAutopilot/childRuns.js',
+ 'pipeline/seriesAutopilot/dispatch.js',
+ 'pipeline/seriesAutopilot/dryRun.js',
+ 'pipeline/seriesAutopilot/editorialSteps.js',
+ 'pipeline/seriesAutopilot/observer.js',
+ 'pipeline/seriesAutopilot/orchestrator.js',
+ 'pipeline/seriesAutopilot/revisionSteps.js',
+ 'pipeline/seriesAutopilot/selfImprove.js',
+ 'pipeline/seriesAutopilot/session.js',
+ 'pipeline/seriesAutopilot/unlockPass.js',
+ 'pipeline/seriesAutopilot/visualSteps.js',
+ ],
+ },
+ // #5917 — caption resolution and subject derivation import each other.
+ { issue: 5917, members: ['loraDatasetCaption.js', 'loraDatasetGenerate.js'] },
+ // #5918 — the fixer reaches back for the review-comment store accessors.
+ { issue: 5918, members: ['pipeline/manuscriptFix.js', 'pipeline/manuscriptReview.js'] },
+ // #5919 — the receive path reaches subscription state back through the barrel.
+ { issue: 5919, members: ['sharing/peerSync.js', 'sharing/peerSyncReceive.js'] },
+ // #5916 — routing imports the metrics reset; metrics imports routing's predicates.
+ { issue: 5916, members: ['taskLearning/metrics.js', 'taskLearning/routing.js'] },
+];
+
+// A component as one comparable string. Members arrive sorted from
+// `findImportCycleComponents`, and the baseline is sorted here rather than by
+// hand so an entry typed in a readable order still matches.
+const componentKey = (members) => [...members].sort().join(' + ');
+
+describe('server/services — static import cycle ratchet (#5693)', () => {
+ const graph = buildStaticImportGraph(SERVICES_DIR);
+ const detected = findImportCycleComponents(graph);
+
+ it('sees the whole services graph', () => {
+ // Every assertion below is a negative or a set comparison, so a resolver gap
+ // that emptied the graph would read as a clean sweep. Pin the scale first.
+ expect(graph.size, 'services graph looks empty — did the scan root move?').toBeGreaterThan(500);
+ const withEdges = [...graph.values()].filter(deps => deps.length > 0);
+ expect(withEdges.length, 'no module has any resolved edge — the specifier resolver is broken')
+ .toBeGreaterThan(100);
+ });
+
+ it('detects a cycle in a hand-built graph', () => {
+ // Negative control for the detector itself: without this, a
+ // `findImportCycleComponents` that always returned `[]` would make the
+ // no-new-cycles assertion pass vacuously forever.
+ const cyclic = new Map([
+ ['a.js', ['b.js']],
+ ['b.js', ['c.js']],
+ ['c.js', ['a.js']],
+ ['leaf.js', ['a.js']],
+ ]);
+ expect(findImportCycleComponents(cyclic).map(members => componentKey(members)))
+ .toEqual(['a.js + b.js + c.js']);
+
+ // And the converse: an acyclic graph must report nothing, or the assertion
+ // would be satisfied by a detector that flags everything.
+ expect(findImportCycleComponents(new Map([['a.js', ['b.js']], ['b.js', []]]))).toEqual([]);
+
+ // A module importing itself is a cycle of one, and the members-length test
+ // inside the component walk is the only thing separating it from the ~1000
+ // acyclic single-module components it must not report.
+ expect(findImportCycleComponents(new Map([['a.js', ['a.js']]]))).toEqual([['a.js']]);
+ });
+
+ it('closes no static import cycle that is not already in the baseline', () => {
+ const known = new Set(KNOWN_CYCLIC_COMPONENTS.map(entry => componentKey(entry.members)));
+ const unexpected = detected.map(members => componentKey(members)).filter(key => !known.has(key));
+
+ // Name the actual rings for a component that is new or that grew — the member
+ // list says WHAT is tangled, the rings say which edges tangled it.
+ const rings = unexpected.length
+ ? findImportCycles(graph).filter(cycle =>
+ unexpected.some(key => cycle.split(' -> ').some(module => key.split(' + ').includes(module))))
+ : [];
+ expect(unexpected, [
+ 'new or grown static import cycle in server/services:',
+ ...unexpected,
+ ...(rings.length ? ['', 'rings closing it:', ...rings] : []),
+ '',
+ 'Break the cycle — import the module that DECLARES the symbol, not the barrel that',
+ 'forwards it. Deferring the import with `await import()` hides it from this guard',
+ 'without removing the boot-order hazard, so it is not a fix.',
+ ].join('\n')).toEqual([]);
+ });
+
+ it('keeps no baseline entry for a cycle that is already fixed', () => {
+ const live = new Set(detected.map(members => componentKey(members)));
+ const stale = KNOWN_CYCLIC_COMPONENTS
+ .map(entry => ({ ...entry, key: componentKey(entry.members) }))
+ .filter(entry => !live.has(entry.key));
+
+ expect(stale.map(entry => `#${entry.issue}: ${entry.key}`), [
+ 'these baseline entries no longer match a live cycle — the cycle was broken, or',
+ 'the component shrank and the entry needs re-recording. Update KNOWN_CYCLIC_COMPONENTS',
+ 'in this file; the baseline only ever shrinks.',
+ ].join('\n')).toEqual([]);
+ });
+
+ it('records each baseline entry once, against a real issue', () => {
+ const keys = KNOWN_CYCLIC_COMPONENTS.map(entry => componentKey(entry.members));
+ expect(keys.length, 'a component is listed twice in the baseline').toBe(new Set(keys).size);
+ for (const entry of KNOWN_CYCLIC_COMPONENTS) {
+ expect(entry.issue, `baseline entry ${componentKey(entry.members)} names no tracking issue`)
+ .toBeGreaterThan(0);
+ expect(entry.members.length, 'a cyclic component has at least one member').toBeGreaterThan(0);
+ }
+ });
+});