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

perf: move blocking sync I/O off request and run-completion hot paths (#1828)

[._.]/ Adam Eivy2fe8944492a6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ce6c3cbd70..3575622342 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,6 +17,7 @@
## Fixed
+- **Blocking sync I/O removed from request/completion hot paths** — several syscalls ran synchronously on paths that serve live SSE/socket traffic, freezing the event loop for their duration. `checkForTaskCommit` (`agentRunTracking.js`) ran a `spawnSync('git', ['log', …])` on the completion path of every failed CoS run (100ms–2s on a large repo); it now uses the async, hard-timeout `bufferedSpawn`. `buildId.js` `statSync`'d `client/dist/index.html` on every SPA navigation; it now serves a cached snapshot and refreshes the mtime/hash off the hot path (deduped + throttled, primed synchronously at boot). The avatar (`routes/avatar.js`) and attachment (`routes/attachments.js`) routes swapped `existsSync`/`statSync` for async `fs.access`/`fs.stat` (via a new canonical `pathExists` helper in `fileUtils.js`), and uploads now call the idempotent `ensureDir` directly. Separately, the tombstone-prune paths for authors/tracks/creative-director projects (DB + file backends) wrapped their per-record `deleteSyncBaseHash` loops in `withBaseHashFlushBatch`, collapsing N `sync_base_hashes.json` rewrites into one. (#1828)
- **External API model/metadata fetches now time out instead of stalling callers indefinitely** — `_fetchGeminiModels` (Gemini model refresh in `aiToolkit/providers.js`) made a `fetch` with no `AbortSignal`, unlike every other provider model-fetch in that file, so a hung Google endpoint could block a model-refresh request forever; it now uses the same `AbortSignal.timeout(8000)`. `fetchCivitaiModel` and `searchCivitaiLoras` (`server/lib/civitai.js`) likewise passed no signal, so a Civitai hang stalled LoRA metadata/search callers; both now default to `AbortSignal.timeout(10000)` and accept a caller-provided `signal` override. (#1827)
- **Unguarded async `child_process` handlers can no longer crash the Node process** — several `close`/`error` event handlers were `async` and `await`ed disk writes / completion bookkeeping with no `try/catch`, so a single failed write (e.g. a full disk) or a throwing completion hook surfaced as an unhandled rejection and took down the whole server. Wrapped the at-risk handler bodies in `server/services/runner.js` (both `close` and `error`), `videoTimeline/local.js`, `agentCliSpawning.js` (both `close` and `error`), and both the CLI `close` handler and the detached `processStream().catch` in `aiToolkit/runner.js`. The recovery paths now still settle callers waiting on `onComplete` with failure metadata (so a finalization failure surfaces as a failed run instead of hanging forever), with the completion hook isolated from `onComplete` so a throwing `onRunFailed` can't block the caller from settling. Also replaced the two silent recovery-critical `.catch(() => {})` swallows in `cos-runner/index.js` with logged failures so a lost completion-metadata write is visible instead of silently dropping a finished task. (#1825)
- Catalog "Appears in" panel no longer renders dangling chips that deep-link to soft-deleted universe/series/creative-director targets — the detail page filters refs to live targets only (the orphan stays recoverable via the "Orphaned" album). Also fixed a stale resolver bug where soft-deleted Creative Director projects (#1564) wrongly resolved as live, and extended orphan-bucket detection so a deleted CD project's ex-cast surfaces as orphaned rather than unlinked. (#1812)
diff --git a/server/lib/README.md b/server/lib/README.md
index 3dee569a0e..6c1964e388 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -108,7 +108,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. **Type-index `config` slot** holds cross-record state (see the `TypeIndexConfig` typedef + header convention): `{ runs?: [], featureFlags?: {}, lockPolicies?: {} }` — `runs` is the shipped slot (universeBuilder's capped history log), the other two are reserved names; consumers may add their own keys but should reuse a reserved name when it fits and document the shape next to the consumer. `saveTypeIndex({ config })` shallow-merges `config` one level deep (a patched `runs` replaces the whole array), so a read-modify-write of a slot must load → mutate a copy → write inside `queueTypeIndexWrite(fn)`. |
| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
| `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. |
| `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
diff --git a/server/lib/buildId.js b/server/lib/buildId.js
index a9a8d6b28f..66e9daa014 100644
--- a/server/lib/buildId.js
+++ b/server/lib/buildId.js
@@ -16,6 +16,7 @@
*/
import { existsSync, readFileSync, statSync } from 'fs';
+import { readFile, stat } from 'fs/promises';
import { createHash } from 'crypto';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
@@ -28,14 +29,27 @@ const INDEX_PATH = join(__dirname, '..', '..', 'client', 'dist', 'index.html');
// cache would keep serving the old stamped HTML (and reporting the old build
// id over the socket) after `npm run build`, so the browser would request
// chunk filenames that no longer exist on disk → 404 → black page.
+//
+// The cache is refreshed OFF the request hot path: the synchronous getters
+// return the cached snapshot immediately and kick a non-blocking `fs.stat` +
+// `fs.readFile` refresh. The previous implementation `statSync`'d on every SPA
+// navigation, blocking the event loop for that I/O on each request. The first
+// call primes the cache synchronously (server boot) so the very first response
+// is correct; thereafter a rebuild is picked up on the next request after the
+// async refresh settles (sub-millisecond on a local disk). Refreshes are
+// deduped (one in flight) and throttled so a request burst can't fan out a
+// `stat` per request.
let cached = null;
+let refreshing = null; // in-flight refresh promise, or null
+let lastRefreshAt = 0; // throttle clock (ms)
-function compute() {
- if (!existsSync(INDEX_PATH)) {
- return { id: 'dev', html: null, mtimeMs: 0 };
- }
- const mtimeMs = statSync(INDEX_PATH).mtimeMs;
- const html = readFileSync(INDEX_PATH, 'utf8');
+const REFRESH_THROTTLE_MS = 1000;
+
+const DEV_SNAPSHOT = { id: 'dev', html: null, mtimeMs: 0 };
+
+// Pure: hash + stamp the meta tag into the html. Shared by the sync prime and
+// the async refresh so the two paths can't drift.
+function deriveFromHtml(html, mtimeMs) {
const id = createHash('sha256').update(html).digest('hex').slice(0, 12);
// Inject the meta tag once. Idempotent: replace if already present
// (defensive — Vite rewrites the whole file so the marker shouldn't survive
@@ -48,13 +62,47 @@ function compute() {
return { id, html: stamped, mtimeMs };
}
-function ensureFresh() {
+// Synchronous prime — used once on the first getter call (server boot) so the
+// cache is never empty when a value is read. One sync stat+read here is fine; it
+// happens at most once, not per request.
+function primeSync() {
if (!existsSync(INDEX_PATH)) {
- if (!cached || cached.id !== 'dev') cached = { id: 'dev', html: null, mtimeMs: 0 };
+ cached = DEV_SNAPSHOT;
return cached;
}
const mtimeMs = statSync(INDEX_PATH).mtimeMs;
- if (!cached || cached.mtimeMs !== mtimeMs) cached = compute();
+ cached = deriveFromHtml(readFileSync(INDEX_PATH, 'utf8'), mtimeMs);
+ return cached;
+}
+
+// Async refresh — recompute only when the mtime moved. Runs off the request
+// path so its I/O never blocks the event loop for the current response.
+async function refresh() {
+ const s = await stat(INDEX_PATH).catch(() => null);
+ if (!s) {
+ if (!cached || cached.id !== 'dev') cached = DEV_SNAPSHOT;
+ return cached;
+ }
+ if (!cached || cached.mtimeMs !== s.mtimeMs) {
+ const html = await readFile(INDEX_PATH, 'utf8').catch(() => null);
+ if (html != null) cached = deriveFromHtml(html, s.mtimeMs);
+ }
+ return cached;
+}
+
+// Kick a deduped, throttled background refresh. Non-blocking — the caller reads
+// the (possibly one-request-stale) cache while this settles.
+function scheduleRefresh() {
+ if (refreshing) return;
+ const now = Date.now();
+ if (now - lastRefreshAt < REFRESH_THROTTLE_MS) return;
+ lastRefreshAt = now;
+ refreshing = refresh().finally(() => { refreshing = null; });
+}
+
+function ensureFresh() {
+ if (!cached) return primeSync();
+ scheduleRefresh();
return cached;
}
@@ -65,3 +113,18 @@ export function getBuildId() {
export function getStampedIndexHtml() {
return ensureFresh().html;
}
+
+/**
+ * Force a refresh and resolve the resulting snapshot. Bypasses the throttle so
+ * callers that need the freshest value right now (boot warm-up, tests) can
+ * `await` it. The hot-path getters never call this — they stay non-blocking via
+ * `scheduleRefresh`.
+ *
+ * @returns {Promise<{id: string, html: string|null, mtimeMs: number}>}
+ */
+export async function refreshBuildId() {
+ if (!cached) primeSync();
+ lastRefreshAt = Date.now();
+ refreshing = refresh().finally(() => { refreshing = null; });
+ return refreshing;
+}
diff --git a/server/lib/buildId.test.js b/server/lib/buildId.test.js
index c9ca00712e..02e2879caa 100644
--- a/server/lib/buildId.test.js
+++ b/server/lib/buildId.test.js
@@ -47,7 +47,7 @@ describe('buildId — cache invalidation', () => {
utimesSync(INDEX_PATH, t0, t0);
const mod = await import('./buildId.js');
- const idA = mod.getBuildId();
+ const idA = mod.getBuildId(); // primes the cache synchronously
const htmlA = mod.getStampedIndexHtml();
expect(idA).not.toBe('dev');
expect(htmlA).toContain(`<meta name="portos-build-id" content="${idA}">`);
@@ -58,6 +58,10 @@ describe('buildId — cache invalidation', () => {
const t1 = new Date('2026-02-01T00:00:00Z');
utimesSync(INDEX_PATH, t1, t1);
+ // The refresh is async + off the hot path, so settle it explicitly (this
+ // bypasses the throttle the synchronous getters honor).
+ await mod.refreshBuildId();
+
const idB = mod.getBuildId();
const htmlB = mod.getStampedIndexHtml();
expect(idB).not.toBe(idA);
@@ -65,6 +69,28 @@ describe('buildId — cache invalidation', () => {
expect(htmlB).toContain('body>B');
});
+ it('getters serve the cached snapshot until the async refresh settles (no hot-path re-stat)', async () => {
+ writeFileSync(INDEX_PATH, '<html><head></head><body>old</body></html>');
+ const t0 = new Date('2026-05-01T00:00:00Z');
+ utimesSync(INDEX_PATH, t0, t0);
+
+ const mod = await import('./buildId.js');
+ const idOld = mod.getBuildId(); // primes
+ expect(idOld).not.toBe('dev');
+
+ // Rebuild on disk. The synchronous getter must still return the cached
+ // (stale) value within the throttle window — it does not re-stat per call.
+ writeFileSync(INDEX_PATH, '<html><head></head><body>new</body></html>');
+ const t1 = new Date('2026-05-02T00:00:00Z');
+ utimesSync(INDEX_PATH, t1, t1);
+ expect(mod.getBuildId()).toBe(idOld);
+
+ // Once the explicit refresh settles, the next read reflects the rebuild.
+ const snap = await mod.refreshBuildId();
+ expect(snap.id).not.toBe(idOld);
+ expect(mod.getStampedIndexHtml()).toContain('body>new');
+ });
+
it('returns the same id from cache when mtime is unchanged', async () => {
writeFileSync(INDEX_PATH, '<html><head></head><body>same</body></html>');
const t0 = new Date('2026-03-01T00:00:00Z');
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index de4764f6e9..cff61a5ba1 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -4,7 +4,7 @@
* Shared utilities for file operations used across services.
*/
-import { appendFile, mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';
+import { access, appendFile, mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';
import { existsSync, statSync, createReadStream } from 'fs';
import { execFile } from 'child_process';
import { promisify } from 'util';
@@ -133,6 +133,22 @@ export async function ensureDir(dir) {
});
}
+/**
+ * Async existence check — the non-blocking replacement for `existsSync` on
+ * request/hot paths. Resolves true iff `path` is accessible, false otherwise.
+ * Never throws (a missing path, permission error, etc. all resolve false), so
+ * it drops in wherever `existsSync` guarded a request handler.
+ *
+ * @param {string} path - File or directory path to test.
+ * @returns {Promise<boolean>}
+ *
+ * @example
+ * if (!(await pathExists(filepath))) throw new ServerError('Not found', { status: 404 });
+ */
+export async function pathExists(path) {
+ return access(path).then(() => true, () => false);
+}
+
/**
* Ensure multiple directories exist.
*
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index 31ec416254..0609a99468 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -16,6 +16,7 @@ vi.mock('fs/promises', async (importOriginal) => {
import {
assertSafeFilename,
ensureDir,
+ pathExists,
expandHome,
isValidJSON,
listDirectoryByExtension,
@@ -384,6 +385,27 @@ describe('fileUtils', () => {
});
});
+ describe('pathExists', () => {
+ const tmpRoot = join(tmpdir(), `fileutils-pathexists-${process.pid}-${Date.now()}`);
+
+ beforeEach(() => mkdir(tmpRoot, { recursive: true }));
+ afterEach(() => rm(tmpRoot, { recursive: true, force: true }));
+
+ it('resolves true for an existing file', async () => {
+ const f = join(tmpRoot, 'present.txt');
+ await writeFile(f, 'hi');
+ expect(await pathExists(f)).toBe(true);
+ });
+
+ it('resolves true for an existing directory', async () => {
+ expect(await pathExists(tmpRoot)).toBe(true);
+ });
+
+ it('resolves false for a missing path without throwing', async () => {
+ expect(await pathExists(join(tmpRoot, 'nope.txt'))).toBe(false);
+ });
+ });
+
describe('formatDuration', () => {
it('should return "0m" for zero or falsy values', () => {
expect(formatDuration(0)).toBe('0m');
diff --git a/server/routes/attachments.js b/server/routes/attachments.js
index 4adaeb9647..2a749128d3 100644
--- a/server/routes/attachments.js
+++ b/server/routes/attachments.js
@@ -5,12 +5,11 @@
import { Router } from 'express';
import { writeFile, unlink, readdir, stat } from 'fs/promises';
-import { existsSync } from 'fs';
import { join, resolve } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
- ensureDir, PATHS, RISKY_MIME_TYPES,
+ ensureDir, pathExists, PATHS, RISKY_MIME_TYPES,
sanitizeFilename, getFileExtension, getMimeType, ATTACHMENT_ALLOWED_EXTENSIONS,
} from '../lib/fileUtils.js';
@@ -54,10 +53,9 @@ router.post('/', asyncHandler(async (req, res) => {
throw new ServerError(`File exceeds maximum size of ${MAX_FILE_SIZE / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });
}
- // Ensure attachments directory exists
- if (!existsSync(ATTACHMENTS_DIR)) {
- await ensureDir(ATTACHMENTS_DIR);
- }
+ // Ensure attachments directory exists (ensureDir is idempotent — mkdir
+ // recursive — so no existence pre-check is needed on this upload path).
+ await ensureDir(ATTACHMENTS_DIR);
const id = uuidv4();
const safeName = sanitizeFilename(filename);
@@ -100,7 +98,7 @@ router.get('/:filename', asyncHandler(async (req, res) => {
throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });
}
- if (!existsSync(filepath)) {
+ if (!(await pathExists(filepath))) {
throw new ServerError('Attachment not found', { status: 404, code: 'NOT_FOUND' });
}
@@ -126,7 +124,7 @@ router.delete('/:filename', asyncHandler(async (req, res) => {
throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });
}
- if (!existsSync(filepath)) {
+ if (!(await pathExists(filepath))) {
throw new ServerError('Attachment not found', { status: 404, code: 'NOT_FOUND' });
}
@@ -139,7 +137,7 @@ router.delete('/:filename', asyncHandler(async (req, res) => {
// GET /api/attachments - List all attachments (for debugging)
router.get('/', asyncHandler(async (req, res) => {
- if (!existsSync(ATTACHMENTS_DIR)) {
+ if (!(await pathExists(ATTACHMENTS_DIR))) {
return res.json({ attachments: [] });
}
diff --git a/server/routes/avatar.js b/server/routes/avatar.js
index db58605578..3884d103a0 100644
--- a/server/routes/avatar.js
+++ b/server/routes/avatar.js
@@ -1,7 +1,8 @@
import { Router } from 'express';
-import { existsSync, statSync, createReadStream } from 'fs';
+import { createReadStream } from 'fs';
+import { stat } from 'fs/promises';
import { join } from 'path';
-import { PATHS } from '../lib/fileUtils.js';
+import { PATHS, pathExists } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
const router = Router();
@@ -18,22 +19,12 @@ function resolveVariant(variant) {
return join(AVATAR_DIR, `${variant}.glb`);
}
-// Non-throwing stat wrapper used by the HEAD handler — file may be removed between
-// existsSync() and statSync() (TOCTOU), which would otherwise crash the process.
-function safeStat(p) {
- try {
- return statSync(p);
- } catch {
- return null;
- }
-}
-
-router.head('/model.glb', (req, res) => {
+router.head('/model.glb', async (req, res) => {
const path = resolveVariant(req.query.variant);
- if (!path || !existsSync(path)) {
- return res.status(404).end();
- }
- const s = safeStat(path);
+ if (!path) return res.status(404).end();
+ // Single async stat off the event loop, doubling as the existence check —
+ // a missing/removed file (TOCTOU) just resolves null → 404.
+ const s = await stat(path).catch(() => null);
if (!s) return res.status(404).end();
res.set('Content-Type', 'model/gltf-binary');
res.set('Content-Length', String(s.size));
@@ -41,9 +32,9 @@ router.head('/model.glb', (req, res) => {
return res.status(200).end();
});
-router.get('/model.glb', (req, res) => {
+router.get('/model.glb', async (req, res) => {
const path = resolveVariant(req.query.variant);
- if (!path || !existsSync(path)) {
+ if (!path || !(await pathExists(path))) {
throw new ServerError('No avatar model configured. Drop a GLB at data/avatar/model.glb', { status: 404 });
}
res.set('Content-Type', 'model/gltf-binary');
diff --git a/server/routes/avatar.test.js b/server/routes/avatar.test.js
index 042ede292c..1e4eee88be 100644
--- a/server/routes/avatar.test.js
+++ b/server/routes/avatar.test.js
@@ -5,16 +5,21 @@ import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
vi.mock('fs', () => ({
- existsSync: vi.fn(),
- statSync: vi.fn(),
createReadStream: vi.fn()
}));
+vi.mock('fs/promises', () => ({
+ stat: vi.fn()
+}));
+
vi.mock('../lib/fileUtils.js', () => ({
- PATHS: { data: '/mock/data' }
+ PATHS: { data: '/mock/data' },
+ pathExists: vi.fn()
}));
-import { existsSync, statSync, createReadStream } from 'fs';
+import { createReadStream } from 'fs';
+import { stat } from 'fs/promises';
+import { pathExists } from '../lib/fileUtils.js';
import avatarRoutes from './avatar.js';
const buildApp = () => {
@@ -31,14 +36,14 @@ describe('avatar routes', () => {
describe('GET /model.glb', () => {
it('returns 404 JSON when file is missing', async () => {
- existsSync.mockReturnValue(false);
+ pathExists.mockResolvedValue(false);
const res = await request(buildApp()).get('/api/avatar/model.glb');
expect(res.status).toBe(404);
expect(res.body.error).toMatch(/avatar model/i);
});
it('streams model.glb content with correct headers', async () => {
- existsSync.mockReturnValue(true);
+ pathExists.mockResolvedValue(true);
const fakeStream = Readable.from([Buffer.from('GLB-FAKE-CONTENT')]);
createReadStream.mockReturnValue(fakeStream);
@@ -50,7 +55,7 @@ describe('avatar routes', () => {
});
it('responds with 404 when stream errors with ENOENT before headers sent', async () => {
- existsSync.mockReturnValue(true);
+ pathExists.mockResolvedValue(true);
const errStream = new Readable({
read() {
process.nextTick(() => {
@@ -70,7 +75,7 @@ describe('avatar routes', () => {
});
it('responds with 500 on non-ENOENT stream error before headers sent', async () => {
- existsSync.mockReturnValue(true);
+ pathExists.mockResolvedValue(true);
const errStream = new Readable({
read() {
process.nextTick(() => {
@@ -89,7 +94,7 @@ describe('avatar routes', () => {
describe('variant resolution', () => {
it('serves a named variant from the avatar dir', async () => {
- existsSync.mockReturnValue(true);
+ pathExists.mockResolvedValue(true);
createReadStream.mockReturnValue(Readable.from([Buffer.from('VARIANT-GLB')]));
const res = await request(buildApp()).get('/api/avatar/model.glb?variant=mini-male-c');
expect(res.status).toBe(200);
@@ -99,7 +104,7 @@ describe('avatar routes', () => {
});
it('rejects path-traversal / illegal variant names with 404', async () => {
- existsSync.mockReturnValue(true);
+ pathExists.mockResolvedValue(true);
// Stub the stream so the empty-string fallback (which hits the default
// model.glb GET success path) is deterministic in isolation — don't rely
// on a prior test's mockReturnValue leaking through vi.clearAllMocks().
@@ -118,8 +123,9 @@ describe('avatar routes', () => {
// The client probes with HEAD before GET, so the HEAD handler runs the
// same resolveVariant() guard — pin it independently of the GET path.
it('HEAD honors a valid variant and rejects traversal', async () => {
- existsSync.mockReturnValue(true);
- statSync.mockReturnValue({ size: 5 });
+ // HEAD stats the resolved path directly (no separate existence check) —
+ // a resolved stat means the file is present.
+ stat.mockResolvedValue({ size: 5 });
const ok = await request(buildApp()).head('/api/avatar/model.glb?variant=mini-male-c');
expect(ok.status).toBe(200);
expect(ok.headers['content-type']).toBe('model/gltf-binary');
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 8904a0f7a1..4a4381b898 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -910,7 +910,7 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
let effectiveSuccess = success;
if (!effectiveSuccess && task?.id) {
const workspacePath = agent.workspacePath || ROOT_DIR;
- const commitFound = checkForTaskCommit(task.id, workspacePath);
+ const commitFound = await checkForTaskCommit(task.id, workspacePath);
if (commitFound) {
emitLog('warn', `Agent ${agentId} reported failure (exit ${exitCode}) but work completed - commit found for task ${task.id}`, { agentId, taskId: task.id, exitCode });
effectiveSuccess = true;
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 955dc38b94..bbcaa3aac2 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -556,7 +556,7 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn) {
}
// Check if the agent actually committed work before treating as orphaned
- const commitFound = checkForTaskCommit(taskId, ROOT_DIR);
+ const commitFound = await checkForTaskCommit(taskId, ROOT_DIR);
if (commitFound) {
emitLog('info', `✅ Orphaned agent ${agentId} actually completed work - commit found for task ${taskId}`, { taskId, agentId });
await updateTask(taskId, { status: 'completed' }, task.taskType || 'user');
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 7cc4367046..0f47b88322 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -53,7 +53,7 @@ vi.mock('./cosEvents.js', () => ({
}));
vi.mock('./agentRunTracking.js', () => ({
- checkForTaskCommit: vi.fn().mockReturnValue(false)
+ checkForTaskCommit: vi.fn().mockResolvedValue(false)
}));
// Stub other transitive imports we don't exercise in handleOrphanedTask.
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index eca46d24df..8cd6882294 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -6,11 +6,10 @@
import { join } from 'path';
import { writeFile, mkdir } from 'fs/promises';
-import { existsSync } from 'fs';
-import { spawnSync } from 'child_process';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { recordSession, recordMessages } from './usage.js';
-import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { bufferedSpawn } from '../lib/bufferedSpawn.js';
+import { ensureDir, pathExists, readJSONFile, PATHS } from '../lib/fileUtils.js';
const RUNS_DIR = PATHS.runs;
@@ -21,9 +20,8 @@ export async function createAgentRun(agentId, task, model, provider, workspacePa
const runId = uuidv4();
const runDir = join(RUNS_DIR, runId);
- if (!existsSync(RUNS_DIR)) {
- await ensureDir(RUNS_DIR);
- }
+ // ensureDir is idempotent (mkdir recursive) — no existence pre-check needed.
+ await ensureDir(RUNS_DIR);
await mkdir(runDir);
const metadata = {
@@ -63,21 +61,29 @@ export async function createAgentRun(agentId, task, model, provider, workspacePa
* Check if a commit was made with the task ID.
* Returns true if a recent commit contains [task-{taskId}].
* Returns false if git command fails (not a repo, git not available, etc.)
+ *
+ * Async + buffered: `git log` on a large repo can block for 100ms–2s, and this
+ * runs on the run-completion path of every failed CoS agent run — a `spawnSync`
+ * here froze all in-flight SSE/socket traffic for that window. `bufferedSpawn`
+ * runs it off the event loop with a hard timeout (a hung git is treated as
+ * "no commit found" rather than stalling completion forever).
*/
-export function checkForTaskCommit(taskId, workspacePath) {
+export async function checkForTaskCommit(taskId, workspacePath) {
// Check if it's a git repo first
const gitDir = join(workspacePath, '.git');
- if (!existsSync(gitDir)) return false;
+ if (!(await pathExists(gitDir))) return false;
const searchPattern = `[task-${taskId}]`;
// --fixed-strings / -F: treat pattern as literal string, not regex. Without
// this, square brackets in `[task-123]` would be parsed as a character class
// and fail to match the literal commit message.
- const result = spawnSync('git', ['log', '--all', '--oneline', '--fixed-strings', '--grep', searchPattern, '-1'], {
- cwd: workspacePath, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, shell: false
- });
- if (result.status !== 0 || result.error) return false;
- return (result.stdout?.trim().length ?? 0) > 0;
+ const result = await bufferedSpawn(
+ 'git',
+ ['log', '--all', '--oneline', '--fixed-strings', '--grep', searchPattern, '-1'],
+ { cwd: workspacePath, timeoutMs: 10_000, shell: false },
+ );
+ if (!result.success) return false; // non-zero exit, spawn error, or timeout
+ return result.stdout.trim().length > 0;
}
/**
@@ -99,7 +105,7 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA
// Post-execution validation: check for task commit even if exit code is non-zero
let success = exitCode === 0;
if (!success && metadata.taskId && metadata.workspacePath) {
- const commitFound = checkForTaskCommit(metadata.taskId, metadata.workspacePath);
+ const commitFound = await checkForTaskCommit(metadata.taskId, metadata.workspacePath);
if (commitFound) {
console.log(`⚠️ Agent ${metadata.agentId} reported failure (exit ${exitCode}) but work completed - commit found for task ${metadata.taskId}`);
success = true;
diff --git a/server/services/authors/db.js b/server/services/authors/db.js
index 253f76091e..9633b1ea38 100644
--- a/server/services/authors/db.js
+++ b/server/services/authors/db.js
@@ -19,6 +19,7 @@ import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
import { buildAuthorRecord, applyAuthorPatch, mergeAuthorRecord } from './logic.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+ withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
function rowToAuthor(row) {
@@ -167,6 +168,10 @@ export async function pruneTombstonedAuthors(olderThanMs) {
RETURNING id`,
[cutoffIso],
);
- for (const r of rows) await deleteSyncBaseHash('author', r.id);
+ // Coalesce the per-author base-hash evictions into ONE disk write — each
+ // `deleteSyncBaseHash` otherwise flushes `sync_base_hashes.json` per row.
+ await withBaseHashFlushBatch(async () => {
+ for (const r of rows) await deleteSyncBaseHash('author', r.id);
+ });
return { pruned: rows.length };
}
diff --git a/server/services/authors/file.js b/server/services/authors/file.js
index 141509d916..0d52117458 100644
--- a/server/services/authors/file.js
+++ b/server/services/authors/file.js
@@ -17,6 +17,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { sanitizeAuthor, buildAuthorRecord, applyAuthorPatch, mergeAuthorRecord } from './logic.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+ withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
const AUTHORS_FILE = join(PATHS.data, 'authors.json');
@@ -134,6 +135,9 @@ export async function pruneTombstonedAuthors(olderThanMs) {
}
if (pruned.length === 0) return { pruned: 0 };
await saveAll(survivors);
- for (const id of pruned) await deleteSyncBaseHash('author', id);
+ // Coalesce the per-author base-hash evictions into ONE disk write.
+ await withBaseHashFlushBatch(async () => {
+ for (const id of pruned) await deleteSyncBaseHash('author', id);
+ });
return { pruned: pruned.length };
}
diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.js
index f147fe754f..6b687bf540 100644
--- a/server/services/creativeDirector/projectsDB.js
+++ b/server/services/creativeDirector/projectsDB.js
@@ -35,6 +35,7 @@ import {
} from './projectsLogic.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+ withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
// The `data` JSONB is the whole record. status/created_at/updated_at are
@@ -218,7 +219,10 @@ export async function pruneTombstonedProjects(olderThanMs) {
RETURNING id`,
[cutoffIso],
);
- for (const r of rows) await deleteSyncBaseHash('creativeDirectorProject', r.id);
+ // Coalesce the per-project base-hash evictions into ONE disk write.
+ await withBaseHashFlushBatch(async () => {
+ for (const r of rows) await deleteSyncBaseHash('creativeDirectorProject', r.id);
+ });
return { pruned: rows.length };
}
diff --git a/server/services/creativeDirector/projectsFile.js b/server/services/creativeDirector/projectsFile.js
index 1dc91c23b8..1f78891c5d 100644
--- a/server/services/creativeDirector/projectsFile.js
+++ b/server/services/creativeDirector/projectsFile.js
@@ -28,6 +28,7 @@ import {
} from './projectsLogic.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+ withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
const PROJECTS_FILE = join(PATHS.data, 'creative-director-projects.json');
@@ -152,7 +153,10 @@ export async function pruneTombstonedProjects(olderThanMs) {
}
if (pruned.length === 0) return { pruned: 0 };
await saveAll(survivors);
- for (const id of pruned) await deleteSyncBaseHash('creativeDirectorProject', id);
+ // Coalesce the per-project base-hash evictions into ONE disk write.
+ await withBaseHashFlushBatch(async () => {
+ for (const id of pruned) await deleteSyncBaseHash('creativeDirectorProject', id);
+ });
return { pruned: pruned.length };
}
diff --git a/server/services/tracks/db.js b/server/services/tracks/db.js
index ecaa177d00..0196d9802c 100644
--- a/server/services/tracks/db.js
+++ b/server/services/tracks/db.js
@@ -14,6 +14,7 @@ import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
import { sanitizeTrack, buildTrackRecord, applyTrackPatch, mergeTrackRecord } from './logic.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+ withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
// Re-sanitize the stored JSONB on read (mirrors the file backend's loadAll →
@@ -147,6 +148,9 @@ export async function pruneTombstonedTracks(olderThanMs) {
RETURNING id`,
[cutoffIso],
);
- for (const r of rows) await deleteSyncBaseHash('track', r.id);
+ // Coalesce the per-track base-hash evictions into ONE disk write.
+ await withBaseHashFlushBatch(async () => {
+ for (const r of rows) await deleteSyncBaseHash('track', r.id);
+ });
return { pruned: rows.length };
}
diff --git a/server/services/tracks/file.js b/server/services/tracks/file.js
index 47a908f1cb..223c925158 100644
--- a/server/services/tracks/file.js
+++ b/server/services/tracks/file.js
@@ -14,6 +14,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { sanitizeTrack, buildTrackRecord, applyTrackPatch, mergeTrackRecord } from './logic.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+ withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
const TRACKS_FILE = join(PATHS.data, 'tracks.json');
@@ -121,6 +122,9 @@ export async function pruneTombstonedTracks(olderThanMs) {
}
if (pruned.length === 0) return { pruned: 0 };
await saveAll(survivors);
- for (const id of pruned) await deleteSyncBaseHash('track', id);
+ // Coalesce the per-track base-hash evictions into ONE disk write.
+ await withBaseHashFlushBatch(async () => {
+ for (const id of pruned) await deleteSyncBaseHash('track', id);
+ });
return { pruned: pruned.length };
}