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
fix: macOS memory usage no longer counts file cache as used (was reading 98% on every box)
Adam Eivyd846ad978de5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 68642a1809..a480f1067b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -12,6 +12,8 @@- **Review Hub: only had a "Mark All Read" (dismiss) bulk action.** Added a green "Complete All" button next to the renamed "Dismiss All" so the user can clear a queue of finished items as completed (correct status for things that were actually done) instead of dismissing them (which means "ignored"). File: `client/src/pages/Review.jsx`.+- **System Health: "High memory usage" alert fired on every box because `os.freemem()` doesn't mean "free" on macOS.** `server/routes/systemHealth.js` and `server/services/proactiveAlerts.js` both calculated memory pressure as `(os.totalmem() - os.freemem()) / os.totalmem()`. On macOS, `os.freemem()` returns *only* `Pages free` from the vm_stat sense — it counts the file cache (inactive + speculative + purgeable + cached file-backed pages, often 8–10 GB) as "used" even though the kernel will reclaim those instantly under pressure. So a healthy 48 GB Mac with Activity Monitor reading ~38 GB / 81% used would surface in PortOS as 47 GB / 98% used and trigger the critical "Memory usage above 90%" alert. New `server/lib/memoryStats.js` helper parses `vm_stat` on macOS and computes `used = (anonymous_pages - purgeable + wired + compressor_occupied) × pageSize`, which matches Activity Monitor's "Memory Used" figure (within a percent or two of natural drift). Linux uses `MemAvailable` from `/proc/meminfo`; other platforms fall back to the previous `os.totalmem - os.freemem`. Wired into both the `/api/system/health/details` endpoint (powering the CyberCity HUD's CPU/MEM/DISK card) and the proactive-alerts critical-memory check. 3 unit tests cover the macOS happy path, the over-count clamp, and the vm_stat-failure fallback. Files: `server/lib/memoryStats.js`, `server/lib/memoryStats.test.js`, `server/routes/systemHealth.js`, `server/services/proactiveAlerts.js`.+- **Review Hub: "Dismiss All" / "Complete All" only marked ~10 items per click.** The first cut of those buttons fanned N parallel `POST /api/review/items/:id/{dismiss,complete}` requests at the server. Each handler did its own `loadItems → mutate → atomicWrite(items)` cycle, so concurrent requests read overlapping snapshots of `data/review/items.json` and the last writer overwrote everyone else's status changes — the user had to keep clicking until every item settled. Added a single `POST /api/review/items/bulk-status` endpoint that does one read-modify-write for `{ status, ids? }` (omit `ids` to target every pending item), and switched the client to call it once instead of N times. Side-effect emits (`item:updated`) now fire after the save, not inside the mutation loop, so socket clients can't observe state ahead of disk. Files: `server/services/review.js`, `server/routes/review.js`, `server/services/review.test.js`, `client/src/services/apiReview.js`, `client/src/pages/Review.jsx`.- **Flux i2i: portrait iPhone photos came out rotated 90°.** Modern browsers honor the EXIF Orientation tag when rendering `<img>`, so the upload thumbnail looked right — but mflux/PIL reads raw pixel data and ignores EXIF, so a portrait iPhone photo (Orientation=6 or 8) landed sideways in the generated output. The init image picker now passes the file through `createImageBitmap({ imageOrientation: 'from-image' })` and re-encodes via canvas before upload, baking the rotation into the actual pixels and stripping the EXIF tag. Any image decoder downstream now sees the same orientation the browser displayed. File: `client/src/pages/ImageGen.jsx`.diff --git a/server/lib/memoryStats.js b/server/lib/memoryStats.jsnew file mode 100644index 0000000000..3720208407--- /dev/null+++ b/server/lib/memoryStats.js@@ -0,0 +1,69 @@+import os from 'os';+import { exec } from 'child_process';+import { promisify } from 'util';+import { readFile } from 'fs/promises';++const execAsync = promisify(exec);++// `os.freemem()` on macOS returns only "Pages free" — it counts the file+// cache, inactive, and purgeable pages as used, even though the OS will+// reclaim them under pressure. That's why naive (totalmem - freemem) reads+// 47 GB used on a 48 GB box that Activity Monitor says is at 38 GB.+//+// This helper parses the host's authoritative numbers and returns a stat+// shape that matches the "Memory Used" figure Activity Monitor / `top`+// (and macOS's own pressure indicator) display.++function fallback() {+ const total = os.totalmem();+ const free = os.freemem();+ return { total, used: total - free, free, source: 'os' };+}++async function macMemory() {+ const { stdout } = await execAsync('vm_stat', { windowsHide: true });+ const pageSizeMatch = stdout.match(/page size of (\d+) bytes/);+ const pageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : 16384;++ const pages = {};+ for (const line of stdout.split('\n')) {+ const m = line.match(/^([^:]+):\s+(\d+)\.?\s*$/);+ if (m) pages[m[1].trim()] = parseInt(m[2], 10);+ }++ const wired = pages['Pages wired down'] || 0;+ const compressorOccupied = pages['Pages occupied by compressor'] || 0;+ const anonymous = pages['Anonymous pages'] || 0;+ const purgeable = pages['Pages purgeable'] || 0;++ const appMemory = Math.max(0, anonymous - purgeable);+ const usedPages = appMemory + wired + compressorOccupied;++ const total = os.totalmem();+ const used = Math.min(total, usedPages * pageSize);+ return { total, used, free: total - used, source: 'vm_stat' };+}++async function linuxMemory() {+ const text = await readFile('/proc/meminfo', 'utf-8');+ const get = (key) => {+ const m = text.match(new RegExp(`^${key}:\\s+(\\d+)\\s+kB`, 'm'));+ return m ? parseInt(m[1], 10) * 1024 : 0;+ };+ const total = get('MemTotal');+ const available = get('MemAvailable')+ || (get('MemFree') + get('Buffers') + get('Cached'));+ if (total === 0) return fallback();+ const used = Math.max(0, total - available);+ 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());+ }+ return fallback();+}diff --git a/server/lib/memoryStats.test.js b/server/lib/memoryStats.test.jsnew file mode 100644index 0000000000..83b1db3b1c--- /dev/null+++ b/server/lib/memoryStats.test.js@@ -0,0 +1,74 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import os from 'os';++vi.mock('child_process', () => ({+ exec: vi.fn()+}));++vi.mock('fs/promises', () => ({+ readFile: vi.fn()+}));++const { exec } = await import('child_process');+const { readFile } = await import('fs/promises');+const { getMemoryStats } = await import('./memoryStats.js');++const mockExec = (stdout) => {+ exec.mockImplementation((_cmd, _opts, cb) => cb(null, { stdout, stderr: '' }));+};++describe('getMemoryStats', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('on macOS, returns "Memory Used" matching Activity Monitor (anonymous - purgeable + wired + compressor)', async () => {+ if (process.platform !== 'darwin') return;++ // Numbers chosen so the math is verifiable: with 16KB pages,+ // anonymous=1000, purgeable=100, wired=200, compressor_occupied=300 →+ // used = (1000 - 100 + 200 + 300) × 16KB = 1400 × 16384 = 22,937,600 bytes+ mockExec(`Mach Virtual Memory Statistics: (page size of 16384 bytes)+Pages free: 10.+Pages active: 500.+Pages inactive: 400.+Pages speculative: 50.+Pages wired down: 200.+Pages purgeable: 100.+Anonymous pages: 1000.+Pages occupied by compressor: 300.+`);++ const stats = await getMemoryStats();+ expect(stats.source).toBe('vm_stat');+ expect(stats.total).toBe(os.totalmem());+ expect(stats.used).toBe(1400 * 16384);+ expect(stats.free).toBe(stats.total - stats.used);+ });++ it('clamps used to total when vm_stat numbers add up to more than physical memory (compressor over-counts on swap-heavy systems)', async () => {+ if (process.platform !== 'darwin') return;++ // Force usedPages × pageSize > totalmem — should clamp.+ const huge = Math.ceil(os.totalmem() / 16384) + 1000;+ mockExec(`Mach Virtual Memory Statistics: (page size of 16384 bytes)+Pages wired down: ${huge}.+Anonymous pages: 0.+Pages purgeable: 0.+Pages occupied by compressor: 0.+`);++ const stats = await getMemoryStats();+ expect(stats.used).toBeLessThanOrEqual(stats.total);+ expect(stats.free).toBeGreaterThanOrEqual(0);+ });++ it('falls back to os.freemem when vm_stat fails on macOS', async () => {+ if (process.platform !== 'darwin') return;++ exec.mockImplementation((_cmd, _opts, cb) => cb(new Error('vm_stat not found')));+ const stats = await getMemoryStats();+ expect(stats.source).toBe('os');+ expect(stats.total).toBe(os.totalmem());+ });+});diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex c1f6e13733..3f866a01f0 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -8,6 +8,7 @@ import { getSelf } from '../services/instances.js';import { checkHealth } from '../lib/db.js';import { getCurrentVersion } from '../services/updateChecker.js';import { asyncHandler } from '../lib/errorHandler.js';+import { getMemoryStats } from '../lib/memoryStats.js';const router = Router();@@ -34,20 +35,21 @@ router.get('/health/details', asyncHandler(async (req, res) => {const startTime = Date.now();// Gather data in parallel- const [pm2Processes, allApps, cosStatus, self, dbHealth, version, diskStats] = await Promise.all([+ const [pm2Processes, allApps, cosStatus, self, dbHealth, version, diskStats, memStats] = await Promise.all([listProcesses().catch(() => []),apps.getAllApps({ includeArchived: false }).catch(() => []),cos.getStatus().catch(() => null),getSelf().catch(() => null),checkHealth().catch(() => ({ connected: false, hasSchema: false, error: 'Health check failed' })),getCurrentVersion().catch(() => null),- statfs('/').catch(() => null)+ statfs('/').catch(() => null),+ getMemoryStats()]);// System metrics- const totalMem = os.totalmem();- const freeMem = os.freemem();- const usedMem = totalMem - freeMem;+ const totalMem = memStats.total;+ const freeMem = memStats.free;+ const usedMem = memStats.used;const memUsagePercent = Math.round((usedMem / totalMem) * 100);const cpuLoad = os.loadavg()[0]; // 1-minute load averageconst cpuCount = os.cpus().length;diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.jsindex 332f339c4d..1e228cd5d9 100644--- a/server/services/proactiveAlerts.js+++ b/server/services/proactiveAlerts.js@@ -17,6 +17,7 @@ import { getGoals } from './identity.js';import { getPerformanceSummary, getLearningSummary } from './taskLearning.js';import { listProcesses } from './pm2.js';import { getUsage } from './usage.js';+import { getMemoryStats } from '../lib/memoryStats.js';const STALL_THRESHOLD_DAYS = 14;const SUCCESS_RATE_WARNING = 50;@@ -84,10 +85,11 @@ async function checkSuccessRates() {async function checkSystemHealth() {const alerts = [];- // Memory check- const totalMem = os.totalmem();- const freeMem = os.freemem();- const memPct = Math.round(((totalMem - freeMem) / totalMem) * 100);+ // 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);if (memPct >= MEMORY_WARNING_PCT) {const formatGB = (bytes) => `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;@@ -95,7 +97,7 @@ async function checkSystemHealth() {type: 'system_resource',severity: memPct >= MEMORY_CRITICAL_PCT ? 'critical' : 'high',title: 'High memory usage',- detail: `${memPct}% — ${formatGB(totalMem - freeMem)} / ${formatGB(totalMem)}`,+ detail: `${memPct}% — ${formatGB(memStats.used)} / ${formatGB(memStats.total)}`,link: '/apps',metadata: { resource: 'memory', percent: memPct }});