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: break the identity / digital-twin barrel import cycles (#5687)

[._.]/ Adam Eivy9675130891d9
diff --git a/server/lib/README.md b/server/lib/README.md
index 68911cfb33..af6f62d213 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -479,7 +479,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; `specifierMatchesPackage(spec, pkg)` matches a package or any subpath. 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` (acyclicity) and `sprites/animationTracks.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`; `specifierMatchesPackage(spec, pkg)` matches a package or any subpath. 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). |
| `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 6d29d8fffd..f385a5052f 100644
--- a/server/lib/staticImportGraph.js
+++ b/server/lib/staticImportGraph.js
@@ -3,13 +3,15 @@
*
* Several suites assert structural properties of the module graph rather than
* runtime behavior: `agentImportCycles.test.js` proves the agent-lifecycle
- * cluster is acyclic, and `sprites/animationTracks.test.js` proves the
+ * cluster is acyclic, and `spriteAnimationTracks.test.js` proves the
* request-validation graph never reaches the native image dependencies
* (sharp/ffmpeg). Both need the same thing — "which modules does this file
* statically import?" — and both had their own copy of the regex pair and the
* `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.
+ * 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.
*
* **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
@@ -19,8 +21,8 @@
* `import`/`export`.
*/
-import { readFileSync, existsSync } from 'fs';
-import { dirname, resolve } from 'path';
+import { readdirSync, readFileSync, existsSync } from 'fs';
+import { dirname, join, relative, resolve } from 'path';
// `import … from 'x'` / `export … from 'x'` (line-anchored, non-greedy up to
// the `from`), and bare `import 'x'` side-effect imports.
@@ -83,3 +85,71 @@ export function staticImportClosure(entry) {
export function specifierMatchesPackage(specifier, pkg) {
return specifier === pkg || specifier.startsWith(`${pkg}/`);
}
+
+/**
+ * Every non-test `.js` file under `rootDir`, keyed by its path relative to that
+ * directory (`identity.js`, `identity/goals.js`). The walk recurses: scanning
+ * only top-level files leaves a hole big enough to drive a cycle back through,
+ * because a subdirectory module can import back up.
+ */
+function listModuleFiles(rootDir, dir = rootDir, prefix = '') {
+ const out = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) out.push(...listModuleFiles(rootDir, join(dir, entry.name), rel));
+ else if (entry.name.endsWith('.js') && !entry.name.includes('.test.')) out.push(rel);
+ }
+ return out;
+}
+
+/**
+ * The STATIC import graph of every non-test module under `rootDir`, as
+ * `Map<relPath, relPath[]>`. Specifiers are resolved relative to the importing
+ * file and re-keyed against `rootDir`, so `./x.js` from a subdirectory and
+ * `../x.js` from a sibling land on the same node; anything resolving outside
+ * `rootDir` is dropped, because these guards ask about one directory's internal
+ * shape. Static edges only — see the module header for why `import()` is out.
+ */
+export function buildStaticImportGraph(rootDir) {
+ const files = listModuleFiles(rootDir);
+ const known = new Set(files);
+ const graph = new Map();
+ for (const file of files) {
+ const abs = join(rootDir, file);
+ const deps = new Set();
+ for (const spec of staticImportSpecifiers(abs)) {
+ if (!spec.startsWith('.')) continue;
+ const rel = relative(rootDir, resolve(dirname(abs), spec));
+ if (known.has(rel)) deps.add(rel);
+ }
+ graph.set(file, [...deps]);
+ }
+ return graph;
+}
+
+/**
+ * Every static import cycle in `graph`, each rendered as `a.js -> b.js -> a.js`
+ * so a failure message names the whole ring rather than one edge. Depth-first
+ * with an on-stack marker: a dep already on the stack closes a cycle, and the
+ * slice from its first appearance is that cycle.
+ */
+export function findImportCycles(graph) {
+ const cycles = new Set();
+ const stack = [];
+ const state = new Map(); // 1 = on stack, 2 = done
+ const visit = (node) => {
+ state.set(node, 1);
+ stack.push(node);
+ for (const dep of graph.get(node) || []) {
+ if (state.get(dep) === 1) {
+ cycles.add(stack.slice(stack.indexOf(dep)).concat(dep).join(' -> '));
+ } else if (!state.has(dep)) {
+ visit(dep);
+ }
+ }
+ stack.pop();
+ state.set(node, 2);
+ };
+ for (const node of graph.keys()) if (!state.has(node)) visit(node);
+ return [...cycles];
+}
diff --git a/server/services/agentImportCycles.test.js b/server/services/agentImportCycles.test.js
index 6ff9d04924..548457c1ec 100644
--- a/server/services/agentImportCycles.test.js
+++ b/server/services/agentImportCycles.test.js
@@ -16,10 +16,10 @@
*/
import { describe, it, expect } from 'vitest';
-import { readdirSync, readFileSync } from 'fs';
+import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join, relative, resolve } from 'path';
-import { staticImportSpecifiers } from '../lib/staticImportGraph.js';
+import { buildStaticImportGraph, findImportCycles } from '../lib/staticImportGraph.js';
const SERVICES_DIR = dirname(fileURLToPath(import.meta.url));
@@ -41,47 +41,17 @@ const CLUSTER = [
'agentOrchestrator.js',
];
-// The static-import scan itself lives in `server/lib/staticImportGraph.js` so
-// this guard and the sprites sharp-free guard share ONE parser — two copies is
-// how a structural guard rots (a fix to one silently under-reports in the
-// other). It matches static `import`/`export … from` and bare side-effect
-// imports only, never `await import()` (deferred to call time, so it can't
-// produce a load-time cycle) and never a specifier inside a comment.
-// Every non-test `.js` under SERVICES_DIR, keyed by its path relative to that
-// directory (`agentLifecycle.js`, `agentTuiSpawning/outputSpooler.js`). The
-// walk recurses: scanning only top-level files left a hole big enough to drive
-// the cycle back through, because a subdirectory module can import back up
-// (`agentTuiSpawning/outputSpooler.js` → `../cosAgentLifecycle.js` is a live example),
-// so a cycle routed through one subdirectory hop was invisible to this guard.
-function listServiceFiles(dir = SERVICES_DIR, prefix = '') {
- const out = [];
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
- const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
- if (entry.isDirectory()) out.push(...listServiceFiles(join(dir, entry.name), rel));
- else if (entry.name.endsWith('.js') && !entry.name.includes('.test.')) out.push(rel);
- }
- return out;
-}
-
-function buildStaticGraph() {
- const files = listServiceFiles();
- const known = new Set(files);
- const graph = new Map();
- for (const file of files) {
- const abs = join(SERVICES_DIR, file);
- const deps = new Set();
- for (const spec of staticImportSpecifiers(abs)) {
- if (!spec.startsWith('.')) continue;
- // Resolve relative to the importing file, then re-key against SERVICES_DIR
- // so `./x.js` from a subdirectory and `../x.js` from a sibling land on the
- // same node. Anything resolving outside the services dir is out of scope.
- const rel = relative(SERVICES_DIR, resolve(dirname(abs), spec));
- if (known.has(rel)) deps.add(rel);
- }
- graph.set(file, [...deps]);
- }
- return graph;
-}
+// The static-import scan, the services-directory graph build and the cycle walk
+// all live in `server/lib/staticImportGraph.js` so this guard and the
+// identity/digital-twin one (`twinImportCycles.test.js`) share ONE parser —
+// two copies is how a structural guard rots (a fix to one silently
+// under-reports in the other). It matches static `import`/`export … from` and
+// bare side-effect imports only, never `await import()` (deferred to call time,
+// so it can't produce a load-time cycle) and never a specifier inside a comment.
+// The walk recurses into subdirectories: a subdirectory module can import back
+// up (`agentTuiSpawning/outputSpooler.js` → `../cosAgentLifecycle.js` is a live
+// example), so a cycle routed through one subdirectory hop would otherwise be
+// invisible here.
// Does `file` reach `mod` with a DEFERRED import? The static graph deliberately
// ignores `import()` — correct for cycle detection, since a deferred import
@@ -150,32 +120,11 @@ const exportedNames = async (mod) => Object.keys(await MODULE_LOADERS[mod]());
// carries this, not just the one that happens to run first today.
const MODULE_LOAD_TIMEOUT_MS = 60_000;
-function findCycles(graph) {
- const cycles = new Set();
- const stack = [];
- const state = new Map(); // 1 = on stack, 2 = done
- const visit = (node) => {
- state.set(node, 1);
- stack.push(node);
- for (const dep of graph.get(node) || []) {
- if (state.get(dep) === 1) {
- cycles.add(stack.slice(stack.indexOf(dep)).concat(dep).join(' -> '));
- } else if (!state.has(dep)) {
- visit(dep);
- }
- }
- stack.pop();
- state.set(node, 2);
- };
- for (const node of graph.keys()) if (!state.has(node)) visit(node);
- return [...cycles];
-}
-
describe('agent lifecycle cluster — no static import cycles (#2837)', () => {
- const graph = buildStaticGraph();
+ const graph = buildStaticImportGraph(SERVICES_DIR);
it('has no static import cycle touching the agent-lifecycle cluster', () => {
- const offending = findCycles(graph).filter(cycle => CLUSTER.some(m => cycle.includes(m)));
+ const offending = findImportCycles(graph).filter(cycle => CLUSTER.some(m => cycle.includes(m)));
expect(offending, `static import cycle(s) reintroduced:\n${offending.join('\n')}`).toEqual([]);
});
@@ -197,7 +146,7 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {
const backEdges = sections.filter(file => (graph.get(file) || []).includes('agentPromptBuilder.js'));
expect(backEdges, `prompt sections must not import agentPromptBuilder.js: ${backEdges.join(', ')}`).toEqual([]);
- const sectionCycles = findCycles(graph).filter(cycle => sections.some(file => cycle.split(' -> ').includes(file)));
+ const sectionCycles = findImportCycles(graph).filter(cycle => sections.some(file => cycle.split(' -> ').includes(file)));
expect(sectionCycles, `prompt section cycle(s) introduced:\n${sectionCycles.join('\n')}`).toEqual([]);
});
@@ -481,7 +430,7 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {
// tools -> askService -> both of those leaves, each one-symbol forward closed
// a 7-module ring. Both now import the DECLARING module, which is the same
// rule the transition-caller guard above enforces for the agent cluster.
- const offending = findCycles(graph).filter(cycle => cycle.split(' -> ').includes('cos.js'));
+ const offending = findImportCycles(graph).filter(cycle => cycle.split(' -> ').includes('cos.js'));
expect(offending, `cos.js is back in a static import cycle:\n${offending.join('\n')}`).toEqual([]);
// Name the two back-edges directly, so a reintroduced one-symbol import of
diff --git a/server/services/digital-twin-avatar-bio.js b/server/services/digital-twin-avatar-bio.js
index ded44b9ad4..a761421a34 100644
--- a/server/services/digital-twin-avatar-bio.js
+++ b/server/services/digital-twin-avatar-bio.js
@@ -18,7 +18,7 @@ import { join } from 'path';
import { DIGITAL_TWIN_DIR, callProviderAI } from './digital-twin-helpers.js';
import { loadMeta } from './digital-twin-meta.js';
import { getTraits } from './digital-twin-analysis.js';
-import { getGoals } from './identity.js';
+import { getGoals } from './identity/goals.js';
import { getProviderById } from './providers.js';
import { estimateTokens, trimContextToBudget } from '../lib/contextBudget.js';
import { tryReadFile } from '../lib/fileUtils.js';
diff --git a/server/services/digital-twin-avatar-bio.test.js b/server/services/digital-twin-avatar-bio.test.js
index 5dd89ca94b..91cf1f4efd 100644
--- a/server/services/digital-twin-avatar-bio.test.js
+++ b/server/services/digital-twin-avatar-bio.test.js
@@ -91,13 +91,13 @@ vi.mock('./digital-twin-helpers.js', () => ({
vi.mock('./digital-twin-meta.js', () => ({ loadMeta: vi.fn() }));
vi.mock('./digital-twin-analysis.js', () => ({ getTraits: vi.fn() }));
-vi.mock('./identity.js', () => ({ getGoals: vi.fn() }));
+vi.mock('./identity/goals.js', () => ({ getGoals: vi.fn() }));
vi.mock('./providers.js', () => ({ getProviderById: vi.fn() }));
import { buildAvatarBio, polishAvatarBio } from './digital-twin-avatar-bio.js';
import { loadMeta } from './digital-twin-meta.js';
import { getTraits } from './digital-twin-analysis.js';
-import { getGoals } from './identity.js';
+import { getGoals } from './identity/goals.js';
import { getProviderById } from './providers.js';
import { callProviderAI } from './digital-twin-helpers.js';
diff --git a/server/services/digital-twin-export.js b/server/services/digital-twin-export.js
index 705e53cce5..7a6631afa5 100644
--- a/server/services/digital-twin-export.js
+++ b/server/services/digital-twin-export.js
@@ -4,7 +4,9 @@ import { join } from 'path';
import { getStories } from './autobiography.js';
import { getGenomeSummary } from './genome.js';
import { getTasteProfile } from './taste-questionnaire.js';
-import { getChronotype, getLongevity, getGoals } from './identity.js';
+import { getChronotype } from './identity/chronotype.js';
+import { getLongevity } from './identity/longevity.js';
+import { getGoals } from './identity/goals.js';
import { getAllAccounts as getAllSocialAccounts } from './socialAccounts.js';
import { DIGITAL_TWIN_DIR, now } from './digital-twin-helpers.js';
import { loadMeta } from './digital-twin-meta.js';
diff --git a/server/services/digital-twin.test.js b/server/services/digital-twin.test.js
index f80d56b04a..2882633117 100644
--- a/server/services/digital-twin.test.js
+++ b/server/services/digital-twin.test.js
@@ -64,9 +64,15 @@ vi.mock('./taste-questionnaire.js', () => ({
getTasteProfile: vi.fn(() => ({ sections: [] }))
}));
-vi.mock('./identity.js', () => ({
- getChronotype: vi.fn(() => null),
- getLongevity: vi.fn(() => null),
+vi.mock('./identity/chronotype.js', () => ({
+ getChronotype: vi.fn(() => null)
+}));
+
+vi.mock('./identity/longevity.js', () => ({
+ getLongevity: vi.fn(() => null)
+}));
+
+vi.mock('./identity/goals.js', () => ({
getGoals: vi.fn(() => ({ goals: [] }))
}));
diff --git a/server/services/taste-questionnaire.js b/server/services/taste-questionnaire.js
index 1931d909bb..b617e97f1c 100644
--- a/server/services/taste-questionnaire.js
+++ b/server/services/taste-questionnaire.js
@@ -18,7 +18,7 @@ import { atomicWrite, ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.j
import { resolveTextProvider, callProviderAISimple } from './aiProvider.js';
import { ServerError } from '../lib/errorHandler.js';
import { buildPrompt } from './promptService.js';
-import { digitalTwinEvents } from './digital-twin.js';
+import { digitalTwinEvents } from './digital-twin-meta.js';
const DIGITAL_TWIN_DIR = PATHS.digitalTwin;
const TASTE_PROFILE_FILE = join(DIGITAL_TWIN_DIR, 'taste-profile.json');
diff --git a/server/services/taste-questionnaire.test.js b/server/services/taste-questionnaire.test.js
index 48ee0b0d9a..b80681474c 100644
--- a/server/services/taste-questionnaire.test.js
+++ b/server/services/taste-questionnaire.test.js
@@ -12,7 +12,7 @@ vi.mock('../lib/fileUtils.js', async () => {
});
// Avoid digitalTwinEvents side effects during answer submit
-vi.mock('./digital-twin.js', () => ({
+vi.mock('./digital-twin-meta.js', () => ({
digitalTwinEvents: { emit: vi.fn() },
}));
diff --git a/server/services/twinImportCycles.test.js b/server/services/twinImportCycles.test.js
new file mode 100644
index 0000000000..0f575cd9b6
--- /dev/null
+++ b/server/services/twinImportCycles.test.js
@@ -0,0 +1,71 @@
+/**
+ * Regression guard for the identity / digital-twin barrel back-edges (#5687).
+ *
+ * `digital-twin.js` and `identity.js` are pure re-export barrels over their
+ * `digital-twin-*.js` / `identity/*.js` leaves. Three leaves used to import a
+ * symbol back THROUGH the barrel instead of from the module that declares it
+ * (`digitalTwinEvents`, `getChronotype`/`getLongevity`/`getGoals`), and because
+ * each barrel transitively reaches those same leaves, every one-symbol forward
+ * closed a static ESM ring. In a static cycle whichever member evaluates first
+ * sees `undefined` for the others' bindings, so a top-level `const` derived
+ * from an imported value anywhere in the ring becomes a boot-time TDZ crash —
+ * and no behavior test notices until a boot-order change surfaces it.
+ *
+ * The rule is the one the agent cluster already documents: a barrel is a public
+ * entry point for callers OUTSIDE the cluster (routes, tools); members of the
+ * cluster must name the declaring module. Static edges only — `await import()`
+ * is deferred to call time and cannot produce a load-time cycle.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { fileURLToPath } from 'url';
+import { dirname } from 'path';
+import { buildStaticImportGraph, findImportCycles } from '../lib/staticImportGraph.js';
+
+const SERVICES_DIR = dirname(fileURLToPath(import.meta.url));
+
+// The two barrels plus the three leaves that used to reach back through them. A
+// cycle anywhere in `server/services` is reported by the walk, but only one
+// TOUCHING this cluster fails here — unrelated pre-existing cycles (meatspacePost,
+// the pipeline autopilot ring) have their own issues.
+const CLUSTER = [
+ 'digital-twin.js',
+ 'identity.js',
+ 'taste-questionnaire.js',
+ 'digital-twin-export.js',
+ 'digital-twin-avatar-bio.js',
+];
+
+// The declaring module each leaf must name, keyed by the barrel it must not.
+const BACK_EDGES = [
+ { leaf: 'taste-questionnaire.js', barrel: 'digital-twin.js', declaring: ['digital-twin-meta.js'], symbols: 'digitalTwinEvents' },
+ { leaf: 'digital-twin-export.js', barrel: 'identity.js', declaring: ['identity/chronotype.js', 'identity/longevity.js', 'identity/goals.js'], symbols: 'getChronotype/getLongevity/getGoals' },
+ { leaf: 'digital-twin-avatar-bio.js', barrel: 'identity.js', declaring: ['identity/goals.js'], symbols: 'getGoals' },
+];
+
+describe('identity / digital-twin cluster — no static import cycles (#5687)', () => {
+ const graph = buildStaticImportGraph(SERVICES_DIR);
+
+ it('sees the whole services graph', () => {
+ // A resolver gap would make every negative assertion below pass vacuously.
+ expect(graph.size, 'services graph looks empty — did the scan root move?').toBeGreaterThan(100);
+ for (const module of CLUSTER) expect([...graph.keys()], `${module} is missing from the graph`).toContain(module);
+ });
+
+ it('has no static import cycle touching the identity / digital-twin cluster', () => {
+ const offending = findImportCycles(graph).filter(cycle =>
+ CLUSTER.some(module => cycle.split(' -> ').includes(module)));
+ expect(offending, `static import cycle(s) reintroduced:\n${offending.join('\n')}`).toEqual([]);
+ });
+
+ it('keeps each cluster leaf naming the module that declares the symbol, never the barrel', () => {
+ // Named directly so a reintroduced one-symbol import of a barrel fails with
+ // the reason rather than as an opaque ring — and so the rule still holds if
+ // some future edge happens not to close a cycle today.
+ for (const { leaf, barrel, declaring, symbols } of BACK_EDGES) {
+ const deps = graph.get(leaf) || [];
+ expect(deps, `${leaf} must import ${symbols} from ${declaring.join(', ')} — not the ${barrel} barrel`).not.toContain(barrel);
+ for (const module of declaring) expect(deps, `${leaf} must import from ${module}`).toContain(module);
+ }
+ });
+});