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
Share one coded-error helper instead of 22 private makeErr copies
Adam Eivy0a2f81f1a5aa
diff --git a/server/lib/README.md b/server/lib/README.mdindex 38ec7f066a..7a48623908 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -313,6 +313,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. || `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. Optional `safetyProfile` runs only maintained no-tool vendor recipes and composes the same restricted environment, refusing extra argv and unsupported providers. || `cliStderrNoise.js` | `isKnownCliStderrNoise(trimmedLine)` — drops the real Anthropic `claude` CLI's harmless `[claude-code:unrecognized_model]` SDK telemetry line, which fires on every claude-ollama / claude-ollama-tui run because those providers point the binary's `ANTHROPIC_BASE_URL` at a local Ollama model the SDK doesn't recognize. |+| `codedError.js` | `codedError(message, code)` — dependency-free `Error` carrying a machine-readable `code`. The one shared form of the per-service `makeErr`: a service owns an `ERR_*` vocabulary, throws `codedError(msg, ERR_X)`, and the route maps `err.code` to a status via `createServiceErrorMapper` (`errorHandler.js`). Reach for `ServerError` instead when the throw site already knows the HTTP status. A leaf so a service can raise one without pulling `errorHandler.js` into its import closure. || `codex.js` | OpenAI Codex CLI (`codex`) provider helpers — the `CODEX_COMMAND`/`CODEX_CLI_ID` constants, the `isCodexCommand` and `isVisionCapableCodexTuiProvider` predicates, and `ensureCodexTuiArgs` (injects `--dangerously-bypass-approvals-and-sandbox` + disables the startup update-check config, skipped when the argv already declares an approval/sandbox posture via `argvHasFlag`). Extracted from `tuiHandshake.js` (#3618) to match the one-file-per-vendor shape of `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`, which `providerVendors.js` consumes as registry rows. Also owns `buildCodexOssArgs` — the `--oss --local-provider <ns>` pair emitted from a record's `ollamaBacked` marker, so the Codex harness runs on a local model without rewriting the user's `~/.codex/config.toml` (the record-classification half of that lives in `providerModels.js`, so `providerPrerequisites.js` can classify a codex record without importing a vendor argv module). || `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — the `CURSOR_COMMAND` binary constant, the `isCursorCommand` predicate, and the `ensureCursorHeadlessArgs` (`--print --force`, folding any pinned reasoning effort into `--model`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. || `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback; `cleanup({ throwOnError: true })` reports cleanup failure to an owning lifecycle). |diff --git a/server/lib/codedError.js b/server/lib/codedError.jsnew file mode 100644index 0000000000..825882cf78--- /dev/null+++ b/server/lib/codedError.js@@ -0,0 +1,12 @@+// Dependency-free leaf: an Error carrying a machine-readable `code`.+//+// Domain services throw these and the route layer maps `err.code` to an HTTP+// status through `createServiceErrorMapper` (lib/errorHandler.js) — so a caller+// branches on the code, never on `err.message`. Kept out of errorHandler.js on+// purpose: that module drags the Socket.IO/express closure into every service+// that only wants to raise an error (see `importScoping.test.js`).+//+// Use `ServerError` (errorHandler.js) when the throw site already knows the+// HTTP status; use this when the service owns a code vocabulary (`ERR_*`) and+// the route owns the status table.+export const codedError = (message, code) => Object.assign(new Error(message), { code });diff --git a/server/lib/index.js b/server/lib/index.jsindex a033ad2a1b..11524eb9e9 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -187,6 +187,7 @@ export * from './localEndpoint.js';export * from './cliProviderArgs.js';export * from './cliProviderRun.js';export * from './cliStderrNoise.js';+export * from './codedError.js';export * from './codex.js';export * from './codexAccount.js';export * from './codexTurn.js';diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.jsindex e4cb514d1e..64cac009d5 100644--- a/server/services/conflictJournalResolver.js+++ b/server/services/conflictJournalResolver.js@@ -43,13 +43,13 @@ import { restoreCommissionFeedback } from './creativeCommissions/feedbackStore.jimport { restoreCommission } from './creativeCommissions/store.js';import { restoreDeck } from './decks.js';import { restoreLoom } from './fableLoom/index.js';+import { codedError } from '../lib/codedError.js';export const ERR_NOT_FOUND = 'CONFLICT_JOURNAL_NOT_FOUND';export const ERR_VALIDATION = 'CONFLICT_JOURNAL_VALIDATION';// The conflict entry exists but the record it targets was tombstoned between// archive time and resolution — distinct from ERR_NOT_FOUND (the entry itself).export const ERR_TARGET_GONE = 'CONFLICT_TARGET_GONE';-const makeErr = (message, code) => Object.assign(new Error(message), { code });// RESTORABLE_FIELDS (the user-authored content fields a restore/merge may write// per kind; id/createdAt/server-owned fields are never overlaid) is owned by@@ -80,7 +80,7 @@ export async function listConflicts({ status = null } = {}) {export async function getConflict(id) {const entry = await store().loadOne(id);- if (!entry) throw makeErr(`Conflict entry not found: ${id}`, ERR_NOT_FOUND);+ if (!entry) throw codedError(`Conflict entry not found: ${id}`, ERR_NOT_FOUND);return entry;}@@ -99,7 +99,7 @@ async function applyToRecord(kind, recordId, patch, { replace = false } = {}) {// 'NOT_FOUND' (no module-specific export) when the row is missing OR// tombstoned — both mean the conflict target is gone.|| err?.code === 'NOT_FOUND') {- throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);+ throw codedError(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);}throw err;};@@ -185,25 +185,25 @@ async function applyToRecord(kind, recordId, patch, { replace = false } = {}) {// null (not throw) for a missing record — translate that to ERR_TARGET_GONE so// the route serves a clean 409 (#2686).const restored = await restoreCommissionFeedback(recordId, patch).catch(translateGone);- if (!restored) throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);+ if (!restored) throw codedError(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);} else if (kind === 'creativeCommission') {// restoreCommission merges the snapshot's brief fields, un-tombstones, and// bumps updatedAt so the restore wins the next LWW. Machine-local schedule/// runs/assignment are kept as-is. Returns null for a missing record (#2686).const restored = await restoreCommission(recordId, patch).catch(translateGone);- if (!restored) throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);+ if (!restored) throw codedError(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);} else if (kind === 'deck') {// restoreDeck merges the snapshot's style-guide/identity fields, un-tombstones,// and bumps updatedAt so the restore wins the next LWW and re-pushes. Returns// null for a deck already hard-pruned by the tombstone sweep (→ ERR_TARGET_GONE).const restored = await restoreDeck(recordId, patch).catch(translateGone);- if (!restored) throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);+ if (!restored) throw codedError(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);} else if (kind === 'fableLoom') {// Restore the authored story graph and playback settings through the normal// loom mutation path so the edit is sanitized, timestamped, and re-pushed.await restoreLoom(recordId, patch).catch(translateGone);} else {- throw makeErr(`Unsupported conflict kind: ${kind}`, ERR_VALIDATION);+ throw codedError(`Unsupported conflict kind: ${kind}`, ERR_VALIDATION);}}@@ -213,9 +213,9 @@ async function applyToRecord(kind, recordId, patch, { replace = false } = {}) {*/export async function resolveConflict(id, { action, fields = [] } = {}) {const entry = await getConflict(id);- if (entry.status !== 'pending') throw makeErr(`Conflict already ${entry.status}`, ERR_VALIDATION);+ if (entry.status !== 'pending') throw codedError(`Conflict already ${entry.status}`, ERR_VALIDATION);const allowed = RESTORABLE_FIELDS[entry.recordKind];- if (!allowed) throw makeErr(`Unsupported conflict kind: ${entry.recordKind}`, ERR_VALIDATION);+ if (!allowed) throw codedError(`Unsupported conflict kind: ${entry.recordKind}`, ERR_VALIDATION);const snapshot = entry.localSnapshot || {};if (action === 'restore-all') {@@ -223,13 +223,13 @@ export async function resolveConflict(id, { action, fields = [] } = {}) {await applyToRecord(entry.recordKind, entry.recordId, pick(snapshot, allowed, entry.recordKind), { replace: true });} else if (action === 'merge-fields') {if (!Array.isArray(fields) || fields.length === 0) {- throw makeErr('merge-fields requires a non-empty `fields` array', ERR_VALIDATION);+ throw codedError('merge-fields requires a non-empty `fields` array', ERR_VALIDATION);}const invalid = fields.filter((f) => !allowed.includes(f));- if (invalid.length) throw makeErr(`Not restorable: ${invalid.join(', ')}`, ERR_VALIDATION);+ if (invalid.length) throw codedError(`Not restorable: ${invalid.join(', ')}`, ERR_VALIDATION);await applyToRecord(entry.recordKind, entry.recordId, pick(snapshot, fields, entry.recordKind));} else if (action !== 'discard') {- throw makeErr(`Unknown resolution action: ${action}`, ERR_VALIDATION);+ throw codedError(`Unknown resolution action: ${action}`, ERR_VALIDATION);}const resolved = { ...entry, status: 'resolved', resolution: action, resolvedAt: new Date().toISOString() };@@ -243,11 +243,11 @@ export async function deleteConflict(id) {// Validate the id BEFORE interpolating it into recordDir(id) — getConflict()// (which we no longer call) used to enforce this via the store's isValidId;// an unguarded id would make recordDir a path-traversal existence oracle.- if (!isSafeRecordId(id)) throw makeErr(`Conflict entry not found: ${id}`, ERR_NOT_FOUND);+ if (!isSafeRecordId(id)) throw codedError(`Conflict entry not found: ${id}`, ERR_NOT_FOUND);// Don't gate on getConflict() — it requires a successful parse, so a corrupt// journal entry would 404 here and become permanently undeletable. Check raw// directory existence instead, then hard-delete (deleteOne is idempotent).- if (!existsSync(store().recordDir(id))) throw makeErr(`Conflict entry not found: ${id}`, ERR_NOT_FOUND);+ if (!existsSync(store().recordDir(id))) throw codedError(`Conflict entry not found: ${id}`, ERR_NOT_FOUND);await store().deleteOne(id);return { id, deleted: true };}diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex 4fb1e29d99..e1c07f5fdc 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -81,6 +81,7 @@ import {tombstoneFeedbackForCommission,} from './feedbackStore.js';import { isStr } from '../../lib/textUtils.js';+import { codedError } from '../../lib/codedError.js';// Emits `commission:changed` on any create/update/delete (not on run-record// appends, which don't affect scheduling). The scheduler subscribes to re-sync.@@ -133,7 +134,6 @@ export const MAX_PERSISTED_FEEDBACK = 100;// createServiceErrorMapper), mirroring the universeBuilder convention.export const ERR_NOT_FOUND = 'NOT_FOUND';export const ERR_VALIDATION = 'VALIDATION_ERROR';-export const makeErr = (message, code) => Object.assign(new Error(message), { code });/*** Normalize a single feedback reaction (#2657, Phase 2). A reaction MUST carry a@@ -563,13 +563,13 @@ export function assertValidSchedule(schedule) {const recurrence = schedule?.kind === 'RECURRENCE' ? schedule.recurrence : null;if (recurrence) {if (!isValidRecurrence(recurrence)) {- throw makeErr('Invalid schedule: could not derive a valid recurrence', ERR_VALIDATION);+ throw codedError('Invalid schedule: could not derive a valid recurrence', ERR_VALIDATION);}return recurrence;}const cron = commissionToCron(schedule);if (!cron || !isValidCron(cron)) {- throw makeErr('Invalid schedule: could not derive a valid cron expression', ERR_VALIDATION);+ throw codedError('Invalid schedule: could not derive a valid cron expression', ERR_VALIDATION);}return cron;}@@ -641,7 +641,7 @@ export async function listCommissions({ strict = false } = {}) {export async function getCommission(id) {const raw = await commissionStore().readRaw(id);const rec = raw ? sanitizeCommission(raw) : null;- if (!rec) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);+ if (!rec) throw codedError(`Commission not found: ${id}`, ERR_NOT_FOUND);// Lazily migrate any legacy inline feedback (Phase 2 storage) into the// federated store, then clear it — so the scheduler's pre-fire read and the// route GET always see the federated feedback even before the boot backfill@@ -753,7 +753,7 @@ export async function updateCommission(id, patch) {);return { next, changedFields };});- if (!merged) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);+ if (!merged) throw codedError(`Commission not found: ${id}`, ERR_NOT_FOUND);const { next: mergedRecord, changedFields } = merged;// Carry the CHANGED key set: the project reconciler only cares about `enabled`// and `assignment`, so an edit that touched neither skips its project lookup —@@ -787,7 +787,7 @@ export async function deleteCommission(id) {await store.writeRaw(id, { ...current, deleted: true, deletedAt: now, updatedAt: now, briefUpdatedAt: now });return true;});- if (!existed) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);+ if (!existed) throw codedError(`Commission not found: ${id}`, ERR_NOT_FOUND);// Re-sync schedules (the scheduler cancels the now-tombstoned commission's cron)// and push the tombstone to peers.commissionEvents.emit('commission:changed', { id, action: 'delete' });@@ -901,7 +901,7 @@ export async function submitCommissionFeedback(id, input) {// The UI always rates a specific run; reject a runId that isn't on the record// so feedback can't dangle against a non-existent run.if (input?.runId && !commission.runs.some((r) => r.id === input.runId)) {- throw makeErr(`Run not found on commission: ${input.runId}`, ERR_VALIDATION);+ throw codedError(`Run not found on commission: ${input.runId}`, ERR_VALIDATION);}// Write to the FEDERATED feedback store (#2686): one record per reaction,// deterministic id per run so a re-rating LWW-updates in place (one reaction@@ -914,7 +914,7 @@ export async function submitCommissionFeedback(id, input) {note: input?.note,tags: input?.tags,});- if (!rec) throw makeErr('Invalid feedback: a non-zero rating (up/down) is required', ERR_VALIDATION);+ if (!rec) throw codedError('Invalid feedback: a non-zero rating (up/down) is required', ERR_VALIDATION);emitRecordInvalidated(CREATIVE_COMMISSION_KIND, id);commission.feedback = await listFeedbackForCommission(id).catch(() => []);return commission;diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex a1ed404f1a..028357f354 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -14,6 +14,7 @@import { join } from 'path';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';import { HHMM_STRICT_RE } from '../lib/timezone.js';+import { codedError } from '../lib/codedError.js';const STATE_PATH = join(PATHS.data, 'dashboard-layouts.json');@@ -21,7 +22,6 @@ const STATE_PATH = join(PATHS.data, 'dashboard-layouts.json');// without string-matching on err.message (which breaks on rename/i18n).export const ERR_NOT_FOUND = 'NOT_FOUND';export const ERR_BUILTIN_PROTECTED = 'BUILTIN_PROTECTED';-const makeErr = (message, code) => Object.assign(new Error(message), { code });// Widget ids are the contract between this file and the client registry —// see client/src/components/dashboard/widgetRegistry.jsx. If a layout refers@@ -455,7 +455,7 @@ export function setActiveLayout(id) {return queueLayoutsWrite(async () => {const state = await getState();if (!state.layouts.find((l) => l.id === id)) {- throw makeErr(`Unknown layout id: ${id}`, ERR_NOT_FOUND);+ throw codedError(`Unknown layout id: ${id}`, ERR_NOT_FOUND);}const next = { activeLayoutId: id, layouts: state.layouts };await atomicWrite(STATE_PATH, next);@@ -507,8 +507,8 @@ export function deleteLayout(id) {return queueLayoutsWrite(async () => {const state = await getState();const target = state.layouts.find((l) => l.id === id);- if (!target) throw makeErr(`Unknown layout id: ${id}`, ERR_NOT_FOUND);- if (target.builtIn) throw makeErr(`Cannot delete built-in layout: ${id}`, ERR_BUILTIN_PROTECTED);+ if (!target) throw codedError(`Unknown layout id: ${id}`, ERR_NOT_FOUND);+ if (target.builtIn) throw codedError(`Cannot delete built-in layout: ${id}`, ERR_BUILTIN_PROTECTED);const remaining = state.layouts.filter((l) => l.id !== id);// Guard against the pathological case where the JSON was hand-edited to// remove every built-in — fall back to reseeding defaults rather thandiff --git a/server/services/importer.js b/server/services/importer.jsindex f7ff6275b6..f6c262b2ea 100644--- a/server/services/importer.js+++ b/server/services/importer.js@@ -43,6 +43,7 @@ import { isStr } from '../lib/textUtils.js';import {deriveImportId, getImportSession, recordImportProgress, withImportLock, SESSION_STATUS,} from './importerSessions.js';+import { codedError } from '../lib/codedError.js';// Surfaced to the route layer so the importer's policy errors become 400s// with stable codes.@@ -53,7 +54,6 @@ export const ERR_LOCKED = 'IMPORTER_LOCKED';// rolled back. Retrying commit is safe (merges are idempotent).export const ERR_PARTIAL_COMMIT_ISSUES = 'IMPORTER_PARTIAL_COMMIT_ISSUES';-const makeErr = (message, code) => Object.assign(new Error(message), { code });// Ordered stages surfaced to the client's live progress checklist during the// analyze phase. Emitted in the `start` frame so the client renders the list@@ -192,10 +192,10 @@ const normName = (s) => String(s || '').trim().toLowerCase();// message live in one place.function assertSourceWithinLimit(source) {if (!isStr(source) || !source.trim()) {- throw makeErr('source is required', ERR_VALIDATION);+ throw codedError('source is required', ERR_VALIDATION);}if (source.length > IMPORTER_SOURCE_CHAR_LIMIT) {- throw makeErr(+ throw codedError(`Source is ${source.length.toLocaleString()} chars — exceeds the ${IMPORTER_SOURCE_CHAR_LIMIT.toLocaleString()}-char ceiling. Trim the source or wait for chunked-extraction support.`,ERR_VALIDATION,);@@ -270,13 +270,13 @@ export function mergeSeasons(existingSeasons, incomingSeasons, buildSeasonImpl =for (const s of incomingSeasons) {if (Number.isInteger(s?.number) && s.number >= 1) {if (s.number > SEASON_NUMBER_MAX) {- throw makeErr(+ throw codedError(`mergeSeasons: explicit season number ${s.number} exceeds the max of ${SEASON_NUMBER_MAX}.`,ERR_VALIDATION,);}if (seenIncomingNumbers.has(s.number)) {- throw makeErr(+ throw codedError(`mergeSeasons: duplicate explicit season number ${s.number} in incoming list — caller must pre-dedupe.`,ERR_VALIDATION,);@@ -304,7 +304,7 @@ export function mergeSeasons(existingSeasons, incomingSeasons, buildSeasonImpl =num = s.number;} else {if (nextFreeNumber > SEASON_NUMBER_MAX) {- throw makeErr(+ throw codedError(`Cannot auto-assign season number — next free slot (${nextFreeNumber}) exceeds the max of ${SEASON_NUMBER_MAX}. Free up a season slot or set season.number explicitly.`,ERR_VALIDATION,);@@ -629,7 +629,7 @@ async function proposeIssues({ seriesName, contentType, source, typeFlags, arcSu// letting it sail through to a confusing commit-time 400.const oversized = mechanical.findIndex((iss) => iss.proseExcerpt.length > IMPORTER_PROSE_EXCERPT_MAX);if (oversized !== -1) {- throw makeErr(+ throw codedError(`Issue ${oversized + 1} of the comic split is ${mechanical[oversized].proseExcerpt.length.toLocaleString()} chars — over the ${IMPORTER_PROSE_EXCERPT_MAX.toLocaleString()}-char per-issue limit. Add ISSUE/PAGE headers so it splits into smaller issues, or split the source.`,ERR_VALIDATION,);@@ -749,10 +749,10 @@ export async function analyzeImport({targetIssueCount,} = {}) {if (!isStr(universeName) || !universeName.trim()) {- throw makeErr('universeName is required', ERR_VALIDATION);+ throw codedError('universeName is required', ERR_VALIDATION);}if (!isStr(seriesName) || !seriesName.trim()) {- throw makeErr('seriesName is required', ERR_VALIDATION);+ throw codedError('seriesName is required', ERR_VALIDATION);}assertSourceWithinLimit(source);@@ -774,7 +774,7 @@ export async function analyzeImport({// FAST — no point spending heavy-tier tokens to extract an arc the commit// phase will refuse to apply.if (existingSeries?.locked?.arc === true) {- throw makeErr(+ throw codedError(`Series "${existingSeries.name}" has a locked arc. Unlock it on the Arc Canvas before importing — or rename the import's series so a fresh series is created.`,ERR_LOCKED,);@@ -1012,7 +1012,7 @@ export async function retryIssueSplit({} = {}) {assertSourceWithinLimit(source);if (!IMPORTER_CONTENT_TYPES.includes(contentType)) {- throw makeErr(`Unknown contentType "${contentType}"`, ERR_VALIDATION);+ throw codedError(`Unknown contentType "${contentType}"`, ERR_VALIDATION);}const userRequestedCount = Number.isFinite(targetIssueCount) && targetIssueCount > 0;const promptSeriesName = isStr(seriesName) && seriesName.trim() ? seriesName.trim() : 'the series';@@ -1068,10 +1068,10 @@ async function commitImportOnce({// a per-series destructive replace would be too coarse). Default false.replaceMode = false,} = {}) {- if (!isStr(universeId)) throw makeErr('universeId is required', ERR_VALIDATION);- if (!isStr(seriesId)) throw makeErr('seriesId is required', ERR_VALIDATION);+ if (!isStr(universeId)) throw codedError('universeId is required', ERR_VALIDATION);+ if (!isStr(seriesId)) throw codedError('seriesId is required', ERR_VALIDATION);if (!Array.isArray(issues) || issues.length === 0) {- throw makeErr('At least one issue is required', ERR_VALIDATION);+ throw codedError('At least one issue is required', ERR_VALIDATION);}// Read for validation (universeId/seriesId linkage, lock checks, the@@ -1095,12 +1095,12 @@ async function commitImportOnce({// legacy data — flag it so the caller decides rather than silently linking.if (series.universeId !== universe.id) {if (series.universeId) {- throw makeErr(+ throw codedError(`Series "${series.name}" is linked to a different universe — commit refused to avoid cross-linking.`,ERR_VALIDATION,);}- throw makeErr(+ throw codedError(`Series "${series.name}" has no universeId — commit refused. Link the series to a universe explicitly before importing.`,ERR_VALIDATION,);@@ -1131,7 +1131,7 @@ async function commitImportOnce({}if (series.locked?.arc === true) {- throw makeErr(+ throw codedError(`Series "${series.name}" has a locked arc — commit refused. Unlock the arc to import.`,ERR_LOCKED,);@@ -1145,7 +1145,7 @@ async function commitImportOnce({for (let i = 0; i < issues.length; i++) {const proposal = issues[i];if (!isStr(proposal?.title) || !proposal.title.trim()) {- throw makeErr(+ throw codedError(`Issue at position ${i + 1} is missing a title — commit refused before any state changed.`,ERR_VALIDATION,);@@ -1161,7 +1161,7 @@ async function commitImportOnce({&& (!Number.isInteger(proposal.arcPosition)|| proposal.arcPosition < 1|| proposal.arcPosition > ARC_POSITION_MAX)) {- throw makeErr(+ throw codedError(`Issue at position ${i + 1} has invalid arcPosition (must be integer 1..${ARC_POSITION_MAX}) — commit refused before any state changed.`,ERR_VALIDATION,);@@ -1171,7 +1171,7 @@ async function commitImportOnce({// a direct caller doesn't seed `stages.prose` with garbage.if (proposal.proseExcerpt !== undefined && proposal.proseExcerpt !== null) {if (!isStr(proposal.proseExcerpt) || !proposal.proseExcerpt.trim()) {- throw makeErr(+ throw codedError(`Issue at position ${i + 1} has invalid proseExcerpt (must be non-empty when present) — commit refused before any state changed.`,ERR_VALIDATION,);@@ -1188,7 +1188,7 @@ async function commitImportOnce({const pos = issues[i]?.arcPosition;if (Number.isInteger(pos) && pos >= 1) {if (seenArcPositions.has(pos)) {- throw makeErr(+ throw codedError(`Duplicate arcPosition ${pos} at issue position ${i + 1} — commit refused before any state changed.`,ERR_VALIDATION,);@@ -1230,7 +1230,7 @@ async function commitImportOnce({for (let i = 0; i < issues.length; i++) {const pos = issues[i]?.arcPosition;if (Number.isInteger(pos) && pos >= 1 && existingArcPositions.has(pos)) {- throw makeErr(+ throw codedError(`Issue at position ${i + 1} explicit arcPosition ${pos} collides with an existing issue on the series — commit refused before any state changed. Either renumber the incoming issue or omit arcPosition to auto-assign.`,ERR_VALIDATION,);@@ -1244,7 +1244,7 @@ async function commitImportOnce({return proposal;}if (nextFreeArcPos > ARC_POSITION_MAX) {- throw makeErr(+ throw codedError(`Cannot auto-assign arcPosition — next free slot (${nextFreeArcPos}) exceeds the max of ${ARC_POSITION_MAX}. Free up a position or set issue.arcPosition explicitly.`,ERR_VALIDATION,);@@ -1263,13 +1263,13 @@ async function commitImportOnce({const s = seasons[i];if (s?.number !== undefined && s?.number !== null) {if (!Number.isInteger(s.number) || s.number < 1 || s.number > SEASON_NUMBER_MAX) {- throw makeErr(+ throw codedError(`Season at position ${i + 1} has invalid number (must be integer 1..${SEASON_NUMBER_MAX}) — commit refused before any state changed.`,ERR_VALIDATION,);}if (seenSeasonNumbers.has(s.number)) {- throw makeErr(+ throw codedError(`Duplicate season number ${s.number} at position ${i + 1} — commit refused before any state changed.`,ERR_VALIDATION,);@@ -1328,7 +1328,7 @@ async function commitImportOnce({? ` ${deletedIds.length} issue${deletedIds.length === 1 ? '' : 's'} were already deleted before the failure (${deletedIds.join(', ')}) and cannot be recovered.`: '';const remainingMsg = ` ${remainingIds.length} issue${remainingIds.length === 1 ? '' : 's'} remain on disk (${remainingIds.join(', ')}, including the failed one); retry will wipe them.`;- throw makeErr(+ throw codedError(`Replace mode aborted on first delete failure — issue ${ex.id} could not be deleted (${failed.message}). No universe, series, or new-issue writes were performed.${deletedMsg}${remainingMsg} Resolve the underlying error and retry.`,ERR_VALIDATION,);diff --git a/server/services/mediaAnnotations.js b/server/services/mediaAnnotations.jsindex 64db495f31..f9b5655aaf 100644--- a/server/services/mediaAnnotations.js+++ b/server/services/mediaAnnotations.js@@ -11,11 +11,11 @@ import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { isValidKey } from '../lib/mediaItemKey.js';import { getInstanceId, UNKNOWN_INSTANCE_ID } from './instanceIdentity.js';import { resolveLocalAuthorName } from './sharing/annotationIdentity.js';+import { codedError } from '../lib/codedError.js';const STATE_PATH = join(PATHS.data, 'media-annotations.json');export const ERR_VALIDATION = 'VALIDATION_ERROR';-const makeErr = (message, code) => Object.assign(new Error(message), { code });export const NOTE_MAX_LENGTH = 2000;@@ -242,23 +242,23 @@ export async function mergePeerAnnotations(payload) {* Returns the post-write projection `{ own, others }` for this key.*/export async function setAnnotation(key, patch) {- if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);+ if (!isValidKey(key)) throw codedError(`Invalid key: ${key}`, ERR_VALIDATION);if (!patch || typeof patch !== 'object') {- throw makeErr('patch must include starred and/or note', ERR_VALIDATION);+ throw codedError('patch must include starred and/or note', ERR_VALIDATION);}const hasStarred = Object.prototype.hasOwnProperty.call(patch, 'starred');const hasNote = Object.prototype.hasOwnProperty.call(patch, 'note');if (!hasStarred && !hasNote) {- throw makeErr('patch must include starred and/or note', ERR_VALIDATION);+ throw codedError('patch must include starred and/or note', ERR_VALIDATION);}if (hasStarred && typeof patch.starred !== 'boolean') {- throw makeErr('starred must be boolean', ERR_VALIDATION);+ throw codedError('starred must be boolean', ERR_VALIDATION);}if (hasNote && typeof patch.note !== 'string') {- throw makeErr('note must be string', ERR_VALIDATION);+ throw codedError('note must be string', ERR_VALIDATION);}if (hasNote && patch.note.length > NOTE_MAX_LENGTH) {- throw makeErr(`note exceeds max length (${NOTE_MAX_LENGTH})`, ERR_VALIDATION);+ throw codedError(`note exceeds max length (${NOTE_MAX_LENGTH})`, ERR_VALIDATION);}return queueWrite(async () => {@@ -268,7 +268,7 @@ export async function setAnnotation(key, patch) {resolveLocalAuthorName().catch(() => ''),]);if (!localInstanceId || localInstanceId === UNKNOWN_INSTANCE_ID) {- throw makeErr('Local instance identity not initialized', ERR_VALIDATION);+ throw codedError('Local instance identity not initialized', ERR_VALIDATION);}const priorAuthors = all[key]?.authors ?? {};diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex d22f5a1989..6f25c437d1 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -35,11 +35,11 @@ import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,withBaseHashFlushBatch,} from '../lib/conflictJournal.js';+import { codedError } from '../lib/codedError.js';export const ERR_NOT_FOUND = 'NOT_FOUND';export const ERR_DUPLICATE = 'DUPLICATE';export const ERR_VALIDATION = 'VALIDATION_ERROR';-const makeErr = (message, code) => Object.assign(new Error(message), { code });export const NAME_MAX_LENGTH = 80;export const DESCRIPTION_MAX_LENGTH = 500;@@ -68,7 +68,7 @@ const COLLECTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;// id, so they don't need this; the write paths throw before `loadOne` runs.const assertCollectionId = (id) => {if (typeof id !== 'string' || !COLLECTION_ID_PATTERN.test(id)) {- throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);}};@@ -252,8 +252,8 @@ export async function listCollectionIds() {export async function getCollection(id, { includeDeleted = false } = {}) {const c = await store().loadOne(id);- if (!c) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);- if (c.deleted === true && !includeDeleted) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (!c) throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (c.deleted === true && !includeDeleted) throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);return c;}@@ -281,10 +281,10 @@ export async function createCollection({ name, description = '', source = 'user'// listCollections() read would silently drop.const trimmedName = typeof name === 'string' ? name.trim() : '';if (!trimmedName || trimmedName.length > NAME_MAX_LENGTH) {- throw makeErr('Collection name is required (1..' + NAME_MAX_LENGTH + ' chars)', ERR_VALIDATION);+ throw codedError('Collection name is required (1..' + NAME_MAX_LENGTH + ' chars)', ERR_VALIDATION);}if (!COLLECTION_SOURCES.includes(source)) {- throw makeErr(`source must be one of ${COLLECTION_SOURCES.join('|')}`, ERR_VALIDATION);+ throw codedError(`source must be one of ${COLLECTION_SOURCES.join('|')}`, ERR_VALIDATION);}const trimmedDescription = typeof description === 'string'? description.trim().slice(0, DESCRIPTION_MAX_LENGTH)@@ -329,7 +329,7 @@ export async function createCollection({ name, description = '', source = 'user'export async function findOrCreateCollectionByName({ name, description = '', universeId = null }) {const trimmed = typeof name === 'string' ? name.trim() : '';if (!trimmed || trimmed.length > NAME_MAX_LENGTH) {- throw makeErr('Collection name is required (1..' + NAME_MAX_LENGTH + ' chars)', ERR_VALIDATION);+ throw codedError('Collection name is required (1..' + NAME_MAX_LENGTH + ' chars)', ERR_VALIDATION);}const trimmedDescription = typeof description === 'string'? description.trim().slice(0, DESCRIPTION_MAX_LENGTH)@@ -493,10 +493,10 @@ export async function findCollectionByUniverseId(universeId) {*/export async function findOrCreateUniverseCollection({ universeId, universeName, description = '' }) {if (!universeId || typeof universeId !== 'string') {- throw makeErr('universeId is required', ERR_VALIDATION);+ throw codedError('universeId is required', ERR_VALIDATION);}if (typeof universeName !== 'string' || !universeName.trim()) {- throw makeErr('universeName is required', ERR_VALIDATION);+ throw codedError('universeName is required', ERR_VALIDATION);}// Normalize the universeId once so lookup and storage both key on the// same string. Without this, an overlong id (e.g. from a malformed@@ -571,10 +571,10 @@ export async function findCollectionBySeriesId(seriesId) {export async function findOrCreateSeriesCollection({ seriesId, seriesName, description = '' }) {if (!seriesId || typeof seriesId !== 'string') {- throw makeErr('seriesId is required', ERR_VALIDATION);+ throw codedError('seriesId is required', ERR_VALIDATION);}if (typeof seriesName !== 'string' || !seriesName.trim()) {- throw makeErr('seriesName is required', ERR_VALIDATION);+ throw codedError('seriesName is required', ERR_VALIDATION);}const normalizedSeriesId = seriesId.slice(0, SERIES_ID_MAX);const desiredName = seriesCollectionNameFor(seriesName);@@ -709,8 +709,8 @@ export async function updateCollection(id, patch) {assertCollectionId(id);const merged = await store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);- if (cur.deleted === true) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted === true) throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);// Product/UI constraint: universe-linked collections own their visible// name. The name is the user-facing identity of a universe's bucket, so// renaming it independent of the universe is confusing — the supported@@ -719,13 +719,13 @@ export async function updateCollection(id, patch) {// this lock exists to keep what the user sees consistent with the// universe's name, not to prevent routing forks.if ('name' in patch && cur.universeId && patch.name !== cur.name) {- throw makeErr(+ throw codedError('This collection is linked to a Universe — rename the universe to rename it.',ERR_VALIDATION,);}if ('name' in patch && cur.seriesId && patch.name !== cur.name) {- throw makeErr(+ throw codedError('This collection is linked to a Series — rename the series to rename it.',ERR_VALIDATION,);@@ -734,7 +734,7 @@ export async function updateCollection(id, patch) {// also reject up-front so the API gives a clear error rather than silently// dropping the cover.if (patch.coverKey != null && !cur.items.find((it) => itemKey(it) === patch.coverKey)) {- throw makeErr('coverKey must reference an item in this collection', ERR_VALIDATION);+ throw codedError('coverKey must reference an item in this collection', ERR_VALIDATION);}const merged = {...cur,@@ -773,7 +773,7 @@ export async function deleteCollection(id) {assertCollectionId(id);const { universeId: deletedUniverseId, seriesId: deletedSeriesId, alreadyDeleted } = await store().queueRecordWrite(id, async () => {const target = await store().loadOne(id);- if (!target) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (!target) throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);// Idempotent on an already-tombstoned record: re-stamping deletedAt/// updatedAt would make an old tombstone look "newer" to a peer's LWW (and// re-emitting churns the sync pipeline). Return without rewriting or@@ -804,11 +804,11 @@ export async function deleteCollection(id) {// Returns a normalized `{ kind, ref }` so callers don't re-trim.const validateItemInput = (item) => {if (!item || !ITEM_KIND.has(item.kind)) {- throw makeErr('item.kind must be "image" or "video"', ERR_VALIDATION);+ throw codedError('item.kind must be "image" or "video"', ERR_VALIDATION);}const ref = typeof item.ref === 'string' ? item.ref.trim() : '';if (!ref || ref.length > REF_MAX_LENGTH || ref.includes(':')) {- throw makeErr('item.ref invalid (empty, too long, or contains ":")', ERR_VALIDATION);+ throw codedError('item.ref invalid (empty, too long, or contains ":")', ERR_VALIDATION);}// Mirror sanitizeItem's path-traversal rejection so the write path can't// persist a ref that the next listCollections() read would silently drop@@ -818,10 +818,10 @@ const validateItemInput = (item) => {// mirror sanitizeItem exactly or local addItem rejects refs that peer// sync would accept (and vice versa).if (ref.includes('/') || ref.includes('\\')) {- throw makeErr('item.ref invalid (contains path separators)', ERR_VALIDATION);+ throw codedError('item.ref invalid (contains path separators)', ERR_VALIDATION);}if (ref === '.' || ref === '..') {- throw makeErr('item.ref invalid (parent-directory segment)', ERR_VALIDATION);+ throw codedError('item.ref invalid (parent-directory segment)', ERR_VALIDATION);}return { kind: item.kind, ref };};@@ -831,16 +831,16 @@ export async function addItem(id, item) {assertCollectionId(id);const merged = await store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);// A soft-deleted collection behaves as not-found for mutations (matches// updateCollection) — never resurrect a tombstone or churn its timestamps.- if (cur.deleted === true) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted === true) throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);const key = `${kind}:${ref}`;if (cur.items.find((it) => itemKey(it) === key)) {- throw makeErr(`Item already in collection: ${key}`, ERR_DUPLICATE);+ throw codedError(`Item already in collection: ${key}`, ERR_DUPLICATE);}if (cur.items.length >= ITEMS_MAX) {- throw makeErr(`Collection full (limit ${ITEMS_MAX})`, ERR_VALIDATION);+ throw codedError(`Collection full (limit ${ITEMS_MAX})`, ERR_VALIDATION);}const updated = {...cur,@@ -879,25 +879,25 @@ export async function addItem(id, item) {* Returns the post-write collection plus counts: `{ collection, added, removed }`.*/export async function bulkUpdateCollectionItems(id, { add = [], remove = [] } = {}) {- if (!Array.isArray(add)) throw makeErr('add must be an array', ERR_VALIDATION);- if (!Array.isArray(remove)) throw makeErr('remove must be an array', ERR_VALIDATION);+ if (!Array.isArray(add)) throw codedError('add must be an array', ERR_VALIDATION);+ if (!Array.isArray(remove)) throw codedError('remove must be an array', ERR_VALIDATION);// Validate every `add` entry up front so a single bad item doesn't leave// a partially-applied batch behind.const cleanAdd = add.map(validateItemInput);for (const key of remove) {if (typeof key !== 'string' || !key) {- throw makeErr('remove keys must be non-empty strings of the form "<kind>:<ref>"', ERR_VALIDATION);+ throw codedError('remove keys must be non-empty strings of the form "<kind>:<ref>"', ERR_VALIDATION);}}assertCollectionId(id);const result = await store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);// A soft-deleted collection behaves as not-found for mutations (matches// updateCollection) — never resurrect a tombstone or churn its timestamps.- if (cur.deleted === true) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted === true) throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);const removeSet = new Set(remove);const remainingItems = cur.items.filter((it) => !removeSet.has(itemKey(it)));@@ -919,7 +919,7 @@ export async function bulkUpdateCollectionItems(id, { add = [], remove = [] } =const nextItems = [...remainingItems, ...additions];if (nextItems.length > ITEMS_MAX) {- throw makeErr(`Collection full (limit ${ITEMS_MAX})`, ERR_VALIDATION);+ throw codedError(`Collection full (limit ${ITEMS_MAX})`, ERR_VALIDATION);}// Drop a cover that pointed at a now-removed item — matches the@@ -947,13 +947,13 @@ export async function removeItem(id, key) {assertCollectionId(id);const merged = await store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);// A soft-deleted collection behaves as not-found for mutations (matches// updateCollection) — never resurrect a tombstone or churn its timestamps.- if (cur.deleted === true) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted === true) throw codedError(`Collection not found: ${id}`, ERR_NOT_FOUND);const before = cur.items.length;const items = cur.items.filter((it) => itemKey(it) !== key);- if (items.length === before) throw makeErr(`Item not in collection: ${key}`, ERR_NOT_FOUND);+ if (items.length === before) throw codedError(`Item not in collection: ${key}`, ERR_NOT_FOUND);const updated = {...cur,items,diff --git a/server/services/mediaSketches.js b/server/services/mediaSketches.jsindex 0bbb754531..71b8ddf726 100644--- a/server/services/mediaSketches.js+++ b/server/services/mediaSketches.js@@ -32,11 +32,11 @@ import { randomUUID } from 'crypto';import { access } from 'fs/promises';import { PATHS, atomicWrite, readJSONFile, ensureDir, tryReadFile, unlinkGuarded } from '../lib/fileUtils.js';import { isValidKey as isValidMediaKey, parseKey } from '../lib/mediaItemKey.js';+import { codedError } from '../lib/codedError.js';const SKETCH_DIR = join(PATHS.data, 'media-sketches');export const ERR_VALIDATION = 'VALIDATION_ERROR';-const makeErr = (message, code) => Object.assign(new Error(message), { code });// Guardrails so a hand-rolled or malicious payload can't balloon a sidecar.export const MAX_STROKES = 5000;@@ -90,10 +90,10 @@ function sanitizeStroke(raw) {}export function sanitizeSketchInput(input) {- if (!input || typeof input !== 'object') throw makeErr('sketch payload required', ERR_VALIDATION);- if (!Array.isArray(input.strokes)) throw makeErr('strokes must be an array', ERR_VALIDATION);+ if (!input || typeof input !== 'object') throw codedError('sketch payload required', ERR_VALIDATION);+ if (!Array.isArray(input.strokes)) throw codedError('strokes must be an array', ERR_VALIDATION);if (!isFinitePositive(input.width) || !isFinitePositive(input.height)) {- throw makeErr('width and height must be positive numbers', ERR_VALIDATION);+ throw codedError('width and height must be positive numbers', ERR_VALIDATION);}const strokes = [];for (const raw of input.strokes) {@@ -104,7 +104,7 @@ export function sanitizeSketchInput(input) {let png = null;if (typeof input.png === 'string' && input.png) {const m = DATA_URL_PNG.exec(input.png);- if (!m) throw makeErr('png must be a data:image/png;base64 URL', ERR_VALIDATION);+ if (!m) throw codedError('png must be a data:image/png;base64 URL', ERR_VALIDATION);png = Buffer.from(m[1], 'base64');}return {@@ -117,7 +117,7 @@ export function sanitizeSketchInput(input) {/** Read the persisted sketch for a key, or null when none exists. */export async function getSketch(key) {- if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);+ if (!isValidKey(key)) throw codedError(`Invalid key: ${key}`, ERR_VALIDATION);// Read-only projection: saveSketch replaces the full canvas from explicit input, never this fallback.const data = await readJSONFile(jsonPathFor(key), null, { logError: false });if (!data || typeof data !== 'object' || !Array.isArray(data.strokes)) return null;@@ -133,7 +133,7 @@ export async function getSketch(key) {/** Raw flattened PNG bytes for a key, or null. */export async function getSketchPng(key) {- if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);+ if (!isValidKey(key)) throw codedError(`Invalid key: ${key}`, ERR_VALIDATION);return tryReadFile(pngPathFor(key), null); // Buffer | null}@@ -143,7 +143,7 @@ export async function getSketchPng(key) {* the init image, so it needs the path (not the bytes) to hand off to the runner.*/export async function getSketchPngPath(key) {- if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);+ if (!isValidKey(key)) throw codedError(`Invalid key: ${key}`, ERR_VALIDATION);const path = pngPathFor(key);return access(path).then(() => path).catch(() => null);}@@ -154,12 +154,12 @@ export async function getSketchPngPath(key) {* Returns the stored projection `{ key, width, height, strokes, updatedAt, hasPng }`.*/export async function saveSketch(key, input) {- if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);+ if (!isValidKey(key)) throw codedError(`Invalid key: ${key}`, ERR_VALIDATION);// A blank-canvas sketch (`sketch:<uuid>`) has no backing media; any other key// must be an `image:<ref>` — video and the rest of the shared vocabulary stay// unsupported (a video can't carry a stroke overlay in this UI).if (!isBlankSketchKey(key) && parseKey(key)?.kind !== 'image') {- throw makeErr('Only image media or blank-canvas sketches can be annotated', ERR_VALIDATION);+ throw codedError('Only image media or blank-canvas sketches can be annotated', ERR_VALIDATION);}const clean = sanitizeSketchInput(input);return withBackupAssetPublication(() => publishImageFiles([pngPathFor(key), jsonPathFor(key)], async () => {@@ -192,7 +192,7 @@ export async function saveSketch(key, input) {/** Remove a key's sidecar (json + png). Idempotent. */export async function removeSketch(key) {- if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);+ if (!isValidKey(key)) throw codedError(`Invalid key: ${key}`, ERR_VALIDATION);return withBackupAssetPublication(() => publishImageFiles([pngPathFor(key), jsonPathFor(key)], async () => {await unlinkGuarded(jsonPathFor(key)).catch(error => { if (error.code !== 'ENOENT') throw error; });await unlinkGuarded(pngPathFor(key)).catch(error => { if (error.code !== 'ENOENT') throw error; });diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex df489982b5..323a0c3055 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -17,12 +17,13 @@ import { getSeason } from '../seasons.js';import { ARC_LIMITS, READER_MAP_BEAT_KINDS, TICKING_CLOCK_LIMITS, buildSeason, cleanThemes, renderArcShapeGuidance, renderArcShapePositionSummary, sanitizeArc, sanitizeReaderMap, sanitizeSeason, sanitizeSeasonList, sanitizeTickingClock } from '../../../lib/storyArc.js';import { sanitizeCharacterArcList } from '../../../lib/seriesCharacterArc.js';import { runPromptRefineRaw, trimChanges } from '../refineHelpers.js';-import { ERR_VALIDATION, SHAPE_GUIDANCE_NONE, appendTickingClock, buildArcBaseContext, buildArcOverviewContext, buildNeighborVolumes, buildReaderMapContext, buildResolveContext, buildVerifyContext, compareIssuesByPosition, findingIdSet, makeErr, matchIssueForEpisodeEdit, matchResolvedFindings, renderVolumeFields, renderVolumeIssue, resolveWorldContext, seasonIdByNumberOf, shapeEpisodeResolutions, shapeFindings, shapeSeasonOutlines, shapeVerifyIssues } from './context.js';+import { ERR_VALIDATION, SHAPE_GUIDANCE_NONE, appendTickingClock, buildArcBaseContext, buildArcOverviewContext, buildNeighborVolumes, buildReaderMapContext, buildResolveContext, buildVerifyContext, compareIssuesByPosition, findingIdSet, matchIssueForEpisodeEdit, matchResolvedFindings, renderVolumeFields, renderVolumeIssue, resolveWorldContext, seasonIdByNumberOf, shapeEpisodeResolutions, shapeFindings, shapeSeasonOutlines, shapeVerifyIssues } from './context.js';+import { codedError } from '../../../lib/codedError.js';export async function generateArcOverview(seriesId, options = {}) {const series = await getSeries(seriesId);if (series.locked?.arc === true) {- throw makeErr(+ throw codedError('Arc is locked — unlock it on the Arc Canvas before regenerating',ERR_VALIDATION,);@@ -86,7 +87,7 @@ export async function generateArcOverview(seriesId, options = {}) {// (`locked.arcFields.readerMap`) does. The locked arc is read as INPUT here.export function assertReaderMapUnlocked(series) {if (series.locked?.arcFields?.readerMap === true) {- throw makeErr('Reader map is locked — unlock it before regenerating', ERR_VALIDATION);+ throw codedError('Reader map is locked — unlock it before regenerating', ERR_VALIDATION);}}@@ -126,7 +127,7 @@ export async function generateReaderMap(seriesId, options = {}) {// rather than letting the caller persist `readerMap: null` over an existing// map (silent data loss).if (!readerMap) {- throw makeErr('LLM returned an empty reader map — try regenerating', ERR_VALIDATION);+ throw codedError('LLM returned an empty reader map — try regenerating', ERR_VALIDATION);}return { readerMap, raw: content, runId, providerId, model };}@@ -160,7 +161,7 @@ export async function refineReaderMap(seriesId, feedback, options = {}) {// nothing usable (mirrors the AGENTS.md absent-vs-empty rule).const safeReaderMap = readerMap || arc.readerMap || null;if (!safeReaderMap) {- throw makeErr('LLM returned an empty reader map and there is none to preserve', ERR_VALIDATION);+ throw codedError('LLM returned an empty reader map and there is none to preserve', ERR_VALIDATION);}// When the refine produced nothing usable and we fell back to the existing// map, the LLM's `changes`/`rationale` describe an attempt that was DISCARDED@@ -193,7 +194,7 @@ export async function refineReaderMap(seriesId, feedback, options = {}) {export async function refineArc(seriesId, feedback, options = {}) {const series = await getSeries(seriesId);if (series.locked?.arc === true) {- throw makeErr('Arc is locked — unlock it on the Arc Canvas before refining', ERR_VALIDATION);+ throw codedError('Arc is locked — unlock it on the Arc Canvas before refining', ERR_VALIDATION);}const arc = series.arc || {};const { content, rationale, runId, providerId, model } = await runPromptRefineRaw({@@ -248,7 +249,7 @@ export async function refineArc(seriesId, feedback, options = {}) {// because every field above falls back to the current arc, means the current// arc was ALSO empty and the LLM added nothing. Nothing to preserve, so error.if (!refinedArc) {- throw makeErr('LLM returned an empty arc and there is none to preserve', ERR_VALIDATION);+ throw codedError('LLM returned an empty arc and there is none to preserve', ERR_VALIDATION);}return { arc: refinedArc, changes: trimChanges(content.changes), rationale, runId, providerId, model };}diff --git a/server/services/pipeline/arcPlanner/completenessPass.js b/server/services/pipeline/arcPlanner/completenessPass.jsindex 0e3230ba5c..1603212a31 100644--- a/server/services/pipeline/arcPlanner/completenessPass.js+++ b/server/services/pipeline/arcPlanner/completenessPass.js@@ -13,7 +13,8 @@ import { getSeries } from '../series.js';import { STAGE_OUTPUT_MAX } from '../issues.js';import { getSeriesCanon } from '../seriesCanon.js';import { canonicalStringify } from '../../../lib/objects.js';-import { ERR_VALIDATION, MANUSCRIPT_STAGES, VERIFY_SEVERITIES, buildArcBaseContext, collectManuscriptSections, makeErr, manuscriptSectionHeader, sectionsCorpus } from './context.js';+import { ERR_VALIDATION, MANUSCRIPT_STAGES, VERIFY_SEVERITIES, buildArcBaseContext, collectManuscriptSections, manuscriptSectionHeader, sectionsCorpus } from './context.js';+import { codedError } from '../../../lib/codedError.js';// ── Manuscript completeness ("finish the draft") ──────────────────────────// Unlike verifyArc/verifyVolume (which read synopsis/beats from idea.input /@@ -215,7 +216,7 @@ export async function analyzeManuscriptCompleteness(seriesId, options = {}) {// guard below and get graded as if it were a drafted manuscript.const sections = await collectManuscriptSections(seriesId, { stageOrder: MANUSCRIPT_STAGES });if (!sections.length) {- throw makeErr(+ throw codedError('No manuscript to analyze — write a comic script, prose, or teleplay on at least one issue first',ERR_VALIDATION,);diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.jsindex 1cd4d2fc2d..7b25af9352 100644--- a/server/services/pipeline/arcPlanner/context.js+++ b/server/services/pipeline/arcPlanner/context.js@@ -26,7 +26,6 @@ import { trimToClause } from '../../../lib/textUtils.js';export const ERR_VALIDATION = 'PIPELINE_ARC_VALIDATION';-export const makeErr = (message, code) => Object.assign(new Error(message), { code });export const VERIFY_SEVERITIES = new Set(['high', 'medium', 'low']);diff --git a/server/services/pipeline/arcPlanner/coverConcepts.js b/server/services/pipeline/arcPlanner/coverConcepts.jsindex 9ff9cd14dd..a7446540e9 100644--- a/server/services/pipeline/arcPlanner/coverConcepts.js+++ b/server/services/pipeline/arcPlanner/coverConcepts.js@@ -6,7 +6,8 @@import { runStagedLLM } from '../../stageRunner.js';import { getSeries, updateSeasonOnSeries } from '../series.js';import { assertStageUnlocked, getIssue, updateStageWithLatest } from '../issues.js';-import { ERR_VALIDATION, makeErr } from './context.js';+import { ERR_VALIDATION } from './context.js';+import { codedError } from '../../../lib/codedError.js';/*** Generate FRONT + BACK cover-art concepts for one volume (season). Returns@@ -24,7 +25,7 @@ export async function generateVolumeCoverConcepts(seriesId, seasonId, options =const seasons = series.seasons || [];const season = seasons.find((s) => s.id === seasonId);if (!season) {- throw makeErr(`Season not found on series: ${seasonId}`, ERR_VALIDATION);+ throw codedError(`Season not found on series: ${seasonId}`, ERR_VALIDATION);}const themesCsv = Array.isArray(season.themes) ? season.themes.join(', ') : '';const ctx = {@@ -107,7 +108,7 @@ export async function generateComicCoverConcepts(issueId, options = {}) {// invalid-target guard below instead of silently defaulting to 'both'.const target = options.target ?? 'both';if (target !== 'cover' && target !== 'backCover' && target !== 'both') {- throw makeErr(`Invalid target: ${target}`, ERR_VALIDATION);+ throw codedError(`Invalid target: ${target}`, ERR_VALIDATION);}const issue = await getIssue(issueId);// `commit: true` mutates `stages.comicPages.cover/backCover.script` —diff --git a/server/services/pipeline/arcPlanner/episodeSeedPass.js b/server/services/pipeline/arcPlanner/episodeSeedPass.jsindex fd14fd1245..0c5678488d 100644--- a/server/services/pipeline/arcPlanner/episodeSeedPass.js+++ b/server/services/pipeline/arcPlanner/episodeSeedPass.js@@ -11,9 +11,10 @@ import { composeStyleNotes } from '../../../lib/styleGuide.js';import { extractCanonFromProse } from '../../universeCanon.js';import { resolveSeriesLlmOverride } from '../../../lib/seriesLlmOverride.js';import { getSeriesPlanningCanon } from '../seriesCanon.js';-import { ARC_ROLES, ERR_VALIDATION, SEASON_LENGTH_PRESETS, SHAPE_GUIDANCE_NONE, appendCharacterFirstArcGuidance, appendTickingClock, lengthProfileForArcRole, makeErr, renderPriorSeason, resolveWorldContext } from './context.js';+import { ARC_ROLES, ERR_VALIDATION, SEASON_LENGTH_PRESETS, SHAPE_GUIDANCE_NONE, appendCharacterFirstArcGuidance, appendTickingClock, lengthProfileForArcRole, renderPriorSeason, resolveWorldContext } from './context.js';import { ARC_LIMITS } from '../../../lib/storyArc.js';import { trimToClause } from '../../../lib/textUtils.js';+import { codedError } from '../../../lib/codedError.js';/*** Build the context for one season's episode breakdown. `priorSeasonsContext`@@ -125,14 +126,14 @@ export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {const seasons = series.seasons || [];const season = seasons.find((s) => s.id === seasonId);if (!season) {- throw makeErr(`Season not found on series: ${seasonId}`, ERR_VALIDATION);+ throw codedError(`Season not found on series: ${seasonId}`, ERR_VALIDATION);}// Per-season lock — same semantics as the arc-level lock above, scoped to// this volume. Generating episodes seeds new issue records under the// season; a locked season's shape is frozen, so refuse before the LLM call.// Verify (read-only) stays available so the user can still inspect findings.if (season.locked === true) {- throw makeErr(+ throw codedError(`Season "${season.title || season.number}" is locked — unlock it before generating episodes`,ERR_VALIDATION,);@@ -141,7 +142,7 @@ export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {// against — fail loud so the user sees the misconfiguration instead of// getting back 8 episodes of "a thing happens then another thing".if (!season.synopsis?.trim() && !season.logline?.trim()) {- throw makeErr(+ throw codedError(`Season "${season.title || season.number}" has no synopsis or logline — fill at least one before generating episodes`,ERR_VALIDATION,);@@ -220,7 +221,7 @@ export async function commitEpisodesToIssues(seriesId, seasonId, episodes = [],.sort((a, b) => (a.number || 0) - (b.number || 0));const canReuse = reusable.length === episodes.length && episodes.length > 0;if (reuseUngrouped && episodes.length > 0 && ungrouped.length > 0 && !canReuse) {- throw makeErr(+ throw codedError(`Cannot safely seed ${episodes.length} generated episode(s): the series has ${ungrouped.length} ungrouped issue record(s), and ${reusable.length} are empty narrative placeholders. Reconcile that set before resuming so Autopilot does not duplicate or overwrite issue work.`,ERR_VALIDATION,);diff --git a/server/services/pipeline/arcPlanner/manuscriptDerive.js b/server/services/pipeline/arcPlanner/manuscriptDerive.jsindex 40ff9454ee..e9c800acd8 100644--- a/server/services/pipeline/arcPlanner/manuscriptDerive.js+++ b/server/services/pipeline/arcPlanner/manuscriptDerive.js@@ -9,8 +9,9 @@ import { getSeries, updateSeries } from '../series.js';import { getIssue, listIssues, recomputeIssueNumbersForSeries, updateIssue, updateStage } from '../issues.js';import { emitRecordUpdated, withReexportSuppressed } from '../../sharing/recordEvents.js';import { buildSeason, sanitizeArc, sanitizeSeason } from '../../../lib/storyArc.js';-import { ERR_VALIDATION, collectIssueSourceText, makeErr, shapeSeasonOutlines } from './context.js';+import { ERR_VALIDATION, collectIssueSourceText, shapeSeasonOutlines } from './context.js';import { commitSeasonsWithRemap, mergeSeasonsWithLocks } from './arcCore.js';+import { codedError } from '../../../lib/codedError.js';/*** Reverse-engineer an arc + seasons from EXISTING finished work (a concatenated@@ -29,13 +30,13 @@ export async function generateArcFromSource(seriesId, {} = {}) {const series = await getSeries(seriesId);if (series.locked?.arc === true) {- throw makeErr(+ throw codedError('Arc is locked — unlock it on the Arc Canvas before regenerating',ERR_VALIDATION,);}const source = String(sourceText || '').trim();- if (!source) throw makeErr('No source content to extract an arc from', ERR_VALIDATION);+ if (!source) throw codedError('No source content to extract an arc from', ERR_VALIDATION);const { content, runId, providerId, model } = await runStagedLLM('importer-arc-extract',{@@ -99,11 +100,11 @@ export function issueSynopsisFromSeason(season) {export async function deriveFromManuscript(seriesId, { providerOverride, modelOverride } = {}) {const series = await getSeries(seriesId);if (series.locked?.arc === true) {- throw makeErr('Arc is locked — unlock it on the Arc Canvas before deriving from the manuscript', ERR_VALIDATION);+ throw codedError('Arc is locked — unlock it on the Arc Canvas before deriving from the manuscript', ERR_VALIDATION);}const sourceText = await collectIssueSourceText(seriesId);if (!sourceText) {- throw makeErr(+ throw codedError('No issue manuscript to derive from — write a comic script, prose, or teleplay on at least one issue first',ERR_VALIDATION,);@@ -179,7 +180,7 @@ export async function seedIssueSynopsis(issueId, synopsis) {export async function commitDerivedManuscript(seriesId, { arc, bible, volume, issues = [] } = {}) {const series = await getSeries(seriesId);if (series.locked?.arc === true) {- throw makeErr('Arc is locked — unlock it on the Arc Canvas before applying', ERR_VALIDATION);+ throw codedError('Arc is locked — unlock it on the Arc Canvas before applying', ERR_VALIDATION);}// 1) Bible — top-level series fields the Arc Canvas sidebar reads. These arediff --git a/server/services/pipeline/comicPdf.js b/server/services/pipeline/comicPdf.jsindex b7c11d122e..a1c707b59e 100644--- a/server/services/pipeline/comicPdf.js+++ b/server/services/pipeline/comicPdf.js@@ -13,6 +13,7 @@ import { getIssue } from './issues.js';import { getSeries } from './series.js';import { pickRenderedFilename } from '../../lib/renderSlot.js';import { readImageFromMedia, embedImageBytes, fitImage } from '../../lib/pdfImageEmbed.js';+import { codedError } from '../../lib/codedError.js';export const PAGE_SIZES = Object.freeze({'us-letter': { width: 612, height: 792 },@@ -22,7 +23,6 @@ export const PAGE_SIZES = Object.freeze({export const DEFAULT_PAGE_SIZE = 'us-letter';export const ERR_NO_RENDERED_PAGES = 'PIPELINE_COMIC_PDF_NO_PAGES';-const makeErr = (message, code) => Object.assign(new Error(message), { code });const READ_OPTS = { subject: 'comic page image' };const EMBED_OPTS = { unsupportedCode: 'PIPELINE_COMIC_PDF_UNSUPPORTED_IMAGE' };@@ -59,7 +59,7 @@ export async function buildComicPdf(issueId, opts = {}) {const backCoverFilename = pickRenderedFilename(backCover);if (backCoverFilename) targets.push(backCoverFilename);if (targets.length === 0) {- throw makeErr('Issue has no rendered pages or cover yet', ERR_NO_RENDERED_PAGES);+ throw codedError('Issue has no rendered pages or cover yet', ERR_NO_RENDERED_PAGES);}// Read all files concurrently — disk I/O parallelizes cleanly; @cantoo/pdf-lib's@@ -97,7 +97,7 @@ export async function buildComicPdf(issueId, opts = {}) {}if (pageCount === 0) {- throw makeErr('No usable pages — all embeds failed', ERR_NO_RENDERED_PAGES);+ throw codedError('No usable pages — all embeds failed', ERR_NO_RENDERED_PAGES);}if (includeColophon) {diff --git a/server/services/pipeline/episodeVideo.js b/server/services/pipeline/episodeVideo.jsindex b6606ae6bc..20999ed5b0 100644--- a/server/services/pipeline/episodeVideo.js+++ b/server/services/pipeline/episodeVideo.js@@ -27,9 +27,9 @@ import { requestCreativeDirectorProjectStart } from '../creativeDirector/projectimport { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';import { buildPlaceByKey } from '../../lib/scenePrompt.js';import { getSettings } from '../settings.js';+import { codedError } from '../../lib/codedError.js';export const ERR_NO_STORYBOARDS = 'PIPELINE_EPISODE_NO_STORYBOARDS';-const makeErr = (message, code) => Object.assign(new Error(message), { code });const DEFAULT_SCENE_DURATION = 3;const MAX_SCENES = 30;@@ -89,7 +89,7 @@ export function buildTreatmentFromStoryboards({ issue, series, canon = null }) {const rawScenes = Array.isArray(storyboards?.scenes) ? storyboards.scenes : [];const usable = rawScenes.filter((s) => (s?.description || '').trim().length > 0);if (!usable.length) {- throw makeErr(+ throw codedError('Storyboards stage has no scenes with descriptions. Add scenes on the Storyboards stage first.',ERR_NO_STORYBOARDS,);diff --git a/server/services/pipeline/issueCrud.js b/server/services/pipeline/issueCrud.jsindex 7c578ec003..03bd84f73c 100644--- a/server/services/pipeline/issueCrud.js+++ b/server/services/pipeline/issueCrud.js@@ -17,11 +17,12 @@ import * as seriesSvc from './series.js';import {store, queueSeriesIssuesWrite, readState, readStateForSeries,saveIssueNow, saveIssuesNow, renumberInline, sanitizeIssue,- snapshotRunHistory, makeErr, ISSUE_ID_RE,+ snapshotRunHistory, ISSUE_ID_RE,ERR_NOT_FOUND, ERR_VALIDATION, ERR_DUPLICATE, ERR_SEASON_LOCKED,TITLE_MAX, SERIES_ID_MAX, ISSUES_PER_RESPONSE_MAX,} from './issuesShared.js';import { isStr, trimTo } from '../../lib/textUtils.js';+import { codedError } from '../../lib/codedError.js';export async function listIssues({seriesId = null,@@ -141,16 +142,16 @@ export async function listRecentIssues({ limit = 10, withHistory = true, includeexport async function getIssue(id, { includeDeleted = false } = {}) {const found = await store().loadOne(id);- if (!found) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- if (found.deleted && !includeDeleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ if (!found) throw codedError(`Issue not found: ${id}`, ERR_NOT_FOUND);+ if (found.deleted && !includeDeleted) throw codedError(`Issue not found: ${id}`, ERR_NOT_FOUND);return found;}export function createIssue(input = {}, { preloadedSeries = null } = {}) {const seriesId = trimTo(input.seriesId, SERIES_ID_MAX);- if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));+ if (!seriesId) return Promise.reject(codedError('seriesId is required', ERR_VALIDATION));const title = trimTo(input.title, TITLE_MAX);- if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));+ if (!title) return Promise.reject(codedError(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));return queueSeriesIssuesWrite(seriesId, async () => {const state = await readState();const next = sanitizeIssue({@@ -173,7 +174,7 @@ export function createIssue(input = {}, { preloadedSeries = null } = {}) {updatedAt: new Date().toISOString(),ephemeral: input.ephemeral === true,});- if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);+ if (!next) throw codedError('Invalid issue payload', ERR_VALIDATION);state.issues.push(next);await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR, preloadedSeries);await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));@@ -222,7 +223,7 @@ export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null, {const findLocked = (id) => (id ? seasons.find((s) => s.id === id && s.locked === true) : null);const blocker = findLocked(fromSeasonId) || findLocked(toSeasonId);if (blocker) {- throw makeErr(+ throw codedError(`Season "${blocker.title || blocker.number}" is locked — unlock it before reassigning issues`,ERR_SEASON_LOCKED,);@@ -280,7 +281,7 @@ export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null, {*/export function reassignIssuesToSeries(fromSeriesId, toSeriesId, { seasonIdMap = {} } = {}) {if (!isStr(fromSeriesId) || !isStr(toSeriesId) || fromSeriesId === toSeriesId) {- return Promise.reject(makeErr('reassignIssuesToSeries: fromSeriesId and toSeriesId must differ', ERR_VALIDATION));+ return Promise.reject(codedError('reassignIssuesToSeries: fromSeriesId and toSeriesId must differ', ERR_VALIDATION));}// This reads/mutates issues belonging to BOTH series (it moves source issues// and renumbers the destination), so serialize on both per-series queues, not@@ -322,22 +323,22 @@ export function reassignIssuesToSeries(fromSeriesId, toSeriesId, { seasonIdMap =*/export function insertIssueWithId(input = {}) {if (!isStr(input.id) || !ISSUE_ID_RE.test(input.id)) {- return Promise.reject(makeErr(`insertIssueWithId: invalid id "${input.id}" (expected iss-<uuid>)`, ERR_VALIDATION));+ return Promise.reject(codedError(`insertIssueWithId: invalid id "${input.id}" (expected iss-<uuid>)`, ERR_VALIDATION));}const seriesId = trimTo(input.seriesId, SERIES_ID_MAX);- if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));+ if (!seriesId) return Promise.reject(codedError('seriesId is required', ERR_VALIDATION));const title = trimTo(input.title, TITLE_MAX);- if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));+ if (!title) return Promise.reject(codedError(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));return queueSeriesIssuesWrite(seriesId, async () => {const state = await readState();// Tombstone-overwrite: same contract as universeBuilder.insertUniverseWithId.const existingIdx = state.issues.findIndex((i) => i.id === input.id);if (existingIdx >= 0 && !state.issues[existingIdx].deleted) {- throw makeErr(`Issue id already exists: ${input.id}`, ERR_DUPLICATE);+ throw codedError(`Issue id already exists: ${input.id}`, ERR_DUPLICATE);}const wasResurrection = existingIdx >= 0;const next = sanitizeIssue({ ...input, seriesId, title });- if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);+ if (!next) throw codedError('Invalid issue payload', ERR_VALIDATION);if (wasResurrection) {console.warn(`♻️ insertIssueWithId: overwriting tombstone for ${input.id}`);state.issues[existingIdx] = next;@@ -416,7 +417,7 @@ function mergeIssuePatch(cur, patch = {}) {stages: mergedStages,updatedAt: new Date().toISOString(),});- if (!merged) throw makeErr('Invalid issue payload', ERR_VALIDATION);+ if (!merged) throw codedError('Invalid issue payload', ERR_VALIDATION);return merged;}@@ -443,8 +444,8 @@ export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {return getIssue(id, { includeDeleted: true }).then((existing) =>queueSeriesIssuesWrite(existing.seriesId, async () => {const cur = await store().loadOne(id);- if (!cur) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Issue not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw codedError(`Issue not found: ${id}`, ERR_NOT_FOUND);const merged = mergeIssuePatch(cur, patch);await saveIssueNow(merged);emitRecordUpdated('series', merged.seriesId);@@ -460,9 +461,9 @@ export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {queueSeriesIssuesWrite(existing.seriesId, async () => {const state = await readState();const idx = state.issues.findIndex((i) => i.id === id);- if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ if (idx < 0) throw codedError(`Issue not found: ${id}`, ERR_NOT_FOUND);const cur = state.issues[idx];- if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw codedError(`Issue not found: ${id}`, ERR_NOT_FOUND);const merged = mergeIssuePatch(cur, patch);state.issues[idx] = merged;// A seasonId move affects both source and destination volumes, so full@@ -493,9 +494,9 @@ export function deleteIssue(id) {queueSeriesIssuesWrite(existing.seriesId, async () => {const state = await readState();const idx = state.issues.findIndex((i) => i.id === id);- if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ if (idx < 0) throw codedError(`Issue not found: ${id}`, ERR_NOT_FOUND);const cur = state.issues[idx];- if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw codedError(`Issue not found: ${id}`, ERR_NOT_FOUND);const seriesId = cur.seriesId;const now = new Date().toISOString();state.issues[idx] = { ...cur, deleted: true, deletedAt: now, updatedAt: now };diff --git a/server/services/pipeline/issueStages.js b/server/services/pipeline/issueStages.jsindex 57d5c4a8da..c172ab8cfd 100644--- a/server/services/pipeline/issueStages.js+++ b/server/services/pipeline/issueStages.js@@ -15,11 +15,12 @@ import { getIssue } from './issueCrud.js';import {store, queueSeriesIssuesWrite, readState, saveIssueNow, saveIssuesNow,sanitizeIssue, sanitizeTextStage, sanitizeVisualStage, sanitizeAudioStage,- snapshotRunHistory, makeErr,+ snapshotRunHistory,ERR_NOT_FOUND, ERR_VALIDATION,STAGE_IDS, TEXT_STAGE_IDS, VISUAL_STAGE_IDS, AUDIO_STAGE_IDS,} from './issuesShared.js';import { isStr } from '../../lib/textUtils.js';+import { codedError } from '../../lib/codedError.js';/*** Partial update to a single stage on an issue. Use this from generators so@@ -52,14 +53,14 @@ function mergeStagePatch(currentStage, stageId, patch, { snapshotPrior = false }export function updateStagesWithLatest(seriesId, updates = [], { snapshotPrior = false } = {}) {if (!isStr(seriesId) || !seriesId) {- return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));+ return Promise.reject(codedError('seriesId is required', ERR_VALIDATION));}if (!Array.isArray(updates) || updates.length === 0) {return Promise.resolve([]);}for (const { stageId } of updates) {if (!STAGE_IDS.includes(stageId)) {- return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));+ return Promise.reject(codedError(`Unknown stage: ${stageId}`, ERR_VALIDATION));}}@@ -75,9 +76,9 @@ export function updateStagesWithLatest(seriesId, updates = [], { snapshotPrior =const indexById = new Map(state.issues.map((i, idx) => [i.id, idx]));for (const update of updates) {const idx = indexById.get(update.issueId) ?? -1;- if (idx < 0) throw makeErr(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);+ if (idx < 0) throw codedError(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);const cur = state.issues[idx];- if (cur.deleted || cur.seriesId !== seriesId) throw makeErr(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);+ if (cur.deleted || cur.seriesId !== seriesId) throw codedError(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);const currentStage = cur.stages[update.stageId];const patch = update.computeFn(currentStage);if (isPlainObject(patch) && Object.keys(patch).length === 0) {@@ -94,7 +95,7 @@ export function updateStagesWithLatest(seriesId, updates = [], { snapshotPrior =stages: { ...cur.stages, [update.stageId]: nextStage },updatedAt: new Date().toISOString(),});- if (!mergedIssue) throw makeErr('Invalid issue payload', ERR_VALIDATION);+ if (!mergedIssue) throw codedError('Invalid issue payload', ERR_VALIDATION);state.issues[idx] = mergedIssue;results.push({ issue: mergedIssue, stage: mergedIssue.stages[update.stageId] });changed = true;@@ -129,14 +130,14 @@ export function updateStagesWithLatest(seriesId, updates = [], { snapshotPrior =*/export function restoreStageFromHistory(issueId, stageId, runId) {if (!TEXT_STAGE_IDS.includes(stageId)) {- return Promise.reject(makeErr(`Stage "${stageId}" does not support history restore`, ERR_VALIDATION));+ return Promise.reject(codedError(`Stage "${stageId}" does not support history restore`, ERR_VALIDATION));}if (!isStr(runId) || !runId) {- return Promise.reject(makeErr('runId is required', ERR_VALIDATION));+ return Promise.reject(codedError('runId is required', ERR_VALIDATION));}return updateStageWithLatest(issueId, stageId, (cur) => {const snapshot = (cur?.runHistory || []).find((entry) => entry.runId === runId);- if (!snapshot) throw makeErr(`Snapshot not found in stage history: ${runId}`, ERR_VALIDATION);+ if (!snapshot) throw codedError(`Snapshot not found in stage history: ${runId}`, ERR_VALIDATION);return {status: 'edited',input: snapshot.input || '',@@ -162,7 +163,7 @@ export function updateStageWithLatest(issueId, stageId, computeFn, { snapshotPriif (!STAGE_IDS.includes(stageId)) {// Validate before queueing so the caller gets an immediate rejection// rather than waiting in line for an error it already knows about.- return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));+ return Promise.reject(codedError(`Unknown stage: ${stageId}`, ERR_VALIDATION));}// Serialize on the SERIES tail (not the per-id queue) so a stage save can't// interleave with a series-wide renumber/bulk write that rewrites this same@@ -174,8 +175,8 @@ export function updateStageWithLatest(issueId, stageId, computeFn, { snapshotPri// lock for the freshest stage.const work = async () => {const cur = await store().loadOne(issueId);- if (!cur) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);- if (cur.deleted) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Issue not found: ${issueId}`, ERR_NOT_FOUND);+ if (cur.deleted) throw codedError(`Issue not found: ${issueId}`, ERR_NOT_FOUND);const currentStage = cur.stages[stageId];const patch = computeFn(currentStage);// Empty-patch fast path: a computeFn that returns `{}` is a "decided notdiff --git a/server/services/pipeline/issuesShared.js b/server/services/pipeline/issuesShared.jsindex cddb80667f..4c7d1d7452 100644--- a/server/services/pipeline/issuesShared.js+++ b/server/services/pipeline/issuesShared.js@@ -81,7 +81,6 @@ export const ERR_VALIDATION = 'PIPELINE_ISSUE_VALIDATION';export const ERR_DUPLICATE = 'PIPELINE_ISSUE_DUPLICATE';export const ERR_SEASON_LOCKED = 'PIPELINE_ISSUE_SEASON_LOCKED';export const ERR_STAGE_LOCKED = 'PIPELINE_STAGE_LOCKED';-const makeErr = (message, code) => Object.assign(new Error(message), { code });const ISSUE_ID_RE = /^iss-[A-Za-z0-9-]+$/;@@ -687,7 +686,6 @@ async function renumberInline(state, seriesId, fromSeasonId = null, preloadedSerexport {store,queueSeriesIssuesWrite,- makeErr,ISSUE_ID_RE,readState,readStateForSeries,diff --git a/server/services/pipeline/manuscriptFix.js b/server/services/pipeline/manuscriptFix.jsindex 7032f57531..8755a56b13 100644--- a/server/services/pipeline/manuscriptFix.js+++ b/server/services/pipeline/manuscriptFix.js@@ -20,10 +20,10 @@ import { getIssue, updateStageWithLatest, updateStagesWithLatest } from './issueimport { collectManuscriptSections, stageVersionsOf, sectionsCorpus, manuscriptSectionHeader } from './arcPlanner.js';import { getComment, updateComment } from './manuscriptComments.js';import { escapeRegExp } from '../../lib/textUtils.js';+import { codedError } from '../../lib/codedError.js';export const ERR_VALIDATION = 'PIPELINE_MANUSCRIPT_FIX_VALIDATION';export const ERR_NOT_FOUND = 'PIPELINE_MANUSCRIPT_FIX_NOT_FOUND';-const makeErr = (message, code) => Object.assign(new Error(message), { code });// Output before input: the drafted artifact wins over the upstream seed.// Mirrors arcPlanner's stageTextOf (inlined there to avoid an import cycle).@@ -36,7 +36,7 @@ const textHash = (s) => createHash('sha256').update(typeof s === 'string' ? s :async function loadStageText(issueId, stageId) {const issue = await getIssue(issueId).catch(() => null);- if (!issue) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);+ if (!issue) throw codedError(`Issue not found: ${issueId}`, ERR_NOT_FOUND);return stageTextOf(issue.stages?.[stageId]);}@@ -63,13 +63,13 @@ async function resolveTargets(seriesId, comment) {if (comment.issueNumber != null) {const section = sections.find((s) => s.number === comment.issueNumber);if (section) return [section];- throw makeErr(+ throw codedError('This comment points to an issue that no longer has drafted manuscript text — regenerate the editorial review',ERR_VALIDATION,);}if (sections.length) return sections;- throw makeErr('No drafted manuscript text is available to edit', ERR_VALIDATION);+ throw codedError('No drafted manuscript text is available to edit', ERR_VALIDATION);}function normalizeModelEdits(content) {@@ -190,7 +190,7 @@ function editsFromAcceptRequest({ comment, find, replace, edits }) {}if (find) {if (typeof replace !== 'string') {- throw makeErr('replace is required when find is provided', ERR_VALIDATION);+ throw codedError('replace is required when find is provided', ERR_VALIDATION);}return [{issueId: comment.issueId,@@ -287,17 +287,17 @@ async function planEditsBySection(edits, comment) {const planned = [];for (const group of groups.values()) {const issue = await getIssue(group.issueId).catch(() => null);- if (!issue) throw makeErr(`Issue not found: ${group.issueId}`, ERR_NOT_FOUND);+ if (!issue) throw codedError(`Issue not found: ${group.issueId}`, ERR_NOT_FOUND);const originalText = stageTextOf(issue.stages?.[group.stageId]);const spans = [];for (const edit of group.edits) {const located = locateFindSpan(originalText, edit.find, comment.anchorQuote);if (!located) {- throw makeErr('Anchor text is no longer present in the manuscript — regenerate the fix', ERR_VALIDATION);+ throw codedError('Anchor text is no longer present in the manuscript — regenerate the fix', ERR_VALIDATION);}const span = { start: located.start, end: located.end, replace: edit.replace };if (spans.some((other) => span.start < other.end && other.start < span.end)) {- throw makeErr('Selected edits overlap in the manuscript — regenerate the fix', ERR_VALIDATION);+ throw codedError('Selected edits overlap in the manuscript — regenerate the fix', ERR_VALIDATION);}spans.push(span);}@@ -317,7 +317,7 @@ async function applyPlannedEdits(seriesId, planned) {stageId: group.stageId,computeFn: (cur) => {if (stageTextOf(cur) !== group.originalText) {- throw makeErr('Manuscript changed while applying the fix — regenerate the fix', ERR_VALIDATION);+ throw codedError('Manuscript changed while applying the fix — regenerate the fix', ERR_VALIDATION);}return { output: group.output, status: 'edited', lastRunId: `fix-${randomUUID()}` };},@@ -339,7 +339,7 @@ async function applyPlannedEdits(seriesId, planned) {*/export async function saveManuscriptSection(seriesId, { issueId, stageId, output } = {}) {if (!MANUSCRIPT_TYPES.includes(stageId)) {- throw makeErr(`Not an editable manuscript stage: ${stageId}`, ERR_VALIDATION);+ throw codedError(`Not an editable manuscript stage: ${stageId}`, ERR_VALIDATION);}const { issue, stage } = await updateStageWithLatest(issueId,@@ -383,7 +383,7 @@ const wordSkeleton = (s) => (typeof s === 'string'// the AI pass is held to "change not one letter".function assertWordsPreserved(before, after) {if (wordSkeleton(before) === wordSkeleton(after)) return;- throw makeErr(+ throw codedError('AI reformat changed the wording, so it was discarded and the text is unchanged. Try again or use the plain Format button.',ERR_VALIDATION,);@@ -415,7 +415,7 @@ export async function reformatManuscriptText(text, { stageId = 'prose', providersource: 'pipeline-manuscript-reformat',});const cleaned = stripReformatWrapper(r?.content);- if (!cleaned) throw makeErr('The model returned no text — try again', ERR_VALIDATION);+ if (!cleaned) throw codedError('The model returned no text — try again', ERR_VALIDATION);assertWordsPreserved(body, cleaned);return { text: cleaned, runId: r?.runId || null, changed: cleaned !== body };}@@ -429,10 +429,10 @@ export async function reformatManuscriptText(text, { stageId = 'prose', provider*/export async function reformatManuscriptStageText(text, { stageId, providerOverride, modelOverride } = {}) {if (!MANUSCRIPT_TYPES.includes(stageId)) {- throw makeErr(`Not an editable manuscript stage: ${stageId}`, ERR_VALIDATION);+ throw codedError(`Not an editable manuscript stage: ${stageId}`, ERR_VALIDATION);}if (!(typeof text === 'string' && text.trim())) {- throw makeErr('There is no drafted text to reformat', ERR_VALIDATION);+ throw codedError('There is no drafted text to reformat', ERR_VALIDATION);}return reformatManuscriptText(text, { stageId, providerOverride, modelOverride });}@@ -467,11 +467,11 @@ function mergeFixes(fixes) {export async function generateManuscriptFix(seriesId, { commentId, providerOverride, providerDefault, modelOverride, modelDefault, effortDefault } = {}) {const series = await getSeries(seriesId);const comment = await getComment(seriesId, commentId);- if (!comment) throw makeErr(`Comment not found: ${commentId}`, ERR_NOT_FOUND);+ if (!comment) throw codedError(`Comment not found: ${commentId}`, ERR_NOT_FOUND);const targets = await resolveTargets(seriesId, comment);if (targets.every((s) => !s.content)) {- throw makeErr('There is no drafted text to edit', ERR_VALIDATION);+ throw codedError('There is no drafted text to edit', ERR_VALIDATION);}const arc = series.arc || {};@@ -547,7 +547,7 @@ export async function generateManuscriptFix(seriesId, { commentId, providerOverrfix = mergeFixes(fixes);runId = first?.runId;}- if (!fix) throw makeErr('The model did not return a usable fix — try again', ERR_VALIDATION);+ if (!fix) throw codedError('The model did not return a usable fix — try again', ERR_VALIDATION);const updated = await updateComment(seriesId, commentId, { fix });return {@@ -567,17 +567,17 @@ export async function generateManuscriptFix(seriesId, { commentId, providerOverr*/export async function acceptManuscriptFix(seriesId, { commentId, find, replace, edits } = {}) {const comment = await getComment(seriesId, commentId);- if (!comment) throw makeErr(`Comment not found: ${commentId}`, ERR_NOT_FOUND);+ if (!comment) throw codedError(`Comment not found: ${commentId}`, ERR_NOT_FOUND);const acceptedEdits = await resolveMissingEditTargets(seriesId,comment,editsFromAcceptRequest({ comment, find, replace, edits }),);if (acceptedEdits.length === 0) {- throw makeErr('No applicable edits were selected', ERR_VALIDATION);+ throw codedError('No applicable edits were selected', ERR_VALIDATION);}if (acceptedEdits.some((e) => !e.issueId || !e.stageId || !e.find)) {- throw makeErr('One selected edit is not anchored to a manuscript section — regenerate the fix', ERR_VALIDATION);+ throw codedError('One selected edit is not anchored to a manuscript section — regenerate the fix', ERR_VALIDATION);}const planned = await planEditsBySection(acceptedEdits, comment);@@ -615,17 +615,17 @@ export async function acceptManuscriptFix(seriesId, { commentId, find, replace,*/export async function undoManuscriptFix(seriesId, { commentId } = {}) {const comment = await getComment(seriesId, commentId);- if (!comment) throw makeErr(`Comment not found: ${commentId}`, ERR_NOT_FOUND);+ if (!comment) throw codedError(`Comment not found: ${commentId}`, ERR_NOT_FOUND);const snapshot = comment.acceptedSnapshot;if (!snapshot || !Array.isArray(snapshot.sections) || snapshot.sections.length === 0) {- throw makeErr('There is no accepted edit to undo for this finding', ERR_VALIDATION);+ throw codedError('There is no accepted edit to undo for this finding', ERR_VALIDATION);}const updates = snapshot.sections.map((s) => ({issueId: s.issueId,stageId: s.stageId,computeFn: (cur) => {if (s.appliedHash && textHash(stageTextOf(cur)) !== s.appliedHash) {- throw makeErr(+ throw codedError('The manuscript changed since this fix was accepted, so undo is unavailable — revert via the section version history instead',ERR_VALIDATION,);diff --git a/server/services/pipeline/proseExport.js b/server/services/pipeline/proseExport.jsindex 93a70cbb3d..f902464bf6 100644--- a/server/services/pipeline/proseExport.js+++ b/server/services/pipeline/proseExport.js@@ -33,9 +33,9 @@ import { resolveExportSettings, TRIM_SIZES, DEFAULT_TRIM_SIZE } from '../../lib/import { getSeries } from './series.js';import { listSeasons } from './seasons.js';import { collectManuscriptSections } from './arcPlanner.js';+import { codedError } from '../../lib/codedError.js';export const ERR_NO_PROSE = 'PIPELINE_PROSE_EXPORT_NO_CONTENT';-const makeErr = (message, code) => Object.assign(new Error(message), { code });// ---------------------------------------------------------------------------// Section gathering — the shared front for all three exports.@@ -58,7 +58,7 @@ export async function gatherProse(seriesId) {// either way (never export an outline as finished prose).const sections = await collectManuscriptSections(seriesId, { stageOrder: ['prose'] });if (!sections.length) {- throw makeErr(+ throw codedError('No drafted prose to export — write or import prose on at least one issue first.',ERR_NO_PROSE,);diff --git a/server/services/pipeline/seasons.js b/server/services/pipeline/seasons.jsindex ffc3ca2122..461a233c4e 100644--- a/server/services/pipeline/seasons.js+++ b/server/services/pipeline/seasons.js@@ -16,12 +16,12 @@ import * as seriesSvc from './series.js';import * as issuesSvc from './issues.js';import { emitRecordUpdated, withReexportSuppressed } from '../sharing/recordEvents.js';import { isStr } from '../../lib/textUtils.js';+import { codedError } from '../../lib/codedError.js';export const ERR_NOT_FOUND = 'PIPELINE_SEASON_NOT_FOUND';export const ERR_VALIDATION = 'PIPELINE_SEASON_VALIDATION';export const ERR_REASSIGN_TARGET = 'PIPELINE_SEASON_REASSIGN_TARGET_INVALID';export const ERR_LOCKED = 'PIPELINE_SEASON_LOCKED';-const makeErr = (message, code) => Object.assign(new Error(message), { code });// Fields a locked-season patch MUST NOT touch. `locked` itself is allowed// (the user has to be able to unlock); `status` is allowed because it tracks@@ -37,19 +37,19 @@ export async function listSeasons(seriesId) {export async function getSeason(seriesId, seasonId) {const seasons = await listSeasons(seriesId);const found = seasons.find((s) => s.id === seasonId);- if (!found) throw makeErr(`Season not found: ${seasonId}`, ERR_NOT_FOUND);+ if (!found) throw codedError(`Season not found: ${seasonId}`, ERR_NOT_FOUND);return found;}export async function createSeason(seriesId, input = {}) {const next = buildSeason(input);if (!next) {- throw makeErr('Season requires a title or a number > 0', ERR_VALIDATION);+ throw codedError('Season requires a title or a number > 0', ERR_VALIDATION);}const series = await seriesSvc.getSeries(seriesId);const existing = series.seasons || [];if (existing.length >= ARC_LIMITS.SEASONS_PER_SERIES_MAX) {- throw makeErr(`Series already has ${ARC_LIMITS.SEASONS_PER_SERIES_MAX} seasons (max)`, ERR_VALIDATION);+ throw codedError(`Series already has ${ARC_LIMITS.SEASONS_PER_SERIES_MAX} seasons (max)`, ERR_VALIDATION);}// If the user didn't pick a number, default to last + 1 so the canonical// ordering reads naturally. Falls back to 1 for the first season.@@ -78,7 +78,7 @@ export async function updateSeason(seriesId, seasonId, patch = {}) {if (cur.locked === true && patch.locked !== false) {const forbidden = Object.keys(patch).filter((k) => !LOCKED_SEASON_ALLOWED_KEYS.has(k));if (forbidden.length > 0) {- throw makeErr(+ throw codedError(`Season "${cur.title || cur.number}" is locked — unlock it before editing (${forbidden.join(', ')})`,ERR_LOCKED,);@@ -92,7 +92,7 @@ export async function updateSeason(seriesId, seasonId, patch = {}) {createdAt: cur.createdAt,updatedAt: new Date().toISOString(),});- if (!next) throw makeErr('Season requires a title or a number > 0', ERR_VALIDATION);+ if (!next) throw codedError('Season requires a title or a number > 0', ERR_VALIDATION);nextNumber = next.number;return next;});@@ -115,12 +115,12 @@ export async function deleteSeason(seriesId, seasonId, { reassignTo = null } = {const series = await seriesSvc.getSeries(seriesId);const seasons = series.seasons || [];const cur = seasons.find((s) => s.id === seasonId);- if (!cur) throw makeErr(`Season not found: ${seasonId}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Season not found: ${seasonId}`, ERR_NOT_FOUND);// Refuse to delete a locked season — destructive ops on locked records// must require an explicit unlock first. Matches the editorial-freeze// semantics that block `updateSeason` content patches above.if (cur.locked === true) {- throw makeErr(+ throw codedError(`Season "${cur.title || cur.number}" is locked — unlock it before deleting`,ERR_LOCKED,);@@ -130,14 +130,14 @@ export async function deleteSeason(seriesId, seasonId, { reassignTo = null } = {// before any disk writes means the caller can retry cleanly.if (reassignTo != null) {if (!isStr(reassignTo)) {- throw makeErr('reassignTo must be a season id or null', ERR_REASSIGN_TARGET);+ throw codedError('reassignTo must be a season id or null', ERR_REASSIGN_TARGET);}if (reassignTo === seasonId) {- throw makeErr('reassignTo cannot be the season being deleted', ERR_REASSIGN_TARGET);+ throw codedError('reassignTo cannot be the season being deleted', ERR_REASSIGN_TARGET);}const target = seasons.find((s) => s.id === reassignTo);if (!target) {- throw makeErr(`reassignTo season not found: ${reassignTo}`, ERR_REASSIGN_TARGET);+ throw codedError(`reassignTo season not found: ${reassignTo}`, ERR_REASSIGN_TARGET);}}// Re-point child issues first so a mid-write crash doesn't leave themdiff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 0aa0a79970..3c91b917f2 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -38,6 +38,7 @@ import {} from '../sharing/recordEvents.js';import { renameCollectionForSeries, unlinkCollectionsForSeries } from '../mediaCollections.js';import { isStr, trimTo } from '../../lib/textUtils.js';+import { codedError } from '../../lib/codedError.js';// Storage backend dispatcher (#1015). Series records moved from per-record// `data/pipeline-series/{id}/index.json` (collectionStore) to one-row-per-series@@ -52,7 +53,6 @@ export const seriesStore = () => store();export const ERR_NOT_FOUND = 'PIPELINE_SERIES_NOT_FOUND';export const ERR_VALIDATION = 'PIPELINE_SERIES_VALIDATION';export const ERR_DUPLICATE = 'PIPELINE_SERIES_DUPLICATE';-const makeErr = (message, code) => Object.assign(new Error(message), { code });export const SERIES_ID_RE = /^ser-[A-Za-z0-9-]+$/;@@ -736,14 +736,14 @@ export async function listSeriesSummaries() {export async function getSeries(id, { includeDeleted = false } = {}) {const found = await store().loadOne(id);- if (!found) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);- if (found.deleted && !includeDeleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);+ if (!found) throw codedError(`Series not found: ${id}`, ERR_NOT_FOUND);+ if (found.deleted && !includeDeleted) throw codedError(`Series not found: ${id}`, ERR_NOT_FOUND);return found;}export async function createSeries(input = {}) {const name = trimTo(input.name, NAME_MAX);- if (!name) throw makeErr(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);+ if (!name) throw codedError(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);const now = new Date().toISOString();const created = sanitizeSeries({id: `ser-${randomUUID()}`,@@ -818,21 +818,21 @@ export async function createSeries(input = {}) {*/export async function insertSeriesWithId(input = {}) {if (!isStr(input.id) || !SERIES_ID_RE.test(input.id)) {- throw makeErr(`insertSeriesWithId: invalid id "${input.id}" (expected ser-<uuid>)`, ERR_VALIDATION);+ throw codedError(`insertSeriesWithId: invalid id "${input.id}" (expected ser-<uuid>)`, ERR_VALIDATION);}const name = trimTo(input.name, NAME_MAX);- if (!name) throw makeErr(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);+ if (!name) throw codedError(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);const { next, wasResurrection } = await store().queueRecordWrite(input.id, async () => {// Tombstone-overwrite: same contract as universeBuilder.insertUniverseWithId —// re-import undeletes; peer-sync resurrection is prevented at the merge// path via LWW, not here.const existing = await store().loadOne(input.id);if (existing && !existing.deleted) {- throw makeErr(`Series id already exists: ${input.id}`, ERR_DUPLICATE);+ throw codedError(`Series id already exists: ${input.id}`, ERR_DUPLICATE);}const wasResurrection = !!existing;const next = sanitizeSeries({ ...input, name });- if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);+ if (!next) throw codedError('Invalid series payload', ERR_VALIDATION);if (wasResurrection) {console.warn(`♻️ insertSeriesWithId: overwriting tombstone for ${input.id}`);}@@ -920,8 +920,8 @@ export async function updateSeries(id, patchOrMutator = {}) {merged, nameChanged, skipped, prevEphemeral, nextEphemeral, linkedUniverseId,} = await store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);- if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Series not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw codedError(`Series not found: ${id}`, ERR_NOT_FOUND);let patch;if (isMutator) {@@ -939,7 +939,7 @@ export async function updateSeries(id, patchOrMutator = {}) {// `typeof === 'object'` matches arrays and null — reject both so a// stray `return []` can't slip through unnoticed.if (Array.isArray(patch) || typeof patch !== 'object') {- throw makeErr('updateSeries mutator must return a plain object or null', ERR_VALIDATION);+ throw codedError('updateSeries mutator must return a plain object or null', ERR_VALIDATION);}} else {patch = patchOrMutator;@@ -948,7 +948,7 @@ export async function updateSeries(id, patchOrMutator = {}) {if (cur.locked?.arc === true && Object.hasOwn(patch, 'arc')&& (patch.arc === null || Object.hasOwn(patch.arc || {}, 'seriesDesign'))&& JSON.stringify(sanitizeSeriesDesign(patch.arc?.seriesDesign)) !== JSON.stringify(cur.arc?.seriesDesign ?? null)) {- throw makeErr('Arc is locked — unlock it before changing the series design', ERR_VALIDATION);+ throw codedError('Arc is locked — unlock it before changing the series design', ERR_VALIDATION);}// Hierarchy invariant: a series lives in exactly one universe. Reject// clearing the link once it's set — moving to a *different* non-empty@@ -957,7 +957,7 @@ export async function updateSeries(id, patchOrMutator = {}) {// land legacy orphans via the service directly (not this guard), so peer// fidelity is preserved.if ('universeId' in patch && cur.universeId && !trimTo(patch.universeId, UNIVERSE_ID_MAX)) {- throw makeErr('Cannot unlink a series from its universe — move it to another universe instead.', ERR_VALIDATION);+ throw codedError('Cannot unlink a series from its universe — move it to another universe instead.', ERR_VALIDATION);}// Per-field merge so `{ provider: 'codex' }` doesn't clobber an existing `model`.const mergedLlm = 'llm' in patch@@ -1035,7 +1035,7 @@ export async function updateSeries(id, patchOrMutator = {}) {llm: mergedLlm,updatedAt: new Date().toISOString(),});- if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);+ if (!next) throw codedError('Invalid series payload', ERR_VALIDATION);await store().saveOneNow(next.id, next);// Surface the universe this series ends up linked to ONLY when (a) this// PATCH set/changed the link and (b) the series itself qualifies to promote@@ -1101,12 +1101,12 @@ export async function updateSeries(id, patchOrMutator = {}) {export async function setArcFieldLock(id, field, locked) {if (!ARC_LOCKABLE_FIELDS.includes(field)) {- throw makeErr(`Unknown arc lock field: ${field}`, ERR_VALIDATION);+ throw codedError(`Unknown arc lock field: ${field}`, ERR_VALIDATION);}return store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);- if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Series not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw codedError(`Series not found: ${id}`, ERR_NOT_FOUND);const arcFields = { ...(cur.locked?.arcFields || {}) };if (locked === true) arcFields[field] = true;else delete arcFields[field];@@ -1118,7 +1118,7 @@ export async function setArcFieldLock(id, field, locked) {locked: nextLocked,updatedAt: new Date().toISOString(),});- if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);+ if (!next) throw codedError('Invalid series payload', ERR_VALIDATION);await store().saveOneNow(next.id, next);emitRecordUpdated('series', next.id);return next;@@ -1140,11 +1140,11 @@ export async function setSeriesCoverImage(id, filename) {const next = isStr(filename) && filename ? filename.slice(0, COVER_IMAGE_MAX) : null;return store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);- if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Series not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw codedError(`Series not found: ${id}`, ERR_NOT_FOUND);if ((cur.coverImage || null) === next) return cur; // no-op guardconst merged = sanitizeSeries({ ...cur, coverImage: next, updatedAt: new Date().toISOString() });- if (!merged) throw makeErr('Invalid series payload', ERR_VALIDATION);+ if (!merged) throw codedError('Invalid series payload', ERR_VALIDATION);await store().saveOneNow(merged.id, merged);emitRecordUpdated('series', merged.id);return merged;@@ -1165,12 +1165,12 @@ export async function setSeriesCoverImage(id, filename) {export async function updateSeasonOnSeries(seriesId, seasonId, patchFn) {return store().queueRecordWrite(seriesId, async () => {const cur = await store().loadOne(seriesId);- if (!cur) throw makeErr(`Series not found: ${seriesId}`, ERR_NOT_FOUND);- if (cur.deleted) throw makeErr(`Series not found: ${seriesId}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Series not found: ${seriesId}`, ERR_NOT_FOUND);+ if (cur.deleted) throw codedError(`Series not found: ${seriesId}`, ERR_NOT_FOUND);const seasons = Array.isArray(cur.seasons) ? cur.seasons : [];const seasonIdx = seasons.findIndex((s) => s.id === seasonId);if (seasonIdx < 0) {- throw makeErr(`Season not found: ${seasonId}`, 'PIPELINE_SEASON_NOT_FOUND');+ throw codedError(`Season not found: ${seasonId}`, 'PIPELINE_SEASON_NOT_FOUND');}const existing = seasons[seasonIdx];const patched = patchFn(existing);@@ -1192,7 +1192,7 @@ export async function updateSeasonOnSeries(seriesId, seasonId, patchFn) {seasons: nextSeasons,updatedAt: new Date().toISOString(),});- if (!merged) throw makeErr('Invalid series payload after season patch', ERR_VALIDATION);+ if (!merged) throw codedError('Invalid series payload after season patch', ERR_VALIDATION);await store().saveOneNow(merged.id, merged);emitRecordUpdated('series', merged.id);return merged;@@ -1206,8 +1206,8 @@ export async function deleteSeries(id) {// on the receiving peer via mergeSeriesFromSync's transition detection.const result = await store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);- if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Series not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw codedError(`Series not found: ${id}`, ERR_NOT_FOUND);const now = new Date().toISOString();await store().saveOneNow(id, { ...cur, deleted: true, deletedAt: now, updatedAt: now });// Any live share-bucket subscription for this series tears itself down viadiff --git a/server/services/pipeline/volumePdf.js b/server/services/pipeline/volumePdf.jsindex 942008992d..70e16d02b5 100644--- a/server/services/pipeline/volumePdf.js+++ b/server/services/pipeline/volumePdf.js@@ -23,10 +23,10 @@ import { getSeries } from './series.js';import { getSeason } from './seasons.js';import { listIssues } from './issues.js';import { PAGE_SIZES, DEFAULT_PAGE_SIZE } from './comicPdf.js';+import { codedError } from '../../lib/codedError.js';export const ERR_NO_VOLUME_COVER = 'PIPELINE_VOLUME_PDF_NO_COVER';export const ERR_NO_RENDERED_ISSUES = 'PIPELINE_VOLUME_PDF_NO_RENDERED_ISSUES';-const makeErr = (message, code) => Object.assign(new Error(message), { code });const READ_OPTS = { subject: 'volume page image' };const EMBED_OPTS = { unsupportedCode: 'PIPELINE_VOLUME_PDF_UNSUPPORTED_IMAGE' };@@ -44,7 +44,7 @@ export async function buildVolumePdf(seriesId, seasonId, opts = {}) {const volCoverFilename = pickRenderedFilename(season.cover);if (!volCoverFilename) {- throw makeErr(+ throw codedError(`Volume ${season.number || 1} has no rendered front cover yet — render it before compiling the volume PDF.`,ERR_NO_VOLUME_COVER,);@@ -99,7 +99,7 @@ export async function buildVolumePdf(seriesId, seasonId, opts = {}) {if (targets.length === 1) {// Only the volume front cover and nothing else — not really a volume.- throw makeErr(+ throw codedError(`Volume ${season.number || 1} has no rendered issue pages yet — render at least one issue's pages first.`,ERR_NO_RENDERED_ISSUES,);@@ -137,7 +137,7 @@ export async function buildVolumePdf(seriesId, seasonId, opts = {}) {}if (pageCount === 0) {- throw makeErr('No usable pages — all embeds failed', ERR_NO_RENDERED_ISSUES);+ throw codedError('No usable pages — all embeds failed', ERR_NO_RENDERED_ISSUES);}if (includeColophon) {diff --git a/server/services/recordMerge.js b/server/services/recordMerge.jsindex 1a20e73313..09708bc9e3 100644--- a/server/services/recordMerge.js+++ b/server/services/recordMerge.js@@ -39,6 +39,7 @@ import {bulkUpdateCollectionItems, deleteCollection,} from './mediaCollections.js';import { isStr } from '../lib/textUtils.js';+import { codedError } from '../lib/codedError.js';// Own error code (both the universe-builder and pipeline routers map it to// 400). get*() NOT_FOUND errors propagate with their own per-record codes,@@ -56,7 +57,6 @@ export const ERR_VALIDATION = 'MERGE_VALIDATION';// context (via `buildCascadeContext`) so the UI can name which children stuck.export const ERR_CASCADE = 'MERGE_CASCADE_INCOMPLETE';-const makeErr = (message, code) => Object.assign(new Error(message), { code });// Build the resumable cascade error. `failed` is `[{ id, name, error, step? }]`.const cascadeError = (kind, survivorId, loserId, failed) =>@@ -335,7 +335,7 @@ export const buildSeriesUnion = (survivor, loser, fieldChoices = {}, fieldOverriconst requireResolved = (conflicts) => {if (conflicts.length > 0) {- throw makeErr(+ throw codedError(`Unresolved conflicting field(s): ${conflicts.map((c) => c.field).join(', ')}`,ERR_VALIDATION,);@@ -351,7 +351,7 @@ const requireResolved = (conflicts) => {*/export async function mergeUniverses(survivorId, loserId, fieldChoices = {}, { dryRun = false, fieldOverrides = {} } = {}) {if (!survivorId || !loserId || survivorId === loserId) {- throw makeErr('survivorId and loserId must be distinct', ERR_VALIDATION);+ throw codedError('survivorId and loserId must be distinct', ERR_VALIDATION);}const survivor = await getUniverse(survivorId);const loser = await getUniverse(loserId);@@ -427,7 +427,7 @@ export async function mergeUniverses(survivorId, loserId, fieldChoices = {}, { d*/export async function mergeSeries(survivorId, loserId, fieldChoices = {}, { dryRun = false, fieldOverrides = {} } = {}) {if (!survivorId || !loserId || survivorId === loserId) {- throw makeErr('survivorId and loserId must be distinct', ERR_VALIDATION);+ throw codedError('survivorId and loserId must be distinct', ERR_VALIDATION);}const survivor = await getSeries(survivorId);const loser = await getSeries(loserId);@@ -437,10 +437,10 @@ export async function mergeSeries(survivorId, loserId, fieldChoices = {}, { dryR// Orphan series are surfaced separately as "never merged"; merging two// unrelated orphans (both universeId null) would fold issues/collections// across unrelated works. Require linking into a universe first.- throw makeErr('Orphan series (no universe) cannot be merged — link them into a universe first', ERR_VALIDATION);+ throw codedError('Orphan series (no universe) cannot be merged — link them into a universe first', ERR_VALIDATION);}if (survivorUniverseId !== loserUniverseId) {- throw makeErr('Series can only be merged within the same universe', ERR_VALIDATION);+ throw codedError('Series can only be merged within the same universe', ERR_VALIDATION);}const { record, conflicts, autoResolved, unionSummary } = buildSeriesUnion(survivor, loser, fieldChoices, fieldOverrides);diff --git a/server/services/rounds.js b/server/services/rounds.jsindex 8dca0d4d9b..0104797fb6 100644--- a/server/services/rounds.js+++ b/server/services/rounds.js@@ -23,6 +23,7 @@ import { PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { HARMONY_PARTS } from '../lib/songCraftRef.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { sanitizeRound as sanitizeRoundRecord } from '../lib/roundsValidation.js';+import { codedError } from '../lib/codedError.js';// Shape bounds re-exported so routes/rounds.js and the seed migrations keep// their existing import surface (svc.TITLE_MAX_LENGTH, …).@@ -43,7 +44,6 @@ export const ERR_NOT_FOUND = 'NOT_FOUND';// Raised when a refresh-from-template is requested for a song that isn't a// bundled built-in default (no shipped template to restore from).export const ERR_NOT_BUILTIN = 'NOT_BUILTIN';-const makeErr = (message, code) => Object.assign(new Error(message), { code });// Project a stored or inbound record onto the canonical song shape, stamping// `builtIn` from the shipped-seed id set. Used on read (defends hand-edited@@ -574,7 +574,7 @@ export async function updateRound(id, patch) {return enqueue(async () => {const songs = await readRounds();const idx = songs.findIndex((s) => s.id === id);- if (idx === -1) throw makeErr(`Song ${id} not found`, ERR_NOT_FOUND);+ if (idx === -1) throw codedError(`Song ${id} not found`, ERR_NOT_FOUND);// Merge field-by-field so an absent key preserves the stored value while a// present key (including empty string / empty array) applies the change.const merged = { ...songs[idx] };@@ -630,9 +630,9 @@ export async function refreshRoundFromTemplate(id) {return enqueue(async () => {const songs = await readRounds();const idx = songs.findIndex((s) => s.id === id);- if (idx === -1) throw makeErr(`Song ${id} not found`, ERR_NOT_FOUND);+ if (idx === -1) throw codedError(`Song ${id} not found`, ERR_NOT_FOUND);const template = seedTemplate(id);- if (!template) throw makeErr(`Song ${id} is not a built-in default`, ERR_NOT_BUILTIN);+ if (!template) throw codedError(`Song ${id} is not a built-in default`, ERR_NOT_BUILTIN);const existing = songs[idx];// Resetting layers to the template set can orphan a recording assigned to a// user-added layer the template doesn't define — unassign those so the@@ -663,7 +663,7 @@ export async function deleteRound(id) {return enqueue(async () => {const songs = await readRounds();const idx = songs.findIndex((s) => s.id === id);- if (idx === -1) throw makeErr(`Song ${id} not found`, ERR_NOT_FOUND);+ if (idx === -1) throw codedError(`Song ${id} not found`, ERR_NOT_FOUND);const [removed] = songs.splice(idx, 1);await atomicWrite(STATE_PATH, { rounds: songs });console.log(`🗑️ Deleted song "${removed.title}" (${id})`);diff --git a/server/services/sharing/buckets.js b/server/services/sharing/buckets.jsindex 7c238b332c..6743d5e614 100644--- a/server/services/sharing/buckets.js+++ b/server/services/sharing/buckets.js@@ -17,6 +17,7 @@ import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtilsimport { SHARING_SCHEMA_VERSION } from './version.js';import { isStr, trimTo } from '../../lib/textUtils.js';import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';+import { codedError } from '../../lib/codedError.js';const REGISTRY_PATH = () => join(PATHS.data, 'sharing', 'buckets.json');@@ -35,7 +36,6 @@ export const ERR_PATH_UNUSABLE = 'SHARING_BUCKET_PATH_UNUSABLE';// queue would still let two snapshots overwrite each other.const queueRegistryWrite = createFileWriteQueue();-const makeErr = (message, code) => Object.assign(new Error(message), { code });const sanitizeBucket = (raw) => {if (!raw || typeof raw !== 'object') return null;@@ -69,15 +69,15 @@ async function assertPathUsable(path) {try {st = await stat(path);} catch (err) {- throw makeErr(`Bucket path does not exist or is unreadable: ${path}`, ERR_PATH_UNUSABLE);+ throw codedError(`Bucket path does not exist or is unreadable: ${path}`, ERR_PATH_UNUSABLE);}if (!st.isDirectory()) {- throw makeErr(`Bucket path is not a directory: ${path}`, ERR_PATH_UNUSABLE);+ throw codedError(`Bucket path is not a directory: ${path}`, ERR_PATH_UNUSABLE);}try {await access(path, constants.R_OK | constants.W_OK);} catch (err) {- throw makeErr(`Bucket path is not writable: ${path}`, ERR_PATH_UNUSABLE);+ throw codedError(`Bucket path is not writable: ${path}`, ERR_PATH_UNUSABLE);}}@@ -99,11 +99,11 @@ const HEX_HASH_RE = /^[0-9a-f]{64}$/;export function isHexHash(v) { return typeof v === 'string' && HEX_HASH_RE.test(v); }export function bucketBlobsDir(bucketPath) { return join(bucketPath, 'assets', 'blobs'); }export function bucketBlobPath(bucketPath, hash) {- if (!isHexHash(hash)) throw makeErr(`Invalid asset hash: ${hash}`, ERR_VALIDATION);+ if (!isHexHash(hash)) throw codedError(`Invalid asset hash: ${hash}`, ERR_VALIDATION);return join(bucketBlobsDir(bucketPath), hash);}export function bucketBlobSidecarPath(bucketPath, hash) {- if (!isHexHash(hash)) throw makeErr(`Invalid asset hash: ${hash}`, ERR_VALIDATION);+ if (!isHexHash(hash)) throw codedError(`Invalid asset hash: ${hash}`, ERR_VALIDATION);return join(bucketBlobsDir(bucketPath), `${hash}.metadata.json`);}// Sidecar mapping `<sourcePath>:<mtimeMs>:<size> → <hash>` so the exporter can@@ -187,15 +187,15 @@ export async function listBuckets() {export async function getBucket(id) {const { buckets } = await readRegistry();const found = buckets.find((b) => b.id === id);- if (!found) throw makeErr(`Bucket not found: ${id}`, ERR_NOT_FOUND);+ if (!found) throw codedError(`Bucket not found: ${id}`, ERR_NOT_FOUND);return found;}export async function createBucket(input = {}) {const name = trimTo(input.name, NAME_MAX);- if (!name) throw makeErr(`Bucket name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);+ if (!name) throw codedError(`Bucket name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);const path = trimTo(input.path, PATH_MAX);- if (!path) throw makeErr('Bucket path is required', ERR_VALIDATION);+ if (!path) throw codedError('Bucket path is required', ERR_VALIDATION);await assertPathUsable(path);return queueRegistryWrite(async () => {const state = await readRegistry();@@ -203,7 +203,7 @@ export async function createBucket(input = {}) {// claim the same on-disk folder (they would fight over bucket.json + the// watcher would double-fire on every manifest).if (state.buckets.some((b) => b.path === path)) {- throw makeErr(`A bucket is already registered at: ${path}`, ERR_VALIDATION);+ throw codedError(`A bucket is already registered at: ${path}`, ERR_VALIDATION);}const now = new Date().toISOString();const bucket = sanitizeBucket({@@ -228,7 +228,7 @@ export function updateBucket(id, patch = {}) {return queueRegistryWrite(async () => {const state = await readRegistry();const idx = state.buckets.findIndex((b) => b.id === id);- if (idx < 0) throw makeErr(`Bucket not found: ${id}`, ERR_NOT_FOUND);+ if (idx < 0) throw codedError(`Bucket not found: ${id}`, ERR_NOT_FOUND);const cur = state.buckets[idx];const merged = sanitizeBucket({...cur,@@ -238,7 +238,7 @@ export function updateBucket(id, patch = {}) {...('bioOverride' in patch ? { bioOverride: patch.bioOverride } : {}),updatedAt: new Date().toISOString(),});- if (!merged) throw makeErr('Invalid bucket payload', ERR_VALIDATION);+ if (!merged) throw codedError('Invalid bucket payload', ERR_VALIDATION);// `path` is intentionally NOT patchable — if the user wants to move a// bucket, they delete and re-register so the registry can re-validate and// re-layout the new path.@@ -253,7 +253,7 @@ export function deleteBucket(id) {const state = await readRegistry();const before = state.buckets.length;state.buckets = state.buckets.filter((b) => b.id !== id);- if (state.buckets.length === before) throw makeErr(`Bucket not found: ${id}`, ERR_NOT_FOUND);+ if (state.buckets.length === before) throw codedError(`Bucket not found: ${id}`, ERR_NOT_FOUND);await writeRegistry(state);return { id };});diff --git a/server/services/sharing/subscriptions.js b/server/services/sharing/subscriptions.jsindex 759ebf98a3..4f50e853c5 100644--- a/server/services/sharing/subscriptions.js+++ b/server/services/sharing/subscriptions.js@@ -39,6 +39,7 @@ export { withReexportSuppressed };import { subscriptionFilename, legacySubscriptionFilename } from './manifest.js';import { getInstanceId } from '../instanceIdentity.js';import { isStr } from '../../lib/textUtils.js';+import { codedError } from '../../lib/codedError.js';// Re-export from the canonical source so other modules can import the// filename helper from either side without forcing a manifest.js import.@@ -49,7 +50,6 @@ export const SUBSCRIBABLE_KINDS = Object.freeze(['series', 'universe']);export const ERR_NOT_FOUND = 'SHARING_SUBSCRIPTION_NOT_FOUND';export const ERR_VALIDATION = 'SHARING_SUBSCRIPTION_VALIDATION';export const ERR_DUPLICATE = 'SHARING_SUBSCRIPTION_DUPLICATE';-const makeErr = (message, code) => Object.assign(new Error(message), { code });const queueStateWrite = createFileWriteQueue();@@ -135,10 +135,10 @@ export async function adoptImportedSubscription({ bucketId, recordKind, recordId*/export async function subscribe({ bucketId, recordKind, recordId }) {if (!SUBSCRIBABLE_KINDS.includes(recordKind)) {- throw makeErr(`subscribable kinds are ${SUBSCRIBABLE_KINDS.join(', ')} (got "${recordKind}")`, ERR_VALIDATION);+ throw codedError(`subscribable kinds are ${SUBSCRIBABLE_KINDS.join(', ')} (got "${recordKind}")`, ERR_VALIDATION);}if (!isStr(bucketId) || !isStr(recordId)) {- throw makeErr('bucketId and recordId are required', ERR_VALIDATION);+ throw codedError('bucketId and recordId are required', ERR_VALIDATION);}// Validate the bucket exists (throws ERR_NOT_FOUND otherwise).await getBucket(bucketId);@@ -171,11 +171,11 @@ async function runExport({ bucketId, recordKind, recordId }) {}export async function unsubscribe(id) {- if (!isStr(id)) throw makeErr('subscription id required', ERR_VALIDATION);+ if (!isStr(id)) throw codedError('subscription id required', ERR_VALIDATION);const sub = await queueStateWrite(async () => {const state = await readState();const idx = state.subscriptions.findIndex((s) => s.id === id);- if (idx < 0) throw makeErr(`Subscription not found: ${id}`, ERR_NOT_FOUND);+ if (idx < 0) throw codedError(`Subscription not found: ${id}`, ERR_NOT_FOUND);const [removed] = state.subscriptions.splice(idx, 1);await writeState(state);return removed;diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.jsindex 10155de9f6..989ed141b8 100644--- a/server/services/storyBuilder.js+++ b/server/services/storyBuilder.js@@ -62,6 +62,7 @@ import {ERR_VALIDATION as ARC_ERR_VALIDATION,} from './pipeline/arcPlanner.js';import { isStr, trimTo } from '../lib/textUtils.js';+import { codedError } from '../lib/codedError.js';// Storage backend dispatcher (#1016): the facade is a drop-in for the// collectionStore surface this service used to call directly, so every method@@ -72,7 +73,6 @@ export const storyBuilderStore = () => store();export const ERR_NOT_FOUND = 'STORY_BUILDER_NOT_FOUND';export const ERR_VALIDATION = 'STORY_BUILDER_VALIDATION';-const makeErr = (message, code) => Object.assign(new Error(message), { code });const SESSION_ID_RE = /^stb-[A-Za-z0-9-]+$/;export const TITLE_MAX = 200;@@ -239,8 +239,8 @@ export async function listStorySessions({ includeDeleted = false } = {}) {export async function getStorySession(id, { includeDeleted = false } = {}) {const found = await store().loadOne(id);- if (!found) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);- if (found.deleted && !includeDeleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ if (!found) throw codedError(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ if (found.deleted && !includeDeleted) throw codedError(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);return found;}@@ -252,7 +252,7 @@ export async function getStorySession(id, { includeDeleted = false } = {}) {*/export async function createStorySession(input = {}) {const title = trimTo(input.title, TITLE_MAX);- if (!title) throw makeErr(`Title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION);+ if (!title) throw codedError(`Title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION);const intakeMode = INTAKE_MODES.includes(input.intakeMode) ? input.intakeMode : 'seed';const seedIdea = trimTo(input.seedIdea, SEED_MAX);@@ -352,7 +352,7 @@ export async function createStorySession(input = {}) {export async function updateStorySession(id, patch = {}) {return store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ if (!cur || cur.deleted) throw codedError(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);const next = sanitizeSession({...cur,...('title' in patch ? { title: patch.title } : {}),@@ -361,7 +361,7 @@ export async function updateStorySession(id, patch = {}) {...('llm' in patch ? { llm: { ...(cur.llm || {}), ...(patch.llm || {}) } } : {}),updatedAt: nowIso(),});- if (!next) throw makeErr('Invalid session payload', ERR_VALIDATION);+ if (!next) throw codedError('Invalid session payload', ERR_VALIDATION);await store().saveOneNow(next.id, next);return next;});@@ -370,7 +370,7 @@ export async function updateStorySession(id, patch = {}) {export async function deleteStorySession(id) {return store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ if (!cur || cur.deleted) throw codedError(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);const now = nowIso();await store().saveOneNow(id, { ...cur, deleted: true, deletedAt: now, updatedAt: now });return { id };@@ -630,7 +630,7 @@ export async function getStorySessionView(id) {async function writeSyncState(id, enabled, hashes) {return store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ if (!cur || cur.deleted) throw codedError(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);const next = sanitizeSession({...cur,sync: enabled === true,@@ -654,7 +654,7 @@ async function writeSyncState(id, enabled, hashes) {export async function reconcileStorySession(id) {const session = await getStorySession(id);if (session.sync !== true) {- throw makeErr('Cross-machine resume is off for this session — enable it before reconciling', ERR_VALIDATION);+ throw codedError('Cross-machine resume is off for this session — enable it before reconciling', ERR_VALIDATION);}const { hashes } = await computeCurrentHashes(session);return writeSyncState(id, true, hashes);@@ -709,13 +709,13 @@ async function applyUnderlyingLock(session, stepId, locked) {}export async function lockStep(id, stepId) {- if (!isValidStepId(stepId)) throw makeErr(`Unknown step: ${stepId}`, ERR_VALIDATION);+ if (!isValidStepId(stepId)) throw codedError(`Unknown step: ${stepId}`, ERR_VALIDATION);const session = await getStorySession(id);const { hashes } = await computeCurrentHashes(session);await applyUnderlyingLock(session, stepId, true);return store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ if (!cur || cur.deleted) throw codedError(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);const steps = { ...cur.steps };steps[stepId] = {...steps[stepId],@@ -746,12 +746,12 @@ export async function lockStep(id, stepId) {}export async function unlockStep(id, stepId) {- if (!isValidStepId(stepId)) throw makeErr(`Unknown step: ${stepId}`, ERR_VALIDATION);+ if (!isValidStepId(stepId)) throw codedError(`Unknown step: ${stepId}`, ERR_VALIDATION);const session = await getStorySession(id);await applyUnderlyingLock(session, stepId, false);return store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ if (!cur || cur.deleted) throw codedError(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);const steps = { ...cur.steps };steps[stepId] = { status: 'ready', locked: false, lockedAt: null, upstreamHash: null };const next = sanitizeSession({ ...cur, steps, updatedAt: nowIso() });@@ -771,17 +771,17 @@ export async function unlockStep(id, stepId) {* underlying record (arc, readerMap, …) still refuses regeneration.*/export async function setCurrentStep(id, stepId) {- if (!isValidStepId(stepId)) throw makeErr(`Unknown step: ${stepId}`, ERR_VALIDATION);+ if (!isValidStepId(stepId)) throw codedError(`Unknown step: ${stepId}`, ERR_VALIDATION);return updateStorySession(id, { currentStep: stepId });}// ── Per-issue locks (issues step loop) ────────────────────────────────────export async function setIssueLock(id, issueId, locked) {- if (!isStr(issueId) || !issueId) throw makeErr('issueId is required', ERR_VALIDATION);+ if (!isStr(issueId) || !issueId) throw codedError('issueId is required', ERR_VALIDATION);return store().queueRecordWrite(id, async () => {const cur = await store().loadOne(id);- if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ if (!cur || cur.deleted) throw codedError(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);const steps = { ...cur.steps };const issueLocks = { ...(steps.issues?.issueLocks || {}) };if (locked) issueLocks[issueId] = { locked: true, lockedAt: nowIso(), upstreamHash: null };@@ -827,18 +827,18 @@ export async function setIssueLock(id, issueId, locked) {*/export async function generateIssuesFromArc(id, options = {}) {const session = await getStorySession(id);- if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);+ if (!session.seriesId) throw codedError('No series linked', ERR_VALIDATION);const series = await getSeries(session.seriesId);const seasons = Array.isArray(series?.seasons) ? series.seasons : [];if (seasons.length === 0) {- throw makeErr('No seasons on the arc yet — generate the plot arc first', ERR_VALIDATION);+ throw codedError('No seasons on the arc yet — generate the plot arc first', ERR_VALIDATION);}const targetSeasons = options.seasonId? seasons.filter((s) => s.id === options.seasonId): seasons;if (options.seasonId && targetSeasons.length === 0) {- throw makeErr(`Season not found on series: ${options.seasonId}`, ERR_VALIDATION);+ throw codedError(`Season not found on series: ${options.seasonId}`, ERR_VALIDATION);}const reqProviderId = options.providerId || session.llm?.provider || undefined;@@ -904,7 +904,7 @@ export async function generateStep(id, stepId, options = {}) {if (options.fromDownstream) emit('Reading existing issues…', 'collect');const sourceMaterial = options.fromDownstream ? await collectIssueSourceText(session.seriesId) : '';if (options.fromDownstream && !sourceMaterial) {- throw makeErr(+ throw codedError('No issue content to backfill the idea from — write a comic script, teleplay, or prose on at least one issue first',ERR_VALIDATION,);@@ -936,7 +936,7 @@ export async function generateStep(id, stepId, options = {}) {return { result: content, runId, providerId, model };}if (stepId === 'universeAesthetic') {- if (!session.universeId) throw makeErr('No universe linked', ERR_VALIDATION);+ if (!session.universeId) throw codedError('No universe linked', ERR_VALIDATION);const universe = await getUniverse(session.universeId);emit('Expanding the aesthetic…', 'generate');const { preservedVariations, preservedCompositeSheets } = extractPreservedFromDraft(universe);@@ -976,7 +976,7 @@ export async function generateStep(id, stepId, options = {}) {return { result: updated, providerId: expanded.providerId, model: expanded.model };}if (stepId === 'plotArc') {- if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);+ if (!session.seriesId) throw codedError('No series linked', ERR_VALIDATION);let arcGenResult;if (options.fromDownstream) {// Backfill: extract the arc + seasons from the issues that already exist@@ -985,7 +985,7 @@ export async function generateStep(id, stepId, options = {}) {emit('Reading existing issues…', 'collect');const sourceText = await collectIssueSourceText(session.seriesId);if (!sourceText) {- throw makeErr(+ throw codedError('No issue content to backfill the arc from — write a comic script, teleplay, or prose on at least one issue first',ERR_VALIDATION,);@@ -1003,7 +1003,7 @@ export async function generateStep(id, stepId, options = {}) {const { arc, seasons, runId, providerId, model } = arcGenResult;// A null arc means the LLM returned nothing identifying — refuse rather// than wiping a previously-generated arc with `updateSeries({ arc: null })`.- if (!arc) throw makeErr('LLM returned an empty arc — try regenerating', ERR_VALIDATION);+ if (!arc) throw codedError('LLM returned an empty arc — try regenerating', ERR_VALIDATION);// Route through commitSeasonsWithRemap so per-field arc locks, per-season// locks, and orphaned child issues are all honored — same path the Arc// Canvas's regenerate uses. A plain updateSeries({ arc, seasons }) would@@ -1015,7 +1015,7 @@ export async function generateStep(id, stepId, options = {}) {return { result: updated, runId, providerId, model };}if (stepId === 'readerMap') {- if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);+ if (!session.seriesId) throw codedError('No series linked', ERR_VALIDATION);emit('Mapping reader emotion…', 'generate');const { readerMap, runId, providerId, model } = await generateReaderMap(session.seriesId, {providerOverride: reqProviderId, modelOverride: reqModel,@@ -1025,7 +1025,7 @@ export async function generateStep(id, stepId, options = {}) {const updated = await updateSeries(session.seriesId, { arc: { ...(series.arc || {}), readerMap } });return { result: updated, runId, providerId, model };}- throw makeErr(`Generate is not supported for step "${stepId}"`, ERR_VALIDATION);+ throw codedError(`Generate is not supported for step "${stepId}"`, ERR_VALIDATION);}export async function refineStep(id, stepId, { feedback, entryId, providerId, model, onProgress } = {}) {@@ -1035,7 +1035,7 @@ export async function refineStep(id, stepId, { feedback, entryId, providerId, moconst reqModel = model || session.llm?.model || undefined;const emit = (label, phase) => onProgress?.({ label, phase });if (stepId === 'universeAesthetic') {- if (!session.universeId) throw makeErr('No universe linked', ERR_VALIDATION);+ if (!session.universeId) throw codedError('No universe linked', ERR_VALIDATION);const universe = await getUniverse(session.universeId);emit('Refining the aesthetic…', 'generate');const refined = await refineWorldPrompts({@@ -1059,7 +1059,7 @@ export async function refineStep(id, stepId, { feedback, entryId, providerId, moreturn { result: updated, changes: refined.changes || [], rationale: refined.rationale || '' };}if (stepId === 'plotArc') {- if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);+ if (!session.seriesId) throw codedError('No series linked', ERR_VALIDATION);emit('Refining the plot arc…', 'generate');const { arc, changes, rationale, runId, providerId: usedProviderId, model: usedModel } = await refineArc(session.seriesId, feedback, { providerId: reqProviderId, model: reqModel });emit('Saving…', 'persist');@@ -1075,14 +1075,14 @@ export async function refineStep(id, stepId, { feedback, entryId, providerId, mo// dropping that re-check (this path bypasses it) would let a refine land if// the arc was locked while the LLM call was in flight.if (latest.locked?.arc === true) {- throw makeErr('Arc is locked — unlock it on the Arc Canvas before refining', ARC_ERR_VALIDATION);+ throw codedError('Arc is locked — unlock it on the Arc Canvas before refining', ARC_ERR_VALIDATION);}const mergedArc = mergeArcWithLocks(latest.arc, { ...arc, seriesDesign: latest.arc?.seriesDesign }, latest.locked?.arcFields);const updated = await updateSeries(session.seriesId, { arc: mergedArc });return { result: updated, changes, rationale, runId, providerId: usedProviderId, model: usedModel };}if (stepId === 'readerMap') {- if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);+ if (!session.seriesId) throw codedError('No series linked', ERR_VALIDATION);emit('Refining the reader map…', 'generate');const { readerMap, changes, rationale, runId, providerId: usedProviderId, model: usedModel } = await refineReaderMap(session.seriesId, feedback, { providerId: reqProviderId, model: reqModel });emit('Saving…', 'persist');@@ -1091,11 +1091,11 @@ export async function refineStep(id, stepId, { feedback, entryId, providerId, moreturn { result: updated, changes, rationale, runId, providerId: usedProviderId, model: usedModel };}if (stepId === 'characters') {- if (!session.universeId) throw makeErr('No universe linked', ERR_VALIDATION);- if (!isStr(entryId)) throw makeErr('entryId is required to refine a character', ERR_VALIDATION);+ if (!session.universeId) throw codedError('No universe linked', ERR_VALIDATION);+ if (!isStr(entryId)) throw codedError('entryId is required to refine a character', ERR_VALIDATION);emit('Refining the character…', 'generate');const out = await refineUniverseCharacter(session.universeId, entryId, { providerId: reqProviderId, model: reqModel });return { result: out.universe, changes: out.changes || [], rationale: out.rationale || '' };}- throw makeErr(`Refine is not supported for step "${stepId}"`, ERR_VALIDATION);+ throw codedError(`Refine is not supported for step "${stepId}"`, ERR_VALIDATION);}diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.jsindex ebafcb2ffd..23a34e9826 100644--- a/server/services/universeBuilder/crud.js+++ b/server/services/universeBuilder/crud.js@@ -16,8 +16,7 @@ import { BIBLE_KEYS, pruneStaleReferenceSheets, mergePreservedSheetPointers } frimport { store } from './storeFacade.js';import {sanitizeTemplate, sanitizeRun, sanitizeImageRefFilename, resolveInfluences,- sanitizeStyleReference, sanitizeInfluences, sanitizeLocked, mergeInfluencesWithLocks,- makeErr, UNIVERSE_ID_RE,+ sanitizeStyleReference, sanitizeInfluences, sanitizeLocked, mergeInfluencesWithLocks, UNIVERSE_ID_RE,ERR_NOT_FOUND, ERR_VALIDATION, ERR_DUPLICATE, ERR_HAS_LIVE_SERIES,NAME_MAX_LENGTH, LOGLINE_MAX, CURRENT_SCHEMA_VERSION, ENTRY_REF_KIND, IMAGE_REFS_PER_ENTRY_MAX,STYLE_REFERENCES_MAX, STYLE_NOTES_MAX,@@ -35,6 +34,7 @@ import {// import is cycle-safe — unlike canonUsage.js, which back-imports this module.import { listSeries } from '../pipeline/series.js';import { isStr, trimTo } from '../../lib/textUtils.js';+import { codedError } from '../../lib/codedError.js';// Once-per-process flag for the canon-backfill log — readState() runs in both// the queue and from un-queued readers, and the in-memory migration is cheap@@ -181,8 +181,8 @@ export async function getUniverse(id, { includeDeleted = false } = {}) {// The store's sanitizer (sanitizeTemplate) runs on the loaded record, so the// returned object is shape-equivalent to what listUniverses would surface.const w = await store().loadOne(id);- if (!w) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);- if (w.deleted && !includeDeleted) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);+ if (!w) throw codedError(`Universe not found: ${id}`, ERR_NOT_FOUND);+ if (w.deleted && !includeDeleted) throw codedError(`Universe not found: ${id}`, ERR_NOT_FOUND);return w;}@@ -245,7 +245,7 @@ export async function needsEntryIdPersist(id) {export async function createUniverse(input = {}) {const name = trimTo(input.name, NAME_MAX_LENGTH);- if (!name) throw makeErr(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);+ if (!name) throw codedError(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);const id = randomUUID();const created = await store().queueRecordWrite(id, async () => {const now = new Date().toISOString();@@ -323,10 +323,10 @@ export async function createUniverse(input = {}) {*/export async function insertUniverseWithId(input = {}) {if (!isStr(input.id) || !UNIVERSE_ID_RE.test(input.id)) {- throw makeErr(`insertUniverseWithId: invalid id "${input.id}"`, ERR_VALIDATION);+ throw codedError(`insertUniverseWithId: invalid id "${input.id}"`, ERR_VALIDATION);}const name = trimTo(input.name, NAME_MAX_LENGTH);- if (!name) throw makeErr(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);+ if (!name) throw codedError(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);const s = store();const { next, wasResurrection } = await s.queueRecordWrite(input.id, async () => {// Tombstone-overwrite: a previously-deleted record with the same id is@@ -337,11 +337,11 @@ export async function insertUniverseWithId(input = {}) {// which is the transport the federation uses.const existing = await s.loadOne(input.id);if (existing && !existing.deleted) {- throw makeErr(`Universe id already exists: ${input.id}`, ERR_DUPLICATE);+ throw codedError(`Universe id already exists: ${input.id}`, ERR_DUPLICATE);}const wasResurrection = !!existing;const next = sanitizeTemplate({ ...input, name });- if (!next) throw makeErr('Invalid universe payload', ERR_VALIDATION);+ if (!next) throw codedError('Invalid universe payload', ERR_VALIDATION);if (wasResurrection) {console.warn(`♻️ insertUniverseWithId: overwriting tombstone for ${input.id}`);}@@ -445,8 +445,8 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {const s = store();const { merged, nameChanged, skipped, removedCharacterIds, prevEphemeral, nextEphemeral } = await s.queueRecordWrite(id, async () => {const cur = await s.loadOne(id);- if (!cur) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);- if (cur.deleted) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Universe not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw codedError(`Universe not found: ${id}`, ERR_NOT_FOUND);let patch;if (isMutator) {@@ -457,7 +457,7 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {// `typeof === 'object'` matches arrays and null — reject both so a stray// `return []` can't slip through and silently no-op the categories merge.if (Array.isArray(patch) || typeof patch !== 'object') {- throw makeErr('updateUniverse mutator must return a plain object or null', ERR_VALIDATION);+ throw codedError('updateUniverse mutator must return a plain object or null', ERR_VALIDATION);}} else {patch = patchOrMutator;@@ -629,7 +629,7 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {llm: mergedLlm,updatedAt: new Date().toISOString(),});- if (!mergedRecord) throw makeErr('Invalid universe payload', ERR_VALIDATION);+ if (!mergedRecord) throw codedError('Invalid universe payload', ERR_VALIDATION);// Stamp `updatedAt = now` on every canon entry whose CONTENT changed vs the// pre-write record. The bible sanitizer preserves a present `updatedAt`, so// an inline edit / AI rewrite that does `{ ...e, ...patch }` keeps the OLD@@ -760,14 +760,14 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {*/export async function addStyleReference(id, reference, { adopt = null } = {}) {const sanitized = sanitizeStyleReference(reference);- if (!sanitized) throw makeErr('Invalid style reference payload', ERR_VALIDATION);+ if (!sanitized) throw codedError('Invalid style reference payload', ERR_VALIDATION);return updateUniverse(id, (cur) => {const current = Array.isArray(cur.styleReferences) ? cur.styleReferences : [];// Idempotent on re-send (a retried request, a double-click): an id already// present is a no-op rather than a duplicate or a cap-exceeded error.if (current.some((ref) => ref?.id === sanitized.id)) return null;if (current.length >= STYLE_REFERENCES_MAX) {- throw makeErr(`A universe can hold up to ${STYLE_REFERENCES_MAX} art references`, ERR_VALIDATION);+ throw codedError(`A universe can hold up to ${STYLE_REFERENCES_MAX} art references`, ERR_VALIDATION);}return {styleReferences: [...current, sanitized],@@ -813,7 +813,7 @@ export async function adoptStyleGuide(id, { styleNotes, influences } = {}) {* removal that raced the image-delete purge is a no-op rather than an error.*/export async function removeStyleReference(id, referenceId) {- if (!isStr(referenceId)) throw makeErr('referenceId is required', ERR_VALIDATION);+ if (!isStr(referenceId)) throw codedError('referenceId is required', ERR_VALIDATION);return updateUniverse(id, (cur) => {const current = Array.isArray(cur.styleReferences) ? cur.styleReferences : [];const next = current.filter((ref) => ref?.id !== referenceId);@@ -844,14 +844,14 @@ export async function deleteUniverse(id) {.map((ser) => ({ id: ser.id, name: ser.name }));if (blockingSeries.length > 0) {throw Object.assign(- makeErr(`Universe has ${blockingSeries.length} live series — move or delete them first`, ERR_HAS_LIVE_SERIES),+ codedError(`Universe has ${blockingSeries.length} live series — move or delete them first`, ERR_HAS_LIVE_SERIES),{ blockingSeries },);}await s.queueRecordWrite(id, async () => {const cur = await s.loadOne(id);- if (!cur) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);- if (cur.deleted) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);+ if (!cur) throw codedError(`Universe not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw codedError(`Universe not found: ${id}`, ERR_NOT_FOUND);const now = new Date().toISOString();const tombstone = { ...cur, deleted: true, deletedAt: now, updatedAt: now };await s.writeRecord(id, tombstone);@@ -877,7 +877,7 @@ export async function deleteUniverse(id) {export async function recordRun(run) {const sanitized = sanitizeRun(run);- if (!sanitized) throw makeErr('Invalid run payload', ERR_VALIDATION);+ if (!sanitized) throw codedError('Invalid run payload', ERR_VALIDATION);// The facade serializes the runs append→cap on its own run-tail (and caps at// 200), so concurrent recordRun + delete-cascade can't clobber each other.await store().appendRun(sanitized);diff --git a/server/services/universeBuilder/sanitize.js b/server/services/universeBuilder/sanitize.jsindex 488dbb579f..8006c5f642 100644--- a/server/services/universeBuilder/sanitize.js+++ b/server/services/universeBuilder/sanitize.js@@ -43,7 +43,6 @@ export const ERR_DUPLICATE = 'DUPLICATE';// thrown error carries `blockingSeries: [{id,name}]` so the route can tell the// user which series to move or delete first. Maps to HTTP 409.export const ERR_HAS_LIVE_SERIES = 'UNIVERSE_HAS_LIVE_SERIES';-export const makeErr = (message, code) => Object.assign(new Error(message), { code });// Universe ids are bare UUIDs (no prefix). Accept any reasonable alphanumeric// id 8–80 chars so future id-scheme changes upstream still round-trip; the