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

refactor: import deriveUiPort from the declaring service and assert services/lib never import routes (#5721)

[._.]/ Adam Eivyd72864f91266
diff --git a/server/lib/README.md b/server/lib/README.md
index c7d1d5e395..45cf53567b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -486,7 +486,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` (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). |
+| `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`); `listModuleFiles(rootDir)` → every non-test `.js` under a directory, keyed by `/`-separated relative path (the same walk the graph builder uses, shared so a layering guard cannot drift from it); `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 02a7963890..35353526a2 100644
--- a/server/lib/staticImportGraph.js
+++ b/server/lib/staticImportGraph.js
@@ -109,7 +109,7 @@ export function toModuleKey(relPath) {
* 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 = '') {
+export function listModuleFiles(rootDir, dir = rootDir, prefix = '') {
const out = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const rel = toModuleKey(prefix ? `${prefix}/${entry.name}` : entry.name);
diff --git a/server/moduleLayering.test.js b/server/moduleLayering.test.js
new file mode 100644
index 0000000000..0a7f2bf0eb
--- /dev/null
+++ b/server/moduleLayering.test.js
@@ -0,0 +1,93 @@
+/**
+ * Layer-direction guard: nothing under `server/services/` or `server/lib/`
+ * statically imports `server/routes/` (#5721).
+ *
+ * Root `AGENTS.md` puts Express handlers in `server/routes/`, domain
+ * orchestration in `server/services/`, and pure helpers in `server/lib/` —
+ * routes consume the lower layers, never the other way round. `appPortConfig.js`
+ * had drifted the other way, importing `deriveUiPort` from
+ * `routes/apps/shared.js`, which only re-exports it from
+ * `services/appListEnrichment.js`. The cost was not a broken behavior — the
+ * symbol was correct — so no behavior test could see it: loading a port-config
+ * service simply dragged in `asyncHandler`, a route middleware factory, and
+ * `services/apps.js`. That is precisely the class of regression a structural
+ * assertion catches and a functional one cannot, and the inversion was a single
+ * line, so the rule is enforceable as a hard zero rather than a baseline.
+ *
+ * Static edges only. `await import('../routes/x.js')` is deferred to call time
+ * and does not pull the route layer into a service's initialization graph, so
+ * it is out of scope here (as it is for the cycle ratchets).
+ */
+
+import { describe, it, expect } from 'vitest';
+import { fileURLToPath } from 'url';
+import { dirname, join, resolve, sep } from 'path';
+import { listModuleFiles, staticImportSpecifiers } from './lib/staticImportGraph.js';
+
+const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
+const ROUTES_DIR = join(SERVER_DIR, 'routes');
+const SCANNED_DIRS = ['services', 'lib'];
+
+// True when `target` is `dir` itself or lives beneath it. The `sep` suffix is
+// what keeps a sibling directory whose name merely starts the same
+// (`routes-legacy/`) from reading as a violation.
+const isUnder = (target, dir) => target === dir || target.startsWith(dir + sep);
+
+/**
+ * The specifiers in `specifiers` that resolve into `server/routes/` when read
+ * from `fileAbs`. Resolution — not string matching — is the whole point: the
+ * vendored toolkit at `lib/aiToolkit/index.js` legitimately imports
+ * `./routes/providers.js`, its OWN self-contained route factories, and a
+ * `includes('routes/')` test would flag it. Bare package specifiers can never
+ * name a repo path, so they are dropped before resolving.
+ */
+const routeImportsOf = (fileAbs, specifiers) => specifiers
+ .filter(spec => spec.startsWith('.'))
+ .filter(spec => isUnder(resolve(dirname(fileAbs), spec), ROUTES_DIR));
+
+describe('server module layering — services and lib never import routes (#5721)', () => {
+ const modules = SCANNED_DIRS.flatMap((dir) => {
+ const root = join(SERVER_DIR, dir);
+ return listModuleFiles(root).map(rel => ({ label: `${dir}/${rel}`, abs: join(root, rel) }));
+ });
+
+ it('sees both module trees', () => {
+ // The assertion below is a negative, so a scan that found nothing would read
+ // as a clean sweep. Pin the scale, and pin it per directory so a moved root
+ // cannot be masked by the other tree's count.
+ for (const dir of SCANNED_DIRS) {
+ const count = modules.filter(entry => entry.label.startsWith(`${dir}/`)).length;
+ expect(count, `server/${dir} scan looks empty — did the root move?`).toBeGreaterThan(100);
+ }
+ });
+
+ it('flags an import that resolves into routes, and only that', () => {
+ // Bypass probe for the detector itself: without it, a `routeImportsOf` that
+ // always returned `[]` would satisfy the real assertion forever.
+ const service = join(SERVER_DIR, 'services', 'appPortConfig.js');
+ expect(routeImportsOf(service, ['../routes/apps/shared.js'])).toEqual(['../routes/apps/shared.js']);
+ expect(routeImportsOf(join(SERVER_DIR, 'services', 'pipeline', 'x.js'), ['../../routes/apps.js']))
+ .toEqual(['../../routes/apps.js']);
+
+ // And the converse — the legitimate shapes must NOT flag, or the guard would
+ // be satisfied by a detector that flags everything.
+ expect(routeImportsOf(service, ['./appListEnrichment.js', 'zod', '../lib/ports.js'])).toEqual([]);
+ // The vendored toolkit's own `routes/` subtree is inside lib, not the
+ // server's route layer.
+ expect(routeImportsOf(join(SERVER_DIR, 'lib', 'aiToolkit', 'index.js'), ['./routes/providers.js']))
+ .toEqual([]);
+ });
+
+ it('has no service or lib module importing the route layer', () => {
+ const violations = modules.flatMap(({ label, abs }) =>
+ routeImportsOf(abs, staticImportSpecifiers(abs)).map(spec => `${label} → ${spec}`));
+
+ expect(violations, [
+ 'a module under server/services or server/lib statically imports server/routes:',
+ ...violations,
+ '',
+ 'Routes consume services and lib, never the reverse. Import the module that',
+ 'DECLARES the symbol — a route barrel that re-exports it is not a source.',
+ ].join('\n')).toEqual([]);
+ });
+});
diff --git a/server/services/appPortConfig.js b/server/services/appPortConfig.js
index 4439eb0c0d..ca1a23b35f 100644
--- a/server/services/appPortConfig.js
+++ b/server/services/appPortConfig.js
@@ -19,7 +19,7 @@
*/
import { parseEcosystemFromPath, writeEcosystemPortEdits } from './streamingDetect.js';
-import { deriveUiPort } from '../routes/apps/shared.js';
+import { deriveUiPort } from './appListEnrichment.js';
const PORT_KEYS = ['apiPort', 'uiPort', 'devUiPort'];
const LABEL_BY_KEY = { apiPort: 'api', uiPort: 'ui', devUiPort: 'devUi' };