Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: consolidate duplicated helpers onto shared canonical utilities
[._.]/ Adam Eivy52ad9d8271c6
diff --git a/client/src/components/agents/tabs/OverviewTab.jsx b/client/src/components/agents/tabs/OverviewTab.jsxindex a5d7b88f56..3bcf5b7329 100644--- a/client/src/components/agents/tabs/OverviewTab.jsx+++ b/client/src/components/agents/tabs/OverviewTab.jsx@@ -7,6 +7,7 @@ import { filterSelectableModels } from '../../../utils/providers';import BrailleSpinner from '../../BrailleSpinner';import { PERSONALITY_STYLES, DEFAULT_PERSONALITY, DEFAULT_AVATAR, PLATFORM_TYPES, ACCOUNT_STATUSES } from '../constants';import { useCooldownTick } from '../../../hooks/useCooldownTick';+import { formatCooldown } from '../../../utils/formatters';export default function OverviewTab({ agentId, agent, onAgentUpdate }) {const navigate = useNavigate();@@ -273,13 +274,6 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {return end ? Math.max(0, end - Date.now()) : 0;};- const formatCooldown = (ms) => {- const totalSeconds = Math.ceil(ms / 1000);- const minutes = Math.floor(totalSeconds / 60);- const seconds = totalSeconds % 60;- return `${minutes}:${seconds.toString().padStart(2, '0')}`;- };-if (!formData) {return <div className="p-4"><BrailleSpinner text="Loading" /></div>;}diff --git a/client/src/components/agents/tabs/ToolsTab.jsx b/client/src/components/agents/tabs/ToolsTab.jsxindex 0b4db79870..cdffc33d85 100644--- a/client/src/components/agents/tabs/ToolsTab.jsx+++ b/client/src/components/agents/tabs/ToolsTab.jsx@@ -3,6 +3,7 @@ import toast from '../../ui/Toast';import * as api from '../../../services/api';import BrailleSpinner from '../../BrailleSpinner';import { useCooldownTick } from '../../../hooks/useCooldownTick';+import { formatCooldown } from '../../../utils/formatters';export default function ToolsTab({ agentId, agent }) {const [selectedAccountId, setSelectedAccountId] = useState('');@@ -310,13 +311,6 @@ export default function ToolsTab({ agentId, agent }) {return end ? Math.max(0, end - Date.now()) : 0;};- const formatCooldown = (ms) => {- const totalSeconds = Math.ceil(ms / 1000);- const minutes = Math.floor(totalSeconds / 60);- const seconds = totalSeconds % 60;- return `${minutes}:${seconds.toString().padStart(2, '0')}`;- };-if (loading) {return <div className="p-4"><BrailleSpinner text="Loading tools" /></div>;}diff --git a/client/src/components/agents/tabs/WorldTab.jsx b/client/src/components/agents/tabs/WorldTab.jsxindex cbcf685c28..fe8a98fc10 100644--- a/client/src/components/agents/tabs/WorldTab.jsx+++ b/client/src/components/agents/tabs/WorldTab.jsx@@ -5,7 +5,7 @@ import BrailleSpinner from '../../BrailleSpinner';import socket from '../../../services/socket';import useMoltworldWs from '../../../hooks/useMoltworldWs';import { useCooldownTick } from '../../../hooks/useCooldownTick';-import { timeAgo } from '../../../utils/formatters';+import { timeAgo, formatCooldown } from '../../../utils/formatters';const EVENT_ICONS = {status: '🔌',@@ -206,10 +206,11 @@ export default function WorldTab({ agentId }) {fetchQueue();}, [accountId, fetchStatus, fetchRateLimits, fetchHistory, fetchQueue]);- // Re-fetch history when filter changes+ // Re-fetch history when filter changes (fetchHistory already captures accountId + historyFilter+ // via useCallback, so adding it to deps here ensures a fresh version runs when accountId changes)useEffect(() => {if (accountId) fetchHistory();- }, [historyFilter]); // eslint-disable-line react-hooks/exhaustive-deps+ }, [accountId, historyFilter, fetchHistory]);// Listen for queue Socket.IO eventsuseEffect(() => {@@ -367,13 +368,6 @@ export default function WorldTab({ agentId }) {return end ? Math.max(0, end - Date.now()) : 0;};- const formatCooldown = (ms) => {- const totalSeconds = Math.ceil(ms / 1000);- const minutes = Math.floor(totalSeconds / 60);- const seconds = totalSeconds % 60;- return `${minutes}:${seconds.toString().padStart(2, '0')}`;- };-if (loading) {return <div className="p-4"><BrailleSpinner text="Loading world tools" /></div>;}diff --git a/client/src/components/apps/tabs/OverviewTab.jsx b/client/src/components/apps/tabs/OverviewTab.jsxindex 49675858f8..44706eda50 100644--- a/client/src/components/apps/tabs/OverviewTab.jsx+++ b/client/src/components/apps/tabs/OverviewTab.jsx@@ -10,6 +10,7 @@ import SlashDoPanel from '../SlashDoPanel';import Banner from '../../ui/Banner';import { useAppOperation } from '../../../hooks/useAppOperation';import * as api from '../../../services/api';+import { formatBytes } from '../../../utils/formatters';const SCRIPT_ICONS = {'deploy.sh': Rocket,@@ -217,7 +218,7 @@ export default function OverviewTab({ app, onRefresh }) {<span className="text-xs text-green-400">{proc.cpu}%</span>)}{proc.memory !== undefined && (- <span className="text-xs text-blue-400">{(proc.memory / 1024 / 1024).toFixed(0)}MB</span>+ <span className="text-xs text-blue-400">{formatBytes(proc.memory)}</span>)}</div>);diff --git a/client/src/components/apps/tabs/ProcessesTab.jsx b/client/src/components/apps/tabs/ProcessesTab.jsxindex 2f28a5b48d..ec72c8193a 100644--- a/client/src/components/apps/tabs/ProcessesTab.jsx+++ b/client/src/components/apps/tabs/ProcessesTab.jsx@@ -4,11 +4,7 @@ import * as api from '../../../services/api';import socket from '../../../services/socket';import BrailleSpinner from '../../BrailleSpinner';import { useAutoRefetch } from '../../../hooks/useAutoRefetch';--const formatMemory = (bytes) => {- if (!bytes) return '0 MB';- return `${(bytes / 1024 / 1024).toFixed(1)} MB`;-};+import { formatBytes } from '../../../utils/formatters';const formatUptime = (ms) => {if (!ms) return '-';@@ -206,7 +202,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {</td><td className="px-4 py-3 text-gray-400 font-mono text-sm">{proc.pid || '-'}</td><td className="px-4 py-3 text-gray-400">{proc.cpu ? `${proc.cpu}%` : '-'}</td>- <td className="px-4 py-3 text-gray-400">{formatMemory(proc.memory)}</td>+ <td className="px-4 py-3 text-gray-400">{formatBytes(proc.memory)}</td><td className="px-4 py-3 text-gray-400">{formatUptime(proc.uptime)}</td><td className="px-4 py-3 text-gray-400">{proc.restarts}</td><td className="px-4 py-3 text-right">diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 37d5156eb5..90154f1976 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -30,6 +30,7 @@ import Modal from '../../ui/Modal';import toast from '../../ui/Toast';import { copyToClipboard } from '../../../lib/clipboard';import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';+import { formatDurationMs } from '../../../utils/formatters';import { useAutoRefetch } from '../../../hooks/useAutoRefetch';// Extract task type from description (matches server-side extractTaskType)@@ -256,13 +257,6 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,? new Date(agent.completedAt) - new Date(agent.startedAt): now - new Date(agent.startedAt);- const formatDuration = (ms) => {- const seconds = Math.floor(ms / 1000);- const minutes = Math.floor(seconds / 60);- if (minutes > 0) return `${minutes}m ${seconds % 60}s`;- return `${seconds}s`;- };-// Calculate duration estimate for running agents// Uses P80 (80th percentile approximation) for progress bars to prevent premature 100%const durationEstimate = useMemo(() => {@@ -502,27 +496,27 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,{!inactive && durationEstimate ? (<spanclassName="flex items-center gap-1.5 text-gray-500 whitespace-nowrap"- title={`Based on ${durationEstimate.basedOn} completed ${durationEstimate.taskType} tasks (avg: ${formatDuration(durationEstimate.avgMs)}, est: ${formatDuration(durationEstimate.estimatedMs)})`}+ title={`Based on ${durationEstimate.basedOn} completed ${durationEstimate.taskType} tasks (avg: ${formatDurationMs(durationEstimate.avgMs)}, est: ${formatDurationMs(durationEstimate.estimatedMs)})`}><Clock size={12} aria-hidden="true" className="shrink-0" />- <span className="font-mono">{formatDuration(duration)}</span>+ <span className="font-mono">{formatDurationMs(duration)}</span>{remainingTime && !remainingTime.isOvertime && (<><span className="text-gray-600">→</span>- <span className="font-mono text-port-accent">~{formatDuration(remainingTime.remaining)} left</span>+ <span className="font-mono text-port-accent">~{formatDurationMs(remainingTime.remaining)} left</span></>)}{remainingTime?.isOvertime && (<><span className="text-gray-600">→</span>- <span className="font-mono text-yellow-500">+{formatDuration(remainingTime.overBy)}</span>+ <span className="font-mono text-yellow-500">+{formatDurationMs(remainingTime.overBy)}</span></>)}</span>) : (<span className="flex items-center gap-1 text-gray-500 whitespace-nowrap"><Clock size={12} aria-hidden="true" className="shrink-0" />- <span className="font-mono">{formatDuration(duration)}</span>+ <span className="font-mono">{formatDurationMs(duration)}</span></span>)}{/* Completed timestamp */}@@ -730,12 +724,12 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,</span>{remainingTime && !remainingTime.isOvertime && (<span className="text-port-accent font-medium">- ETA: ~{formatDuration(remainingTime.remaining)}+ ETA: ~{formatDurationMs(remainingTime.remaining)}</span>)}{remainingTime?.isOvertime && (<span className="text-yellow-500 font-medium animate-pulse">- +{formatDuration(remainingTime.overBy)} over estimate+ +{formatDurationMs(remainingTime.overBy)} over estimate</span>)}</div>diff --git a/client/src/components/digital-twin/tabs/ImportTab.jsx b/client/src/components/digital-twin/tabs/ImportTab.jsxindex e32e0e29fa..c91369bfa7 100644--- a/client/src/components/digital-twin/tabs/ImportTab.jsx+++ b/client/src/components/digital-twin/tabs/ImportTab.jsx@@ -14,6 +14,7 @@ import {} from 'lucide-react';import * as api from '../../../services/api';import toast from '../../ui/Toast';+import { formatBytes } from '../../../utils/formatters';const SOURCE_ICONS = {goodreads: BookOpen,@@ -228,7 +229,7 @@ export default function ImportTab() {{fileContent && (<div className="mt-2 flex items-center gap-2 text-sm text-green-400"><Check className="w-4 h-4" />- File loaded ({Math.round(fileContent.length / 1024)} KB)+ File loaded ({formatBytes(fileContent.length, 0)})</div>)}</div>diff --git a/client/src/components/goals/GoalProgressLog.jsx b/client/src/components/goals/GoalProgressLog.jsxindex 3f4cdbdfe2..9d97e412b8 100644--- a/client/src/components/goals/GoalProgressLog.jsx+++ b/client/src/components/goals/GoalProgressLog.jsx@@ -1,4 +1,5 @@import { NotebookPen, Plus, Clock, Trash2 } from 'lucide-react';+import { formatDurationMin } from '../../utils/formatters';export default function GoalProgressLog({goal, showProgressForm, setShowProgressForm, progressForm, setProgressForm,@@ -80,9 +81,7 @@ export default function GoalProgressLog({{entry.durationMinutes && (<span className="flex items-center gap-0.5"><Clock className="w-3 h-3" />- {entry.durationMinutes >= 60- ? `${Math.floor(entry.durationMinutes / 60)}h${entry.durationMinutes % 60 ? ` ${entry.durationMinutes % 60}m` : ''}`- : `${entry.durationMinutes}m`}+ {formatDurationMin(entry.durationMinutes)}</span>)}</div>diff --git a/client/src/components/goals/ProgressSlider.jsx b/client/src/components/goals/ProgressSlider.jsxindex f131046410..2bf9e5d4dd 100644--- a/client/src/components/goals/ProgressSlider.jsx+++ b/client/src/components/goals/ProgressSlider.jsx@@ -1,5 +1,6 @@import { useState, useEffect } from 'react';import { TrendingUp, TrendingDown, Minus, Clock } from 'lucide-react';+import { formatDurationMin } from '../../utils/formatters';export default function ProgressSlider({ goal, onCommit }) {const [draft, setDraft] = useState(goal.progress ?? 0);@@ -49,9 +50,7 @@ export default function ProgressSlider({ goal, onCommit }) {{goal.timeTracking?.totalMinutes > 0 && (<div className="flex items-center gap-1 mt-1 text-xs text-gray-600"><Clock className="w-3 h-3" />- {goal.timeTracking.totalMinutes >= 60- ? `${Math.floor(goal.timeTracking.totalMinutes / 60)}h${goal.timeTracking.totalMinutes % 60 ? ` ${goal.timeTracking.totalMinutes % 60}m` : ''}`- : `${goal.timeTracking.totalMinutes}m`}+ {formatDurationMin(goal.timeTracking.totalMinutes)}{' total'}{goal.timeTracking.weeklyAverage > 0 && ` · ${goal.timeTracking.weeklyAverage}m/wk`}</div>diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex aaf32f7a9a..216d1bfc99 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -4,7 +4,7 @@ import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, Eximport toast from '../ui/Toast';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import BrailleSpinner from '../BrailleSpinner';-import { formatBytes, formatContextLength, timeAgo } from '../../utils/formatters';+import { formatBytes, formatContextLength, timeAgo, parseSizeGb, recommendedRamGb } from '../../utils/formatters';import { localLlmTargetKey } from '../../lib/localLlmTargetKey';import {getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,@@ -44,22 +44,6 @@ const CAPABILITY_META = {tools: { Icon: Wrench, label: 'Tool use', cls: 'text-blue-400 border-blue-400/50' },};-// Parse a human size string ("4.7 GB", "512 MB") back to GB for the RAM hint.-function parseSizeGb(sizeStr) {- const match = /([\d.]+)\s*(TB|GB|MB|KB)/i.exec(String(sizeStr || ''));- if (!match) return null;- const val = parseFloat(match[1]);- if (!Number.isFinite(val)) return null;- return val * ({ TB: 1024, GB: 1, MB: 1 / 1024, KB: 1 / (1024 * 1024) }[match[2].toUpperCase()]);-}--// Rough RAM/VRAM to run a model: weights + ~20% overhead (KV cache/runtime),-// rounded up to whole GB with a 1 GB floor. Prefers exact bytes when known.-function recommendedRamGb(m) {- const gb = Number.isFinite(m?.sizeBytes) ? m.sizeBytes / 1024 ** 3 : parseSizeGb(m?.size);- if (!gb || gb <= 0) return null;- return Math.max(1, Math.ceil(gb * 1.2));-}// Summarize a migrate result for the success toast (per-model statuses → counts).function summarizeMigrate(r) {@@ -686,7 +670,7 @@ export function LocalLlmTab() {)}<div className="grid grid-cols-1 md:grid-cols-2 gap-2">{group.models.map((m) => {- const ram = recommendedRamGb(m);+ const ram = recommendedRamGb(m?.sizeBytes, m?.size);const isHf = m.source === 'huggingface';const createdMs = new Date(m.createdAt).getTime();const updatedMs = new Date(m.updatedAt).getTime();diff --git a/client/src/components/settings/LocalSetupPanel.jsx b/client/src/components/settings/LocalSetupPanel.jsxindex 76b905b935..a609958eff 100644--- a/client/src/components/settings/LocalSetupPanel.jsx+++ b/client/src/components/settings/LocalSetupPanel.jsx@@ -4,6 +4,7 @@ import toast from '../ui/Toast';import Banner from '../ui/Banner';import BrailleSpinner from '../BrailleSpinner';import { usePrevious } from '../../hooks/usePrevious.js';+import { safeParseJSON } from '../../lib/genUtils.js';export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPackagesChanged }) {const [detecting, setDetecting] = useState(false);@@ -109,7 +110,7 @@ export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPackinstallEsRef.current = es;es.onmessage = (e) => {- const event = (() => { try { return JSON.parse(e.data); } catch { return null; } })();+ const event = safeParseJSON(e.data);if (!event) return;setInstallLog(prev => [...prev.slice(-200), event]);if (event.type === 'complete') {diff --git a/client/src/components/videoGen/AudioPanel.jsx b/client/src/components/videoGen/AudioPanel.jsxindex 3ed71e2c44..39169edf06 100644--- a/client/src/components/videoGen/AudioPanel.jsx+++ b/client/src/components/videoGen/AudioPanel.jsx@@ -6,6 +6,7 @@* "no compatible model installed" condition are owned by the VideoGen page.*/import { Upload, Music } from 'lucide-react';+import { formatBytes } from '../../utils/formatters';export default function AudioPanel({ audioFile, numFrames, fps, hasCompatibleModel, onPick, onClear }) {return (@@ -20,7 +21,7 @@ export default function AudioPanel({ audioFile, numFrames, fps, hasCompatibleMod<div className="flex items-center gap-2 text-[11px] text-gray-300"><Music className="w-3.5 h-3.5 text-port-accent" /><span className="truncate" title={audioFile.name}>{audioFile.name}</span>- <span className="text-gray-500">{(audioFile.size / 1024 / 1024).toFixed(2)} MB</span>+ <span className="text-gray-500">{formatBytes(audioFile.size, 2)}</span></div>) : (<label className="flex items-center gap-2 text-[11px] text-gray-400 cursor-pointer hover:text-white">diff --git a/client/src/components/videoGen/AudioPanel.test.jsx b/client/src/components/videoGen/AudioPanel.test.jsxindex 2cd25e3e5b..d561b1a89d 100644--- a/client/src/components/videoGen/AudioPanel.test.jsx+++ b/client/src/components/videoGen/AudioPanel.test.jsx@@ -34,7 +34,7 @@ describe('AudioPanel', () => {/>,);expect(screen.getByText('track.wav')).toBeTruthy();- expect(screen.getByText(/2\.00 MB/)).toBeTruthy();+ expect(screen.getByText(/2 MB/)).toBeTruthy();fireEvent.click(screen.getByText('Clear'));expect(onClear).toHaveBeenCalled();});diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsxindex 9c82772b22..b2abadddce 100644--- a/client/src/pages/Apps.jsx+++ b/client/src/pages/Apps.jsx@@ -12,6 +12,7 @@ import { useAppOperation } from '../hooks/useAppOperation';import * as api from '../services/api';import socket from '../services/socket';import { NON_PM2_TYPES, getAppTypeLabel } from '../components/apps/constants';+import { formatBytes } from '../utils/formatters';export default function Apps() {const [apps, setApps] = useState([]);@@ -463,7 +464,7 @@ export default function Apps() {<span className="text-xs text-green-400">{proc.cpu}%</span>)}{proc.memory !== undefined && (- <span className="text-xs text-blue-400">{(proc.memory / 1024 / 1024).toFixed(0)}MB</span>+ <span className="text-xs text-blue-400">{formatBytes(proc.memory)}</span>)}</div>);diff --git a/client/src/pages/LocalLlmPlayground.jsx b/client/src/pages/LocalLlmPlayground.jsxindex 3890886194..1a38aa37ac 100644--- a/client/src/pages/LocalLlmPlayground.jsx+++ b/client/src/pages/LocalLlmPlayground.jsx@@ -6,7 +6,7 @@ import PlaygroundOutput from '../components/localLlm/PlaygroundOutput';import toast from '../components/ui/Toast';import { copyToClipboard } from '../lib/clipboard';import { localLlmTargetKey } from '../lib/localLlmTargetKey';-import { formatBytes } from '../utils/formatters';+import { formatBytes, parseSizeGb, recommendedRamGb } from '../utils/formatters';import { compareLocalLlmModels, getLocalLlmCatalog, getLocalLlmStatus, streamLocalLlmTest } from '../services/api';const BACKEND_LABEL = { ollama: 'Ollama', lmstudio: 'LM Studio' };@@ -42,20 +42,6 @@ function formatRate(value) {return `${value.toFixed(value >= 10 ? 1 : 2)} chars/s`;}-function parseSizeGb(sizeStr) {- const match = /([\d.]+)\s*(TB|GB|MB|KB)/i.exec(String(sizeStr || ''));- if (!match) return null;- const val = parseFloat(match[1]);- if (!Number.isFinite(val)) return null;- return val * ({ TB: 1024, GB: 1, MB: 1 / 1024, KB: 1 / (1024 * 1024) }[match[2].toUpperCase()]);-}--function recommendedRamGb(model) {- const gb = Number.isFinite(model?.size) ? model.size / 1024 ** 3 : parseSizeGb(model?.catalog?.size);- if (!gb || gb <= 0) return null;- return Math.max(1, Math.ceil(gb * 1.2));-}-function modelSizeLabel(model) {if (Number.isFinite(model?.size)) return formatBytes(model.size);return model?.catalog?.size || '';@@ -450,7 +436,7 @@ export default function LocalLlmPlayground() {{models.map((target) => {const selected = selectedKeys.has(localLlmTargetKey(target));const size = modelSizeLabel(target);- const ram = recommendedRamGb(target);+ const ram = recommendedRamGb(target?.size, target?.catalog?.size);const tags = getUseCaseTags(target);const detailParts = [target.catalog?.params || target.params,diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 885a99223e..3037decca7 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -22,7 +22,7 @@ grep -i "what you want to do" client/src/utils/README.md| Module | Purpose ||---|---|-| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. |+| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. || `cronHelpers` | Cron preset list, `isCronExpression` detection, and `describeCron` human-readable rendering. || `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.jsindex f5471caca3..0d6b4c3cf0 100644--- a/client/src/utils/formatters.js+++ b/client/src/utils/formatters.js@@ -313,3 +313,42 @@ export function getAppName(appId, apps, fallback = null) {const app = apps?.find(a => a.id === appId);return app?.name || fallback;}++/**+ * Format a cooldown countdown in milliseconds as "M:SS" (e.g., "1:05", "0:09").+ * @param {number} ms - Remaining milliseconds (negative values clamp to 0:00)+ * @returns {string} Minutes:seconds countdown string+ */+export function formatCooldown(ms) {+ const totalSeconds = Math.max(0, Math.ceil(ms / 1000));+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ return `${minutes}:${seconds.toString().padStart(2, '0')}`;+}++/**+ * Parse a human size string ("4.7 GB", "512 MB") to GB.+ * @param {string|null|undefined} sizeStr - Human-readable size string+ * @returns {number|null} Size in GB, or null when unparseable+ */+export function parseSizeGb(sizeStr) {+ const match = /([\d.]+)\s*(TB|GB|MB|KB)/i.exec(String(sizeStr || ''));+ if (!match) return null;+ const val = parseFloat(match[1]);+ if (!Number.isFinite(val)) return null;+ return val * ({ TB: 1024, GB: 1, MB: 1 / 1024, KB: 1 / (1024 * 1024) }[match[2].toUpperCase()]);+}++/**+ * Rough RAM/VRAM needed to run a local model: weights + ~20% overhead+ * (KV cache/runtime), rounded up to whole GB with a 1 GB floor.+ * Prefers exact bytes when known, falling back to a human size string.+ * @param {number|null|undefined} sizeBytes - Exact model size in bytes+ * @param {string|null|undefined} sizeStr - Human size string fallback ("4.7 GB")+ * @returns {number|null} Whole GB recommendation, or null when size is unknown+ */+export function recommendedRamGb(sizeBytes, sizeStr) {+ const gb = Number.isFinite(sizeBytes) ? sizeBytes / 1024 ** 3 : parseSizeGb(sizeStr);+ if (!gb || gb <= 0) return null;+ return Math.max(1, Math.ceil(gb * 1.2));+}diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.jsindex e61f63163e..6877fa0cc4 100644--- a/client/src/utils/formatters.test.js+++ b/client/src/utils/formatters.test.js@@ -1,5 +1,8 @@import { describe, it, expect } from 'vitest';-import { formatContextLength, formatDurationMin, formatEventDateTime, timeAgo } from './formatters.js';+import {+ formatContextLength, formatDurationMin, formatEventDateTime, timeAgo,+ formatCooldown, parseSizeGb, recommendedRamGb, parseTimeoutMs,+} from './formatters.js';describe('formatContextLength', () => {it('formats common context windows compactly', () => {@@ -100,3 +103,111 @@ describe('timeAgo', () => {expect(timeAgo(threeDaysAgo)).toBe('3d ago');});});++describe('formatCooldown', () => {+ it('formats 0 ms as 0:00', () => {+ expect(formatCooldown(0)).toBe('0:00');+ });++ it('clamps negative values to 0:00', () => {+ expect(formatCooldown(-5000)).toBe('0:00');+ expect(formatCooldown(-1)).toBe('0:00');+ });++ it('formats 65000 ms (1 min 5 sec) as 1:05', () => {+ expect(formatCooldown(65000)).toBe('1:05');+ });++ it('formats exactly 60000 ms as 1:00', () => {+ expect(formatCooldown(60000)).toBe('1:00');+ });++ it('formats sub-minute values with leading zero seconds', () => {+ expect(formatCooldown(9000)).toBe('0:09');+ expect(formatCooldown(59000)).toBe('0:59');+ });+});++describe('parseSizeGb', () => {+ it('parses GB strings', () => {+ expect(parseSizeGb('4.7 GB')).toBeCloseTo(4.7);+ expect(parseSizeGb('1GB')).toBe(1);+ });++ it('parses MB strings (converts to fractional GB)', () => {+ const result = parseSizeGb('512 MB');+ expect(result).toBeCloseTo(0.5);+ });++ it('parses TB strings (converts to large GB)', () => {+ const result = parseSizeGb('2 TB');+ expect(result).toBeCloseTo(2048);+ });++ it('returns null for garbage input', () => {+ expect(parseSizeGb('not a size')).toBeNull();+ expect(parseSizeGb('')).toBeNull();+ expect(parseSizeGb(null)).toBeNull();+ expect(parseSizeGb(undefined)).toBeNull();+ });+});++describe('recommendedRamGb', () => {+ it('uses exact bytes when provided', () => {+ // 4 GB in bytes: 4 * 1024^3 = 4294967296; + 20% overhead = 4.8 → ceil = 5+ expect(recommendedRamGb(4 * 1024 ** 3, null)).toBe(5);+ });++ it('falls back to size string when bytes are null', () => {+ // 4.7 GB string: 4.7 * 1.2 = 5.64 → ceil = 6+ expect(recommendedRamGb(null, '4.7 GB')).toBe(6);+ });++ it('returns null when both inputs are absent', () => {+ expect(recommendedRamGb(null, null)).toBeNull();+ expect(recommendedRamGb(undefined, undefined)).toBeNull();+ });++ it('enforces a 1 GB floor for tiny models', () => {+ // 10 MB: 10/1024 GB * 1.2 < 1 → floor to 1+ expect(recommendedRamGb(10 * 1024 * 1024, null)).toBe(1);+ });+});++describe('parseTimeoutMs', () => {+ it('returns null for null/empty/blank', () => {+ expect(parseTimeoutMs(null)).toBeNull();+ expect(parseTimeoutMs(undefined)).toBeNull();+ expect(parseTimeoutMs('')).toBeNull();+ expect(parseTimeoutMs(' ')).toBeNull();+ });++ it('returns null for values below the 1000ms floor', () => {+ expect(parseTimeoutMs('999')).toBeNull();+ expect(parseTimeoutMs('0')).toBeNull();+ });++ it('accepts the minimum boundary (1000)', () => {+ expect(parseTimeoutMs('1000')).toBe(1000);+ });++ it('accepts the maximum boundary (1800000)', () => {+ expect(parseTimeoutMs('1800000')).toBe(1800000);+ });++ it('returns null for values above the 1800000ms ceiling', () => {+ expect(parseTimeoutMs('1800001')).toBeNull();+ });++ it('rejects scientific notation ("1e3") — digit-only gate', () => {+ expect(parseTimeoutMs('1e3')).toBeNull();+ });++ it('rejects decimal strings ("1.5") — must be integer digit-only', () => {+ expect(parseTimeoutMs('1.5')).toBeNull();+ });++ it('accepts a mid-range valid value', () => {+ expect(parseTimeoutMs('30000')).toBe(30000);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 1ed751142d..4845e6c9d8 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -89,7 +89,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `hfToken.js` | HuggingFace token resolution (settings > env > CLI). || `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. || `hfDownload.js` | `downloadHfRepo({repo,onEvent})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in the FLUX.2 venv (fallback: mflux pythonPath) and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. |-| `sseDownload.js` | `startHfDownloadStream({req,res,repo,alreadyDownloadedMessage})` — shared SSE driver used by both image and video gen `/models/:id/download` routes. Owns the cross-route in-flight Map so a double-click (or both pages running) can't spawn two python children against the same repo. |+| `sseDownload.js` | `startHfDownloadStream({req,res,repo,alreadyDownloadedMessage})`, `openSseStream(res)` (`{send,safeEnd}` SSE boilerplate), `SSE_HEADERS` — shared SSE driver used by both image and video gen `/models/:id/download` routes. Owns the cross-route in-flight Map so a double-click (or both pages running) can't spawn two python children against the same repo. |## File & I/O@@ -98,7 +98,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. **Type-index `config` slot** holds cross-record state (see the `TypeIndexConfig` typedef + header convention): `{ runs?: [], featureFlags?: {}, lockPolicies?: {} }` — `runs` is the shipped slot (universeBuilder's capped history log), the other two are reserved names; consumers may add their own keys but should reuse a reserved name when it fits and document the shape next to the consumer. `saveTypeIndex({ config })` shallow-merges `config` one level deep (a patched `runs` replaces the whole array), so a read-modify-write of a slot must load → mutate a copy → write inside `queueTypeIndexWrite(fn)`. || `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, `expandHome` (`~/foo` → absolute), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. || `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. || `imageClean.js` | `cleanImageBuffer` (sharp-based denoise + C2PA strip) + `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. || `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 7aad9d6e69..242c990b30 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -525,6 +525,17 @@ export const MINUTE = 60 * 1000;export const HOUR = 60 * MINUTE;export const DAY = 24 * HOUR;+/**+ * Promise-based delay. Canonical replacement for the per-module+ * `const delay = (ms) => new Promise(...)` one-liners.+ *+ * @param {number} ms - Milliseconds to wait+ * @returns {Promise<void>}+ */+export function sleep(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}+/*** Format a date as YYYY-MM-DD string.*diff --git a/server/lib/imageClean.js b/server/lib/imageClean.jsindex 9cdae3962c..92ecc120d0 100644--- a/server/lib/imageClean.js+++ b/server/lib/imageClean.js@@ -12,7 +12,6 @@// honest about that distinction.import sharp from 'sharp';-import { readFile } from 'fs/promises';import { basename } from 'node:path';import { ServerError } from './errorHandler.js';import { tryReadFile, safeJSONParse, atomicWrite } from './fileUtils.js';@@ -271,7 +270,7 @@ export async function autoCleanGeneratedImage({ cleanC2PA = false, denoise = fal// before the readFile so the two disk ops overlap.const sidecarReadP = sidecarPath ? tryReadFile(sidecarPath) : Promise.resolve(null);- const buffer = await readFile(pngPath).catch(() => null);+ const buffer = await tryReadFile(pngPath, null);if (!buffer) {console.warn(`⚠️ Auto-clean skipped (source missing): ${pngPath}`);return { cleaned: false };diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 770e013598..aea9deca81 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -28,9 +28,8 @@* add an entry here.*/-import { readFile } from 'fs/promises';import { join } from 'path';-import { PATHS } from './fileUtils.js';+import { PATHS, tryReadFile, safeJSONParse } from './fileUtils.js';export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// Type-level (storage layout) version for `data/universes/{id}/index.json`.@@ -217,9 +216,9 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({*/export async function getPortosVersion() {const pkgPath = join(PATHS.root, 'package.json');- const raw = await readFile(pkgPath, 'utf-8').catch(() => null);+ const raw = await tryReadFile(pkgPath);if (!raw) return '0.0.0';- const parsed = (() => { try { return JSON.parse(raw); } catch { return null; } })();+ const parsed = safeJSONParse(raw, null);return typeof parsed?.version === 'string' && parsed.version ? parsed.version : '0.0.0';}diff --git a/server/routes/agentTools.js b/server/routes/agentTools.jsindex 038a1b8cde..d2e1789e78 100644--- a/server/routes/agentTools.js+++ b/server/routes/agentTools.js@@ -26,6 +26,11 @@ import { generatePost, generateComment, generateReply } from '../services/agentCimport { findRelevantPosts } from '../services/agentFeedFilter.js';import { MoltbookClient } from '../integrations/moltbook/index.js';import { collectPublishedPosts } from '../services/agentPublished.js';+import { sleep } from '../lib/fileUtils.js';++// Throttle between successive platform writes (votes/comments/replies) so a+// single agent run doesn't burst the platform API.+const MOLTBOOK_ACTION_DELAY_MS = 1500;const router = Router();@@ -166,7 +171,6 @@ router.post('/engage', asyncHandler(async (req, res) => {const votes = [];const comments = [];- const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));// Vote on relevant postsfor (const post of relevantPosts) {@@ -177,7 +181,7 @@ router.post('/engage', asyncHandler(async (req, res) => {await client.upvote(post.id);votes.push({ postId: post.id, title: post.title });- await delay(1500);+ await sleep(MOLTBOOK_ACTION_DELAY_MS);}// Comment on best matches@@ -205,7 +209,7 @@ router.post('/engage', asyncHandler(async (req, res) => {content: generated.content,reason: opportunity.reason});- await delay(1500);+ await sleep(MOLTBOOK_ACTION_DELAY_MS);}}@@ -415,7 +419,6 @@ router.post('/check-posts', asyncHandler(async (req, res) => {let totalComments = 0;let newComments = 0;let suspended = false;- const delayMs = (ms) => new Promise(resolve => setTimeout(resolve, ms));for (const post of posts) {if (suspended) break;@@ -458,7 +461,7 @@ router.post('/check-posts', asyncHandler(async (req, res) => {snippet: (comment.content || '').substring(0, 80)});}- await delayMs(1500);+ await sleep(MOLTBOOK_ACTION_DELAY_MS);}}@@ -484,7 +487,7 @@ router.post('/check-posts', asyncHandler(async (req, res) => {reply: generated.content});}- await delayMs(1500);+ await sleep(MOLTBOOK_ACTION_DELAY_MS);}}diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 7281b53df6..806cfe49ed 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -14,19 +14,10 @@ import { provisionTailscaleCert } from '../services/certProvisioner.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { DEFAULT_PEER_PORT } from '../lib/ports.js';import { findTailscale } from '../lib/tailscale.js';+import { safeJSONParse } from '../lib/fileUtils.js';const execFileAsync = promisify(execFile);-// Safely parse JSON, returning null on malformed input. Used when consuming CLI output-// that may interleave warnings with the JSON payload or be partial.-function safeJsonParse(str) {- try {- return JSON.parse(str);- } catch {- return null;- }-}-const router = Router();// Optional HTTP Basic credential for a peer behind an auth proxy. `null` clears@@ -148,7 +139,7 @@ router.get('/tailnet-suffix', asyncHandler(async (req, res) => {const { stdout } = await execFileAsync(bin, ['status', '--json'], { timeout: 5000 }).catch(() => ({ stdout: null }));if (!stdout) return res.json({ suffix: null, reason: 'tailscale-not-running' });// Guard against non-JSON output (warnings, partial reads, etc.) so we never 500 the endpoint.- const status = safeJsonParse(stdout);+ const status = safeJSONParse(stdout, null);if (!status) return res.json({ suffix: null, reason: 'tailscale-parse-error' });const suffix = status?.CurrentTailnet?.MagicDNSSuffix ?? status?.MagicDNSSuffix ?? null;// Also include the peer map so the UI can auto-match a peer's instanceId/hostnamediff --git a/server/services/agentActionExecutor.js b/server/services/agentActionExecutor.jsindex 92b0366e85..f988281ab0 100644--- a/server/services/agentActionExecutor.js+++ b/server/services/agentActionExecutor.js@@ -14,8 +14,7 @@ import { MoltbookClient, checkRateLimit, isAccountSuspended } from '../integratiimport { MoltworldClient } from '../integrations/moltworld/index.js';import { generatePost, generateComment, generateReply } from './agentContentGenerator.js';import { findRelevantPosts, findReplyOpportunities } from './agentFeedFilter.js';--const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));+import { sleep as delay } from '../lib/fileUtils.js';// Throttle between successive platform writes (votes/comments/replies) so a// single agent run doesn't burst the platform API.diff --git a/server/services/agentActivity.js b/server/services/agentActivity.jsindex 6c4655dd23..91d175d0e4 100644--- a/server/services/agentActivity.js+++ b/server/services/agentActivity.js@@ -5,11 +5,11 @@* and rate limit enforcement. Activity is stored per-agent per-day.*/-import { readFile, writeFile, readdir } from 'fs/promises';+import { readFile, readdir } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import EventEmitter from 'events';-import { ensureDir, getDateString, PATHS } from '../lib/fileUtils.js';+import { ensureDir, getDateString, atomicWrite, PATHS } from '../lib/fileUtils.js';const AGENTS_DIR = PATHS.agentPersonalities;const ACTIVITY_DIR = join(AGENTS_DIR, 'activity');@@ -53,7 +53,7 @@ async function loadActivity(agentId, date = new Date()) {async function saveActivity(agentId, date, data) {await ensureActivityDir(agentId);const filePath = getActivityFilePath(agentId, date);- await writeFile(filePath, JSON.stringify(data, null, 2));+ await atomicWrite(filePath, data);}/**diff --git a/server/services/appActivity.js b/server/services/appActivity.jsindex 67dcd46cac..39ef3bebdf 100644--- a/server/services/appActivity.js+++ b/server/services/appActivity.js@@ -5,9 +5,8 @@* Prevents the CoS from working on the same app in a loop.*/-import { writeFile } from 'fs/promises';import { join } from 'path';-import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';+import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';const DATA_DIR = PATHS.cos;const ACTIVITY_FILE = join(DATA_DIR, 'app-activity.json');@@ -35,7 +34,7 @@ export async function loadAppActivity() {*/export async function saveAppActivity(activity) {await ensureDir(DATA_DIR);- await writeFile(ACTIVITY_FILE, JSON.stringify(activity, null, 2));+ await atomicWrite(ACTIVITY_FILE, activity);}/**diff --git a/server/services/backup.js b/server/services/backup.jsindex 15395e500e..9dc5713ac6 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -7,10 +7,10 @@*/import { spawn } from 'child_process';-import { access, readdir, readFile, stat, unlink, writeFile } from 'fs/promises';+import { access, readdir, readFile, stat, unlink } from 'fs/promises';import { hostname } from 'os';import { join, resolve, relative, isAbsolute } from 'path';-import { PATHS, ensureDir, readJSONFile, sha256File } from '../lib/fileUtils.js';+import { PATHS, ensureDir, readJSONFile, atomicWrite, sha256File } from '../lib/fileUtils.js';import { getEvent } from './eventScheduler.js';import { checkHealth, getServerMajorVersion } from '../lib/db.js';import { resolvePgDumpBinary } from '../lib/pgTools.js';@@ -585,7 +585,7 @@ export async function saveState(patch) {await ensureDir(join(PATHS.data, 'backup'));const current = await getState();const updated = { ...current, ...patch };- await writeFile(STATE_PATH, JSON.stringify(updated, null, 2), 'utf-8');+ await atomicWrite(STATE_PATH, updated);}/**diff --git a/server/services/calendarAccounts.js b/server/services/calendarAccounts.jsindex e63af46037..8750f39f18 100644--- a/server/services/calendarAccounts.js+++ b/server/services/calendarAccounts.js@@ -1,7 +1,6 @@-import { writeFile } from 'fs/promises';import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';-import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';+import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';const ACCOUNTS_FILE = join(PATHS.calendar, 'accounts.json');@@ -14,7 +13,7 @@ async function loadAccounts() {async function saveAccounts(accounts) {await ensureDir(PATHS.calendar);- await writeFile(ACCOUNTS_FILE, JSON.stringify(accounts, null, 2));+ await atomicWrite(ACCOUNTS_FILE, accounts);}export async function listAccounts() {diff --git a/server/services/calendarAccounts.test.js b/server/services/calendarAccounts.test.jsnew file mode 100644index 0000000000..b78a6151fb--- /dev/null+++ b/server/services/calendarAccounts.test.js@@ -0,0 +1,105 @@+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'calendar-accounts-test-'));++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), {+ dataRoot: TEST_DATA_ROOT,+ extraOverrides: (root) => ({ calendar: join(root, 'calendar') }),+ }));++vi.mock('../lib/uuid.js', () => ({+ v4: vi.fn().mockReturnValue('test-uuid-1234'),+}));++const calendarAccounts = await import('./calendarAccounts.js');++afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++describe('calendarAccounts', () => {+ beforeEach(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ mkdirSync(TEST_DATA_ROOT, { recursive: true });+ });++ describe('createAccount', () => {+ it('creates an account with field defaults', async () => {+ const acc = await calendarAccounts.createAccount({+ name: 'Work Cal',+ type: 'outlook-calendar',+ email: '[email protected]',+ });++ expect(acc.id).toBe('test-uuid-1234');+ expect(acc.name).toBe('Work Cal');+ expect(acc.type).toBe('outlook-calendar');+ expect(acc.email).toBe('[email protected]');+ expect(acc.enabled).toBe(true);+ expect(acc.lastSyncAt).toBeNull();+ expect(acc.lastSyncStatus).toBeNull();+ expect(acc.createdAt).toBeTruthy();+ expect(acc.syncConfig.maxAge).toBe('90d');+ expect(acc.syncConfig.syncInterval).toBe(300000);+ expect(acc.syncConfig.calendarIds).toEqual(['default']);+ });++ it('defaults email to empty string when not provided', async () => {+ const acc = await calendarAccounts.createAccount({+ name: 'Personal',+ type: 'outlook-calendar',+ });+ expect(acc.email).toBe('');+ });+ });++ describe('updateAccount', () => {+ it('merges partial fields without clobbering existing fields', async () => {+ await calendarAccounts.createAccount({ name: 'My Cal', type: 'outlook-calendar', email: '[email protected]' });+ const updated = await calendarAccounts.updateAccount('test-uuid-1234', { name: 'Updated Cal' });++ expect(updated.name).toBe('Updated Cal');+ expect(updated.email).toBe('[email protected]'); // untouched+ expect(updated.type).toBe('outlook-calendar'); // untouched+ });++ it('returns null for a missing id', async () => {+ const result = await calendarAccounts.updateAccount('no-such-id', { name: 'x' });+ expect(result).toBeNull();+ });+ });++ describe('deleteAccount', () => {+ it('removes the account and returns true', async () => {+ await calendarAccounts.createAccount({ name: 'Del Me', type: 'outlook-calendar' });+ const result = await calendarAccounts.deleteAccount('test-uuid-1234');+ expect(result).toBe(true);++ const list = await calendarAccounts.listAccounts();+ expect(list).toHaveLength(0);+ });++ it('returns false for a missing id', async () => {+ const result = await calendarAccounts.deleteAccount('ghost-id');+ expect(result).toBe(false);+ });+ });++ describe('updateSyncStatus', () => {+ it('stamps lastSyncAt and lastSyncStatus', async () => {+ await calendarAccounts.createAccount({ name: 'Sync Test', type: 'outlook-calendar' });+ const result = await calendarAccounts.updateSyncStatus('test-uuid-1234', 'success');++ expect(result.lastSyncStatus).toBe('success');+ expect(result.lastSyncAt).toBeTruthy();+ });++ it('returns null for an absent account id', async () => {+ const result = await calendarAccounts.updateSyncStatus('absent-id', 'ok');+ expect(result).toBeNull();+ });+ });+});diff --git a/server/services/catalogIngestSources.js b/server/services/catalogIngestSources.jsindex 978a16d0aa..9d21f075f8 100644--- a/server/services/catalogIngestSources.js+++ b/server/services/catalogIngestSources.js@@ -30,7 +30,7 @@ import {evaluateOnPage,} from './browserService.js';import { lookup } from 'dns/promises';-import { PATHS, ensureDir } from '../lib/fileUtils.js';+import { PATHS, ensureDir, sleep } from '../lib/fileUtils.js';import { isSafeIngestUrl, isBlockedIngestHost } from '../lib/catalogValidation.js';// Cap fetched/transcribed bodies at the scrap column boundary (the Zod@@ -44,7 +44,6 @@ const PAGE_SETTLE_MS = 2_500;const clampText = (s) => (typeof s === 'string' ? s.slice(0, RAW_TEXT_MAX) : '');-const sleep = (ms) => new Promise((r) => setTimeout(r, ms));/*** Shared tail for every source: create a typed scrap and run the SAMEdiff --git a/server/services/catalogIngestSources.test.js b/server/services/catalogIngestSources.test.jsindex fb0eb917a6..1c62e54708 100644--- a/server/services/catalogIngestSources.test.js+++ b/server/services/catalogIngestSources.test.js@@ -38,6 +38,7 @@ vi.mock('dns/promises', () => ({vi.mock('../lib/fileUtils.js', () => ({PATHS: { audio: '/tmp/data/audio' },ensureDir: vi.fn(),+ sleep: vi.fn(() => Promise.resolve()),}));const catalogDB = await import('./catalogDB.js');diff --git a/server/services/cosReports.js b/server/services/cosReports.jsindex 5efcb9c754..40434d577b 100644--- a/server/services/cosReports.js+++ b/server/services/cosReports.js@@ -5,12 +5,12 @@* Handles daily reports, briefings, activity summaries, and recent tasks.*/-import { readFile, writeFile, readdir } from 'fs/promises';+import { readFile, readdir } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { loadState, ensureDirectories, REPORTS_DIR, isDaemonRunning } from './cosState.js';import { getAgentsByDate } from './cosAgents.js';-import { formatDuration, safeJSONParse } from '../lib/fileUtils.js';+import { formatDuration, safeJSONParse, atomicWrite } from '../lib/fileUtils.js';// A completed agent's work duration in ms: prefer the recorded `result.duration`,// else derive from completedAt − startedAt. Clamped to >=0 so a clock-skewed@@ -53,7 +53,7 @@ export async function generateReport(date = null) {// Save reportconst reportFile = join(REPORTS_DIR, `${reportDate}.json`);- await writeFile(reportFile, JSON.stringify(report, null, 2));+ await atomicWrite(reportFile, report);return report;}diff --git a/server/services/creativeDirector/stitchRunner.js b/server/services/creativeDirector/stitchRunner.jsindex 1f3c665ec8..21eafcaf29 100644--- a/server/services/creativeDirector/stitchRunner.js+++ b/server/services/creativeDirector/stitchRunner.js@@ -26,7 +26,7 @@ import { getProject, updateProject } from './local.js';import { getIssue, sanitizeAudioMode } from '../pipeline/issues.js';import { muxMusicBed, muxVoLines, muxCueBed, muxStripAudio, resolveMusicTrackPath, selectPlacedVoLines, selectPlacedCues } from '../pipeline/audioMux.js';import { placeCuesOnTimeline } from '../pipeline/audioCuePlacement.js';-import { PATHS } from '../../lib/fileUtils.js';+import { PATHS, sleep } from '../../lib/fileUtils.js';import { probeVideoDuration } from '../../lib/ffmpeg.js';const FINAL_RENDER_POLL_MS = 3000;@@ -131,10 +131,6 @@ export async function runStitch(projectId) {}}-function sleep(ms) {- return new Promise((r) => setTimeout(r, ms));-}-async function maybeMuxPipelineAudio(project, finalEntry) {if (!project?.sourceIssueId) return;const issue = await getIssue(project.sourceIssueId).catch(() => null);diff --git a/server/services/digital-twin-meta.js b/server/services/digital-twin-meta.jsindex 6f3e556c36..23d9377340 100644--- a/server/services/digital-twin-meta.js+++ b/server/services/digital-twin-meta.js@@ -1,9 +1,9 @@-import { readFile, writeFile, readdir } from 'fs/promises';+import { readFile, readdir } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import EventEmitter from 'events';import { digitalTwinMetaSchema } from '../lib/digitalTwinValidation.js';-import { safeJSONParse } from '../lib/fileUtils.js';+import { safeJSONParse, atomicWrite } from '../lib/fileUtils.js';import { DIGITAL_TWIN_DIR, generateId, ensureSoulDir } from './digital-twin-helpers.js';export const META_FILE = join(DIGITAL_TWIN_DIR, 'meta.json');@@ -152,7 +152,7 @@ function getPriorityForFile(filename) {export async function saveMeta(meta) {await ensureSoulDir();- await writeFile(META_FILE, JSON.stringify(meta, null, 2));+ await atomicWrite(META_FILE, meta);cache.meta.data = meta;cache.meta.timestamp = Date.now();digitalTwinEvents.emit('meta:changed', meta);diff --git a/server/services/digital-twin.test.js b/server/services/digital-twin.test.jsindex 258b31f2b1..15854868ec 100644--- a/server/services/digital-twin.test.js+++ b/server/services/digital-twin.test.js@@ -42,6 +42,7 @@ vi.mock('../lib/digitalTwinValidation.js', () => ({vi.mock('../lib/fileUtils.js', () => ({tryReadFile: vi.fn().mockResolvedValue(null),ensureDir: vi.fn(),+ atomicWrite: vi.fn(),safeJSONParse: vi.fn((str, defaultValue) => {if (!str || !str.trim()) return defaultValue;const parsed = JSON.parse(str);@@ -85,7 +86,7 @@ import { readFile, writeFile, unlink, readdir, mkdir, stat } from 'fs/promises';import { existsSync } from 'fs';import { getProviderById, getActiveProvider } from './providers.js';import { buildPrompt } from './promptService.js';-import { safeJSONParse } from '../lib/fileUtils.js';+import { safeJSONParse, atomicWrite } from '../lib/fileUtils.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';import {@@ -190,8 +191,9 @@ const setupMetaFile = async (meta) => {});// Prime the module's in-memory cache so loadMeta returns our test dataawait saveMeta(meta);- // Clear writeFile calls from the saveMeta priming+ // Clear write calls from the saveMeta primingwriteFile.mockClear();+ atomicWrite.mockClear();};// ============================================================================@@ -207,6 +209,7 @@ describe('digital-twin.js', () => {existsSync.mockReturnValue(true);mkdir.mockResolvedValue(undefined);writeFile.mockResolvedValue(undefined);+ atomicWrite.mockResolvedValue(undefined);unlink.mockResolvedValue(undefined);readdir.mockResolvedValue([]);stat.mockResolvedValue({ mtime: new Date('2025-01-01'), size: 1024 });@@ -303,8 +306,8 @@ describe('digital-twin.js', () => {await saveMeta(meta);- expect(writeFile).toHaveBeenCalledTimes(1);- const writtenJSON = JSON.parse(writeFile.mock.calls[0][1]);+ expect(atomicWrite).toHaveBeenCalledTimes(1);+ const writtenJSON = atomicWrite.mock.calls[0][1];expect(writtenJSON.version).toBe('1.0.0');expect(emitSpy).toHaveBeenCalledWith('meta:changed', meta);emitSpy.mockRestore();@@ -418,8 +421,9 @@ describe('digital-twin.js', () => {expect(result.filename).toBe('NEW_DOC.md');expect(result.id).toBe('test-uuid-1');expect(result.content).toBe('# New Doc\n\nContent here.');- // writeFile called for: the document file + meta save- expect(writeFile).toHaveBeenCalledTimes(2);+ // writeFile for the document file; atomicWrite for the meta save+ expect(writeFile).toHaveBeenCalledTimes(1);+ expect(atomicWrite).toHaveBeenCalledTimes(1);});it('should throw if document already exists', async () => {@@ -491,7 +495,7 @@ describe('digital-twin.js', () => {await updateDocument('doc-1', { priority: 5 });// The saveMeta call should have sorted docs- const savedMeta = JSON.parse(writeFile.mock.calls[0][1]);+ const savedMeta = atomicWrite.mock.calls[0][1];expect(savedMeta.documents[0].id).toBe('doc-1');});});@@ -1127,9 +1131,9 @@ Forgets the budget and recommends lodging that exceeds it.});// Check that saveMeta was called with completedCategories including core_memories- const savedJSON = writeFile.mock.calls.find(c => c[0].includes('meta.json'));- expect(savedJSON).toBeTruthy();- const savedMeta = JSON.parse(savedJSON[1]);+ const savedCall = atomicWrite.mock.calls.find(c => c[0].includes('meta.json'));+ expect(savedCall).toBeTruthy();+ const savedMeta = savedCall[1];expect(savedMeta.enrichment.completedCategories).toContain('core_memories');});});@@ -1211,8 +1215,8 @@ Forgets the budget and recommends lodging that exceeds it.expect(result.category).toBe('favorite_books');expect(result.itemCount).toBe(2);- const savedJSON = writeFile.mock.calls.find(c => c[0].includes('meta.json'));- const savedMeta = JSON.parse(savedJSON[1]);+ const savedCall = atomicWrite.mock.calls.find(c => c[0].includes('meta.json'));+ const savedMeta = savedCall[1];expect(savedMeta.enrichment.completedCategories).toContain('favorite_books');expect(savedMeta.enrichment.listItems.favorite_books).toEqual(items);});@@ -1274,6 +1278,7 @@ Forgets the budget and recommends lodging that exceeds it.});await saveMeta(meta);writeFile.mockClear();+ atomicWrite.mockClear();readFile.mockImplementation(async (filePath) => {if (filePath.includes('meta.json')) return JSON.stringify(meta);if (filePath.includes('SOUL.md')) return '# Soul\n\nIdentity doc.';diff --git a/server/services/googleOAuthAutoConfig.js b/server/services/googleOAuthAutoConfig.jsindex 5468432179..0541d42335 100644--- a/server/services/googleOAuthAutoConfig.js+++ b/server/services/googleOAuthAutoConfig.js@@ -18,10 +18,7 @@import { findOrOpenPage, evaluateOnPage, getPages } from './messagePlaywrightSync.js';import { navigateToUrl } from './browserService.js';import { saveCredentials, getAuthUrl, OAUTH_REDIRECT_URI } from './googleAuth.js';--function sleep(ms) {- return new Promise(resolve => setTimeout(resolve, ms));-}+import { sleep } from '../lib/fileUtils.js';async function getGcpPage() {const pages = await getPages();diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 1eb4f5d4c8..fb360ebe0c 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -32,7 +32,7 @@ import { EventEmitter } from 'events';import { randomUUID } from 'crypto';import { unlink } from 'fs/promises';import { join, resolve as pathResolve, sep as PATH_SEP } from 'path';-import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';+import { PATHS, readJSONFile, atomicWrite, ensureDir, sleep } from '../../lib/fileUtils.js';import {broadcastSse,attachSseClient as attachSse,@@ -962,10 +962,6 @@ export function attachSseClient(jobId, res) {return true;}-function sleep(ms) {- return new Promise((resolve) => setTimeout(resolve, ms));-}-// Test-only reset hook. Real callers go through enqueueJob/cancelJob.export function __resetForTests() {queue.length = 0;diff --git a/server/services/memory.test.js b/server/services/memory.test.jsindex 8e5abfc4be..d1fcd203ac 100644--- a/server/services/memory.test.js+++ b/server/services/memory.test.js@@ -3,7 +3,6 @@ import EventEmitter from 'events';// Mock fs/promisesvi.mock('fs/promises', () => ({- writeFile: vi.fn().mockResolvedValue(undefined),readdir: vi.fn().mockResolvedValue([]),rm: vi.fn().mockResolvedValue(undefined)}));@@ -37,10 +36,11 @@ vi.mock('./notifications.js', () => ({// Mock fileUtilsvi.mock('../lib/fileUtils.js', () => ({-tryReadFile: vi.fn().mockResolvedValue(null),+ tryReadFile: vi.fn().mockResolvedValue(null),ensureDir: vi.fn(),ensureDirs: vi.fn(),readJSONFile: vi.fn(),+ atomicWrite: vi.fn().mockResolvedValue(undefined),PATHS: { memory: '/tmp/test/memory' }}));@@ -73,9 +73,9 @@ vi.mock('./memoryConfig.js', () => ({decrementAgentPendingApproval: vi.fn().mockResolvedValue(undefined)}));-import { writeFile, rm } from 'fs/promises';+import { rm } from 'fs/promises';import { existsSync } from 'fs';-import { ensureDir, ensureDirs, readJSONFile } from '../lib/fileUtils.js';+import { ensureDir, ensureDirs, readJSONFile, atomicWrite } from '../lib/fileUtils.js';import * as memoryBM25 from './memoryBM25.js';import * as notifications from './notifications.js';import { findTopK, findAboveThreshold, clusterBySimilarity } from '../lib/vectorMath.js';@@ -199,7 +199,7 @@ describe('memory service', () => {expect(result.embedding).toEqual([0.1, 0.2, 0.3]);expect(result.embeddingModel).toBe('test-embedding-model');// Should save embeddings file- const embeddingsCall = writeFile.mock.calls.find(c => c[0].includes('embeddings.json'));+ const embeddingsCall = atomicWrite.mock.calls.find(c => c[0].includes('embeddings.json'));expect(embeddingsCall).toBeDefined();});@@ -207,7 +207,7 @@ describe('memory service', () => {const data = { type: 'fact', content: 'no embedding' };await createMemory(data);- const embeddingsCall = writeFile.mock.calls.find(c => c[0].includes('embeddings.json'));+ const embeddingsCall = atomicWrite.mock.calls.find(c => c[0].includes('embeddings.json'));expect(embeddingsCall).toBeUndefined();});@@ -215,12 +215,12 @@ describe('memory service', () => {const data = { type: 'learning', content: 'Learned something' };await createMemory(data);- // writeFile is called for saving memory and saving index- const indexCall = writeFile.mock.calls.find(call =>+ // atomicWrite is called for saving memory and saving index+ const indexCall = atomicWrite.mock.calls.find(call =>call[0].includes('index.json'));expect(indexCall).toBeDefined();- const savedIndex = JSON.parse(indexCall[1]);+ const savedIndex = indexCall[1];expect(savedIndex.count).toBe(1);expect(savedIndex.memories).toHaveLength(1);expect(savedIndex.memories[0].id).toBe('test-uuid-1234');@@ -618,9 +618,9 @@ describe('memory service', () => {expect(result).toEqual({ success: true, id: 'mem-1' });expect(rm).not.toHaveBeenCalled();// The memory should have been saved with archived status- const memorySaveCall = writeFile.mock.calls.find(c => c[0].includes('memory.json'));+ const memorySaveCall = atomicWrite.mock.calls.find(c => c[0].includes('memory.json'));expect(memorySaveCall).toBeDefined();- const savedMemory = JSON.parse(memorySaveCall[1]);+ const savedMemory = memorySaveCall[1];expect(savedMemory.status).toBe('archived');});@@ -1388,7 +1388,7 @@ describe('memory service', () => {expect(result.sourceId).toBe('src');expect(result.targetId).toBe('tgt');// Both memories should be saved with the link- const memorySaves = writeFile.mock.calls.filter(c => c[0].includes('memory.json'));+ const memorySaves = atomicWrite.mock.calls.filter(c => c[0].includes('memory.json'));expect(memorySaves.length).toBe(2);});@@ -1416,9 +1416,9 @@ describe('memory service', () => {await linkMemories('src', 'tgt');// Should not add duplicate - memories saved but relatedMemories should still be length 1- const memorySaves = writeFile.mock.calls.filter(c => c[0].includes('memory.json'));+ const memorySaves = atomicWrite.mock.calls.filter(c => c[0].includes('memory.json'));for (const save of memorySaves) {- const saved = JSON.parse(save[1]);+ const saved = save[1];expect(saved.relatedMemories).toHaveLength(1);}});diff --git a/server/services/memoryStore.js b/server/services/memoryStore.jsindex b88491c6b8..2480b6159d 100644--- a/server/services/memoryStore.js+++ b/server/services/memoryStore.js@@ -8,10 +8,10 @@* CRUD/search logic and events on top of these primitives.*/-import { writeFile, rm } from 'fs/promises';+import { rm } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';-import { ensureDir, ensureDirs, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { ensureDir, ensureDirs, readJSONFile, atomicWrite, PATHS } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';const MEMORY_DIR = PATHS.memory;@@ -53,7 +53,7 @@ export async function saveIndex(index) {await ensureDirectories();index.lastUpdated = new Date().toISOString();indexCache = index;- await writeFile(INDEX_FILE, JSON.stringify(index, null, 2));+ await atomicWrite(INDEX_FILE, index);}/**@@ -75,7 +75,9 @@ export async function loadEmbeddings() {export async function saveEmbeddings(embeddings) {await ensureDirectories();embeddingsCache = embeddings;- await writeFile(EMBEDDINGS_FILE, JSON.stringify(embeddings));+ // Pre-stringify compactly: atomicWrite pretty-prints plain objects, which+ // would inflate the largest file in the memory store on every save.+ await atomicWrite(EMBEDDINGS_FILE, JSON.stringify(embeddings));}/**@@ -91,10 +93,8 @@ export async function loadMemory(id) {*/export async function saveMemory(memory) {const memoryDir = join(MEMORIES_DIR, memory.id);- if (!existsSync(memoryDir)) {- await ensureDir(memoryDir);- }- await writeFile(join(memoryDir, 'memory.json'), JSON.stringify(memory, null, 2));+ await ensureDir(memoryDir);+ await atomicWrite(join(memoryDir, 'memory.json'), memory);}/**diff --git a/server/services/memoryStore.test.js b/server/services/memoryStore.test.jsnew file mode 100644index 0000000000..7ea910adfb--- /dev/null+++ b/server/services/memoryStore.test.js@@ -0,0 +1,187 @@+/**+ * memoryStore.test.js+ *+ * Tests for the persistence + cache layer of the file-backed memory service.+ * Covers: cache invalidation, atomicWrite (verified via real-file round-trips),+ * and deleteMemoryFiles path.+ *+ * memoryStore does NOT call createUniverse/createSeries and does not import+ * peerSync or instances, so mockNoPeers / mockNoPeerSync are not needed.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'memorystore-test-'));++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), {+ dataRoot: TEST_DATA_ROOT,+ extraOverrides: (root) => ({+ cos: join(root, 'cos'),+ memory: join(root, 'cos', 'memory'),+ }),+ }));++// Pass-through mutex: no locking overhead in tests+vi.mock('../lib/asyncMutex.js', () => ({+ createMutex: () => (fn) => fn(),+}));++afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++// Dynamically import AFTER mocks are hoisted so the module reads the mocked PATHS+const {+ loadIndex, saveIndex,+ loadEmbeddings, saveEmbeddings,+ loadMemory, saveMemory,+ deleteMemoryFiles,+ invalidateCaches,+} = await import('./memoryStore.js');++describe('memoryStore', () => {+ beforeEach(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ mkdirSync(join(TEST_DATA_ROOT, 'cos', 'memory', 'memories'), { recursive: true });+ invalidateCaches();+ });++ // ---------------------------------------------------------------------------+ // loadIndex + cache+ // ---------------------------------------------------------------------------+ describe('loadIndex', () => {+ it('returns a default index when no file exists', async () => {+ const idx = await loadIndex();+ expect(idx.version).toBe(1);+ expect(idx.count).toBe(0);+ expect(Array.isArray(idx.memories)).toBe(true);+ });++ it('caches the index on second call (same reference returned)', async () => {+ const first = await loadIndex();+ const second = await loadIndex();+ expect(first).toBe(second); // cache hit — same object+ });++ it('reloads from disk after invalidateCaches()', async () => {+ const idx = { version: 1, lastUpdated: '', count: 3, memories: [] };+ await saveIndex(idx);+ // cache is warm; force reload+ invalidateCaches();+ const loaded = await loadIndex();+ expect(loaded.count).toBe(3);+ });+ });++ // ---------------------------------------------------------------------------+ // saveIndex — atomicWrite verified via round-trip+ // ---------------------------------------------------------------------------+ describe('saveIndex', () => {+ it('persists via atomicWrite: reload after invalidate returns the saved data', async () => {+ const idx = { version: 1, lastUpdated: '', count: 0, memories: [] };+ await saveIndex(idx);+ // lastUpdated should have been stamped+ expect(idx.lastUpdated).not.toBe('');++ invalidateCaches();+ const loaded = await loadIndex();+ expect(loaded.count).toBe(0);+ expect(loaded.lastUpdated).toBeTruthy();+ });++ it('round-trips multi-entry index', async () => {+ const idx = {+ version: 1, lastUpdated: '',+ count: 2,+ memories: [{ id: 'a', type: 'fact' }, { id: 'b', type: 'learning' }]+ };+ await saveIndex(idx);+ invalidateCaches();+ const loaded = await loadIndex();+ expect(loaded.count).toBe(2);+ expect(loaded.memories).toHaveLength(2);+ expect(loaded.memories[0].id).toBe('a');+ });+ });++ // ---------------------------------------------------------------------------+ // loadEmbeddings + saveEmbeddings+ // ---------------------------------------------------------------------------+ describe('loadEmbeddings', () => {+ it('returns empty defaults when file is absent', async () => {+ const e = await loadEmbeddings();+ expect(e.model).toBeNull();+ expect(e.dimension).toBe(0);+ expect(e.vectors).toEqual({});+ });++ it('caches embeddings on subsequent loads', async () => {+ const e1 = await loadEmbeddings();+ const e2 = await loadEmbeddings();+ expect(e1).toBe(e2);+ });+ });++ describe('saveEmbeddings', () => {+ it('persists embeddings so they reload after cache invalidation', async () => {+ const emb = { model: 'test-model', dimension: 3, vectors: { 'mem-1': [0.1, 0.2, 0.3] } };+ await saveEmbeddings(emb);+ invalidateCaches();+ const loaded = await loadEmbeddings();+ expect(loaded.model).toBe('test-model');+ expect(loaded.vectors['mem-1']).toEqual([0.1, 0.2, 0.3]);+ });+ });++ // ---------------------------------------------------------------------------+ // saveMemory + loadMemory+ // ---------------------------------------------------------------------------+ describe('saveMemory / loadMemory', () => {+ it('persists and reloads a memory record via the per-id path', async () => {+ const mem = { id: 'mem-42', content: 'hello', status: 'active' };+ await saveMemory(mem);++ const loaded = await loadMemory('mem-42');+ expect(loaded.id).toBe('mem-42');+ expect(loaded.content).toBe('hello');+ expect(loaded.status).toBe('active');+ });++ it('creates the per-id directory under memories/', async () => {+ const mem = { id: 'mem-dir-test', content: 'dir check' };+ await saveMemory(mem);+ const memDir = join(TEST_DATA_ROOT, 'cos', 'memory', 'memories', 'mem-dir-test');+ expect(existsSync(memDir)).toBe(true);+ });++ it('returns null for a memory that does not exist', async () => {+ const result = await loadMemory('no-such-id');+ expect(result).toBeNull();+ });+ });++ // ---------------------------------------------------------------------------+ // deleteMemoryFiles+ // ---------------------------------------------------------------------------+ describe('deleteMemoryFiles', () => {+ it('removes the memory directory when it exists', async () => {+ const mem = { id: 'del-me', content: 'bye' };+ await saveMemory(mem);++ const before = await loadMemory('del-me');+ expect(before).not.toBeNull();++ await deleteMemoryFiles('del-me');++ const after = await loadMemory('del-me');+ expect(after).toBeNull();+ });++ it('is a no-op for a non-existent id (does not throw)', async () => {+ await expect(deleteMemoryFiles('ghost-id')).resolves.not.toThrow();+ });+ });+});diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.jsindex 87e31ec0d0..2b58f68608 100644--- a/server/services/messageAccounts.js+++ b/server/services/messageAccounts.js@@ -1,7 +1,6 @@-import { writeFile } from 'fs/promises';import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';-import { ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { ensureDir, PATHS, safeJSONParse, tryReadFile, atomicWrite } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';const ACCOUNTS_FILE = join(PATHS.messages, 'accounts.json');@@ -16,7 +15,7 @@ async function loadAccounts() {async function saveAccounts(accounts) {await ensureDir(PATHS.messages);- await writeFile(ACCOUNTS_FILE, JSON.stringify(accounts, null, 2));+ await atomicWrite(ACCOUNTS_FILE, accounts);}export async function listAccounts() {diff --git a/server/services/messageAccounts.test.js b/server/services/messageAccounts.test.jsnew file mode 100644index 0000000000..cff0ccf58d--- /dev/null+++ b/server/services/messageAccounts.test.js@@ -0,0 +1,107 @@+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'message-accounts-test-'));++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), {+ dataRoot: TEST_DATA_ROOT,+ extraOverrides: (root) => ({ messages: join(root, 'messages') }),+ }));++vi.mock('../lib/uuid.js', () => ({+ v4: vi.fn().mockReturnValue('msg-uuid-5678'),+}));++const messageAccounts = await import('./messageAccounts.js');++afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++describe('messageAccounts', () => {+ beforeEach(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ mkdirSync(TEST_DATA_ROOT, { recursive: true });+ });++ describe('createAccount', () => {+ it('creates a gmail account with correct defaults', async () => {+ const acc = await messageAccounts.createAccount({+ name: 'Gmail Work',+ type: 'gmail',+ email: '[email protected]',+ });++ expect(acc.id).toBe('msg-uuid-5678');+ expect(acc.name).toBe('Gmail Work');+ expect(acc.type).toBe('gmail');+ expect(acc.provider).toBe('api');+ expect(acc.email).toBe('[email protected]');+ expect(acc.enabled).toBe(true);+ expect(acc.lastSyncAt).toBeNull();+ expect(acc.lastSyncStatus).toBeNull();+ expect(acc.createdAt).toBeTruthy();+ expect(acc.syncConfig.maxAge).toBe('30d');+ expect(acc.syncConfig.maxMessages).toBe(500);+ expect(acc.syncConfig.syncInterval).toBe(300000);+ });++ it('sets provider to playwright for non-gmail types', async () => {+ const acc = await messageAccounts.createAccount({ name: 'Outlook', type: 'outlook' });+ expect(acc.provider).toBe('playwright');+ });++ it('defaults email to empty string when omitted', async () => {+ const acc = await messageAccounts.createAccount({ name: 'No Email', type: 'gmail' });+ expect(acc.email).toBe('');+ });+ });++ describe('updateAccount', () => {+ it('merges partial updates without overwriting untouched fields', async () => {+ await messageAccounts.createAccount({ name: 'Old Name', type: 'gmail', email: '[email protected]' });+ const updated = await messageAccounts.updateAccount('msg-uuid-5678', { name: 'New Name' });++ expect(updated.name).toBe('New Name');+ expect(updated.email).toBe('[email protected]'); // untouched+ });++ it('returns null for a missing id', async () => {+ const result = await messageAccounts.updateAccount('no-such-id', { name: 'x' });+ expect(result).toBeNull();+ });+ });++ describe('deleteAccount', () => {+ it('removes the account and returns true', async () => {+ await messageAccounts.createAccount({ name: 'Delete Me', type: 'gmail' });+ const result = await messageAccounts.deleteAccount('msg-uuid-5678');+ expect(result).toBe(true);++ const list = await messageAccounts.listAccounts();+ expect(list).toHaveLength(0);+ });++ it('returns false for a missing id', async () => {+ const result = await messageAccounts.deleteAccount('ghost');+ expect(result).toBe(false);+ });+ });++ describe('updateSyncStatus', () => {+ it('stamps lastSyncAt and lastSyncStatus', async () => {+ await messageAccounts.createAccount({ name: 'Sync Me', type: 'gmail' });+ const result = await messageAccounts.updateSyncStatus('msg-uuid-5678', 'ok');++ expect(result.lastSyncStatus).toBe('ok');+ expect(result.lastSyncAt).toBeTruthy();+ });++ it('returns null for an absent id', async () => {+ const result = await messageAccounts.updateSyncStatus('absent-id', 'fail');+ expect(result).toBeNull();+ });+ });+});diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.jsindex 475235b919..ed12494e2c 100644--- a/server/services/messagePlaywrightSync.js+++ b/server/services/messagePlaywrightSync.js@@ -1,8 +1,7 @@-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, tryReadFile } from '../lib/fileUtils.js';+import { ensureDir, PATHS, safeJSONParse, tryReadFile, atomicWrite } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';import { findOrOpenPage, listCdpPages, isAuthPage, evaluateOnPage } from './browserService.js';@@ -34,7 +33,7 @@ export async function updateSelectors(provider, selectors) {const all = await getSelectors();all[provider] = selectors;await ensureDir(PATHS.messages);- await writeFile(SELECTORS_FILE, JSON.stringify(all, null, 2));+ await atomicWrite(SELECTORS_FILE, all);return all[provider];}diff --git a/server/services/productivity.js b/server/services/productivity.jsindex 145ad933da..b67d534cbb 100644--- a/server/services/productivity.js+++ b/server/services/productivity.js@@ -5,11 +5,10 @@* insights about optimal working times.*/-import { writeFile } from 'fs/promises';import { join } from 'path';import { cosEvents } from './cosEvents.js';import { getAgents } from './cosAgents.js';-import { ensureDir, getDateString, PATHS, readJSONFile } from '../lib/fileUtils.js';+import { ensureDir, getDateString, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';const DATA_DIR = PATHS.cos;const PRODUCTIVITY_FILE = join(DATA_DIR, 'productivity.json');@@ -61,7 +60,7 @@ export async function loadProductivity() {async function saveProductivity(data) {await ensureDir(DATA_DIR);data.lastUpdated = new Date().toISOString();- await writeFile(PRODUCTIVITY_FILE, JSON.stringify(data, null, 2));+ await atomicWrite(PRODUCTIVITY_FILE, data);return data;}