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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: unify service errors on ServerError (#2534)
[._.]/ Adam Eivyf5baf3501a96
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 380b4358ae..0601d7b40a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -7,7 +7,7 @@## Changed-- **[issue-2530] Decompose `cos.js` `dequeueNextTask` and split `cosAgents.js` into focused modules.** The ~370-line `dequeueNextTask` scheduler is now a thin orchestrator that threads a shared `ctx` through five `spawnDequeuePriorityN(ctx)` tier helpers (mirroring `evaluateTasks`), with the pure per-cycle capacity tracker (`createDequeueCapacity`) and mission/idle tier-eligibility predicates extracted to a new `server/services/cosDequeue.js` — so the scheduler and its unit tests exercise the *same* guards instead of a local replica. The ~1090-line `cosAgents.js` is split into focused siblings — `cosAgentIndex.js` (date-bucket index / migration / prune / archive layout), `cosAgentLifecycle.js` (register / complete / output / terminate / pause / kill / BTW / zombie cleanup), `cosAgentFeedback.js` (feedback capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — with `cosAgents.js` kept as a thin barrel so every existing import path is unchanged. Pure mechanical refactor: no behavior change.+- **[issue-2534] Unify service errors on `ServerError` and delete the duplicated `mapServiceError` copies.** Routes now speak one error model. A single `createServiceErrorMapper(statusMap, buildContext?)` factory in `server/lib/errorHandler.js` replaces the nine near-identical local `mapServiceError` bodies that had accreted across the pipeline / builder / media routers (`pipeline/shared.js`, `storyBuilder.js`, `universeBuilder.js`, `importer.js`, `dashboardLayouts.js`, `conflictJournal.js`, `mediaSketches.js`, `mediaCollections.js`, `mediaAnnotations.js`) — each now just wires its own domain `code → status` map (and optional diagnostic-context builder) through the shared factory. Separately, the CoS agent service functions that returned result-shaped `{ error }` payloads (`getAgentPrompt`, `deleteAgent`, `submitAgentFeedback`, `sendBtwToAgent`) now throw `ServerError` with an explicit `status`/`code`, so `cosAgentRoutes.js` no longer string-matches `result.error === 'Agent not found'` to guess 404-vs-400 — the errors bubble straight to the centralized middleware and every route returns the same `{ error, code, timestamp, context? }` envelope. No client-visible behavior change (the same statuses/codes are preserved). Pure architecture refactor. The ~370-line `dequeueNextTask` scheduler is now a thin orchestrator that threads a shared `ctx` through five `spawnDequeuePriorityN(ctx)` tier helpers (mirroring `evaluateTasks`), with the pure per-cycle capacity tracker (`createDequeueCapacity`) and mission/idle tier-eligibility predicates extracted to a new `server/services/cosDequeue.js` — so the scheduler and its unit tests exercise the *same* guards instead of a local replica. The ~1090-line `cosAgents.js` is split into focused siblings — `cosAgentIndex.js` (date-bucket index / migration / prune / archive layout), `cosAgentLifecycle.js` (register / complete / output / terminate / pause / kill / BTW / zombie cleanup), `cosAgentFeedback.js` (feedback capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — with `cosAgents.js` kept as a thin barrel so every existing import path is unchanged. Pure mechanical refactor: no behavior change.- **[issue-2533] Thin the apps-list route and split the imageGen setup routes into their own module.** The `GET /api/apps` handler's ~80 lines of inline PM2 enrichment (one read per `pm2Home`, absent-vs-empty status classification, ecosystem-config process backfill, port derivation) moved into a new `server/services/appListEnrichment.js` (`enrichAppsWithPm2Status(apps)`), so the route just fetches the raw records and responds; the pure port/status helpers (`deriveUiPort`/`deriveAppPorts`/`computeOverallStatus`) live there too and are re-exported from `routes/apps/shared.js` so the detail/lifecycle routes keep one shared implementation. The `/api/image-gen/setup/*` handlers (python probe/venv bootstrap, FLUX.2 install/status, HuggingFace-token store, pip installer) split out of the large `routes/imageGen.js` render router into `routes/imageGenSetup.js`, with the setup-check cache and pip allowlist relocated to `services/imageGen/setup.js`. Pure mechanical refactor — no behavior change.- **[issue-2531] Split the pipeline `issues.js` and `visualStages.js` monoliths along CRUD/stage/sync seams.** The ~1470-line `server/services/pipeline/issues.js` is now a thin barrel over `issuesShared.js` (store facade + per-series write queue + record sanitizers + `renumberInline`), `issueCrud.js` (create/read/list/update/delete + numbering/reassign), `issueStages.js` (per-stage merge/history/restore), and `issueSync.js` (peer-sync LWW merge + tombstone GC). The ~1760-line `visualStages.js` is now a thin barrel over `visualStageHelpers.js` (shared style/prompt composers + image-gen enqueue plumbing), `covers.js` (comic + volume front/back covers), `comicPages.js` (comic page renders + panel prompt refine), and `storyboards.js` (scene/shot renders + scene refine). Pure mechanical refactor — no behavior change; the single-tail-per-series write serialization (`queueSeriesIssuesWrite`) and the store's `queueTypeIndexWrite` merge snapshot are preserved, and every existing `from './issues.js'` / `from './visualStages.js'` import path still resolves through the barrels.diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.jsindex 98bfd02ede..c2ebced9ba 100644--- a/server/lib/errorHandler.js+++ b/server/lib/errorHandler.js@@ -76,6 +76,35 @@ export function failValidation(parsed) {);}+/**+ * Build a service-error → ServerError mapper for route handlers.+ *+ * Domain services throw coded plain Errors (`Object.assign(new Error(msg),+ * { code })`); routes catch them and rethrow as `ServerError`s so the+ * centralized middleware renders the standard `{ error, code, timestamp,+ * context? }` envelope. This factory replaces the ~identical `mapServiceError`+ * copies that had accreted across the pipeline / builder / media routers.+ *+ * @param {Record<string, number>} statusMap service error `code` → HTTP status.+ * @param {(err: any) => object|undefined} [buildContext] optional per-error+ * context builder (e.g. a merge-cascade or delete-guard diagnostic payload);+ * an empty/undefined result is omitted from the response envelope.+ * @returns {(err: any) => any} mapper — recognized codes become a `ServerError`;+ * anything else passes through untouched (it normalizes to a 500).+ */+export function createServiceErrorMapper(statusMap, buildContext) {+ return (err) => {+ const status = statusMap[err?.code];+ if (!status) return err;+ const context = buildContext ? buildContext(err) : undefined;+ return new ServerError(err.message, {+ status,+ code: err.code,+ ...(context && Object.keys(context).length > 0 ? { context } : {}),+ });+ };+}+export function asyncHandler(fn) {return (req, res, next) => {Promise.resolve(fn(req, res, next)).catch((err) => {diff --git a/server/lib/errorHandler.test.js b/server/lib/errorHandler.test.jsindex 2fa2d12a75..6446744b08 100644--- a/server/lib/errorHandler.test.js+++ b/server/lib/errorHandler.test.js@@ -4,7 +4,8 @@ import {normalizeError,emitErrorEvent,errorEvents,- errorMiddleware+ errorMiddleware,+ createServiceErrorMapper} from './errorHandler.js';describe('errorHandler.js', () => {@@ -231,4 +232,45 @@ describe('errorHandler.js', () => {errorEvents.off('error', listener);});});++ describe('createServiceErrorMapper', () => {+ const STATUS = { SVC_NOT_FOUND: 404, SVC_VALIDATION: 400 };++ it('maps a recognized code to a ServerError with the mapped status', () => {+ const map = createServiceErrorMapper(STATUS);+ const mapped = map(Object.assign(new Error('missing'), { code: 'SVC_NOT_FOUND' }));+ expect(mapped).toBeInstanceOf(ServerError);+ expect(mapped.status).toBe(404);+ expect(mapped.code).toBe('SVC_NOT_FOUND');+ expect(mapped.message).toBe('missing');+ });++ it('passes an unrecognized error through untouched', () => {+ const map = createServiceErrorMapper(STATUS);+ const original = Object.assign(new Error('boom'), { code: 'SOMETHING_ELSE' });+ expect(map(original)).toBe(original);+ });++ it('passes a code-less error through untouched', () => {+ const map = createServiceErrorMapper(STATUS);+ const original = new Error('plain');+ expect(map(original)).toBe(original);+ });++ it('attaches a non-empty buildContext result as context', () => {+ const map = createServiceErrorMapper(STATUS, (err) => ({ blockingSeries: err.blockingSeries }));+ const mapped = map(Object.assign(new Error('busy'), { code: 'SVC_VALIDATION', blockingSeries: ['s1'] }));+ expect(mapped.context).toEqual({ blockingSeries: ['s1'] });+ });++ it('omits context when buildContext returns undefined or an empty object', () => {+ const map = createServiceErrorMapper(STATUS, () => undefined);+ const mapped = map(Object.assign(new Error('x'), { code: 'SVC_VALIDATION' }));+ expect(mapped.context).toEqual({});++ const mapEmpty = createServiceErrorMapper(STATUS, () => ({}));+ const mappedEmpty = mapEmpty(Object.assign(new Error('y'), { code: 'SVC_VALIDATION' }));+ expect(mappedEmpty.context).toEqual({});+ });+ });});diff --git a/server/routes/conflictJournal.js b/server/routes/conflictJournal.jsindex 34668b8798..6d376ee363 100644--- a/server/routes/conflictJournal.js+++ b/server/routes/conflictJournal.js@@ -5,7 +5,7 @@import { Router } from 'express';import { z } from 'zod';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { asyncHandler, createServiceErrorMapper } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as resolver from '../services/conflictJournalResolver.js';@@ -18,11 +18,7 @@ const SERVICE_ERROR_STATUS = {// still actionable via discard, so surface 409 rather than a generic 500.[resolver.ERR_TARGET_GONE]: 409,};-const mapServiceError = (err) => {- const status = SERVICE_ERROR_STATUS[err?.code];- if (status) return new ServerError(err.message, { status, code: err.code });- return err;-};+const mapServiceError = createServiceErrorMapper(SERVICE_ERROR_STATUS);// Entries are only ever 'pending' (on archive) or 'resolved' (after the user// restores/merges/discards); there is no 'dismissed' state — discard resolvesdiff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsindex 24ca1bfa81..2aa3c450b7 100644--- a/server/routes/cos.test.js+++ b/server/routes/cos.test.js@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';+import { ServerError } from '../lib/errorHandler.js';import cosRoutes from './cos.js';// Mock the cos service@@ -663,7 +664,7 @@ describe('CoS Routes', () => {});it('should return 404 if agent not found', async () => {- cos.deleteAgent.mockResolvedValue({ error: 'Agent not found' });+ cos.deleteAgent.mockRejectedValue(new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' }));const response = await request(app).delete('/api/cos/agents/agent-999');@@ -1129,7 +1130,7 @@ describe('CoS Routes', () => {});it('should return 404 if agent not found', async () => {- cos.submitAgentFeedback.mockResolvedValue({ error: 'Agent not found' });+ cos.submitAgentFeedback.mockRejectedValue(new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' }));const response = await request(app).post('/api/cos/agents/agent-999/feedback')@@ -1137,6 +1138,17 @@ describe('CoS Routes', () => {expect(response.status).toBe(404);});++ it('should return 400 (INVALID_STATE) when the agent is not completed', async () => {+ cos.submitAgentFeedback.mockRejectedValue(new ServerError('Can only submit feedback for completed agents', { status: 400, code: 'INVALID_STATE' }));++ const response = await request(app)+ .post('/api/cos/agents/agent-001/feedback')+ .send({ rating: 'positive' });++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('INVALID_STATE');+ });});describe('POST /api/cos/agents/:id/btw', () => {@@ -1176,7 +1188,7 @@ describe('CoS Routes', () => {});it('should return 404 if agent not found', async () => {- cos.sendBtwToAgent.mockResolvedValue({ error: 'Agent not found' });+ cos.sendBtwToAgent.mockRejectedValue(new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' }));const response = await request(app).post('/api/cos/agents/agent-999/btw')@@ -1184,6 +1196,17 @@ describe('CoS Routes', () => {expect(response.status).toBe(404);});++ it('should return 400 (INVALID_STATE) when BTW is unsupported for the agent', async () => {+ cos.sendBtwToAgent.mockRejectedValue(new ServerError('Agent is not running', { status: 400, code: 'INVALID_STATE' }));++ const response = await request(app)+ .post('/api/cos/agents/agent-001/btw')+ .send({ message: 'hello' });++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('INVALID_STATE');+ });});describe('GET /api/cos/feedback/stats', () => {diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.jsindex 59758cba43..442adca2cb 100644--- a/server/routes/cosAgentRoutes.js+++ b/server/routes/cosAgentRoutes.js@@ -60,11 +60,10 @@ router.get('/agents/:id', asyncHandler(async (req, res) => {}));// GET /api/cos/agents/:id/prompt - Read the prompt.txt saved at spawn time+// The service throws a ServerError (404) when the agent or prompt file is+// missing — asyncHandler renders the standard envelope.router.get('/agents/:id/prompt', asyncHandler(async (req, res) => {const result = await cos.getAgentPrompt(req.params.id);- if (result.error) {- throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });- }res.json(result);}));@@ -107,11 +106,9 @@ router.delete('/agents/completed', asyncHandler(async (req, res) => {}));// DELETE /api/cos/agents/:id - Delete a single agent+// The service throws a ServerError (404) when the agent doesn't exist.router.delete('/agents/:id', asyncHandler(async (req, res) => {const result = await cos.deleteAgent(req.params.id);- if (result?.error) {- throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });- }res.json(result);}));@@ -123,14 +120,9 @@ router.post('/agents/:id/feedback', asyncHandler(async (req, res) => {throw new ServerError('rating must be positive, negative, or neutral', { status: 400, code: 'VALIDATION_ERROR' });}+ // The service throws a ServerError — 404 when the agent is missing, 400+ // (INVALID_STATE) when it isn't completed — so no result-shape mapping here.const result = await cos.submitAgentFeedback(req.params.id, { rating, comment });- if (result?.error) {- const isNotFound = result.error === 'Agent not found';- throw new ServerError(result.error, {- status: isNotFound ? 404 : 400,- code: isNotFound ? 'NOT_FOUND' : 'INVALID_STATE'- });- }res.json(result);}));@@ -146,14 +138,10 @@ router.post('/agents/:id/btw', asyncHandler(async (req, res) => {throw new ServerError('message must be 5000 characters or less', { status: 400, code: 'VALIDATION_ERROR' });}+ // The service throws a ServerError — 404 when the agent is missing, 400+ // (INVALID_STATE) for the not-running / not-a-Claude-TUI refusals — so no+ // result-shape string-matching here.const result = await cos.sendBtwToAgent(req.params.id, message.trim());- if (result?.error) {- const isNotFound = result.error === 'Agent not found';- throw new ServerError(result.error, {- status: isNotFound ? 404 : 400,- code: isNotFound ? 'NOT_FOUND' : 'INVALID_STATE'- });- }res.json(result);}));diff --git a/server/routes/dashboardLayouts.js b/server/routes/dashboardLayouts.jsindex 255f790843..e269cdab65 100644--- a/server/routes/dashboardLayouts.js+++ b/server/routes/dashboardLayouts.js@@ -7,7 +7,7 @@import { Router } from 'express';import { z } from 'zod';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { asyncHandler, createServiceErrorMapper } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as svc from '../services/dashboardLayouts.js';@@ -88,11 +88,7 @@ const SERVICE_ERROR_STATUS = {[svc.ERR_BUILTIN_PROTECTED]: 400,};-const mapServiceError = (err) => {- const status = SERVICE_ERROR_STATUS[err?.code];- if (status) return new ServerError(err.message, { status, code: err.code });- return err;-};+const mapServiceError = createServiceErrorMapper(SERVICE_ERROR_STATUS);router.get('/', asyncHandler(async (_req, res) => {res.json(await svc.getState());diff --git a/server/routes/importer.js b/server/routes/importer.jsindex 8897b48f85..d269f8a9f2 100644--- a/server/routes/importer.js+++ b/server/routes/importer.js@@ -1,5 +1,5 @@import { Router } from 'express';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { asyncHandler, createServiceErrorMapper } from '../lib/errorHandler.js';import {validateRequest,importerAnalyzeSchema,@@ -45,17 +45,9 @@ const SERVICE_ERROR_STATUS = {[seriesSvc.ERR_NOT_FOUND]: 404,};-const mapServiceError = (err) => {- const status = SERVICE_ERROR_STATUS[err?.code];- // Preserve `err.context` — ERR_PARTIAL_COMMIT_ISSUES carries the- // arcAlreadyPersisted retry signal the client gates on.- if (status) return new ServerError(err.message, {- status,- code: err.code,- ...(err.context ? { context: err.context } : {}),- });- return err;-};+// Preserve `err.context` — ERR_PARTIAL_COMMIT_ISSUES carries the+// arcAlreadyPersisted retry signal the client gates on.+const mapServiceError = createServiceErrorMapper(SERVICE_ERROR_STATUS, (err) => err.context);// Surfaces server-canonical constants so the client doesn't hardcode (and// drift from) the source-char limit, the arc-role enum, or the arc-shapediff --git a/server/routes/mediaAnnotations.js b/server/routes/mediaAnnotations.jsindex 133288cb0b..9923420ed2 100644--- a/server/routes/mediaAnnotations.js+++ b/server/routes/mediaAnnotations.js@@ -13,7 +13,7 @@import { Router } from 'express';import { z } from 'zod';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { asyncHandler, createServiceErrorMapper } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as svc from '../services/mediaAnnotations.js';@@ -23,11 +23,7 @@ const SERVICE_ERROR_STATUS = {[svc.ERR_VALIDATION]: 400,};-const mapServiceError = (err) => {- const status = SERVICE_ERROR_STATUS[err?.code];- if (status) return new ServerError(err.message, { status, code: err.code });- return err;-};+const mapServiceError = createServiceErrorMapper(SERVICE_ERROR_STATUS);const patchSchema = z.object({starred: z.boolean().optional(),diff --git a/server/routes/mediaCollections.js b/server/routes/mediaCollections.jsindex c8da77d6f1..9f9360d484 100644--- a/server/routes/mediaCollections.js+++ b/server/routes/mediaCollections.js@@ -12,7 +12,7 @@import { Router } from 'express';import { z } from 'zod';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { asyncHandler, ServerError, createServiceErrorMapper } from '../lib/errorHandler.js';import { validateRequest, mediaCollectionBulkItemsSchema } from '../lib/validation.js';import * as svc from '../services/mediaCollections.js';@@ -24,11 +24,7 @@ const SERVICE_ERROR_STATUS = {[svc.ERR_VALIDATION]: 400,};-const mapServiceError = (err) => {- const status = SERVICE_ERROR_STATUS[err?.code];- if (status) return new ServerError(err.message, { status, code: err.code });- return err;-};+const mapServiceError = createServiceErrorMapper(SERVICE_ERROR_STATUS);const nameSchema = z.string().trim().min(1).max(svc.NAME_MAX_LENGTH);const descriptionSchema = z.string().trim().max(svc.DESCRIPTION_MAX_LENGTH);diff --git a/server/routes/mediaSketches.js b/server/routes/mediaSketches.jsindex 89dc985315..4919c7d708 100644--- a/server/routes/mediaSketches.js+++ b/server/routes/mediaSketches.js@@ -15,18 +15,13 @@*/import { Router } from 'express';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { asyncHandler, ServerError, createServiceErrorMapper } from '../lib/errorHandler.js';import { validateRequest, mediaSketchSaveSchema } from '../lib/validation.js';import * as svc from '../services/mediaSketches.js';const router = Router();-const mapServiceError = (err) => {- if (err?.code === svc.ERR_VALIDATION) {- return new ServerError(err.message, { status: 400, code: err.code });- }- return err;-};+const mapServiceError = createServiceErrorMapper({ [svc.ERR_VALIDATION]: 400 });// Mint a blank-canvas sketch key. The client can't rely on crypto.randomUUID// (PortOS is served over plain HTTP on Tailscale, an insecure origin), so thediff --git a/server/routes/pipeline/shared.js b/server/routes/pipeline/shared.jsindex 717be04478..40c6f55258 100644--- a/server/routes/pipeline/shared.js+++ b/server/routes/pipeline/shared.js@@ -5,7 +5,7 @@*/import { z } from 'zod';-import { ServerError } from '../../lib/errorHandler.js';+import { createServiceErrorMapper } from '../../lib/errorHandler.js';import * as seriesSvc from '../../services/pipeline/series.js';import * as issuesSvc from '../../services/pipeline/issues.js';import * as seasonsSvc from '../../services/pipeline/seasons.js';@@ -48,15 +48,10 @@ const SERVICE_ERROR_STATUS = {MERGE_CASCADE_INCOMPLETE: 409,};-export const mapServiceError = (err) => {- const status = SERVICE_ERROR_STATUS[err?.code];- if (status) {- // An incomplete merge cascade forwards the survivor/loser ids + which step- // failed so the UI can tell the user exactly what didn't move.- return new ServerError(err.message, { status, code: err.code, context: buildCascadeContext(err) });- }- return err;-};+// An incomplete merge cascade forwards the survivor/loser ids + which step+// failed (via buildCascadeContext) so the UI can tell the user exactly what+// didn't move.+export const mapServiceError = createServiceErrorMapper(SERVICE_ERROR_STATUS, buildCascadeContext);// Arc / season-episodes / verify — Phase 3 of Story Arc Planning. The LLM// calls share a provider/model override shape.diff --git a/server/routes/storyBuilder.js b/server/routes/storyBuilder.jsindex 6c354add99..77b9a186c1 100644--- a/server/routes/storyBuilder.js+++ b/server/routes/storyBuilder.js@@ -1,5 +1,5 @@import { Router } from 'express';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { asyncHandler, ServerError, createServiceErrorMapper } from '../lib/errorHandler.js';import {validateRequest,storySessionCreateSchema,@@ -36,11 +36,7 @@ const SERVICE_ERROR_STATUS = {[ERR_NOT_FOUND]: 404,[ERR_VALIDATION]: 400,};-const mapServiceError = (err) => {- const status = SERVICE_ERROR_STATUS[err?.code];- if (status) return new ServerError(err.message, { status, code: err.code });- return err;-};+const mapServiceError = createServiceErrorMapper(SERVICE_ERROR_STATUS);// Echo the step manifest so the client stepper doesn't hardcode the order /// labels (single source of truth is server/lib/storyBuilderSteps.js).diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 8c2c6be2e4..3810e3734d 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -15,7 +15,7 @@import { Router } from 'express';import { z } from 'zod';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { asyncHandler, ServerError, createServiceErrorMapper } from '../lib/errorHandler.js';import { validateRequest, optionalBooleanMap, llmSchema } from '../lib/validation.js';import * as svc from '../services/universeBuilder.js';import * as canonSvc from '../services/universeCanon.js';@@ -57,19 +57,12 @@ const SERVICE_ERROR_STATUS = {MERGE_CASCADE_INCOMPLETE: 409,};-const mapServiceError = (err) => {- const status = SERVICE_ERROR_STATUS[err?.code];- if (status) {- // Propagate diagnostic context onto the response body via `context`: the- // blocking-series list for a delete-guard 409, or the survivor/loser ids +- // which children failed to re-point for an incomplete merge cascade.- const context = err?.blockingSeries- ? { blockingSeries: err.blockingSeries }- : buildCascadeContext(err);- return new ServerError(err.message, { status, code: err.code, context });- }- return err;-};+// Propagate diagnostic context onto the response body via `context`: the+// blocking-series list for a delete-guard 409, or the survivor/loser ids ++// which children failed to re-point for an incomplete merge cascade.+const mapServiceError = createServiceErrorMapper(SERVICE_ERROR_STATUS, (err) =>+ err?.blockingSeries ? { blockingSeries: err.blockingSeries } : buildCascadeContext(err),+);// ---- shared zod fragments ----// `id` is optional on input — the service-layer sanitizer mints one with adiff --git a/server/services/cosAgentFeedback.js b/server/services/cosAgentFeedback.jsindex d37831121f..ebc4101a99 100644--- a/server/services/cosAgentFeedback.js+++ b/server/services/cosAgentFeedback.js@@ -13,6 +13,7 @@ import { cosEvents, emitLog } from './cosEvents.js';import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';import { atomicWrite, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { loadAgentIndex, getAgentDir } from './cosAgentIndex.js';+import { ServerError } from '../lib/errorHandler.js';// Submit feedback for a completed agentexport async function submitAgentFeedback(agentId, feedback) {@@ -28,7 +29,7 @@ export async function submitAgentFeedback(agentId, feedback) {if (state.agents[agentId]) {const agent = state.agents[agentId];if (agent.status !== 'completed') {- return { error: 'Can only submit feedback for completed agents' };+ throw new ServerError('Can only submit feedback for completed agents', { status: 400, code: 'INVALID_STATE' });}state.agents[agentId].feedback = feedbackData;await saveState(state);@@ -56,14 +57,14 @@ export async function submitAgentFeedback(agentId, feedback) {// Agent not in state — look up from disk via indexconst idx = await loadAgentIndex();const dateStr = idx.get(agentId);- if (!dateStr) return { error: 'Agent not found' };+ if (!dateStr) throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });const metaPath = join(AGENTS_DIR, dateStr, agentId, 'metadata.json');const content = await tryReadFile(metaPath);- if (!content) return { error: 'Agent not found' };+ if (!content) throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });const raw = safeJSONParse(content, null);- if (!raw) return { error: 'Agent not found' };+ if (!raw) throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });raw.feedback = feedbackData;await atomicWrite(metaPath, raw);diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex 939763c0bc..4d5c8fc528 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -13,6 +13,7 @@ import { readFile, writeFile, rename, readdir, rm } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { cosEvents } from './cosEvents.js';+import { ServerError } from '../lib/errorHandler.js';import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';import { atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { recordDomainUsage } from './domainUsage.js';@@ -347,10 +348,10 @@ export async function getAgent(agentId) {export async function getAgentPrompt(agentId) {const state = await loadState();const agent = state.agents[agentId];- if (!agent) return { error: 'Agent not found' };+ if (!agent) throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });const agentDir = getAgentDir(agentId, agent.archiveDate);const promptPath = join(agentDir, 'prompt.txt');- if (!existsSync(promptPath)) return { error: 'Prompt file not found' };+ if (!existsSync(promptPath)) throw new ServerError('Prompt file not found', { status: 404, code: 'NOT_FOUND' });const prompt = await readFile(promptPath, 'utf8');return { prompt, bytes: prompt.length };}@@ -389,25 +390,23 @@ export async function sendBtwToAgent(agentId, message) {const agentInfo = await withStateLock(async () => {const state = await loadState();const agent = state.agents[agentId];- if (!agent) return { error: 'Agent not found' };- if (agent.status !== 'running') return { error: 'Agent is not running' };+ if (!agent) throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });+ if (agent.status !== 'running') throw new ServerError('Agent is not running', { status: 400, code: 'INVALID_STATE' });if (agent.metadata?.executionMode !== 'tui') {- return { error: 'BTW is only supported for Claude Code TUI agents.' };+ throw new ServerError('BTW is only supported for Claude Code TUI agents.', { status: 400, code: 'INVALID_STATE' });}if (agent.metadata?.tuiKind !== 'claude') {- return { error: `BTW is only supported for Claude Code TUI agents (this agent runs ${agent.metadata.tuiKind || 'an unknown TUI'}).` };+ throw new ServerError(`BTW is only supported for Claude Code TUI agents (this agent runs ${agent.metadata.tuiKind || 'an unknown TUI'}).`, { status: 400, code: 'INVALID_STATE' });}if (!agent.metadata?.tuiSessionId) {- return { error: 'Agent has no attached TUI session' };+ throw new ServerError('Agent has no attached TUI session', { status: 400, code: 'INVALID_STATE' });}return { tuiSessionId: agent.metadata.tuiSessionId };});- if (agentInfo.error) return agentInfo;-const shellService = await import('./shell.js');if (!shellService.getSession(agentInfo.tuiSessionId)) {- return { error: 'TUI session is no longer alive' };+ throw new ServerError('TUI session is no longer alive', { status: 400, code: 'INVALID_STATE' });}// Bracketed-paste + delayed Enter, mirroring the initial prompt paste in// agentTuiSpawning.js: Claude Code commits the paste buffer before the@@ -560,7 +559,7 @@ export async function deleteAgent(agentId) {const inState = !!state.agents[agentId];const inIndex = idx.has(agentId);if (!inState && !inIndex) {- return { error: 'Agent not found' };+ throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });}delete state.agents[agentId];