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: tighten memoryStats helper after /simplify review
Adam Eivy7de1c1e582c5
diff --git a/server/lib/memoryStats.js b/server/lib/memoryStats.jsindex 3720208407..d16a3b3f36 100644--- a/server/lib/memoryStats.js+++ b/server/lib/memoryStats.js@@ -14,6 +14,9 @@ const execAsync = promisify(exec);// shape that matches the "Memory Used" figure Activity Monitor / `top`// (and macOS's own pressure indicator) display.+const CACHE_TTL_MS = 3000;+let cached = null;+function fallback() {const total = os.totalmem();const free = os.freemem();@@ -21,7 +24,7 @@ function fallback() {}async function macMemory() {- const { stdout } = await execAsync('vm_stat', { windowsHide: true });+ const { stdout } = await execAsync('vm_stat', { windowsHide: true, timeout: 5000 });const pageSizeMatch = stdout.match(/page size of (\d+) bytes/);const pageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : 16384;@@ -58,12 +61,21 @@ async function linuxMemory() {return { total, used, free: available, source: 'meminfo' };}-export async function getMemoryStats() {- if (process.platform === 'darwin') {- return macMemory().catch(() => fallback());- }- if (process.platform === 'linux') {- return linuxMemory().catch(() => fallback());- }+async function probe() {+ if (process.platform === 'darwin') return macMemory().catch(() => fallback());+ if (process.platform === 'linux') return linuxMemory().catch(() => fallback());return fallback();}++export async function getMemoryStats() {+ const now = Date.now();+ if (cached && (now - cached.at) < CACHE_TTL_MS) return cached.stats;+ const stats = await probe();+ cached = { stats, at: now };+ return stats;+}++// Test hook — drop the cache so tests can swap mocked vm_stat output between cases.+export function _resetMemoryStatsCache() {+ cached = null;+}diff --git a/server/lib/memoryStats.test.js b/server/lib/memoryStats.test.jsindex 83b1db3b1c..993062db72 100644--- a/server/lib/memoryStats.test.js+++ b/server/lib/memoryStats.test.js@@ -11,7 +11,7 @@ vi.mock('fs/promises', () => ({const { exec } = await import('child_process');const { readFile } = await import('fs/promises');-const { getMemoryStats } = await import('./memoryStats.js');+const { getMemoryStats, _resetMemoryStatsCache } = await import('./memoryStats.js');const mockExec = (stdout) => {exec.mockImplementation((_cmd, _opts, cb) => cb(null, { stdout, stderr: '' }));@@ -20,6 +20,7 @@ const mockExec = (stdout) => {describe('getMemoryStats', () => {beforeEach(() => {vi.clearAllMocks();+ _resetMemoryStatsCache();});it('on macOS, returns "Memory Used" matching Activity Monitor (anonymous - purgeable + wired + compressor)', async () => {@@ -71,4 +72,20 @@ Pages occupied by compressor: 0.expect(stats.source).toBe('os');expect(stats.total).toBe(os.totalmem());});++ it('caches the result and skips the subprocess on rapid repeat calls', async () => {+ if (process.platform !== 'darwin') return;++ mockExec(`Mach Virtual Memory Statistics: (page size of 16384 bytes)+Pages wired down: 100.+Anonymous pages: 500.+Pages purgeable: 0.+Pages occupied by compressor: 50.+`);++ await getMemoryStats();+ await getMemoryStats();+ await getMemoryStats();+ expect(exec).toHaveBeenCalledTimes(1);+ });});diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex 3f866a01f0..0e4accf3d1 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -46,11 +46,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {getMemoryStats()]);- // System metrics- const totalMem = memStats.total;- const freeMem = memStats.free;- const usedMem = memStats.used;- const memUsagePercent = Math.round((usedMem / totalMem) * 100);+ const memUsagePercent = Math.round((memStats.used / memStats.total) * 100);const cpuLoad = os.loadavg()[0]; // 1-minute load averageconst cpuCount = os.cpus().length;const cpuUsagePercent = Math.round((cpuLoad / cpuCount) * 100);@@ -182,13 +178,13 @@ router.get('/health/details', asyncHandler(async (req, res) => {uptime,uptimeFormatted,memory: {- total: totalMem,- used: usedMem,- free: freeMem,+ total: memStats.total,+ used: memStats.used,+ free: memStats.free,usagePercent: memUsagePercent,- totalFormatted: formatBytes(totalMem),- usedFormatted: formatBytes(usedMem),- freeFormatted: formatBytes(freeMem)+ totalFormatted: formatBytes(memStats.total),+ usedFormatted: formatBytes(memStats.used),+ freeFormatted: formatBytes(memStats.free)},cpu: {cores: cpuCount,diff --git a/server/services/cos.js b/server/services/cos.jsindex 11f2f634b2..665005a218 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -34,6 +34,7 @@ import { recordDecision, DECISION_TYPES } from './decisionLog.js';import { isRecoveryTask } from './recoveryTasks.js';import { getUserTimezone, getLocalParts, nextLocalTime, todayInTimezone } from '../lib/timezone.js';import { PORTOS_UI_URL } from '../lib/ports.js';+import { getMemoryStats } from '../lib/memoryStats.js';// Shared state management (extracted to avoid circular deps)import { loadState, saveState, withStateLock, ensureDirectories, isImprovementEnabled, AGENTS_DIR, REPORTS_DIR, SCRIPTS_DIR, ROOT_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';@@ -2027,11 +2028,7 @@ export async function runHealthCheck() {});}- // Get system memory- const memCmd = process.platform === 'win32' ? 'wmic OS get FreePhysicalMemory,TotalVisibleMemorySize /VALUE' :- process.platform === 'darwin' ? 'vm_stat' : 'free -m';- const memResult = await execAsync(memCmd, { windowsHide: true }).catch(() => ({ stdout: '' }));- metrics.memory = { raw: memResult.stdout.slice(0, 500) }; // Truncate for storage+ metrics.memory = await getMemoryStats();// Store health check result with lock to prevent race conditionsawait withStateLock(async () => {diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.jsindex 1e228cd5d9..7539a6ff08 100644--- a/server/services/proactiveAlerts.js+++ b/server/services/proactiveAlerts.js@@ -85,9 +85,6 @@ async function checkSuccessRates() {async function checkSystemHealth() {const alerts = [];- // Memory check — uses getMemoryStats() so the percentage matches Activity- // Monitor's "Memory Used" instead of (totalmem - freemem), which on macOS- // counts the reclaimable file cache as used and reads ~98% on every box.const memStats = await getMemoryStats();const memPct = Math.round((memStats.used / memStats.total) * 100);