Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([code-quality-dedup-batch]): ship 8 dedup helpers + hook + test

[._.]/ Adam Eivy8ccade84d61e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e8fb936d88..4e08916921 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,6 +17,7 @@
- `/claim` slash command accepts `--review-with=<copilot|codex|gemini|claude>` to pick the post-PR reviewer. Default `copilot` preserves the existing `/do:pr` Copilot loop; `codex`/`gemini`/`claude` skip the Copilot loop and drive an iterative CLI-based review against `gh pr diff` instead (CLIs invoked the same way the PortOS AI Toolkit drives them — `codex exec -`, `gemini -p`, `claude -p -`).
- Removed the CLAUDE.md "Worktrees" section that prohibited TUI worktrees; it conflicted with `/claim`'s explicit worktree requirement.
- **`atomicWrite` migration.** 10 services + 4 aiToolkit modules switched from inline `ensureDir + writeFile + JSON.stringify` to the `atomicWrite` helper (toolkit gets a self-contained copy at `server/lib/aiToolkit/internal/atomicWrite.js`). Prevents partial-write corruption on shared JSON state files.
+- **Code-quality dedup batch.** Eight `/simplify` follow-up items shipped together: new `tryReadFile` helper in `fileUtils.js` (collapses the `readFile(...).catch(() => null)` pattern at ~60 sites); new `optionalBooleanMap` Zod helper (3 sites); new `assertProvider` helper in `promptRunner.js` (7 sites); new `useLockToggle` React hook (4 sites in ArcCanvas + PipelineIssue); three more `resolveProviderAndModel` migrations (agentContentGenerator, agentPersonalityGenerator, loops); TUI text-accumulator skip in `runPromptThroughProvider` (avoids hundreds of KB of screen-redraw concat per TUI run); `loadProviders` JSON.parse rescue (renames `<path>.corrupt.<ts>` instead of crashing boot); new `createProvider` field-parity test guarding the schema-vs-explicit-list regression noted in CLAUDE.md.
- **AI Toolkit runner: PortOS-aware `deleteRun` override.** Now stops the live child process before deleting the run on disk (closes a zombie-process leak when an in-flight CLI run was deleted via the UI).
## Fixed
diff --git a/DONE.md b/DONE.md
index 0a36476ac6..4dacca3598 100644
--- a/DONE.md
+++ b/DONE.md
@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
### 2026-05-19
+- **[code-quality-dedup-batch] Code quality / dedup batch — 8 items shipped together.** (1) `[extract-optionalbooleanmap-zod-helper]` — new `optionalBooleanMap(keys)` helper in `server/lib/validation.js` collapsing the `Object.fromEntries(KEYS.map((k) => [k, z.boolean().optional()]))` pattern at 3 sites (`server/routes/universeBuilder.js`, `server/routes/pipeline.js` ×2). (2) `[extract-a-tryreadfile-helper]` — new `tryReadFile(path, encoding='utf8')` in `server/lib/fileUtils.js` replacing the `readFile(...).catch(() => null)` pattern at ~60 sites across `server/`; `readFile` import removed from 22 files where all uses migrated. Auto-injected `tryReadFile` mock into ~80 test files' `vi.mock('../lib/fileUtils.js')` bodies to keep partial mocks working. (3) `[aitoolkit-loadproviders-corrupt-fallback]` — `loadProviders` in `server/lib/aiToolkit/providers.js` now wraps `JSON.parse` in a `parseOrRescue(content, source)` helper that renames the corrupt user file to `<path>.corrupt.<timestamp>` + logs + returns `{ activeProvider: null, providers: {} }` so a garbled providers.json can't crash server boot. The shipped-sample path parses BEFORE persisting so a malformed sample can't seed user-side providers.json with garbage (per codex review). (4) `[more-resolveproviderandmodel-migration-candidates]` — migrated 3 sites onto the existing `resolveProviderAndModel` helper (`server/services/agentContentGenerator.js#runAIGeneration`, `server/services/agentPersonalityGenerator.js`, `server/services/loops.js#runIteration`); loops.js wraps with `.catch(() => ({ provider: null }))` to preserve the original "swallow all" semantics across both `getProviderById` and `getActiveProvider` failures. (5) `[extract-assertprovider-helper]` — new `assertProvider(provider, { message, code, status = 503 })` helper in `server/lib/promptRunner.js`; throws `ServerError` with code+status when `code` is provided, plain `Error` otherwise (preserves each caller's original error shape). Migrated 7 `if (!provider) throw …` sites (`universeBuilderAutoSort.js`, `universeBuilderRefine.js`, `universeBuilderExpand.js` ×2, `universeBuilderPromote.js`, `agentContentGenerator.js`, `agentPersonalityGenerator.js`). Auto-injected `assertProvider` mock into 6 test files mocking `promptRunner.js`. (6) `[extract-uselocktoggle-hook]` — new `useLockToggle({ patchFn, onSuccess, lockedMessage, unlockedMessage, errorMessage })` returning `{ busy, toggle }` in `client/src/hooks/useLockToggle.js` collapsing the optimistic-PATCH lock toggle pattern at 4 sites: `toggleArcLock`/`FieldLockToggle#toggle`/`toggleSeasonLock` in `client/src/components/pipeline/ArcCanvas.jsx`, `handleStageLockToggle` in `client/src/pages/PipelineIssue.jsx` (removes the now-dead `stageLockSaving` useState). (7) `[skip-the-text-accumulator-in-promptrunner]` — `runPromptThroughProvider`'s `onData` now skips the `APPEND_CHUNK` text concat for TUI providers (which discard the accumulated `text` anyway in favor of `result.text` from `executeTuiRun`); TUI screen-redraw streams can hit hundreds of KB per run. (8) `[aitoolkit-createprovider-field-parity-test]` — new exhaustive test in `server/lib/aiToolkit/providers.test.js` that round-trips all 20 fields defined in `createProvider`'s explicit field list through `create → save → reload`, guarding against the regression where a Zod-schema field is added without being mirrored into the explicit `createProvider` field list. All 5690 server tests + 103 client tests pass; client build clean.
- **[characterdetaileditor-listrow-row-draft-hook] Extract `ListRow`'s multi-column row-draft state into a shared `useRowDraft` hook.** `client/src/components/universe/CharacterDetailEditor.jsx`'s `ListRow` carried 19 lines of inline `useState({})` draft buffer + `draftFor`/`setDraft`/`commit` triple, with the load-bearing sibling-draft "ride-along" merge (`{...row, ...drafts, [col]: v}`) that keeps a fast A-blur → B-blur sequence from losing column A when the parent hasn't re-rendered yet. Lifted into new `client/src/hooks/useRowDraft.js` — the row-level analogue of `useFieldDraft` (single-field draft+blur). Hook signature is `useRowDraft(row, onChange)` returning `{ draftFor, setDraft, commit }`; preserves the ride-along merge verbatim and coerces `null`/`undefined` persisted columns to `''` so inputs stay controlled. `ListRow` collapses to a single hook call. 9 new vitest cases cover persisted/empty fallback, draft buffering without firing onChange, commit no-op when value equals persisted, commit no-op when no draft set, null-as-empty equivalence, the ride-along race-protection invariant (committing column B with a pending column-A draft ships both in one onChange), and that commit clears only the committed column from the drafts map. All 112 client tests pass.
- **Better-audit residue refactor bundle.** Shipped four PLAN.md items from the Better-audit residue section as one PR — three landed as scoped fixes, one was rescoped after the underlying premise eroded. (1) `[medium-client-4-components-still-redefine]` — added `formatTimecode` (M:SS.ss for video timecodes), `formatDurationSec` (M:SS for seconds, `'—'` fallback), and `formatDateShort` (short-month date, `'—'` fallback) to `client/src/utils/formatters.js`; migrated `VideoTimelineEditor.jsx`, `VideoTimeline.jsx`, and `ImportTab.jsx` off their local re-definitions. `MortalLoomTab.jsx` (also named in PLAN) already imported `formatBytes` from the shared module, so no change there. (2) `[medium-perf-feeds-js-getitems-303-319-full-sort]` — `server/services/feeds.js` now maintains the newest-first sort invariant on writes (`addFeed`, `refreshFeed`, `applyParsedFeed` end-of-batch in `refreshAllFeeds`); `getItems` drops the per-call sort. New `ensureItemsSorted()` runs once on first read after server boot to normalize legacy disk data, with an `isSortedNewestFirst()` guard so an already-sorted file isn't re-saved on every restart. (3) `[medium-code-magic-numbers-in-cos-js-166-357]` — replaced the brittle `err.message.startsWith('unknown piper voice:')` check in `routes/voice.js` and the `err.message.includes('not initialized')` check in `services/visionTest.js` with typed error codes. `services/voice/tts.js` now throws `new ServerError(\`unknown piper voice: …\`, { status: 400, code: 'UNKNOWN_VOICE' })`; `services/providers.js` consolidated its nine `if (!aiToolkitInstance) throw new Error(…)` duplicates into a single `requireToolkit()` helper that throws `new ServerError('AI Toolkit not initialized', { status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })`. Both new ServerErrors bubble through `asyncHandler` automatically — the voice.js try/catch around `synthesize` dropped entirely (~10 LOC + 1 narrative comment). visionTest.js's error path now surfaces a more accurate "AI provider service is still initializing" message when the toolkit isn't warmed (previously it masqueraded as "provider not found", sending the user looking for the wrong root cause). Named time constants extracted in `cos.js` (`CD_RECOVERY_BOOT_TIMEOUT_MS = 60_000`, `POST_STARTUP_QUEUE_DELAY_MS = 30_000`, `RECENT_COMPLETION_GRACE_MS = 60_000`) and `lmStudioManager.js` (`DEFAULT_REQUEST_TIMEOUT_MS = 30_000`, `AVAILABILITY_PROBE_TIMEOUT_MS = 5_000`). (4) `[low-client-extract-shared-usepopoverposition-hook]` — **skipped, premise eroded.** The original PLAN flagged 4 components (`AddToCollectionMenu`, `BulkTargetPicker`, `ThemeSwitcher`, `VisualStylePicker`) but `VisualStylePicker` no longer exists in the codebase and `AddToCollectionMenu`/`BulkTargetPicker` no longer use the portal-positioning pattern. Today only `ThemeSwitcher` and `CollectionPickerShell` match the shape; the abstraction isn't worth the indirection at 2 callers. PLAN.md entry rewritten to reflect current state — extract when a 3rd caller lands. Updated `voice.test.js` to mock `ServerError` directly (drops the legacy back-compat test, asserts `code: 'UNKNOWN_VOICE'` on the body); loosened `visionTest.integration.test.js`'s "non-existent provider" assertion to accept either the "not found" branch (toolkit warmed) or "still initializing" branch (toolkit not yet wired in the test context). One `/simplify` follow-up deferred to PLAN.md as `[extract-requiretoolkit-pattern-to-runner-js]` — `runner.js` has 13 more sites of the same inlined `if (!aiToolkitInstance)` check that should adopt the new `requireToolkit()` helper. All 5703 server tests + 103 client tests pass.
- **[clear-pending-sheet-slot-on-entry-delete] Prune `_latestPendingByCharacter` on character / universe delete.** The in-process slot map that supersede-checks character reference-sheet renders previously persisted entries for the full Node process lifetime — even after the character or its universe was deleted. Extracted the Map + its `claim`/`get`/`release` helpers into `server/services/universeCharacterSheetSlot.js` (standalone module so `universeBuilder.js` can clear slots without a `universeCharacterSheet.js → universeBuilder.js` import cycle) and added two delete-path helpers: `clearPendingSheetSlot(universeId, entryId)` (unconditional single-character drop) and `clearPendingSheetSlotsForUniverse(universeId)` (walks the map once, drops every `${universeId}:` prefix). `universeCharacterSheet.js` now consumes `claimPendingSheetSlot` / `getPendingSheetSlot` / `releasePendingSheetSlot` instead of inline `_latestPendingByCharacter.set/.get/.delete` — behavior is unchanged, the supersede-aware contract still holds. Wired into two paths: (a) `deleteUniverse` calls `clearPendingSheetSlotsForUniverse(id)` after the file-write queue releases, alongside the existing `unlinkCollectionsForUniverse` cascade; (b) `updateUniverse` computes a `prevIds`/`nextIds` diff against `cur.characters` vs `mergedRecord.characters` INSIDE the write queue (so the diff sees the freshest persisted state) and calls `clearPendingSheetSlot(id, removedId)` for each dropped id after the queue returns. The in-flight render path is unaffected — if a render's character is deleted mid-flight the slot becomes empty, `onSheetComplete` treats itself as superseded, saves the file on disk, and skips stamping a now-orphaned `referenceSheetImageRef` pointer (the `updateUniverse` mutator inside `onSheetComplete` is also a no-op since the character record is gone). Coverage: 11 new tests in `universeCharacterSheetSlot.test.js` covering claim/get/release contracts, unconditional vs conditional drop, prefix-anchored universe sweep (with explicit anti-collision case proving `u-a` doesn't match `u-ab`), falsy-id no-ops; 3 new integration tests in `universeBuilder.test.js#"pending sheet slot cleanup"` covering character-drop via PATCH, character-preserve when the patch keeps them, and universe-delete clearing only that universe's slots. All 5703 server tests + 14 reused `universeCharacterSheet.test.js` cases pass.
diff --git a/PLAN.md b/PLAN.md
index d29a0dc31d..9a3e32cae8 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -65,10 +65,6 @@ _Nothing currently parked — pick the next item from the Backlog._
### Code quality / dedup (from `/simplify` passes)
-- [ ] [extract-uselocktoggle-hook-for-arc-season-stage-field] **Extract `useLockToggle()` hook.** Four near-identical optimistic-PATCH lock toggles now exist: `toggleArcLock` (`client/src/components/pipeline/ArcCanvas.jsx:208`), `toggleSeasonLock` (same file, ~937), `FieldLockToggle#toggle` (same file, ~570, new in `[per-field-locks-arc-and-stage-granularity]`), `handleStageLockToggle` (`client/src/pages/PipelineIssue.jsx:179`, also new). All share: `useState(busy)` → optimistic PATCH-with-`.catch(() => null)` → `setBusy(false)` → on-success setState + toast. A `useLockToggle({ patchFn, onSuccess, lockedMessage, unlockedMessage })` returning `{ busy, toggle }` would absorb ~80 LOC. Pre-existing toggles AND new ones should be migrated in one pass to avoid the file having two patterns. Surfaced by `/simplify` during `[per-field-locks-arc-and-stage-granularity]`.
-- [ ] [extract-optionalbooleanmap-zod-helper] **Extract `optionalBooleanMap(keys)` Zod helper.** Three call sites now build a Zod sub-schema from a string array of boolean-typed keys via `Object.fromEntries(KEYS.map((k) => [k, z.boolean().optional()]))`: `server/routes/universeBuilder.js:106` (`LOCKABLE_FIELDS`), `server/routes/pipeline.js:183` (`LOCKABLE_STAGES`), and `server/routes/pipeline.js:185` (`ARC_LOCKABLE_FIELDS`, new in `[per-field-locks-arc-and-stage-granularity]`). Tiny helper in `server/lib/validation.js` would collapse each site to `optionalBooleanMap(seriesSvc.ARC_LOCKABLE_FIELDS)`. Surfaced by `/simplify`.
-- [ ] [more-resolveproviderandmodel-migration-candidates] **More `resolveProviderAndModel` migration candidates.** When the helper landed in `server/lib/promptRunner.js` (universe-builder PR), three additional pure two-step provider-resolution chains were left alone to keep scope tight: `server/services/agentContentGenerator.js#runAIGeneration` (line ~80–90), `server/services/agentPersonalityGenerator.js` (line ~68–79), `server/services/loops.js` (line ~64–77). All three are textbook fits (no `enabled` gate, no typed-error throw mid-chain). Migration is one-import + 5-line collapse per file.
-- [ ] [extract-assertprovider-provider-errormessage-code] **Extract `assertProvider(provider, { errorMessage, code, status })` helper.** After the `resolveProviderAndModel` migration there are now 4 `if (!provider) throw …` sites with varying error shapes (`Error` vs `ServerError`, `status: 400/503`, codes `NO_PROVIDER`/`UNIVERSE_PROMOTE_NO_PROVIDER`/etc.). One helper that takes the error-shape args would consolidate without forcing each caller to share the same error type.
- [ ] [extract-mergeexpandintodraft-draft-result-from] **Extract `mergeExpandIntoDraft(draft, result)` from `UniverseBuilder.jsx#handleExpand`.** The function is ~150 lines mixing pure-merge logic (categories, sheets, canon, locks) with I/O shell (API call, setDraft, auto-save, toast). Pull the merge into a top-level pure helper so the I/O surface shrinks and the merge is unit-testable. Deferred from Phase B `/simplify` to keep that PR tightly scoped.
- [x] [auto-save-after-expand-can-clobber-concurrent] ~~**Auto-save after expand can clobber concurrent canon edits.**~~ **Fixed in Phase B Copilot iteration 13** — both `handleExpand`'s auto-save and `handleSave`'s manual-save (when `canonDirty`) now refetch the server's canon via `getUniverse(selectedId)` and merge local additions with `mergeCanonByName` before the update payload is sent. Concurrent edits from NounsStage/other tabs are preserved on identity collision.
- [x] [canon-merge-can-revert-concurrent-deletions] ~~**Canon-merge can revert concurrent deletions/renames.**~~ **Fixed in Phase B Copilot iteration 15** — handleExpand records each merge's NEW canon entries in a `pendingCanonAdditionsRef` sidecar; handleSave + handleExpand auto-save + handleCanonChange now merge ONLY that ledger onto the refetched server canon (not the full stale draft). Concurrent deletions in other tabs/surfaces are preserved because the deleted entry isn't in the ledger, so the server response (which already lacks it) wins.
@@ -79,11 +75,7 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [extract-usecanonpatch-universe-setuniverse] **Extract `useCanonPatch(universe, setUniverse, universeId, mountedRef)`.** `UniverseCanon.jsx` + `NounsStage.jsx` 95% identical optimistic-patch handlers. Extract when a 3rd caller appears.
- [ ] [client-tests-for-deep-routing-drag-smoke-tests-for] **Client tests for deep routing + drag.** Smoke tests for `goToWorld(id)` URL transitions and chip-reorder ordering (mock `useSortable`).
- [ ] [shallow-equal-guard-in-usemediaannotations-socket] **Shallow-equal guard in `useMediaAnnotations` socket handler.** Speculative micro-opt; theoretical until observed.
-- [ ] [extract-a-tryreadfile-path-encoding-utf8-helper] **Extract a `tryReadFile(path, encoding='utf8')` helper into `server/lib/fileUtils.js`.** The `readFile(path).catch(() => null)` pattern is inlined 15+ times across the codebase (`server/routes/apps.js:38` `safeReadJson`, `server/lib/fileUtils.js:505`, `server/lib/hfToken.js:16`, `server/services/agentDrafts.js:22`, `server/services/messageAccounts.js:10`, `server/services/missions.js:35`, `server/lib/tuiPromptRunner.js` new at line ~202, etc.). One helper + migrate; small win, prevents future drift. Defer until next infra pass.
- [ ] [sweep-provider-type-tui-inline-checks-in-client] **Sweep `provider.type === 'tui'` inline checks in client.** New `isTuiProvider` helper in `client/src/utils/providers.js` not yet adopted in `client/src/pages/AIProviders.jsx` (3 remaining inline checks at lines 262, 396, 421 of CONFIG-style chips) and `client/src/components/cos/TaskAddForm.jsx`. Low priority — these are visual chip predicates, not behavioral.
-- [ ] [skip-the-text-accumulator-in-promptrunner] **Skip the `text` accumulator in `promptRunner.runPromptThroughProvider` for TUI providers.** `APPEND_CHUNK(acc, chunk)` runs per stream chunk regardless of provider type, but the TUI branch (post `fix-prose-stage-override`) discards the accumulated `text` and uses `result.text` from `executeTuiRun` instead. Streams can hit hundreds of KB of screen redraws per run — gate the accumulator on `effectiveProvider.type !== 'tui'` in `onData` to skip the per-chunk string concat. Pre-existing buffer cap on `outputBuffer` inside `executeTuiRun` already bounds memory; this is a CPU/alloc micro-opt, not a correctness fix.
-- [ ] [aitoolkit-loadproviders-corrupt-fallback] **`loadProviders` JSON.parse `try/catch` with `.corrupt` rename fallback.** `server/lib/aiToolkit/providers.js:58-79` calls `JSON.parse` unguarded (lines 65, 71); a corrupt file crashes startup. Catch + rename to `.corrupt` + start from empty, with a single-line `console.error` log.
-- [ ] [aitoolkit-createprovider-field-parity-test] **`createProvider` field-parity test.** Existing `providers.test.js` covers basic fields only. Add an exhaustive assertion that every field in `providerSchema` survives the `createProvider → save → loadProviders` round-trip — guards against the `createProvider` field-list regression noted in CLAUDE.md ("`updateProvider` uses spread but `createProvider` has explicit field list").
- [ ] [datasync-migrate-categories-to-atomicwrite] **Migrate all `dataSync.js` categories to `atomicWrite`.** Every category (`goals`, `character`, `digitalTwin`, `meatspace`, `universe`, `pipeline`) inlines `ensureDir + writeFile + JSON.stringify(..., null, 2)` — 6+ duplicate sites. `server/lib/fileUtils.js:124` exports `atomicWrite(path, data)` that handles all three steps as a temp+rename atomic write. One-line collapse per site + meaningful partial-write protection for the larger pipeline JSON files (which other services write concurrently). Surfaced by /simplify during `extend-syncorchestrator-to-cover-pipeline-universe`; deferred to keep that PR focused on the new categories.
- [ ] [datasync-checksum-only-fast-path] **Add a checksum-only fast path to `dataSync.js`.** `getChecksum(category)` currently calls the category's `getSnapshot` and discards `data` (`server/services/dataSync.js:451-456`) — every probe materializes the full payload. With pipeline/universe added the wasted work scales with the largest user-creative payload. Define per-category `getChecksum` shortcuts (e.g. hash file size+mtime, or hash raw bytes without parse) and dispatch via `CATEGORIES[cat].getChecksum`. The orchestrator hits the checksum endpoint every cycle — this is the hottest sync-side I/O. Surfaced by /simplify during `extend-syncorchestrator-to-cover-pipeline-universe`.
- [ ] [extract-flatten-canon-descriptor-fragments-helper] **Extract `flattenCanonDescriptorFragments(fragments, { separator, trailingPeriod })` into `server/lib/canonPrompt.js` (+ client mirror).** The `.map(f => f.prefix ? \`${f.prefix}: ${f.value}\` : f.value).join(...)` pattern is now inlined at 4+ sites: `descriptorForCanonEntry` (server/lib/canonPrompt.js:175 — joins with `. `, no trailing-period), `buildScenePrompt` (server/lib/scenePrompt.js + client mirror — per-frag trailing-period, later joined with single space), `composeComicPagePrompt` (server/services/pipeline/visualStages.js:613 — joins with `. `, no trailing-period), and `synthesizeCanonPrompt` (server/services/universeBuilder.js ~1417). Two flag axes (separator, per-frag trailing-period) collapse to a small helper. Deferred from /simplify during `[pipeline-visual-stages-setting-field-injection]` to keep that PR tightly scoped to the field-injection.
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index d444f5fb2c..465af0aba8 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -33,6 +33,7 @@ import {
import toast from '../ui/Toast';
import { timeAgo } from '../../utils/formatters';
import { useArmedAction } from '../../hooks/useArmedAction';
+import { useLockToggle } from '../../hooks/useLockToggle';
import {
createPipelineIssue, deletePipelineIssue, updatePipelineIssue,
createPipelineSeason, updatePipelineSeason, deletePipelineSeason,
@@ -175,7 +176,18 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
// show its own spinner without blocking the rest of the page.
const [resolvingIdx, setResolvingIdx] = useState(new Set());
const [confirmingRegen, setConfirmingRegen] = useState(false);
- const [lockBusy, setLockBusy] = useState(false);
+ const { busy: lockBusy, toggle: toggleArcLock } = useLockToggle({
+ patchFn: (next) => updatePipelineSeries(series.id, {
+ locked: { ...(series.locked || {}), arc: next },
+ }, { silent: true }),
+ onSuccess: (updated, next) => {
+ onSeriesUpdate(updated);
+ if (next) setConfirmingRegen(false);
+ },
+ lockedMessage: 'Arc locked — regeneration and auto-resolve are now blocked',
+ unlockedMessage: 'Arc unlocked',
+ errorMessage: 'Failed to update lock',
+ });
const llmOverride = useMemo(() => ({
providerOverride: series.llm?.provider || undefined,
@@ -205,23 +217,6 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
toast.success('Arc generated and saved');
};
- const toggleArcLock = async () => {
- const next = !arcLocked;
- setLockBusy(true);
- const updated = await updatePipelineSeries(series.id, {
- locked: { ...(series.locked || {}), arc: next },
- }, { silent: true }).catch((err) => {
- toast.error(err.message || 'Failed to update lock');
- return null;
- });
- setLockBusy(false);
- if (!updated) return;
- onSeriesUpdate(updated);
- if (next) setConfirmingRegen(false);
- toast.success(next
- ? 'Arc locked — regeneration and auto-resolve are now blocked'
- : 'Arc unlocked');
- };
const runVerify = async () => {
setRunning('verify');
const result = await withFlush(() =>
@@ -317,7 +312,7 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
{hasGeneratedArc ? (
<button
type="button"
- onClick={toggleArcLock}
+ onClick={() => toggleArcLock(arcLocked)}
disabled={lockBusy || !!running}
title={arcLocked
? 'Arc is locked — click to unlock and allow regeneration'
@@ -567,24 +562,17 @@ function ThemeChips({ series, arc, onSeriesUpdate }) {
function FieldLockToggle({ series, field, label, onSeriesUpdate }) {
const lockedFields = series.locked?.arcFields || {};
const locked = lockedFields[field] === true;
- const [saving, setSaving] = useState(false);
- const toggle = async () => {
- if (saving) return;
- setSaving(true);
- const updated = await setPipelineArcFieldLock(series.id, field, !locked, { silent: true })
- .catch((err) => {
- toast.error(err.message || `${label} lock update failed`);
- return null;
- });
- setSaving(false);
- if (!updated) return;
- onSeriesUpdate(updated);
- toast.success(locked ? `${label} unlocked` : `${label} locked — preserved on regenerate / auto-resolve`);
- };
+ const { busy: saving, toggle } = useLockToggle({
+ patchFn: (next) => setPipelineArcFieldLock(series.id, field, next, { silent: true }),
+ onSuccess: (updated) => onSeriesUpdate(updated),
+ lockedMessage: `${label} locked — preserved on regenerate / auto-resolve`,
+ unlockedMessage: `${label} unlocked`,
+ errorMessage: `${label} lock update failed`,
+ });
return (
<button
type="button"
- onClick={toggle}
+ onClick={() => toggle(locked)}
disabled={saving}
aria-pressed={locked}
title={locked
@@ -818,8 +806,17 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp
const [editing, setEditing] = useState(false);
const [verifying, setVerifying] = useState(false);
const [verifyIssues, setVerifyIssues] = useState(null);
- const [lockBusy, setLockBusy] = useState(false);
const seasonLocked = season.locked === true;
+ const { busy: lockBusy, toggle: toggleSeasonLock } = useLockToggle({
+ patchFn: (next) => updatePipelineSeason(series.id, season.id, { locked: next }),
+ onSuccess: (updated) => onSeriesUpdate({
+ ...series,
+ seasons: seasons.map((s) => (s.id === season.id ? updated : s)),
+ }),
+ lockedMessage: `Volume ${season.number} locked — generation, delete, and content edits are blocked`,
+ unlockedMessage: `Volume ${season.number} unlocked`,
+ errorMessage: 'Lock toggle failed',
+ });
// Volume beat-sheet bulk run — `active` gates SSE subscription; the latest
// frame drives the per-issue label on the button.
const [beatsActive, setBeatsActive] = useState(false);
@@ -930,24 +927,6 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp
toast.success(`Generated ${n} issue${n === 1 ? '' : 's'} / episode${n === 1 ? '' : 's'}${extractedSummary}`);
};
- const toggleSeasonLock = async () => {
- const next = !seasonLocked;
- setLockBusy(true);
- const updated = await updatePipelineSeason(series.id, season.id, { locked: next }).catch((err) => {
- toast.error(err.message || 'Lock toggle failed');
- return null;
- });
- setLockBusy(false);
- if (!updated) return;
- onSeriesUpdate({
- ...series,
- seasons: seasons.map((s) => (s.id === season.id ? updated : s)),
- });
- toast.success(next
- ? `Volume ${season.number} locked — generation, delete, and content edits are blocked`
- : `Volume ${season.number} unlocked`);
- };
-
// 'idle' | 'confirm' | 'deleting' — drives an inline confirm row that swaps
// in for the Edit/Trash buttons. Two-click "arm" was confusing (see
// feedback memory); inline confirm matches LayoutEditor's pattern.
@@ -994,7 +973,7 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp
<>
<button
type="button"
- onClick={toggleSeasonLock}
+ onClick={() => toggleSeasonLock(seasonLocked)}
disabled={lockBusy}
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs border disabled:opacity-50 ${
seasonLocked
diff --git a/client/src/hooks/useLockToggle.js b/client/src/hooks/useLockToggle.js
new file mode 100644
index 0000000000..314bb478e9
--- /dev/null
+++ b/client/src/hooks/useLockToggle.js
@@ -0,0 +1,33 @@
+import { useState } from 'react';
+import toast from '../components/ui/Toast';
+
+// Shared optimistic-PATCH lock-toggle action. Four near-identical implementations
+// (arc lock, per-arc-field lock, per-season lock, per-stage lock) collapsed to
+// one hook: `setBusy(true) → PATCH-with-catch → setBusy(false) → onSuccess + toast`.
+//
+// Usage:
+// const { busy, toggle } = useLockToggle({
+// patchFn: (next) => updatePipelineSeries(id, { locked: { ...locked, arc: next } }, { silent: true }),
+// onSuccess: (updated, next) => { onSeriesUpdate(updated); if (next) closeConfirm(); },
+// lockedMessage: 'Arc locked — regeneration is now blocked',
+// unlockedMessage: 'Arc unlocked',
+// errorMessage: 'Failed to update lock',
+// });
+// <button disabled={busy} onClick={() => toggle(currentlyLocked)} />
+export function useLockToggle({ patchFn, onSuccess, lockedMessage, unlockedMessage, errorMessage = 'Lock toggle failed' }) {
+ const [busy, setBusy] = useState(false);
+ const toggle = async (currentlyLocked) => {
+ if (busy) return;
+ const next = !currentlyLocked;
+ setBusy(true);
+ const updated = await patchFn(next).catch((err) => {
+ toast.error(err?.message || errorMessage);
+ return null;
+ });
+ setBusy(false);
+ if (!updated) return;
+ onSuccess?.(updated, next);
+ toast.success(next ? lockedMessage : unlockedMessage);
+ };
+ return { busy, toggle };
+}
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
index f7e728bd6f..63c41a9a0c 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -21,6 +21,7 @@ import {
PIPELINE_STAGES, PIPELINE_TAB_STAGES, PIPELINE_STAGE_LABELS,
} from '../services/api';
import { usePipelineAutoRunProgress } from '../hooks/usePipelineAutoRunProgress';
+import { useLockToggle } from '../hooks/useLockToggle';
import IdeaStage from '../components/pipeline/stages/IdeaStage';
import ProseStage from '../components/pipeline/stages/ProseStage';
import NounsStage from '../components/pipeline/stages/NounsStage';
@@ -96,7 +97,6 @@ export default function PipelineIssue() {
const [settingsOpen, setSettingsOpen] = useState(false);
const [lengthProfileSaving, setLengthProfileSaving] = useState(false);
const [genConfigSaving, setGenConfigSaving] = useState(false);
- const [stageLockSaving, setStageLockSaving] = useState(false);
// Close the settings modal whenever the active stage changes so it doesn't
// reopen unexpectedly when the user returns to a previously-visited stage.
useEffect(() => { setSettingsOpen(false); }, [stageId]);
@@ -192,23 +192,19 @@ export default function PipelineIssue() {
// boundary (textStages.generateStage, visualStages.enqueueXxx, etc.).
// The merged Comic tab owns both text (`comicScript`) and render/page
// artifacts (`comicPages`), so it toggles both persisted stages together.
- const handleStageLockToggle = async () => {
- if (stageLockSaving || !issue || !canLockActiveStage) return;
- const next = !activeStageLocked;
- setStageLockSaving(true);
- const stages = Object.fromEntries(activeLockStageIds.map((id) => [id, { locked: next }]));
- const updated = await updatePipelineIssue(issueId, {
- stages,
- }, { silent: true }).catch((err) => {
- toast.error(err.message || `${PIPELINE_STAGE_LABELS[stageId]} lock update failed`);
- return null;
- });
- setStageLockSaving(false);
- if (!updated) return;
- setIssue(updated);
- toast.success(next
- ? `${PIPELINE_STAGE_LABELS[stageId]} locked — regeneration is now blocked`
- : `${PIPELINE_STAGE_LABELS[stageId]} unlocked`);
+ const { busy: stageLockSaving, toggle: toggleStageLock } = useLockToggle({
+ patchFn: (next) => {
+ const stages = Object.fromEntries(activeLockStageIds.map((id) => [id, { locked: next }]));
+ return updatePipelineIssue(issueId, { stages }, { silent: true });
+ },
+ onSuccess: (updated) => setIssue(updated),
+ lockedMessage: `${PIPELINE_STAGE_LABELS[stageId]} locked — regeneration is now blocked`,
+ unlockedMessage: `${PIPELINE_STAGE_LABELS[stageId]} unlocked`,
+ errorMessage: `${PIPELINE_STAGE_LABELS[stageId]} lock update failed`,
+ });
+ const handleStageLockToggle = () => {
+ if (!issue || !canLockActiveStage) return;
+ toggleStageLock(activeStageLocked);
};
const handleStageUpdate = (id, updatedStage, updatedIssue) => {
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 1d3d88f7c6..7ab12dac35 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -1,4 +1,4 @@
-import { readFile } from 'fs/promises';
+import { readFile, rename } from 'fs/promises';
import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { atomicWrite } from './internal/atomicWrite.js';
@@ -50,18 +50,33 @@ export function createProviderService(config = {}) {
const PROVIDERS_PATH = join(dataDir, providersFile);
+ // JSON.parse with a corrupt-file rescue. A garbled providers.json (truncated
+ // write, hand-edit typo, disk corruption) would otherwise crash server boot.
+ // Rename the bad file to <path>.corrupt + start from empty so the CLI can
+ // reseed from the sample on next save.
+ async function parseOrRescue(content, source) {
+ try {
+ return JSON.parse(content);
+ } catch (err) {
+ const corruptPath = `${source}.corrupt.${Date.now()}`;
+ console.error(`❌ providers.json parse failed (${err.message}); renamed to ${corruptPath} and starting from empty`);
+ await rename(source, corruptPath).catch(() => {});
+ return { activeProvider: null, providers: {} };
+ }
+ }
+
async function loadProviders() {
if (!existsSync(PROVIDERS_PATH)) {
if (sampleFile && existsSync(sampleFile)) {
const sample = await readFile(sampleFile, 'utf-8');
await atomicWrite(PROVIDERS_PATH, sample);
- return JSON.parse(sample);
+ return await parseOrRescue(sample, sampleFile);
}
return { activeProvider: null, providers: {} };
}
const content = await readFile(PROVIDERS_PATH, 'utf-8');
- const data = JSON.parse(content);
+ const data = await parseOrRescue(content, PROVIDERS_PATH);
if (migrateCodexProvider(data)) {
await atomicWrite(PROVIDERS_PATH, data);
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index d32a5098e5..186ba9fded 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -118,6 +118,56 @@ describe('Provider Service', () => {
).rejects.toThrow('Provider with this ID already exists');
});
+ // Guards the regression noted in CLAUDE.md: `updateProvider` uses spread so
+ // existing providers preserve custom fields, but `createProvider` has an
+ // explicit field list. A field added to the schema without being added to
+ // `createProvider` would silently disappear on the create → save → load
+ // round-trip. Exhaust every field in the explicit list.
+ it('round-trips every field defined by createProvider through save + reload', async () => {
+ const seed = {
+ id: 'parity-fixture',
+ name: 'Parity Fixture',
+ type: 'tui',
+ command: 'codex',
+ args: ['exec', '--full-auto'],
+ endpoint: 'https://api.example.com/v1',
+ apiKey: 'sk-test-secret',
+ models: ['model-a', 'model-b', 'model-c'],
+ defaultModel: 'model-a',
+ lightModel: 'model-b',
+ mediumModel: 'model-a',
+ heavyModel: 'model-c',
+ fallbackProvider: 'fallback-provider-id',
+ timeout: 600000,
+ enabled: false,
+ envVars: { OPENAI_BASE_URL: 'https://example.com', LOG_LEVEL: 'debug' },
+ secretEnvVars: ['OPENAI_API_KEY', 'ANTHROPIC_API_KEY'],
+ headlessArgs: ['--quiet', '--no-color'],
+ tuiPromptDelayMs: 5000,
+ tuiIdleTimeoutMs: 120000,
+ };
+
+ const created = await providerService.createProvider(seed);
+
+ // First-pass: createProvider itself returns the full record
+ for (const key of Object.keys(seed)) {
+ expect(created[key]).toStrictEqual(seed[key]);
+ }
+
+ // Second-pass: after a fresh service instance reads from disk, every field
+ // must survive the JSON write + parse round-trip
+ const reloadedService = createProviderService({
+ dataDir: TEST_DATA_DIR,
+ providersFile: 'providers.json'
+ });
+ const reloaded = await reloadedService.getProviderById('parity-fixture');
+
+ expect(reloaded).not.toBeNull();
+ for (const key of Object.keys(seed)) {
+ expect(reloaded[key]).toStrictEqual(seed[key]);
+ }
+ });
+
describe('getSampleProviders', () => {
it('should return sample providers from default sample file', async () => {
// No providers created yet — all samples should be returned
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index c2610ede5c..cab9ac7c0f 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -285,6 +285,21 @@ export function safeJSONParse(str, defaultValue = null, { allowArray = true, log
* const config = await readJSONFile('./config.json', { port: 3000 });
* const items = await readJSONFile('./items.json', []);
*/
+/**
+ * Read a file, returning null on any error (missing file, permission denied, etc.).
+ *
+ * Collapses the inlined `readFile(path, encoding).catch(() => null)` pattern used
+ * across services for "optional file — fall through if absent." For Buffer reads,
+ * pass `encoding: null` (or omit when calling with no second arg, default 'utf8').
+ *
+ * @param {string} filePath - Path to read
+ * @param {string|null} [encoding='utf8'] - Encoding (null for Buffer)
+ * @returns {Promise<string|Buffer|null>} File contents or null on any read error
+ */
+export async function tryReadFile(filePath, encoding = 'utf8') {
+ return readFile(filePath, encoding).catch(() => null);
+}
+
export async function readJSONFile(filePath, defaultValue = null, { allowArray = true, logError = true } = {}) {
let content;
try {
diff --git a/server/lib/hfToken.js b/server/lib/hfToken.js
index fa94f89266..4baa3fa3d4 100644
--- a/server/lib/hfToken.js
+++ b/server/lib/hfToken.js
@@ -5,15 +5,15 @@
// Final fallback reads ~/.cache/huggingface/token (written by `hf auth login`)
// so the FLUX.2 banner doesn't nag users who already authenticated via the CLI.
-import { readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
+import { tryReadFile } from './fileUtils.js';
import { getSettings } from '../services/settings.js';
const HF_CLI_TOKEN_PATH = join(homedir(), '.cache', 'huggingface', 'token');
async function readHfCliToken() {
- const buf = await readFile(HF_CLI_TOKEN_PATH, 'utf8').catch(() => null);
+ const buf = await tryReadFile(HF_CLI_TOKEN_PATH);
const trimmed = buf?.trim();
return trimmed || null;
}
diff --git a/server/lib/peerSelfHost.test.js b/server/lib/peerSelfHost.test.js
index 8086c2d8b6..622b1e3eed 100644
--- a/server/lib/peerSelfHost.test.js
+++ b/server/lib/peerSelfHost.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
vi.mock('./fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
safeJSONParse: (s, fallback) => { try { return JSON.parse(s); } catch { return fallback; } }
}));
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index 60af74940e..fbbd21132f 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -29,6 +29,7 @@
import { createRun, executeApiRun, executeCliRun, extractBakedModel, hasModelFlag, stopRun, patchRunMetadata } from '../services/runner.js';
import { getActiveProvider, getProviderById } from '../services/providers.js';
import { executeTuiRun } from './tuiPromptRunner.js';
+import { ServerError } from './errorHandler.js';
const DEFAULT_TIMEOUT_MS = 300000;
const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk : (chunk?.text || ''));
@@ -104,6 +105,26 @@ export async function resolveProviderAndModel({ providerId, model } = {}) {
return { provider, selectedModel };
}
+/**
+ * Throw a typed "no AI provider available" error when `provider` is falsy.
+ *
+ * Sites that surface to HTTP route handlers should pass `code` (+ optional
+ * `status`, defaults to 503) so the centralized error middleware emits a
+ * structured response. Sites that are internal-only (service-to-service)
+ * can omit both and get a plain `Error` — matching the legacy shape.
+ *
+ * @param {object|null} provider
+ * @param {object} opts
+ * @param {string} opts.message — human-readable error message
+ * @param {string} [opts.code] — error code constant (e.g. `NO_PROVIDER`)
+ * @param {number} [opts.status=503] — HTTP status; only used when `code` is set
+ */
+export function assertProvider(provider, { message, code, status = 503 } = {}) {
+ if (provider) return;
+ if (code) throw new ServerError(message, { status, code });
+ throw new Error(message);
+}
+
/**
* Run a prompt through a provider and resolve with the streamed text +
* run id. Rejects (via the strictest discriminator) on any runner-
@@ -228,8 +249,12 @@ export async function runPromptThroughProvider({ provider, prompt, source, model
const safeResolve = (value) => { if (!settled) { settled = true; if (apiTimeoutHandle) clearTimeout(apiTimeoutHandle); resolve(value); } };
const safeReject = (err) => { if (!settled) { settled = true; if (apiTimeoutHandle) clearTimeout(apiTimeoutHandle); reject(err); } };
+ // TUI runs discard `text` and use `result.text` from executeTuiRun (see
+ // onComplete below), so the per-chunk APPEND_CHUNK concat is pure waste —
+ // TUI streams can emit hundreds of KB of screen redraws per run.
+ const isTui = effectiveProvider.type === 'tui';
const onData = (chunk) => {
- text = APPEND_CHUNK(text, chunk);
+ if (!isTui) text = APPEND_CHUNK(text, chunk);
if (onDataCallback) {
const chunkText = typeof chunk === 'string' ? chunk : (chunk?.text || '');
if (chunkText) onDataCallback(chunkText);
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
index a3281654e6..a2a6abc843 100644
--- a/server/lib/storyBible.test.js
+++ b/server/lib/storyBible.test.js
@@ -242,6 +242,7 @@ describe('storyBible — sanitizeCharacter', () => {
it('caps the list at BIBLE_LIMITS.WARDROBES_PER_CHARACTER_MAX', () => {
const tooMany = Array.from({ length: BIBLE_LIMITS.WARDROBES_PER_CHARACTER_MAX + 5 }, (_, i) => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
name: `Outfit ${i}`,
}));
const out = sanitizeCharacter({ name: 'A', wardrobes: tooMany });
diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.js
index 2867b2f660..b9176b158d 100644
--- a/server/lib/tuiPromptRunner.js
+++ b/server/lib/tuiPromptRunner.js
@@ -26,9 +26,9 @@
*/
import { spawn as ptySpawn } from 'node-pty';
-import { readFile } from 'fs/promises';
+
import { join, resolve } from 'path';
-import { ensureDir, PATHS } from './fileUtils.js';
+import { ensureDir, PATHS, tryReadFile } from './fileUtils.js';
import { createStreamingAnsiStripper } from './ansiStrip.js';
import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun } from '../services/runner.js';
import {
@@ -394,7 +394,7 @@ ${prompt}`;
*/
export async function resolveTuiResponseText({ success, responseFilePath, outputBuffer, wrappedPrompt }) {
if (success) {
- const fileText = await readFile(responseFilePath, 'utf8').catch(() => null);
+ const fileText = await tryReadFile(responseFilePath);
if (typeof fileText === 'string' && fileText.trim()) {
return { text: fileText.trim(), usedResponseFile: true };
}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 16aa3085af..91f474536b 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -19,6 +19,13 @@ export const refineImagePixelCap = (d) =>
!(d.width && d.height) || d.width * d.height <= MAX_IMAGE_PIXELS;
export const PIXEL_CAP_MESSAGE = `Total pixels (width × height) must be ≤ ${MAX_IMAGE_PIXELS.toLocaleString()}`;
+// Build a sparse-map Zod shape from a string array of boolean-typed keys.
+// Returns the raw record so callers can either spread it (...optionalBooleanMap(KEYS))
+// into a larger object schema or wrap it directly (z.object(optionalBooleanMap(KEYS))).
+// Mirrors the `{ field?: boolean }` shape used for per-field lock maps.
+export const optionalBooleanMap = (keys) =>
+ Object.fromEntries(keys.map((k) => [k, z.boolean().optional()]));
+
// =============================================================================
// AGENT PERSONALITY SCHEMAS
// =============================================================================
diff --git a/server/routes/apps.js b/server/routes/apps.js
index 5db4793e07..d9df6fb30e 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -2,7 +2,7 @@ import { Router } from 'express';
import { spawn } from 'child_process';
import { readFile, writeFile, stat, access, mkdir } from 'fs/promises';
import { join, resolve, extname } from 'path';
-import { PATHS } from '../lib/fileUtils.js';
+import { PATHS, tryReadFile } from '../lib/fileUtils.js';
import * as appsService from '../services/apps.js';
import { notifyAppsChanged, PORTOS_APP_ID } from '../services/apps.js';
import * as pm2Service from '../services/pm2.js';
@@ -971,7 +971,7 @@ router.post('/:id/refresh-config', loadApp, asyncHandler(async (req, res) => {
// Detect buildCommand from package.json if not already set
if (!app.buildCommand) {
const pkgPath = join(app.repoPath, 'package.json');
- const pkgContent = await readFile(pkgPath, 'utf-8').catch(() => null);
+ const pkgContent = await tryReadFile(pkgPath);
if (pkgContent) {
const pkg = safeJSONParse(pkgContent);
if (pkg?.scripts?.build) updates.buildCommand = 'npm run build';
diff --git a/server/routes/avatar.test.js b/server/routes/avatar.test.js
index 3feec9c7e4..2976342947 100644
--- a/server/routes/avatar.test.js
+++ b/server/routes/avatar.test.js
@@ -11,6 +11,7 @@ vi.mock('fs', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' }
}));
diff --git a/server/routes/detect.js b/server/routes/detect.js
index 8a8a8bfab7..3ab1a26d66 100644
--- a/server/routes/detect.js
+++ b/server/routes/detect.js
@@ -7,7 +7,7 @@ import { promisify } from 'util';
import { execPm2 } from '../services/pm2.js';
import { detectAppWithAi } from '../services/aiDetect.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
const execAsync = promisify(exec);
const router = Router();
@@ -53,7 +53,7 @@ router.post('/repo', asyncHandler(async (req, res) => {
const packageJsonPath = join(path, 'package.json');
if (existsSync(packageJsonPath)) {
result.hasPackageJson = true;
- const content = await readFile(packageJsonPath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(packageJsonPath);
if (content) {
const pkg = safeJSONParse(content, null);
if (!pkg) {
diff --git a/server/routes/imageGen.clean.test.js b/server/routes/imageGen.clean.test.js
index 49dc4a4eff..622b02c3fb 100644
--- a/server/routes/imageGen.clean.test.js
+++ b/server/routes/imageGen.clean.test.js
@@ -39,6 +39,7 @@ vi.mock('../services/imageGen/index.js', async () => {
});
vi.mock('../services/settings.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
getSettings: vi.fn(async () => ({ imageGen: { mode: 'external' } })),
}));
diff --git a/server/routes/imageGen.multipart.test.js b/server/routes/imageGen.multipart.test.js
index a352cad005..3f49063f3e 100644
--- a/server/routes/imageGen.multipart.test.js
+++ b/server/routes/imageGen.multipart.test.js
@@ -42,6 +42,7 @@ vi.mock('../services/imageGen/index.js', async () => {
// reference-image gate. Default: `mode: 'local'` with a fake pythonPath.
let mockedSettings = { imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } };
vi.mock('../services/settings.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
getSettings: vi.fn(async () => mockedSettings),
}));
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index c11e367ff3..573d2d37d0 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -30,6 +30,7 @@ import {
imageEdgeSchema,
refineImagePixelCap,
PIXEL_CAP_MESSAGE,
+ optionalBooleanMap,
} from '../lib/validation.js';
import * as seriesSvc from '../services/pipeline/series.js';
@@ -176,10 +177,8 @@ const seasonSchema = z.object({
// holds the per-field arc locks (logline / summary / themes / etc.) that
// `commitSeasonsWithRemap` honors when rewriting `series.arc`.
const seriesLockedSchema = z.object({
- ...Object.fromEntries(seriesSvc.LOCKABLE_STAGES.map((k) => [k, z.boolean().optional()])),
- arcFields: z.object(
- Object.fromEntries(seriesSvc.ARC_LOCKABLE_FIELDS.map((k) => [k, z.boolean().optional()])),
- ).optional(),
+ ...optionalBooleanMap(seriesSvc.LOCKABLE_STAGES),
+ arcFields: z.object(optionalBooleanMap(seriesSvc.ARC_LOCKABLE_FIELDS)).optional(),
}).passthrough();
const seriesCreateSchema = z.object({
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 1f703603d0..9a0bae0478 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -6,6 +6,7 @@ import { errorMiddleware } from '../lib/errorHandler.js';
const fileStore = new Map();
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/routes/sdapi.js b/server/routes/sdapi.js
index bd2f84f7a2..0605879935 100644
--- a/server/routes/sdapi.js
+++ b/server/routes/sdapi.js
@@ -16,11 +16,11 @@
*/
import { Router } from 'express';
-import { readFile } from 'fs/promises';
+
import { join } from 'path';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { PATHS } from '../lib/fileUtils.js';
+import { PATHS, tryReadFile } from '../lib/fileUtils.js';
import { getSettings } from '../services/settings.js';
import { generateImage, getMode, getActiveJob } from '../services/imageGen/index.js';
import { local as localImage } from '../services/imageGen/index.js';
@@ -213,7 +213,7 @@ router.post('/txt2img', asyncHandler(async (req, res) => {
// it with a 5xx instead of returning images:[] (which A1111 clients
// silently treat as a no-op).
const filePath = join(PATHS.images, result.filename);
- const buf = await readFile(filePath).catch(() => null);
+ const buf = await tryReadFile(filePath, null);
if (!buf) {
throw new ServerError(`Generation completed but ${result.filename} could not be read`, { status: 500, code: 'GEN_OUTPUT_MISSING' });
}
diff --git a/server/routes/sdapi.test.js b/server/routes/sdapi.test.js
index beacc340a2..30ac89854b 100644
--- a/server/routes/sdapi.test.js
+++ b/server/routes/sdapi.test.js
@@ -26,18 +26,15 @@ vi.mock('../services/videoGen/local.js', () => ({
defaultVideoModelId: vi.fn(() => 'ltx_video'),
}));
-vi.mock('fs/promises', () => ({
- readFile: vi.fn(),
-}));
-
vi.mock('../lib/fileUtils.js', () => ({
+ tryReadFile: vi.fn(),
PATHS: { images: '/mock/images' },
}));
import { getSettings } from '../services/settings.js';
import * as imageGen from '../services/imageGen/index.js';
import { imageGenEvents as realEmitter } from '../services/imageGenEvents.js';
-import { readFile } from 'fs/promises';
+import { tryReadFile } from '../lib/fileUtils.js';
import sdapiRoutes from './sdapi.js';
const enabled = () => getSettings.mockResolvedValue({ imageGen: { expose: { a1111: true } } });
@@ -144,7 +141,7 @@ describe('sdapi routes — A1111-compatible surface', () => {
generationId: 'g-1', filename: 'g-1.png', path: '/data/images/g-1.png',
mode: 'external', model: 'sd-1.5', seed: 1234,
});
- readFile.mockResolvedValue(Buffer.from([1, 2, 3]));
+ tryReadFile.mockResolvedValue(Buffer.from([1, 2, 3]));
const r = await request(app).post('/sdapi/v1/txt2img').send({ prompt: 'a cat', width: 512, height: 512 });
@@ -163,7 +160,7 @@ describe('sdapi routes — A1111-compatible surface', () => {
generationId: 'g-2', filename: 'g-2.png', path: '/data/images/g-2.png',
mode: 'external', model: 'sd-1.5', seed: 1,
});
- readFile.mockResolvedValue(null);
+ tryReadFile.mockResolvedValue(null);
const r = await request(app).post('/sdapi/v1/txt2img').send({ prompt: 'a cat' });
expect(r.status).toBe(500);
@@ -186,7 +183,7 @@ describe('sdapi routes — A1111-compatible surface', () => {
setImmediate(() => realEmitter.emit('completed', { generationId: 'g-3', seed: 4242 }));
return result;
});
- readFile.mockResolvedValue(Buffer.from('png'));
+ tryReadFile.mockResolvedValue(Buffer.from('png'));
const r = await request(app).post('/sdapi/v1/txt2img').send({ prompt: 'fire' });
expect(r.status).toBe(200);
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index f0a3bac60e..ae9f8f205a 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -15,7 +15,7 @@ import { Router } from 'express';
import { z } from 'zod';
import { randomUUID } from 'crypto';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { validateRequest } from '../lib/validation.js';
+import { validateRequest, optionalBooleanMap } from '../lib/validation.js';
import * as svc from '../services/universeBuilder.js';
import * as canonSvc from '../services/universeCanon.js';
import { expandUniverseCharacter } from '../services/universeCharacterExpand.js';
@@ -103,7 +103,7 @@ export const llmSchema = z.object({
// PATCHing a previously saved lock map still pass validation (sanitizeLocked
// rewrites it on read into the per-list keys).
const lockedSchema = z.object({
- ...Object.fromEntries(svc.LOCKABLE_FIELDS.map((k) => [k, z.boolean().optional()])),
+ ...optionalBooleanMap(svc.LOCKABLE_FIELDS),
influences: z.boolean().optional(),
}).strict();
diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.js
index c345490b46..0963694a36 100644
--- a/server/routes/universeBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -7,6 +7,7 @@ import { enqueueJob } from '../services/mediaJobQueue/index.js';
const fileStore = new Map();
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 3dc4e9c503..e9c6c5f9e0 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -58,6 +58,7 @@ vi.mock('../lib/multipart.js', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { images: '/mock/images', videos: '/mock/videos', uploads: '/mock/uploads' },
// Route awaits ensureDir before staging the upload; no-op for tests since
// we mock copyFile too.
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index e5a0ff083d..f028db6877 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -29,6 +29,7 @@ vi.mock('./agentState.js', () => ({
userTerminatedAgents: new Set(),
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
safeJSONParse: (str, fallback) => { try { return JSON.parse(str); } catch { return fallback; } },
PATHS: { root: '/tmp', cosAgents: '/tmp/agents', data: '/tmp/data' },
}));
diff --git a/server/services/agentContentGenerator.js b/server/services/agentContentGenerator.js
index 915d5deb19..a15ccf18da 100644
--- a/server/services/agentContentGenerator.js
+++ b/server/services/agentContentGenerator.js
@@ -5,10 +5,9 @@
* Includes recent activity context to avoid repetition.
*/
-import { getActiveProvider, getProviderById } from './providers.js';
import * as agentActivity from './agentActivity.js';
import { safeJSONParse } from '../lib/fileUtils.js';
-import { runPromptThroughProvider } from '../lib/promptRunner.js';
+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';
/**
* Parse JSON from AI response text (handles markdown blocks, extra text)
@@ -78,16 +77,8 @@ export async function getRecentAgentContent(agentId, actionType, limit = 5) {
* Run AI generation using the same pattern as agentPersonalityGenerator
*/
async function runAIGeneration(prompt, providerId, model, source) {
- let provider;
- if (providerId) {
- provider = await getProviderById(providerId).catch(() => null);
- }
- if (!provider) {
- provider = await getActiveProvider();
- }
- if (!provider) {
- throw new Error('No AI provider available for content generation');
- }
+ const { provider } = await resolveProviderAndModel({ providerId, model });
+ assertProvider(provider, { message: 'No AI provider available for content generation' });
const { text: responseText, model: selectedModel } = await runPromptThroughProvider({
provider, prompt, source, model,
diff --git a/server/services/agentDrafts.js b/server/services/agentDrafts.js
index 3814337d17..e72a350eab 100644
--- a/server/services/agentDrafts.js
+++ b/server/services/agentDrafts.js
@@ -5,10 +5,9 @@
* Drafts are stored as JSON files: data/agents/drafts/{agentId}.json
*/
-import { readFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { atomicWrite, ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
const DRAFTS_DIR = join(PATHS.agentPersonalities, 'drafts');
@@ -19,7 +18,7 @@ async function getDraftsPath(agentId) {
async function loadDrafts(agentId) {
const filePath = await getDraftsPath(agentId);
- const content = await readFile(filePath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(filePath);
if (!content) return [];
return safeJSONParse(content, [], { context: `agentDrafts:${agentId}` });
}
diff --git a/server/services/agentDrafts.test.js b/server/services/agentDrafts.test.js
index 92fa87c9c8..96933a7a79 100644
--- a/server/services/agentDrafts.test.js
+++ b/server/services/agentDrafts.test.js
@@ -22,6 +22,7 @@ vi.mock('../lib/uuid.js', () => {
});
vi.mock('../lib/fileUtils.js', () => ({
+ tryReadFile: vi.fn(async (path) => fileStore.has(path) ? fileStore.get(path) : null),
atomicWrite: vi.fn(async (path, data) => {
fileStore.set(path, typeof data === 'string' ? data : JSON.stringify(data, null, 2));
}),
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 633ca155eb..7098be1d74 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -17,7 +17,7 @@ import { getActiveProvider, getAllProviders, getProviderById } from './providers
import { isProviderAvailable, markProviderUsageLimit, markProviderRateLimited, getFallbackProvider, getProviderStatus } from './providerStatus.js';
import { PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
-import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';
import { getAppById } from './apps.js';
import { createToolExecution, startExecution, completeExecution, errorExecution } from './toolStateMachine.js';
import { determineLane, acquire, release } from './executionLanes.js';
@@ -878,7 +878,7 @@ export async function extractPipelineOutputSummary(task, workspacePath, outputBu
// For review stages: read REVIEW.md from workspace (the deliverable)
if (promptKey.includes('review') && !promptKey.includes('implement') && workspacePath) {
const reviewPath = join(workspacePath, 'REVIEW.md');
- const content = await readFile(reviewPath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(reviewPath);
if (content?.trim()) return content.trim();
}
@@ -1210,7 +1210,7 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
const planWorkspace = agentState?.metadata?.workspacePath || task?.metadata?.repoPath || ROOT_DIR;
const markerPath = join(planWorkspace, '.plan-questions.md');
- const markerContent = await readFile(markerPath, 'utf8').catch(() => null);
+ const markerContent = await tryReadFile(markerPath);
if (markerContent) {
const titleMatch = markerContent.match(/^#\s+Plan Question:\s*(.+)/m);
const title = titleMatch?.[1]?.trim() || 'PLAN.md item needs your input';
diff --git a/server/services/agentPersonalityGenerator.js b/server/services/agentPersonalityGenerator.js
index 2f0d10b7b5..94b011900b 100644
--- a/server/services/agentPersonalityGenerator.js
+++ b/server/services/agentPersonalityGenerator.js
@@ -5,8 +5,7 @@
* Generates style, tone, topics, quirks, and prompt prefix for social platform agents.
*/
-import { runPromptThroughProvider } from '../lib/promptRunner.js';
-import { getActiveProvider, getProviderById } from './providers.js';
+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';
const GENERATION_PROMPT = `You are creating a unique AI agent personality for a social media platform where AI agents interact with each other and humans.
@@ -65,18 +64,8 @@ export async function generateAgentPersonality(seed = {}, providerId = null, mod
console.log(`🎨 Generating personality${hasName ? ` for "${name}"` : ' (full generation)'}`);
- // Get provider
- let provider;
- if (providerId) {
- provider = await getProviderById(providerId).catch(() => null);
- }
- if (!provider) {
- provider = await getActiveProvider();
- }
-
- if (!provider) {
- throw new Error('No AI provider available for personality generation');
- }
+ const { provider } = await resolveProviderAndModel({ providerId, model });
+ assertProvider(provider, { message: 'No AI provider available for personality generation' });
// Caller's requested model — passed to the central handler as a hint.
// The handler returns the model that actually executed, which is what
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index e693f6e124..68928f3998 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -7,7 +7,7 @@
*/
import { join } from 'path';
-import { readFile, stat } from 'fs/promises';
+import { stat } from 'fs/promises';
import { homedir } from 'os';
import { getMemorySection } from './memoryRetriever.js';
import { getDigitalTwinForPrompt } from './digital-twin.js';
@@ -15,7 +15,7 @@ import { buildPrompt } from './promptService.js';
import { getToolsSummaryForPrompt } from './tools.js';
import { getActiveProvider } from './providers.js';
import { runPromptThroughProvider } from '../lib/promptRunner.js';
-import { readJSONFile, loadSlashdoFile, PATHS } from '../lib/fileUtils.js';
+import { readJSONFile, loadSlashdoFile, PATHS, tryReadFile } from '../lib/fileUtils.js';
import * as jiraService from './jira.js';
import { emitLog } from './cosEvents.js';
@@ -76,7 +76,7 @@ export function detectSkillTemplate(task) {
* @returns {Promise<string|null>} Template content or null
*/
export async function loadSkillTemplate(skillName) {
- const content = await readFile(join(SKILLS_DIR, `${skillName}.md`), 'utf-8').catch(() => null);
+ const content = await tryReadFile(join(SKILLS_DIR, `${skillName}.md`));
if (content) console.log(`🎯 Loaded skill template: ${skillName}`);
return content;
}
@@ -90,14 +90,14 @@ export async function getClaudeMdContext(workspaceDir) {
// Try to read global CLAUDE.md from ~/.claude/CLAUDE.md
const globalPath = join(homedir(), '.claude', 'CLAUDE.md');
- const globalContent = await readFile(globalPath, 'utf-8').catch(() => null);
+ const globalContent = await tryReadFile(globalPath);
if (globalContent?.trim()) {
contexts.push({ type: 'Global Instructions', path: globalPath, content: globalContent.trim() });
}
// Try to read project-specific CLAUDE.md from workspace directory
const projectPath = join(workspaceDir, 'CLAUDE.md');
- const projectContent = await readFile(projectPath, 'utf-8').catch(() => null);
+ const projectContent = await tryReadFile(projectPath);
if (projectContent?.trim()) {
contexts.push({ type: 'Project Instructions', path: projectPath, content: projectContent.trim() });
}
@@ -478,9 +478,9 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch
if (hasPlanningDir) {
const planningParts = [];
const [stateContent, concernsContent, roadmapContent] = await Promise.all([
- readFile(join(planningPath, 'STATE.md'), 'utf-8').catch(() => null),
- readFile(join(planningPath, 'CONCERNS.md'), 'utf-8').catch(() => null),
- readFile(join(planningPath, 'ROADMAP.md'), 'utf-8').catch(() => null)
+ tryReadFile(join(planningPath, 'STATE.md')),
+ tryReadFile(join(planningPath, 'CONCERNS.md')),
+ tryReadFile(join(planningPath, 'ROADMAP.md'))
]);
if (stateContent) planningParts.push(`### Current State\n\`\`\`\n${stateContent.slice(0, 1000)}\n\`\`\``);
if (concernsContent) planningParts.push(`### Known Concerns\n\`\`\`\n${concernsContent.slice(0, 1500)}\n\`\`\``);
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index c6830e2567..cf1ac4640f 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -35,6 +35,12 @@ vi.mock('./providers.js', () => ({
getActiveProvider: vi.fn().mockResolvedValue(null),
}));
vi.mock('../lib/promptRunner.js', () => ({
+assertProvider: (provider, { message, code, status = 503 } = {}) => {
+ if (provider) return;
+ const err = new Error(message || 'No AI provider available');
+ if (code) { err.status = status; err.code = code; }
+ throw err;
+ },
runPromptThroughProvider: vi.fn().mockResolvedValue(null),
}));
vi.mock('../lib/fileUtils.js', async (importOriginal) => {
@@ -45,6 +51,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {
};
});
vi.mock('./jira.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
createTicket: vi.fn().mockResolvedValue(null),
}));
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index e19c098ba8..e033e382f7 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -75,6 +75,7 @@ vi.mock('fs/promises', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { root: '/tmp/portos-root' }
}));
diff --git a/server/services/aiDetect.js b/server/services/aiDetect.js
index 85440a3957..200320055c 100644
--- a/server/services/aiDetect.js
+++ b/server/services/aiDetect.js
@@ -3,7 +3,7 @@ import { existsSync } from 'fs';
import { join, basename } from 'path';
import { getActiveProvider, getProviderById } from './providers.js';
import { spawn } from 'child_process';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
/**
* Gather project context for AI analysis
@@ -24,7 +24,7 @@ async function gatherProjectContext(dirPath) {
// Read package.json
const pkgPath = join(dirPath, 'package.json');
if (existsSync(pkgPath)) {
- const content = await readFile(pkgPath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(pkgPath);
if (content) {
context.packageJson = content;
}
@@ -43,7 +43,7 @@ async function gatherProjectContext(dirPath) {
for (const pattern of configPatterns) {
const configPath = join(dirPath, pattern);
if (existsSync(configPath)) {
- const content = await readFile(configPath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(configPath);
if (content) {
context.configFiles.push({ name: pattern, content: content.substring(0, 2000) });
}
diff --git a/server/services/appIconDetect.js b/server/services/appIconDetect.js
index fb89cda330..f904781e1d 100644
--- a/server/services/appIconDetect.js
+++ b/server/services/appIconDetect.js
@@ -1,7 +1,7 @@
import { existsSync } from 'fs';
-import { readFile, readdir } from 'fs/promises';
+import { readdir } from 'fs/promises';
import { join, extname } from 'path';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
/**
* Well-known icon paths to check, ordered by priority.
@@ -61,7 +61,7 @@ const CONTENT_TYPES = {
// even though the file exists. Skip them and let detection fall through to a
// sibling PNG/raster file. Inline data: URIs are fine.
export async function isUsableSvg(filePath) {
- const content = await readFile(filePath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(filePath);
if (content === null) return false;
const externalImage = /<image\b[^>]*\b(?:xlink:)?href\s*=\s*['"](?!data:)/i;
return !externalImage.test(content);
@@ -115,7 +115,7 @@ async function findXcodeAppIcon(repoPath) {
// Read Contents.json to find actual icon filenames and sizes
const contentsPath = join(iconSetPath, 'Contents.json');
if (existsSync(contentsPath)) {
- const contents = await readFile(contentsPath, 'utf-8').catch(() => null);
+ const contents = await tryReadFile(contentsPath);
if (contents) {
const parsed = safeJSONParse(contents, {})?.images || [];
// Find the largest icon by parsing size (prefer 1024x1024, then smaller)
diff --git a/server/services/apps.test.js b/server/services/apps.test.js
index 893cd1168c..60cd7542c2 100644
--- a/server/services/apps.test.js
+++ b/server/services/apps.test.js
@@ -5,6 +5,7 @@ vi.mock('fs/promises', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
atomicWrite: vi.fn().mockResolvedValue(undefined),
ensureDir: vi.fn().mockResolvedValue(undefined),
readJSONFile: vi.fn(),
diff --git a/server/services/autobiography.test.js b/server/services/autobiography.test.js
index 1d000def55..7cff7f8ad0 100644
--- a/server/services/autobiography.test.js
+++ b/server/services/autobiography.test.js
@@ -60,6 +60,7 @@ import {
// Helper: build stories data
const makeStoriesData = (overrides = {}) => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
version: 1,
stories: [],
usedPrompts: [],
diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.js
index 785edaee39..c52e9a19fd 100644
--- a/server/services/autonomousJobs.js
+++ b/server/services/autonomousJobs.js
@@ -14,14 +14,14 @@
* - Custom user-defined jobs
*/
-import { writeFile, readFile, rename, readdir, stat, rm } from 'fs/promises'
+import { writeFile, rename, readdir, stat, rm } from 'fs/promises'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import { existsSync } from 'fs'
import { v4 as uuidv4 } from '../lib/uuid.js'
import { spawn } from 'child_process'
import { cosEvents } from './cosEvents.js'
-import { DAY, ensureDir, HOUR, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js'
+import { DAY, ensureDir, HOUR, PATHS, readJSONFile, atomicWrite, tryReadFile } from '../lib/fileUtils.js'
import { createMutex } from '../lib/asyncMutex.js'
import { checkAndPrompt as autobiographyCheckAndPrompt } from './autobiography.js'
import { runGoalCheckIn } from './goalCheckIn.js'
@@ -481,9 +481,9 @@ async function syncSkillTemplatesFromSample() {
if (!file.endsWith('.md')) continue
const destPath = join(JOBS_SKILLS_DIR, file)
const shippedPath = join(shippedDir, file)
- const sampleContent = await readFile(join(sampleDir, file), 'utf-8').catch(() => null)
+ const sampleContent = await tryReadFile(join(sampleDir, file))
if (!sampleContent) continue
- const existingContent = await readFile(destPath, 'utf-8').catch(() => null)
+ const existingContent = await tryReadFile(destPath)
if (!existingContent) {
// Case a: fresh install — seed file and record shipped snapshot
await writeFile(destPath, sampleContent)
@@ -493,11 +493,11 @@ async function syncSkillTemplatesFromSample() {
}
if (existingContent === sampleContent) {
// Case b: file already matches sample — ensure .shipped is current
- const shippedContent = await readFile(shippedPath, 'utf-8').catch(() => null)
+ const shippedContent = await tryReadFile(shippedPath)
if (shippedContent !== sampleContent) await writeFile(shippedPath, sampleContent)
continue
}
- const shippedContent = await readFile(shippedPath, 'utf-8').catch(() => null)
+ const shippedContent = await tryReadFile(shippedPath)
if (existingContent === shippedContent) {
// Case c: file matches last-shipped snapshot but sample has changed — safe to update
await writeFile(destPath, sampleContent)
@@ -537,7 +537,7 @@ async function loadJobs() {
*/
async function migrateScriptsState(jobsData) {
const scriptsFile = join(DATA_DIR, 'scripts-state.json')
- const raw = await readFile(scriptsFile, 'utf-8').catch(() => null)
+ const raw = await tryReadFile(scriptsFile)
if (!raw) return false
let scriptsState
@@ -1101,7 +1101,7 @@ async function toggleJob(jobId) {
*/
async function loadJobSkillTemplate(skillName) {
const filePath = join(JOBS_SKILLS_DIR, `${skillName}.md`)
- const content = await readFile(filePath, 'utf-8').catch(() => null)
+ const content = await tryReadFile(filePath)
if (content) {
console.log(`🎯 Loaded job skill template: ${skillName}`)
}
@@ -1379,7 +1379,6 @@ async function executeScriptJob(job) {
return result
}
-
/**
* Execute a shell job directly (no AI agent needed)
*/
diff --git a/server/services/autonomousJobs.syncSkillTemplates.test.js b/server/services/autonomousJobs.syncSkillTemplates.test.js
index 22919a21d4..805da5177c 100644
--- a/server/services/autonomousJobs.syncSkillTemplates.test.js
+++ b/server/services/autonomousJobs.syncSkillTemplates.test.js
@@ -30,7 +30,8 @@ vi.mock('../lib/fileUtils.js', async () => {
// These mocks satisfy the module's top-level side-effect imports that are
// irrelevant to syncSkillTemplatesFromSample — avoids loading PM2, etc.
-vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() } }))
+vi.mock('./cosEvents.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null), cosEvents: { emit: vi.fn() } }))
vi.mock('./autobiography.js', () => ({ checkAndPrompt: vi.fn() }))
vi.mock('./goalCheckIn.js', () => ({ runGoalCheckIn: vi.fn() }))
vi.mock('./eventScheduler.js', () => ({ parseCronToNextRun: vi.fn() }))
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
index 1a55a55493..a2c3553838 100644
--- a/server/services/autonomousJobs.test.js
+++ b/server/services/autonomousJobs.test.js
@@ -6,6 +6,7 @@ vi.mock('./cosEvents.js', () => ({
}))
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
readJSONFile: vi.fn(),
ensureDir: vi.fn().mockResolvedValue(),
atomicWrite: vi.fn().mockResolvedValue(),
diff --git a/server/services/brain.test.js b/server/services/brain.test.js
index 3fc4ff0fb3..b4268ecc36 100644
--- a/server/services/brain.test.js
+++ b/server/services/brain.test.js
@@ -72,6 +72,7 @@ vi.mock('../lib/validation.js', () => ({
// Mock fileUtils
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
safeJSONParse: vi.fn((str, defaultVal) => {
if (!str) return defaultVal;
try { return JSON.parse(str); } catch { return defaultVal; }
@@ -84,6 +85,12 @@ vi.mock('../lib/fileUtils.js', () => ({
// flag injection, stdio shape, gemini-cli --output-format) are covered by
// runner.test.js, not here.
vi.mock('../lib/promptRunner.js', () => ({
+assertProvider: (provider, { message, code, status = 503 } = {}) => {
+ if (provider) return;
+ const err = new Error(message || 'No AI provider available');
+ if (code) { err.status = status; err.code = code; }
+ throw err;
+ },
runPromptThroughProvider: vi.fn()
}));
diff --git a/server/services/brainJournal.test.js b/server/services/brainJournal.test.js
index f80a416537..8f1e5719d8 100644
--- a/server/services/brainJournal.test.js
+++ b/server/services/brainJournal.test.js
@@ -20,6 +20,7 @@ vi.mock('../lib/fileUtils.js', async () => {
});
vi.mock('../lib/timezone.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
getUserTimezone: () => Promise.resolve('UTC'),
todayInTimezone: () => '2026-04-17',
}));
diff --git a/server/services/brainSyncLog.test.js b/server/services/brainSyncLog.test.js
index a43cf070da..348943ccca 100644
--- a/server/services/brainSyncLog.test.js
+++ b/server/services/brainSyncLog.test.js
@@ -13,6 +13,7 @@ vi.mock('../lib/asyncMutex.js', () => ({
createMutex: () => async (fn) => fn()
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn(),
atomicWrite: vi.fn().mockResolvedValue(undefined),
safeJSONParse: (str, fallback) => {
diff --git a/server/services/browserService.js b/server/services/browserService.js
index bf1e2d351e..195551b267 100644
--- a/server/services/browserService.js
+++ b/server/services/browserService.js
@@ -4,12 +4,12 @@
* Stores config in data/browser-config.json
*/
-import { readFile, writeFile, readdir, stat, unlink } from 'fs/promises';
+import { writeFile, readdir, stat, unlink } from 'fs/promises';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { join, basename, resolve, extname } from 'path';
import { EventEmitter } from 'events';
-import { ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';
+import { ensureDir, safeJSONParse, PATHS, tryReadFile } from '../lib/fileUtils.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
const execFileAsync = promisify(execFile);
@@ -48,7 +48,7 @@ let cachedConfig = null;
export async function loadConfig() {
if (cachedConfig) return cachedConfig;
- const raw = await readFile(CONFIG_FILE, 'utf-8').catch(() => null);
+ const raw = await tryReadFile(CONFIG_FILE);
const parsed = safeJSONParse(raw, null);
cachedConfig = parsed ? { ...DEFAULT_CONFIG, ...parsed } : { ...DEFAULT_CONFIG };
return cachedConfig;
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 2290ef6658..dd8e580694 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -101,6 +101,7 @@ vi.mock('./taskLearning.js', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(undefined),
readJSONFile: vi.fn().mockResolvedValue({}),
PATHS: {
diff --git a/server/services/clinvar.js b/server/services/clinvar.js
index 3d80f24409..c1f2239054 100644
--- a/server/services/clinvar.js
+++ b/server/services/clinvar.js
@@ -1,10 +1,10 @@
import { createWriteStream, createReadStream } from 'fs';
-import { readFile, writeFile, stat, unlink } from 'fs/promises';
+import { writeFile, stat, unlink } from 'fs/promises';
import { join } from 'path';
import { createGunzip } from 'zlib';
import { createInterface } from 'readline';
import { pipeline } from 'stream/promises';
-import { PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
const GENOME_DIR = PATHS.meatspace;
const CLINVAR_GZ = join(GENOME_DIR, 'clinvar-raw.txt.gz');
@@ -44,7 +44,7 @@ let clinvarIndex = null;
*/
export async function getClinvarStatus() {
await ensureDir(GENOME_DIR);
- const meta = await readFile(CLINVAR_META, 'utf-8').catch(() => null);
+ const meta = await tryReadFile(CLINVAR_META);
if (!meta) return { synced: false };
return JSON.parse(meta);
}
@@ -290,7 +290,7 @@ export async function syncClinvar(onProgress) {
async function loadClinvarIndex() {
if (clinvarIndex) return clinvarIndex;
- const raw = await readFile(CLINVAR_INDEX, 'utf-8').catch(() => null);
+ const raw = await tryReadFile(CLINVAR_INDEX);
if (!raw) return null;
clinvarIndex = safeJSONParse(raw, null, { logError: true, context: 'ClinVar index' });
diff --git a/server/services/codexSummaryRepair.js b/server/services/codexSummaryRepair.js
index 91a79b842c..ed4f529cca 100644
--- a/server/services/codexSummaryRepair.js
+++ b/server/services/codexSummaryRepair.js
@@ -5,9 +5,10 @@
// display, this module re-extracts the real assistant tail from the
// matching output.txt and rewrites metadata.json in place.
-import { readFile, writeFile } from 'fs/promises';
+import { writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
+import { tryReadFile } from '../lib/fileUtils.js';
import { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';
// Any taskSummary above this size is almost certainly a transcript dump —
@@ -33,7 +34,7 @@ export async function repairCodexTaskSummary(agentDir, agent) {
const outputFile = join(agentDir, 'output.txt');
if (!existsSync(outputFile)) return null;
- const fullOutput = await readFile(outputFile, 'utf-8').catch(() => null);
+ const fullOutput = await tryReadFile(outputFile);
if (!fullOutput) return null;
const repaired = extractCodexAssistantTail(fullOutput);
@@ -41,7 +42,7 @@ export async function repairCodexTaskSummary(agentDir, agent) {
if (repaired === storedTask && !simplifyWonky) return null;
const metaPath = join(agentDir, 'metadata.json');
- const rawContent = await readFile(metaPath, 'utf-8').catch(() => null);
+ const rawContent = await tryReadFile(metaPath);
if (!rawContent) return null;
const raw = JSON.parse(rawContent);
raw.metadata = { ...(raw.metadata || {}), taskSummary: repaired, simplifySummary: null };
diff --git a/server/services/cosAgents.js b/server/services/cosAgents.js
index 41d92e20ce..e5b4bb58bd 100644
--- a/server/services/cosAgents.js
+++ b/server/services/cosAgents.js
@@ -11,7 +11,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { cosEvents, emitLog } from './cosEvents.js';
import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
-import { ensureDir, safeJSONParse } from '../lib/fileUtils.js';
+import { ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { repairCodexTaskSummary } from './codexSummaryRepair.js';
const INDEX_FILE = join(AGENTS_DIR, 'index.json');
@@ -126,7 +126,7 @@ async function migrateAgentsToDateBuckets() {
// Try to get date from metadata
if (existsSync(metaPath)) {
- const content = await readFile(metaPath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(metaPath);
if (content) {
const raw = safeJSONParse(content, null);
if (raw?.completedAt) {
@@ -426,7 +426,7 @@ export async function getAgentsByDate(date) {
const batch = agentDirs.slice(i, i + BATCH_SIZE);
const reads = batch.map(async (entry) => {
const metaPath = join(dateDir, entry.name, 'metadata.json');
- const content = await readFile(metaPath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(metaPath);
if (!content) return;
const raw = safeJSONParse(content, null);
if (!raw) return;
@@ -454,7 +454,7 @@ export async function getAgent(agentId) {
const dateStr = idx.get(agentId);
if (dateStr) {
const metaPath = join(AGENTS_DIR, dateStr, agentId, 'metadata.json');
- const content = await readFile(metaPath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(metaPath);
if (content) {
const raw = safeJSONParse(content, null);
if (raw) {
@@ -736,7 +736,7 @@ export async function submitAgentFeedback(agentId, feedback) {
const agentDir = getAgentDir(agentId, dateBucket);
const metaPath = join(agentDir, 'metadata.json');
if (existsSync(metaPath)) {
- const content = await readFile(metaPath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(metaPath);
if (content) {
const raw = safeJSONParse(content, null);
if (raw) {
@@ -757,7 +757,7 @@ export async function submitAgentFeedback(agentId, feedback) {
if (!dateStr) return { error: 'Agent not found' };
const metaPath = join(AGENTS_DIR, dateStr, agentId, 'metadata.json');
- const content = await readFile(metaPath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(metaPath);
if (!content) return { error: 'Agent not found' };
const raw = safeJSONParse(content, null);
@@ -883,7 +883,7 @@ export async function archiveStaleAgents() {
await ensureDir(targetDir);
const files = await readdir(flatDir).catch(() => []);
for (const file of files) {
- const content = await readFile(join(flatDir, file)).catch(() => null);
+ const content = await tryReadFile(join(flatDir, file), null);
if (content !== null) await writeFile(join(targetDir, file), content);
}
await rm(flatDir, { recursive: true }).catch(() => {});
diff --git a/server/services/creativeDirector/local.test.js b/server/services/creativeDirector/local.test.js
index e0dec012ef..0ed733954d 100644
--- a/server/services/creativeDirector/local.test.js
+++ b/server/services/creativeDirector/local.test.js
@@ -6,6 +6,7 @@ const mockAtomicWrite = vi.fn();
const mockEnsureDir = vi.fn();
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/fake/data' },
readJSONFile: (...args) => mockReadJSONFile(...args),
atomicWrite: (...args) => mockAtomicWrite(...args),
diff --git a/server/services/creativeDirector/smokeTest.test.js b/server/services/creativeDirector/smokeTest.test.js
index 872e37a752..c07563f723 100644
--- a/server/services/creativeDirector/smokeTest.test.js
+++ b/server/services/creativeDirector/smokeTest.test.js
@@ -5,6 +5,7 @@ const mockAtomicWrite = vi.fn();
const mockEnsureDir = vi.fn();
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/fake/data' },
readJSONFile: (...args) => mockReadJSONFile(...args),
atomicWrite: (...args) => mockAtomicWrite(...args),
diff --git a/server/services/datadog.test.js b/server/services/datadog.test.js
index fe4a83893e..0e06b562d2 100644
--- a/server/services/datadog.test.js
+++ b/server/services/datadog.test.js
@@ -14,6 +14,7 @@ vi.mock('fs', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn(),
readJSONFile: vi.fn()
diff --git a/server/services/decisionLog.test.js b/server/services/decisionLog.test.js
index 17f70ad8a6..8cb50d77d1 100644
--- a/server/services/decisionLog.test.js
+++ b/server/services/decisionLog.test.js
@@ -15,6 +15,7 @@ vi.mock('./cosEvents.js', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn(),
PATHS: { cos: '/mock/data/cos' },
readJSONFile: vi.fn()
diff --git a/server/services/digital-twin.test.js b/server/services/digital-twin.test.js
index 03ea6ca6df..aab7aea55d 100644
--- a/server/services/digital-twin.test.js
+++ b/server/services/digital-twin.test.js
@@ -40,6 +40,7 @@ vi.mock('../lib/digitalTwinValidation.js', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn(),
safeJSONParse: vi.fn((str, defaultValue) => {
if (!str || !str.trim()) return defaultValue;
diff --git a/server/services/epigenetic.js b/server/services/epigenetic.js
index e0ea215e73..6716733ba6 100644
--- a/server/services/epigenetic.js
+++ b/server/services/epigenetic.js
@@ -1,7 +1,7 @@
-import { readFile, writeFile } from 'fs/promises';
+import { writeFile } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
const DATA_DIR = PATHS.meatspace;
const EPIGENETIC_FILE = join(DATA_DIR, 'epigenetic.json');
@@ -192,7 +192,7 @@ export const CURATED_INTERVENTIONS = [
async function loadData() {
await ensureDir(DATA_DIR);
- const raw = await readFile(EPIGENETIC_FILE, 'utf-8').catch(() => null);
+ const raw = await tryReadFile(EPIGENETIC_FILE);
if (!raw) return { ...DEFAULT_DATA };
return safeJSONParse(raw, { ...DEFAULT_DATA });
}
diff --git a/server/services/genome.js b/server/services/genome.js
index b59d05b12d..447bea9ab5 100644
--- a/server/services/genome.js
+++ b/server/services/genome.js
@@ -1,7 +1,7 @@
-import { readFile, writeFile, unlink } from 'fs/promises';
+import { writeFile, unlink } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { CURATED_MARKERS, MARKER_CATEGORIES, classifyGenotype, formatGenotype, resolveApoeHaplotype } from '../lib/curatedGenomeMarkers.js';
const GENOME_DIR = PATHS.meatspace;
@@ -29,7 +29,7 @@ async function ensureGenomeDir() {
async function loadMeta() {
await ensureGenomeDir();
- const raw = await readFile(META_FILE, 'utf-8').catch(() => null);
+ const raw = await tryReadFile(META_FILE);
if (!raw) return { ...DEFAULT_META };
return safeJSONParse(raw, { ...DEFAULT_META });
}
@@ -86,7 +86,7 @@ export async function getSnpIndex() {
return snpIndex;
}
- const content = await readFile(RAW_FILE, 'utf-8').catch(() => null);
+ const content = await tryReadFile(RAW_FILE);
if (!content) {
snpIndex = null;
return null;
diff --git a/server/services/goalProgress.js b/server/services/goalProgress.js
index 26a7b5c5e0..c941770cb3 100644
--- a/server/services/goalProgress.js
+++ b/server/services/goalProgress.js
@@ -8,9 +8,8 @@
* Task completions are categorized by keywords and mapped to goal progress.
*/
-import { readFile } from 'fs/promises'
import { join } from 'path'
-import { readJSONFile, PATHS } from '../lib/fileUtils.js'
+import { readJSONFile, PATHS, tryReadFile } from '../lib/fileUtils.js'
const GOALS_FILE = join(PATHS.root, 'GOALS.md')
const LEARNING_FILE = join(PATHS.cos, 'learning.json')
@@ -57,7 +56,7 @@ const GOAL_MAPPINGS = {
* @returns {Promise<Array>} Parsed goals with titles and items
*/
async function parseGoalsFile() {
- const content = await readFile(GOALS_FILE, 'utf-8').catch(() => null)
+ const content = await tryReadFile(GOALS_FILE)
if (!content) return []
const goals = []
diff --git a/server/services/goalProgress.test.js b/server/services/goalProgress.test.js
index ce133b0f55..5b8a0ce631 100644
--- a/server/services/goalProgress.test.js
+++ b/server/services/goalProgress.test.js
@@ -1,11 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock dependencies before importing the module
-vi.mock('fs/promises', () => ({
- readFile: vi.fn()
-}));
-
vi.mock('../lib/fileUtils.js', () => ({
+ tryReadFile: vi.fn(),
readJSONFile: vi.fn(),
PATHS: {
root: '/mock',
@@ -14,8 +11,8 @@ vi.mock('../lib/fileUtils.js', () => ({
}
}));
-import { readFile } from 'fs/promises';
-import { readJSONFile } from '../lib/fileUtils.js';
+import { tryReadFile, readJSONFile } from '../lib/fileUtils.js';
+const readFile = tryReadFile;
import {
getGoalProgress,
getGoalProgressSummary,
@@ -78,7 +75,7 @@ describe('goalProgress.js', () => {
});
it('should return empty array when file does not exist', async () => {
- readFile.mockRejectedValue(new Error('ENOENT'));
+ readFile.mockResolvedValue(null);
const result = await parseGoalsFile();
diff --git a/server/services/googleAuth.js b/server/services/googleAuth.js
index 797eda68be..1b11b963b8 100644
--- a/server/services/googleAuth.js
+++ b/server/services/googleAuth.js
@@ -1,7 +1,7 @@
import { google } from 'googleapis';
-import { readFile, writeFile } from 'fs/promises';
+import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';
const AUTH_DIR = join(PATHS.calendar, 'google-auth');
const CREDENTIALS_FILE = join(AUTH_DIR, 'credentials.json');
@@ -20,7 +20,7 @@ async function ensureAuthDir() {
export async function getCredentials() {
await ensureAuthDir();
- const raw = await readFile(CREDENTIALS_FILE, 'utf-8').catch(() => null);
+ const raw = await tryReadFile(CREDENTIALS_FILE);
if (!raw) return null;
return JSON.parse(raw);
}
@@ -36,7 +36,7 @@ export async function saveCredentials({ clientId, clientSecret }) {
export async function getTokens() {
await ensureAuthDir();
- const raw = await readFile(TOKENS_FILE, 'utf-8').catch(() => null);
+ const raw = await tryReadFile(TOKENS_FILE);
if (!raw) return null;
return JSON.parse(raw);
}
diff --git a/server/services/identity.js b/server/services/identity.js
index 8feaf13b6f..020dab7385 100644
--- a/server/services/identity.js
+++ b/server/services/identity.js
@@ -1,7 +1,7 @@
-import { readFile, writeFile } from 'fs/promises';
+import { writeFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
import { getGenomeSummary } from './genome.js';
import { getTasteProfile } from './taste-questionnaire.js';
@@ -175,7 +175,7 @@ async function ensureIdentityDir() {
}
async function loadJSON(filePath, defaultVal) {
- const raw = await readFile(filePath, 'utf-8').catch(() => null);
+ const raw = await tryReadFile(filePath);
const data = raw ? safeJSONParse(raw, structuredClone(defaultVal)) : structuredClone(defaultVal);
// When MortalLoom iCloud sync is enabled, the goals array is sourced from
// MortalLoom.json; birthDate and lifeExpectancy metadata stay in local PortOS.
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index ade7d09516..db0296a35a 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -18,7 +18,7 @@ import { existsSync, watch as fsWatch } from 'fs';
import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
-import { assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage, resolveImageInputPath } from '../../lib/fileUtils.js';
+import { assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage, resolveImageInputPath, tryReadFile } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
@@ -591,7 +591,7 @@ export async function readImageSidecar(filename) {
const portosSidecar = join(PATHS.images, filename.replace('.png', '.metadata.json'));
const altSidecar = join(PATHS.images, `${filename}.metadata.json`);
for (const path of [portosSidecar, altSidecar]) {
- const raw = await readFile(path, 'utf-8').catch(() => null);
+ const raw = await tryReadFile(path);
if (raw != null) return { path, metadata: safeJSONParse(raw, {}) };
}
return { path: portosSidecar, metadata: {} };
diff --git a/server/services/importer.test.js b/server/services/importer.test.js
index 31df16222f..1fd998b572 100644
--- a/server/services/importer.test.js
+++ b/server/services/importer.test.js
@@ -48,6 +48,7 @@ vi.mock('../lib/fileUtils.js', async () => {
// LLM call resolves to a canned JSON shape we control per-test.
const mockRunStagedLLM = vi.fn();
vi.mock('../lib/stageRunner.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
runStagedLLM: (...args) => mockRunStagedLLM(...args),
}));
diff --git a/server/services/instances.test.js b/server/services/instances.test.js
index b60819857a..7b74bed850 100644
--- a/server/services/instances.test.js
+++ b/server/services/instances.test.js
@@ -7,6 +7,7 @@ vi.mock('fs/promises', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
dataPath: (name) => `/mock/data/${name}`,
readJSONFile: vi.fn(),
ensureDir: vi.fn().mockResolvedValue(undefined),
diff --git a/server/services/loops.js b/server/services/loops.js
index 751e91b8ea..9f568a7472 100644
--- a/server/services/loops.js
+++ b/server/services/loops.js
@@ -13,8 +13,8 @@ import { join } from 'path';
import { PATHS, ensureDir } from '../lib/fileUtils.js';
import { randomUUID } from 'crypto';
import { createRun } from './runner.js';
-import { runPromptThroughProvider } from '../lib/promptRunner.js';
-import { getProviderById, getAllProviders, getActiveProvider } from './providers.js';
+import { resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';
+import { getAllProviders, getActiveProvider } from './providers.js';
export const loopEvents = new EventEmitter();
@@ -61,13 +61,8 @@ async function executeIteration(loop) {
loopEvents.emit('iteration:start', { id, iteration: iterationNum, timestamp: Date.now() });
- let provider;
- if (loop.providerId) {
- provider = await getProviderById(loop.providerId).catch(() => null);
- }
- if (!provider) {
- provider = await getActiveProvider().catch(() => null);
- }
+ const { provider } = await resolveProviderAndModel({ providerId: loop.providerId })
+ .catch(() => ({ provider: null }));
if (!provider) {
const msg = 'No AI provider available';
loopEvents.emit('iteration:error', { id, iteration: iterationNum, error: msg, timestamp: Date.now() });
diff --git a/server/services/loops.test.js b/server/services/loops.test.js
index bb122c5d17..7e9c0379a1 100644
--- a/server/services/loops.test.js
+++ b/server/services/loops.test.js
@@ -13,6 +13,7 @@ vi.mock('fs/promises', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(undefined),
PATHS: { data: '/fake/data', root: '/fake/root' },
readJSONFile: vi.fn()
@@ -23,19 +24,24 @@ vi.mock('./runner.js', () => ({
}));
vi.mock('../lib/promptRunner.js', () => ({
- runPromptThroughProvider: vi.fn()
+assertProvider: (provider, { message, code, status = 503 } = {}) => {
+ if (provider) return;
+ const err = new Error(message || 'No AI provider available');
+ if (code) { err.status = status; err.code = code; }
+ throw err;
+ },
+ runPromptThroughProvider: vi.fn(),
+ resolveProviderAndModel: vi.fn(),
}));
vi.mock('./providers.js', () => ({
- getProviderById: vi.fn(),
getAllProviders: vi.fn(),
- getActiveProvider: vi.fn()
+ getActiveProvider: vi.fn(),
}));
import { readFile, writeFile } from 'fs/promises';
import { createRun } from './runner.js';
-import { runPromptThroughProvider } from '../lib/promptRunner.js';
-import { getProviderById, getActiveProvider } from './providers.js';
+import { runPromptThroughProvider, resolveProviderAndModel } from '../lib/promptRunner.js';
import {
createLoop,
stopLoop,
@@ -47,8 +53,9 @@ import {
// Convenience aliases after import
const mockCreateRun = createRun;
const mockRunPrompt = runPromptThroughProvider;
-const mockGetProviderById = getProviderById;
-const mockGetActiveProvider = getActiveProvider;
+const mockResolveProvider = resolveProviderAndModel;
+const mockGetProviderById = { mockResolvedValue: (v) => mockResolveProvider.mockResolvedValue({ provider: v, selectedModel: null }) };
+const mockGetActiveProvider = mockGetProviderById;
const MOCK_PROVIDER = {
id: 'claude',
diff --git a/server/services/meatspaceCustomDrinks.test.js b/server/services/meatspaceCustomDrinks.test.js
index 13bebf4fe4..889eeb73b1 100644
--- a/server/services/meatspaceCustomDrinks.test.js
+++ b/server/services/meatspaceCustomDrinks.test.js
@@ -5,6 +5,7 @@ vi.mock('fs/promises', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
readJSONFile: vi.fn(),
PATHS: {
root: '/mock',
diff --git a/server/services/meatspacePostLlm.test.js b/server/services/meatspacePostLlm.test.js
index d7b926728c..dd8719b680 100644
--- a/server/services/meatspacePostLlm.test.js
+++ b/server/services/meatspacePostLlm.test.js
@@ -10,6 +10,12 @@ vi.mock('./providers.js', () => ({
// + fetch directly, but now delegates to runPromptThroughProvider. Runner
// internals (spawn args, --model flag injection) are covered by runner.test.js.
vi.mock('../lib/promptRunner.js', () => ({
+assertProvider: (provider, { message, code, status = 503 } = {}) => {
+ if (provider) return;
+ const err = new Error(message || 'No AI provider available');
+ if (code) { err.status = status; err.code = code; }
+ throw err;
+ },
runPromptThroughProvider: vi.fn()
}));
diff --git a/server/services/meatspacePostMemory.test.js b/server/services/meatspacePostMemory.test.js
index 45e47ab283..a5c8ca651a 100644
--- a/server/services/meatspacePostMemory.test.js
+++ b/server/services/meatspacePostMemory.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock file I/O so tests stay pure
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
atomicWrite: vi.fn().mockResolvedValue(undefined),
PATHS: { meatspace: '/tmp/test-meatspace' },
ensureDir: vi.fn().mockResolvedValue(undefined),
diff --git a/server/services/meatspacePostTraining.test.js b/server/services/meatspacePostTraining.test.js
index 92a29b66c6..3e2a7c7684 100644
--- a/server/services/meatspacePostTraining.test.js
+++ b/server/services/meatspacePostTraining.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
atomicWrite: vi.fn().mockResolvedValue(undefined),
PATHS: { meatspace: '/tmp/test-meatspace' },
ensureDir: vi.fn().mockResolvedValue(undefined),
diff --git a/server/services/mediaAnnotations.test.js b/server/services/mediaAnnotations.test.js
index 424aa719d8..0795a76f41 100644
--- a/server/services/mediaAnnotations.test.js
+++ b/server/services/mediaAnnotations.test.js
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.js
index a472ea88ae..5f2e0ee2a1 100644
--- a/server/services/mediaCollections.test.js
+++ b/server/services/mediaCollections.test.js
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index a25565c488..fde24a77a3 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -28,7 +28,8 @@ vi.mock('../../lib/fileUtils.js', async () => {
// 'completed' or 'failed' for the worker to advance — we drive those events
// directly from each test.
const stubs = {
- generateVideo: vi.fn(async () => ({ jobId: 'whatever' })),
+ generateVideo: vi.fn(async () => ({
+tryReadFile: vi.fn().mockResolvedValue(null), jobId: 'whatever' })),
generateChainedVideo: vi.fn(async () => ({ jobId: 'whatever' })),
generateImage: vi.fn(async () => ({ jobId: 'whatever' })),
generateImageCodex: vi.fn(async () => ({ jobId: 'whatever' })),
diff --git a/server/services/memory.test.js b/server/services/memory.test.js
index d876c4abe3..63dd9aa58c 100644
--- a/server/services/memory.test.js
+++ b/server/services/memory.test.js
@@ -37,6 +37,7 @@ vi.mock('./notifications.js', () => ({
// Mock fileUtils
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn(),
ensureDirs: vi.fn(),
readJSONFile: vi.fn(),
diff --git a/server/services/memoryBM25.test.js b/server/services/memoryBM25.test.js
index 3c01c40f61..43c2b58720 100644
--- a/server/services/memoryBM25.test.js
+++ b/server/services/memoryBM25.test.js
@@ -9,6 +9,7 @@ vi.mock('fs', () => ({
}))
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(),
PATHS: { memory: '/mock/data/memory' }
}))
diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.js
index 8edc4bfff5..293977d1e8 100644
--- a/server/services/messageAccounts.js
+++ b/server/services/messageAccounts.js
@@ -1,13 +1,13 @@
-import { readFile, writeFile } from 'fs/promises';
+import { writeFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
const ACCOUNTS_FILE = join(PATHS.messages, 'accounts.json');
async function loadAccounts() {
await ensureDir(PATHS.messages);
- const content = await readFile(ACCOUNTS_FILE, 'utf-8').catch(() => null);
+ const content = await tryReadFile(ACCOUNTS_FILE);
if (!content) return {};
const parsed = safeJSONParse(content, {}, { context: 'messageAccounts' });
return (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) ? parsed : {};
diff --git a/server/services/messageActions.js b/server/services/messageActions.js
index a8defdb1e3..8bd0b94f92 100644
--- a/server/services/messageActions.js
+++ b/server/services/messageActions.js
@@ -2,9 +2,9 @@ import { getAccount } from './messageAccounts.js';
import { getMessage } from './messageSync.js';
import { findOrOpenPage, getPages, isAuthPage, evaluateOnPage } from './messagePlaywrightSync.js';
import { recordCorrection } from './messageTriageRules.js';
-import { readFile, writeFile } from 'fs/promises';
+import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, PATHS, safeJSONParse, UUID_RE } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, safeJSONParse, UUID_RE, tryReadFile } from '../lib/fileUtils.js';
const CACHE_DIR = join(PATHS.messages, 'cache');
@@ -16,7 +16,7 @@ const PROVIDER_URLS = {
async function loadCache(accountId) {
await ensureDir(CACHE_DIR);
const filePath = join(CACHE_DIR, `${accountId}.json`);
- const content = await readFile(filePath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(filePath);
if (!content) return { syncCursor: null, messages: [] };
return safeJSONParse(content, { syncCursor: null, messages: [] }, { context: `messageCache:${accountId}` });
}
diff --git a/server/services/messageDrafts.js b/server/services/messageDrafts.js
index 5d40aeface..977ae6cd60 100644
--- a/server/services/messageDrafts.js
+++ b/server/services/messageDrafts.js
@@ -1,13 +1,13 @@
-import { readFile } from 'fs/promises';
+
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { atomicWrite, ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
const DRAFTS_FILE = join(PATHS.messages, 'drafts.json');
async function loadDrafts() {
await ensureDir(PATHS.messages);
- const content = await readFile(DRAFTS_FILE, 'utf-8').catch(() => null);
+ const content = await tryReadFile(DRAFTS_FILE);
if (!content) return [];
const parsed = safeJSONParse(content, [], { context: 'messageDrafts' });
return Array.isArray(parsed) ? parsed : [];
diff --git a/server/services/messageEvaluator.js b/server/services/messageEvaluator.js
index caf4befda7..b7c844936a 100644
--- a/server/services/messageEvaluator.js
+++ b/server/services/messageEvaluator.js
@@ -1,9 +1,9 @@
-import { readFile } from 'fs/promises';
+
import { join } from 'path';
import { getSettings } from './settings.js';
import { getProviderById, getAllProviders } from './providers.js';
import { buildRulesPromptSection } from './messageTriageRules.js';
-import { PATHS } from '../lib/fileUtils.js';
+import { PATHS, tryReadFile } from '../lib/fileUtils.js';
import { runPromptThroughProvider } from '../lib/promptRunner.js';
import { extractJson } from '../lib/jsonExtract.js';
@@ -139,7 +139,7 @@ const VOICE_DOCS = ['SOUL.md', 'COMMUNICATION.md', 'PERSONALITY.md', 'VALUES.md'
async function loadVoiceContext() {
const contents = await Promise.all(
VOICE_DOCS.map(filename =>
- readFile(join(PATHS.digitalTwin, filename), 'utf-8').catch(() => null)
+ tryReadFile(join(PATHS.digitalTwin, filename))
)
);
const sections = contents
diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.js
index 63c91f6c62..b3c63b093b 100644
--- a/server/services/messagePlaywrightSync.js
+++ b/server/services/messagePlaywrightSync.js
@@ -1,8 +1,8 @@
-import { readFile, writeFile } from 'fs/promises';
+import { writeFile } from 'fs/promises';
import { join } from 'path';
import crypto from 'crypto';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { findOrOpenPage, listCdpPages, isAuthPage, evaluateOnPage } from './browserService.js';
// Compat re-exports — older consumers and test mocks import these from here
@@ -23,7 +23,7 @@ function makeExternalId(date, sender, subject) {
}
export async function getSelectors() {
- const content = await readFile(SELECTORS_FILE, 'utf-8').catch(() => null);
+ const content = await tryReadFile(SELECTORS_FILE);
if (!content) return {};
const parsed = safeJSONParse(content, {}, { context: 'messageSelectors' });
return (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) ? parsed : {};
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index 19abfbc32b..8f73402c7d 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -1,6 +1,6 @@
-import { readFile } from 'fs/promises';
+
import { join } from 'path';
-import { atomicWrite, ensureDir, filterBySearch as genericFilterBySearch, PATHS, safeDate, safeJSONParse, UUID_RE } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, filterBySearch as genericFilterBySearch, PATHS, safeDate, safeJSONParse, UUID_RE, tryReadFile } from '../lib/fileUtils.js';
import { getAccount, updateSyncStatus } from './messageAccounts.js';
const CACHE_DIR = join(PATHS.messages, 'cache');
@@ -15,7 +15,7 @@ async function loadCache(accountId) {
if (!UUID_RE.test(accountId)) throw new Error(`Invalid accountId: ${accountId}`);
await ensureDir(CACHE_DIR);
const filePath = join(CACHE_DIR, `${accountId}.json`);
- const content = await readFile(filePath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(filePath);
if (!content) return { syncCursor: null, messages: [] };
const parsed = safeJSONParse(content, { syncCursor: null, messages: [] }, { context: `messageCache:${accountId}` });
if (!parsed || !Array.isArray(parsed.messages)) return { syncCursor: null, messages: [] };
diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.js
index a969ccf26b..f95b49e13d 100644
--- a/server/services/messageSync.test.js
+++ b/server/services/messageSync.test.js
@@ -2,13 +2,13 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock fs/promises before importing the module
vi.mock('fs/promises', () => ({
- readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
unlink: vi.fn()
}));
vi.mock('../lib/fileUtils.js', () => ({
+ tryReadFile: vi.fn(),
atomicWrite: vi.fn().mockResolvedValue(undefined),
ensureDir: vi.fn(),
PATHS: { messages: '/mock/data/messages' },
@@ -44,8 +44,8 @@ vi.mock('./messagePlaywrightSync.js', () => ({
syncPlaywright: vi.fn()
}));
-import { readFile, readdir, unlink } from 'fs/promises';
-import { atomicWrite } from '../lib/fileUtils.js';
+import { readdir, unlink } from 'fs/promises';
+import { tryReadFile as readFile, atomicWrite } from '../lib/fileUtils.js';
import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus } from './messageSync.js';
import { getAccount, updateSyncStatus } from './messageAccounts.js';
import { syncGmail } from './messageGmailSync.js';
@@ -56,8 +56,8 @@ const VALID_UUID_2 = '22222222-2222-2222-2222-222222222222';
beforeEach(() => {
vi.clearAllMocks();
- // Default: cache file not found
- readFile.mockRejectedValue(new Error('ENOENT'));
+ // Default: cache file not found — tryReadFile returns null on read error
+ readFile.mockResolvedValue(null);
});
// ─── Cache I/O: getMessages ───
diff --git a/server/services/messageTriageRules.js b/server/services/messageTriageRules.js
index bdc5628cbb..667488c330 100644
--- a/server/services/messageTriageRules.js
+++ b/server/services/messageTriageRules.js
@@ -1,12 +1,12 @@
-import { readFile, writeFile } from 'fs/promises';
+import { writeFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
const RULES_FILE = join(PATHS.messages, 'triage-rules.json');
async function loadRules() {
await ensureDir(PATHS.messages);
- const content = await readFile(RULES_FILE, 'utf-8').catch(() => null);
+ const content = await tryReadFile(RULES_FILE);
if (!content) return { rules: [] };
return safeJSONParse(content, { rules: [] }, { context: 'triage-rules' });
}
diff --git a/server/services/missions.js b/server/services/missions.js
index da73cafcf0..0128e2f0f0 100644
--- a/server/services/missions.js
+++ b/server/services/missions.js
@@ -9,7 +9,7 @@ import { promises as fs } from 'fs'
import path from 'path'
import { v4 as uuidv4 } from '../lib/uuid.js'
import { cosEvents } from './cosEvents.js'
-import { atomicWrite, safeJSONParse, ensureDir, PATHS } from '../lib/fileUtils.js'
+import { atomicWrite, safeJSONParse, ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js'
const DATA_DIR = PATHS.missions
@@ -32,7 +32,7 @@ async function loadMissions() {
if (!file.endsWith('.json')) continue
const filePath = path.join(DATA_DIR, file)
- const content = await fs.readFile(filePath, 'utf-8').catch(() => null)
+ const content = await tryReadFile(filePath)
if (content) {
const mission = safeJSONParse(content, null, { context: `mission:${file}` })
if (mission) missions.push(mission)
diff --git a/server/services/notifications.test.js b/server/services/notifications.test.js
index 5ddf75073a..3ae003f931 100644
--- a/server/services/notifications.test.js
+++ b/server/services/notifications.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(),
atomicWrite: vi.fn().mockResolvedValue(),
readJSONFile: vi.fn(),
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index f2a9d1614c..ec4cc6f1a1 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -4,6 +4,7 @@ const fileStore = new Map();
let stageRunnerSpy;
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/pipeline/audio.test.js b/server/services/pipeline/audio.test.js
index 5e97180d81..39d3718811 100644
--- a/server/services/pipeline/audio.test.js
+++ b/server/services/pipeline/audio.test.js
@@ -18,6 +18,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
const synthesizeMock = vi.fn();
const listVoicesMock = vi.fn();
vi.mock('../voice/tts.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
synthesize: (...a) => synthesizeMock(...a),
listVoices: (...a) => listVoicesMock(...a),
VALID_ENGINES: new Set(['kokoro', 'piper']),
diff --git a/server/services/pipeline/autoRunner.test.js b/server/services/pipeline/autoRunner.test.js
index 5e3acd3369..642868c080 100644
--- a/server/services/pipeline/autoRunner.test.js
+++ b/server/services/pipeline/autoRunner.test.js
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/pipeline/comicPdf.test.js b/server/services/pipeline/comicPdf.test.js
index 5a1127cd25..25d4216179 100644
--- a/server/services/pipeline/comicPdf.test.js
+++ b/server/services/pipeline/comicPdf.test.js
@@ -52,6 +52,7 @@ const mockSeries = {
const getIssueMock = vi.fn(async () => structuredClone(mockIssue));
const getSeriesMock = vi.fn(async () => structuredClone(mockSeries));
vi.mock('./issues.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
getIssue: (...a) => getIssueMock(...a),
VISUAL_STAGE_IDS: ['comicPages', 'storyboards', 'episodeVideo'],
STAGE_IDS: ['idea', 'prose', 'comicScript', 'teleplay', 'comicPages', 'storyboards', 'episodeVideo'],
diff --git a/server/services/pipeline/coverFilenameHooks.integration.test.js b/server/services/pipeline/coverFilenameHooks.integration.test.js
index 35f050bcd1..bf3d4251a1 100644
--- a/server/services/pipeline/coverFilenameHooks.integration.test.js
+++ b/server/services/pipeline/coverFilenameHooks.integration.test.js
@@ -58,6 +58,7 @@ const updateStageWithLatestMock = vi.fn(async (issueId, _stageId, computeFn) =>
});
vi.mock('./series.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
getSeries: vi.fn(async (id) => seriesStore.get(id) || null),
updateSeasonOnSeries: updateSeasonOnSeriesMock,
}));
diff --git a/server/services/pipeline/coverUniverseFiler.test.js b/server/services/pipeline/coverUniverseFiler.test.js
index 98ad8ace00..80c3659f0f 100644
--- a/server/services/pipeline/coverUniverseFiler.test.js
+++ b/server/services/pipeline/coverUniverseFiler.test.js
@@ -3,6 +3,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
const fileStore = new Map();
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/pipeline/episodeVideo.test.js b/server/services/pipeline/episodeVideo.test.js
index b3b16d8eae..a0382943be 100644
--- a/server/services/pipeline/episodeVideo.test.js
+++ b/server/services/pipeline/episodeVideo.test.js
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index 140a0c727d..968885629e 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/pipeline/seasons.test.js b/server/services/pipeline/seasons.test.js
index 79c2832436..ea8b11d52c 100644
--- a/server/services/pipeline/seasons.test.js
+++ b/server/services/pipeline/seasons.test.js
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index 8e622324a5..1f6f2cb353 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.js
index 59984495ce..9a9d941dce 100644
--- a/server/services/pipeline/textStages.test.js
+++ b/server/services/pipeline/textStages.test.js
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/pipeline/volumeBeatsRunner.test.js b/server/services/pipeline/volumeBeatsRunner.test.js
index fb917bab63..5186f12b6b 100644
--- a/server/services/pipeline/volumeBeatsRunner.test.js
+++ b/server/services/pipeline/volumeBeatsRunner.test.js
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.js
index b77ca8d9e3..8743abc9c5 100644
--- a/server/services/pm2Standardizer.js
+++ b/server/services/pm2Standardizer.js
@@ -5,7 +5,7 @@ import { exec } from 'child_process';
import { promisify } from 'util';
import { getActiveProvider, getProviderById } from './providers.js';
import { spawn } from 'child_process';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { runPromptThroughProvider } from '../lib/promptRunner.js';
const execAsync = promisify(exec);
@@ -38,14 +38,14 @@ async function gatherConfigContext(dirPath) {
// Read package.json
const pkgPath = join(dirPath, 'package.json');
if (existsSync(pkgPath)) {
- context.packageJson = await readFile(pkgPath, 'utf-8').catch(() => null);
+ context.packageJson = await tryReadFile(pkgPath);
}
// Read ecosystem.config
for (const name of ['ecosystem.config.cjs', 'ecosystem.config.js']) {
const path = join(dirPath, name);
if (existsSync(path)) {
- context.ecosystemConfig = await readFile(path, 'utf-8').catch(() => null);
+ context.ecosystemConfig = await tryReadFile(path);
context.ecosystemPath = name;
break;
}
@@ -383,7 +383,7 @@ export async function applyStandardization(repoPath, plan, { skipBackup = false
const filePath = join(repoPath, stray.file);
if (!existsSync(filePath)) continue;
- const content = await readFile(filePath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(filePath);
if (!content) continue;
// Remove the port line from .env files
diff --git a/server/services/referenceRepos.test.js b/server/services/referenceRepos.test.js
index 3ccd9c3473..fa17fa26a2 100644
--- a/server/services/referenceRepos.test.js
+++ b/server/services/referenceRepos.test.js
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// ─── mocks (must precede the import under test) ──────────────────────────────
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn(async () => {}),
PATHS: { data: '/mock/data', root: '/mock/root' },
readJSONFile: vi.fn(async () => ({ apps: {} })),
diff --git a/server/services/review.test.js b/server/services/review.test.js
index 44682218f1..52c12f1b34 100644
--- a/server/services/review.test.js
+++ b/server/services/review.test.js
@@ -17,6 +17,7 @@ const cosEvents = {
vi.mock('./cosEvents.js', () => ({ cosEvents }));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn(),
atomicWrite: vi.fn().mockResolvedValue(undefined),
PATHS: {
diff --git a/server/services/runner.js b/server/services/runner.js
index 1c1f0adb87..3748dced29 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -5,7 +5,7 @@
import { spawn } from 'child_process';
import { writeFile, readFile } from 'fs/promises';
import { join } from 'path';
-import { ensureDir } from '../lib/fileUtils.js';
+import { ensureDir, tryReadFile } from '../lib/fileUtils.js';
import { resolveCliModel, hasModelFlag, extractBakedModel } from '../lib/providerModels.js';
// Re-exported so `server/lib/promptRunner.js` can import via the runner
@@ -202,7 +202,7 @@ export function emitRunStarted({ runId, provider, model }) {
export async function patchRunMetadata(runId, patch) {
if (!patch || typeof patch !== 'object') return;
const metadataPath = join(getRunsPath(), runId, 'metadata.json');
- const metadataStr = await readFile(metadataPath, 'utf-8').catch(() => null);
+ const metadataStr = await tryReadFile(metadataPath);
if (!metadataStr) return;
let metadata;
try { metadata = JSON.parse(metadataStr); } catch { return; }
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index ca6847ff55..57aba35a25 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -7,6 +7,7 @@ vi.mock('child_process', async (importOriginal) => {
});
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(undefined),
}));
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 2e1e0fd15d..eda6e73aab 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -42,6 +42,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
// Stub instances.getInstanceId so the exporter doesn't try to read the
// real identity.json. Returns a fixed id for assertions.
vi.mock('../instances.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
getInstanceId: () => Promise.resolve('test-instance-id'),
}));
diff --git a/server/services/sharing/subscriptions.test.js b/server/services/sharing/subscriptions.test.js
index 9847171dd3..43aa3f7dd4 100644
--- a/server/services/sharing/subscriptions.test.js
+++ b/server/services/sharing/subscriptions.test.js
@@ -22,7 +22,8 @@ vi.mock('../../lib/fileUtils.js', async () => {
},
});
});
-vi.mock('../instances.js', () => ({ getInstanceId: () => Promise.resolve('inst-test') }));
+vi.mock('../instances.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null), getInstanceId: () => Promise.resolve('inst-test') }));
vi.mock('../mediaJobQueue/index.js', () => ({ getJob: () => null }));
const buckets = await import('./buckets.js');
diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.js
index 8f2c57fa07..c5fef43b0f 100644
--- a/server/services/streamingDetect.js
+++ b/server/services/streamingDetect.js
@@ -3,7 +3,7 @@ import { existsSync } from 'fs';
import { join, basename } from 'path';
import { homedir } from 'os';
import { execPm2 } from './pm2.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { detectAppIcon } from './appIconDetect.js';
/** App types that do not use PM2 for process management */
@@ -535,7 +535,7 @@ export async function streamDetection(socket, dirPath) {
const pkgPath = join(dirPath, 'package.json');
if (existsSync(pkgPath)) {
- const content = await readFile(pkgPath, 'utf-8').catch(() => null);
+ const content = await tryReadFile(pkgPath);
if (content) {
const pkg = safeJSONParse(content, null);
if (!pkg) {
diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.js
index 0582019e24..ea1e198bd7 100644
--- a/server/services/syncOrchestrator.test.js
+++ b/server/services/syncOrchestrator.test.js
@@ -31,6 +31,7 @@ vi.mock('./instanceEvents.js', () => ({
instanceEvents: { on: vi.fn(), removeListener: vi.fn() }
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
readJSONFile: vi.fn().mockResolvedValue({}),
ensureDir: vi.fn().mockResolvedValue(),
atomicWrite: vi.fn().mockResolvedValue(),
diff --git a/server/services/taskLearning.js b/server/services/taskLearning.js
index dca7aba6a1..3ca2df2a87 100644
--- a/server/services/taskLearning.js
+++ b/server/services/taskLearning.js
@@ -6,11 +6,10 @@
* to provide smarter task prioritization and model selection.
*/
-import { readFile } from 'fs/promises';
import { existsSync, readdirSync } from 'fs';
import { join } from 'path';
import { cosEvents, emitLog } from './cosEvents.js';
-import { ensureDir, readJSONFile, PATHS, atomicWrite } from '../lib/fileUtils.js';
+import { ensureDir, readJSONFile, PATHS, atomicWrite, tryReadFile } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
const withLock = createMutex();
@@ -1333,7 +1332,7 @@ export async function recalculateDurationStats() {
}
const results = await Promise.all(
- metaPaths.map(p => readFile(p, 'utf-8').catch(() => null))
+ metaPaths.map(p => tryReadFile(p))
);
for (const raw of results) {
diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.js
index 8786e07dcd..14b4bb9cee 100644
--- a/server/services/taskLearning.test.js
+++ b/server/services/taskLearning.test.js
@@ -38,6 +38,7 @@ import { atomicWrite } from '../lib/fileUtils.js';
import { resetTaskTypeLearning, getSkippedTaskTypes, recordTaskCompletion, getRoutingAccuracy, suggestModelTier, recalculateModelTierMetrics, clearLearningCache, getTaskTypeConfidence, getConfidenceLevels, dismissRecommendation, restoreRecommendation, getDismissedRecommendations, clearDismissedRecommendations, getLearningInsights } from './taskLearning.js';
const makeLearningData = (overrides = {}) => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
version: 1,
lastUpdated: '2026-01-26T00:00:00.000Z',
byTaskType: {
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index da38d74514..1603aff745 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -8,6 +8,7 @@ vi.mock('./cosEvents.js', () => ({
// fileUtils mock: include every named export consumed by ./cosState.js too,
// so vi.importActual('./cosState.js') below resolves cleanly.
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(),
ensureDirs: vi.fn().mockResolvedValue(),
readJSONFile: vi.fn(),
diff --git a/server/services/taskTemplates.test.js b/server/services/taskTemplates.test.js
index 387a2decc0..fd8daca4e6 100644
--- a/server/services/taskTemplates.test.js
+++ b/server/services/taskTemplates.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
// Mock dependencies before importing the module
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn(),
readJSONFile: vi.fn(),
PATHS: { cos: '/tmp/test/cos' }
diff --git a/server/services/telegramBridge.js b/server/services/telegramBridge.js
index a89be8fa9e..b050ed53ee 100644
--- a/server/services/telegramBridge.js
+++ b/server/services/telegramBridge.js
@@ -9,9 +9,9 @@
* Reads chat ID from ~/.claude/channels/telegram/access.json (first allowFrom entry)
*/
-import { readFile } from 'fs/promises';
import { join } from 'path';
import { homedir } from 'os';
+import { tryReadFile } from '../lib/fileUtils.js';
import { notificationEvents, NOTIFICATION_TYPES } from './notifications.js';
const CHANNELS_DIR = join(homedir(), '.claude', 'channels', 'telegram');
@@ -77,7 +77,7 @@ function escapeHtml(text) {
* Read bot token from MCP plugin's .env file
*/
async function loadBotToken() {
- const content = await readFile(ENV_FILE, 'utf-8').catch(() => null);
+ const content = await tryReadFile(ENV_FILE);
if (!content) return null;
const match = content.match(/^TELEGRAM_BOT_TOKEN=(.+)$/m);
return match ? match[1].trim() : null;
@@ -87,7 +87,7 @@ async function loadBotToken() {
* Read first allowed chat ID from MCP plugin's access.json
*/
async function loadChatId() {
- const content = await readFile(ACCESS_FILE, 'utf-8').catch(() => null);
+ const content = await tryReadFile(ACCESS_FILE);
if (!content) return null;
const access = JSON.parse(content);
return access.allowFrom?.[0] || null;
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 9ffb20afc9..f7375f8eec 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -9,6 +9,7 @@ const fileStore = new Map();
// resolveImageRef to return null for the stale filename.
const refSheetFilesByName = new Map();
vi.mock("../lib/fileUtils.js", () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: "/mock/data" },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => {
diff --git a/server/services/universeBuilderAutoSort.js b/server/services/universeBuilderAutoSort.js
index 476c07e409..3ce43e39eb 100644
--- a/server/services/universeBuilderAutoSort.js
+++ b/server/services/universeBuilderAutoSort.js
@@ -23,7 +23,7 @@ import {
import { VALID_TARGET_KINDS } from './universeBuilderPromote.js';
import { ServerError } from '../lib/errorHandler.js';
import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';
-import { resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';
+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';
// The 3 real trunks — derived from BIBLE_FIELD via universeBuilderPromote so
// adding a new canon kind reaches this resolver automatically.
@@ -153,12 +153,10 @@ export async function autoSortOtherBuckets(universeId, options = {}) {
}
const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
- if (!provider) {
- throw new ServerError('No AI provider available for auto-sort', {
- status: 503,
- code: 'UNIVERSE_AUTOSORT_NO_PROVIDER',
- });
- }
+ assertProvider(provider, {
+ message: 'No AI provider available for auto-sort',
+ code: 'UNIVERSE_AUTOSORT_NO_PROVIDER',
+ });
const prompt = buildAutoSortPrompt({ buckets: otherBuckets, universe });
console.log(
diff --git a/server/services/universeBuilderAutoSort.test.js b/server/services/universeBuilderAutoSort.test.js
index dcb3baf5b3..f1aed602c9 100644
--- a/server/services/universeBuilderAutoSort.test.js
+++ b/server/services/universeBuilderAutoSort.test.js
@@ -6,6 +6,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
@@ -21,6 +22,12 @@ vi.mock('crypto', async () => {
const resolveProviderAndModelMock = vi.fn();
const runPromptThroughProviderMock = vi.fn();
vi.mock('../lib/promptRunner.js', () => ({
+assertProvider: (provider, { message, code, status = 503 } = {}) => {
+ if (provider) return;
+ const err = new Error(message || 'No AI provider available');
+ if (code) { err.status = status; err.code = code; }
+ throw err;
+ },
runPromptThroughProvider: (...a) => runPromptThroughProviderMock(...a),
resolveProviderAndModel: (...a) => resolveProviderAndModelMock(...a),
}));
diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.js
index 8221b58c62..e9c477dd4f 100644
--- a/server/services/universeBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -33,6 +33,7 @@ import { sanitizeBibleList, stripCanonControlFields, BIBLE_KIND, BIBLE_SOURCE }
import { ServerError } from "../lib/errorHandler.js";
import { extractJson as extractJsonShared } from "../lib/jsonExtract.js";
import {
+ assertProvider,
resolveProviderAndModel,
runPromptThroughProvider,
} from "../lib/promptRunner.js";
@@ -344,8 +345,7 @@ export async function expandWorldTemplate({
// Resolve the model the runner will ACTUALLY execute (honoring CLI baked
// --model flags) so the log line + returned `llm.model` don't lie.
const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
- if (!provider)
- throw new Error("No AI provider available for universe expansion");
+ assertProvider(provider, { message: "No AI provider available for universe expansion" });
const fullPrompt = buildExpansionPrompt({
starterPrompt: starterPrompt.trim(),
@@ -590,7 +590,7 @@ export async function generateCategoryVariations({
: [];
const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
- if (!provider) throw new Error("No AI provider available for variation generation");
+ assertProvider(provider, { message: "No AI provider available for variation generation" });
const fullPrompt = buildCategoryGeneratePrompt({
category: category.trim(),
diff --git a/server/services/universeBuilderPromote.js b/server/services/universeBuilderPromote.js
index 9ca18a8294..c3304a9837 100644
--- a/server/services/universeBuilderPromote.js
+++ b/server/services/universeBuilderPromote.js
@@ -22,7 +22,7 @@ import {
} from '../lib/storyBible.js';
import { ServerError } from '../lib/errorHandler.js';
import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';
-import { resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';
+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';
// Inverse of BIBLE_FIELD: trunk-name (canon array key) → singular BIBLE_KIND.
// Derived from the source-of-truth map so the two can't drift. `other` is
@@ -238,11 +238,10 @@ export async function promoteVariationToCanon(universeId, options = {}) {
}
const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
- if (!provider) {
- throw new ServerError('No AI provider available for variation promotion', {
- status: 503, code: 'UNIVERSE_PROMOTE_NO_PROVIDER',
- });
- }
+ assertProvider(provider, {
+ message: 'No AI provider available for variation promotion',
+ code: 'UNIVERSE_PROMOTE_NO_PROVIDER',
+ });
const prompt = buildPromotePrompt({
targetKind,
diff --git a/server/services/universeBuilderPromote.test.js b/server/services/universeBuilderPromote.test.js
index ee85afbbde..5b8a2c6dc6 100644
--- a/server/services/universeBuilderPromote.test.js
+++ b/server/services/universeBuilderPromote.test.js
@@ -6,6 +6,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
@@ -27,6 +28,12 @@ vi.mock('crypto', async () => {
const resolveProviderAndModelMock = vi.fn();
const runPromptThroughProviderMock = vi.fn();
vi.mock('../lib/promptRunner.js', () => ({
+assertProvider: (provider, { message, code, status = 503 } = {}) => {
+ if (provider) return;
+ const err = new Error(message || 'No AI provider available');
+ if (code) { err.status = status; err.code = code; }
+ throw err;
+ },
runPromptThroughProvider: (...a) => runPromptThroughProviderMock(...a),
resolveProviderAndModel: (...a) => resolveProviderAndModelMock(...a),
}));
diff --git a/server/services/universeBuilderRefine.js b/server/services/universeBuilderRefine.js
index 009b46dc86..b780fa9391 100644
--- a/server/services/universeBuilderRefine.js
+++ b/server/services/universeBuilderRefine.js
@@ -12,7 +12,7 @@
*/
import { ServerError } from "../lib/errorHandler.js";
-import { resolveProviderAndModel, runPromptThroughProvider } from "../lib/promptRunner.js";
+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from "../lib/promptRunner.js";
import {
renderCategoriesForPrompt as renderCategoriesShared,
renderCompositesForPrompt as renderCompositesShared,
@@ -409,12 +409,11 @@ export async function refineWorldPrompts({
}
const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
- if (!provider) {
- throw new ServerError("No AI provider available for universe refinement", {
- status: 400,
- code: "NO_PROVIDER",
- });
- }
+ assertProvider(provider, {
+ message: "No AI provider available for universe refinement",
+ code: "NO_PROVIDER",
+ status: 400,
+ });
if (provider.enabled === false) {
throw new ServerError(
`Provider "${provider.name || provider.id}" is disabled — enable it in Settings → Providers first`,
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
index 5ae0151a90..94249a969f 100644
--- a/server/services/universeCanon.test.js
+++ b/server/services/universeCanon.test.js
@@ -5,6 +5,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fileStore = new Map();
vi.mock('../lib/fileUtils.js', () => ({
+ tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data', imageRefs: '/mock/data/image-refs' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
diff --git a/server/services/updateChecker.test.js b/server/services/updateChecker.test.js
index cb7a9586de..1360c770c2 100644
--- a/server/services/updateChecker.test.js
+++ b/server/services/updateChecker.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock dependencies before importing the module
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
readJSONFile: vi.fn(),
PATHS: {
root: '/mock',
diff --git a/server/services/updateExecutor.test.js b/server/services/updateExecutor.test.js
index 967e9df2a2..16d9ecf00a 100644
--- a/server/services/updateExecutor.test.js
+++ b/server/services/updateExecutor.test.js
@@ -6,6 +6,7 @@ vi.mock('child_process', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { root: '/mock', data: '/mock/data' }
}));
diff --git a/server/services/usage.test.js b/server/services/usage.test.js
index 6121cb3eab..4f685d2d1e 100644
--- a/server/services/usage.test.js
+++ b/server/services/usage.test.js
@@ -12,6 +12,7 @@ vi.mock('fs/promises', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(undefined),
PATHS: { data: '/fake/data' },
readJSONFile: vi.fn()
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 20077ad7b2..67738b49a7 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -21,6 +21,7 @@ const MOCK_PATHS = {
};
vi.mock('../../lib/fileUtils.js', () => ({
+tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn(async () => {}),
PATHS: MOCK_PATHS,
readJSONFile: vi.fn(async () => []),
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 6bd62bfa50..8471771453 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -10,9 +10,9 @@
*/
import { existsSync, realpathSync } from 'fs';
-import { readdir, readFile, rm, stat } from 'fs/promises';
+import { readdir, rm, stat } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';
import { execGit } from '../lib/execGit.js';
const WORKTREES_DIR = PATHS.worktrees;
@@ -511,7 +511,7 @@ async function cleanupExternalRepoWorktrees(activeAgentIds, alreadyHandled) {
// This is a normal git repo, not a worktree — skip to avoid accidental data loss
continue;
}
- const gitContent = gitStat ? await readFile(gitFile, 'utf-8').catch(() => null) : null;
+ const gitContent = gitStat ? await tryReadFile(gitFile) : null;
if (!gitContent?.startsWith('gitdir:')) {
// No .git file or unreadable — skip rather than removing potentially valuable data
console.log(`🌳 Skipping worktree directory ${agentId} — cannot determine parent repo`);
diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.js
index 88b453834b..35a6ab64bc 100644
--- a/server/services/writersRoom/evaluator.js
+++ b/server/services/writersRoom/evaluator.js
@@ -6,7 +6,7 @@
import { join } from 'path';
import { readFile, readdir, rm } from 'fs/promises';
-import { PATHS, atomicWrite, ensureDir, safeJSONParse } from '../../lib/fileUtils.js';
+import { PATHS, atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { stripCodeFences } from '../../lib/aiProvider.js';
import { runStagedLLM } from '../../lib/stageRunner.js';
@@ -188,7 +188,7 @@ async function migrateLegacyAnalyses(workId) {
if (legacy.length === 0) return 0;
const loaded = (await Promise.all(legacy.map(async (id) => {
const path = join(dir, `${id}.json`);
- const content = await readFile(path, 'utf-8').catch(() => null);
+ const content = await tryReadFile(path);
if (content === null) return null;
const parsed = safeJSONParse(content, null, { allowArray: false, logError: true, context: path });
return parsed ? { id, snapshot: parsed } : null;