Skip to content

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

2.8 KB
Raw Blame
import os from 'os';
import { exec } from './childProcess.js';
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.

const CACHE_TTL_MS = 3000;
let cached = null;

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', { timeout: 5000 });
  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' };
}

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;
}