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: spell staticImportGraph keys with / on every platform (#5909)

[._.]/ Adam Eivy68ce811a7b35
diff --git a/server/lib/README.md b/server/lib/README.md
index 9b9c344d77..bec4525102 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -483,7 +483,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. 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`; `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). |
| `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 d9fbe5cc48..67c3d3b6d3 100644
--- a/server/lib/staticImportGraph.js
+++ b/server/lib/staticImportGraph.js
@@ -86,6 +86,23 @@ export function specifierMatchesPackage(specifier, pkg) {
return specifier === pkg || specifier.startsWith(`${pkg}/`);
}
+/**
+ * A relative path as a graph key: always `/`-separated, whatever the platform.
+ *
+ * The keys are minted by two different mechanisms — `listModuleFiles` builds
+ * them by concatenating directory entry names, while `buildStaticImportGraph`
+ * derives them from a resolved absolute path via `path.relative`. On POSIX both
+ * yield `identity/goals.js`; on Windows `path.relative` yields
+ * `identity\\goals.js`, so every edge into a subdirectory module missed the
+ * `known` lookup and was silently dropped. That does not fail loudly — it makes
+ * an acyclicity guard pass VACUOUSLY on Windows while a "leaf must import the
+ * declaring module" assertion fails. Both mints go through here so they cannot
+ * drift again.
+ */
+export function toModuleKey(relPath) {
+ return relPath.split(sep).join('/');
+}
+
/**
* Every non-test `.js` file under `rootDir`, keyed by its path relative to that
* directory (`identity.js`, `identity/goals.js`). The walk recurses: scanning
@@ -95,7 +112,7 @@ export function specifierMatchesPackage(specifier, pkg) {
function listModuleFiles(rootDir, dir = rootDir, prefix = '') {
const out = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
- const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ const rel = toModuleKey(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);
}
@@ -119,7 +136,7 @@ export function buildStaticImportGraph(rootDir) {
const deps = new Set();
for (const spec of staticImportSpecifiers(abs)) {
if (!spec.startsWith('.')) continue;
- const rel = relative(rootDir, resolve(dirname(abs), spec)).split(sep).join('/');
+ const rel = toModuleKey(relative(rootDir, resolve(dirname(abs), spec)));
if (known.has(rel)) deps.add(rel);
}
graph.set(file, [...deps]);
diff --git a/server/lib/staticImportGraph.test.js b/server/lib/staticImportGraph.test.js
new file mode 100644
index 0000000000..e742380d41
--- /dev/null
+++ b/server/lib/staticImportGraph.test.js
@@ -0,0 +1,65 @@
+/**
+ * Contract for the graph-key mint in `staticImportGraph.js`.
+ *
+ * The keys are built two different ways — `listModuleFiles` concatenates
+ * directory entry names, `buildStaticImportGraph` derives them from a resolved
+ * absolute path via `path.relative` — and they are compared with `Set.has`. On
+ * POSIX both spell a subdirectory module `identity/goals.js`, so a mismatch is
+ * invisible there; on Windows `path.relative` spells it `identity\goals.js`,
+ * every edge INTO a subdirectory module fails the lookup, and the graph loses
+ * them silently. That is not a loud failure: an acyclicity guard built on the
+ * graph then passes VACUOUSLY (a ring through a subdirectory module is
+ * unreachable), while a "this leaf must import the declaring module" assertion
+ * fails for a reason that has nothing to do with the leaf (#5909).
+ *
+ * The subdirectory-edge assertions below are the ones that would have caught
+ * it. They pass on POSIX either way — the defect is Windows-only — so CI's
+ * Windows job is where they earn their keep.
+ */
+import { describe, it, expect } from 'vitest';
+import { fileURLToPath } from 'url';
+import { dirname, join, sep } from 'path';
+import { buildStaticImportGraph, toModuleKey } from './staticImportGraph.js';
+
+const SERVICES_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'services');
+
+describe('toModuleKey', () => {
+ it('spells a native-separator relative path with forward slashes', () => {
+ expect(toModuleKey(['identity', 'goals.js'].join(sep))).toBe('identity/goals.js');
+ expect(toModuleKey(['a', 'b', 'c.js'].join(sep))).toBe('a/b/c.js');
+ });
+
+ it('leaves a top-level file and an already-posix path alone', () => {
+ expect(toModuleKey('identity.js')).toBe('identity.js');
+ expect(toModuleKey('identity/goals.js')).toBe('identity/goals.js');
+ });
+});
+
+describe('buildStaticImportGraph — subdirectory modules are reachable (#5909)', () => {
+ const graph = buildStaticImportGraph(SERVICES_DIR);
+ const keys = [...graph.keys()];
+ const edges = [...graph.values()].flat();
+
+ it('sees the whole services graph', () => {
+ // Guards every assertion below from passing vacuously on an empty scan.
+ expect(graph.size, 'services graph looks empty — did the scan root move?').toBeGreaterThan(100);
+ });
+
+ it('keys every module with forward slashes, including nested ones', () => {
+ expect(keys.filter(key => key.includes('/')).length,
+ 'no nested module keys — the recursive walk stopped at the top level').toBeGreaterThan(0);
+ expect(keys.filter(key => key.includes('\\')),
+ 'a graph key kept a native path separator').toEqual([]);
+ });
+
+ it('records edges that TARGET a nested module, not just edges between top-level ones', () => {
+ // The Windows defect: `known` holds `identity/goals.js` while the resolver
+ // produces `identity\goals.js`, so this list comes back empty and every
+ // subdirectory dependency vanishes from the graph.
+ const nested = edges.filter(dep => dep.includes('/'));
+ expect(nested.length,
+ 'no edge targets a nested module — the resolver and the key mint disagree').toBeGreaterThan(0);
+ expect(edges.filter(dep => dep.includes('\\')),
+ 'an edge kept a native path separator').toEqual([]);
+ });
+});