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

fix: stop flagging cumulative pm2 restarts as a health warning

Adam Eivy861fcf4d24fe
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a480f1067b..2bc2f46ea3 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: "N total restarts" warning treated developer-driven `pm2 restart`s as a problem.** `server/routes/systemHealth.js` was warning whenever `processStats.totalRestarts > 10`, summed from PM2's `restart_time` — a cumulative counter that increments equally for crash loops AND for routine `pm2 restart` calls during development/deploys. So a perfectly healthy PortOS instance with months of feature work would surface "97 total restarts" as a yellow warning forever. Switched the warning to PM2's `unstable_restarts`, which only ticks when a process exits inside its `min_uptime` window (i.e., a real crash loop). Exposed `unstableRestarts` from `pm2.js` `getProcessSummary` / `listProcesses`, added it (and a `crashingProcesses` name list) to the `processStats` payload, and rewrote the warning message to "N crash-loop restart(s) (proc-name)". Cumulative `totalRestarts` is still in the payload for telemetry but no longer drives the alert. Two regression tests: a 97-restart healthy process produces 0 warnings; a 3-unstable-restart process produces a "crash-loop" warning naming the process. Files: `server/services/pm2.js`, `server/routes/systemHealth.js`, `server/routes/health.test.js`.
+
- **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`.
diff --git a/server/routes/health.test.js b/server/routes/health.test.js
index 3090b27f56..3bee4b01e9 100644
--- a/server/routes/health.test.js
+++ b/server/routes/health.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, vi } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
import systemHealthRoutes from './systemHealth.js';
+import { listProcesses } from '../services/pm2.js';
vi.mock('../services/pm2.js', () => ({
listProcesses: vi.fn().mockResolvedValue([])
@@ -40,4 +41,24 @@ describe('System Health Routes', () => {
expect(response.body).toHaveProperty('apps');
expect(response.body).toHaveProperty('overallHealth');
});
+
+ it('does not warn on cumulative restart_time (developer-driven restarts)', async () => {
+ listProcesses.mockResolvedValueOnce([
+ { name: 'portos', status: 'online', restarts: 97, unstableRestarts: 0, cpu: 0, memory: 0 }
+ ]);
+ const response = await request(app).get('/api/system/health/details');
+ const restartWarnings = (response.body.warnings || []).filter(w => w.type === 'restarts');
+ expect(restartWarnings).toHaveLength(0);
+ });
+
+ it('warns when a process has unstable_restarts (real crash loop)', async () => {
+ listProcesses.mockResolvedValueOnce([
+ { name: 'flaky-svc', status: 'online', restarts: 5, unstableRestarts: 3, cpu: 0, memory: 0 }
+ ]);
+ const response = await request(app).get('/api/system/health/details');
+ const restartWarnings = (response.body.warnings || []).filter(w => w.type === 'restarts');
+ expect(restartWarnings).toHaveLength(1);
+ expect(restartWarnings[0].message).toContain('crash-loop');
+ expect(restartWarnings[0].message).toContain('flaky-svc');
+ });
});
diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.js
index 0e4accf3d1..dc374d0934 100644
--- a/server/routes/systemHealth.js
+++ b/server/routes/systemHealth.js
@@ -79,7 +79,12 @@ router.get('/health/details', asyncHandler(async (req, res) => {
errored: pm2Processes.filter(p => p.status === 'errored').length,
totalMemory: pm2Processes.reduce((sum, p) => sum + (p.memory || 0), 0),
totalCpu: pm2Processes.reduce((sum, p) => sum + (p.cpu || 0), 0),
- totalRestarts: pm2Processes.reduce((sum, p) => sum + (p.restarts || 0), 0)
+ totalRestarts: pm2Processes.reduce((sum, p) => sum + (p.restarts || 0), 0),
+ // unstable_restarts is incremented only when a process exits inside its
+ // min_uptime window — i.e., a real crash loop, not a developer-driven
+ // restart. We use this for the warning, not totalRestarts.
+ unstableRestarts: pm2Processes.reduce((sum, p) => sum + (p.unstableRestarts || 0), 0),
+ crashingProcesses: pm2Processes.filter(p => (p.unstableRestarts || 0) > 0).map(p => p.name)
};
// App status summary
@@ -122,9 +127,13 @@ router.get('/health/details', asyncHandler(async (req, res) => {
warnings.push({ type: 'process', message: `${processStats.errored} process(es) errored` });
}
- if (processStats.totalRestarts > 10) {
+ if (processStats.unstableRestarts > 0) {
if (overallHealth !== 'critical') overallHealth = 'warning';
- warnings.push({ type: 'restarts', message: `${processStats.totalRestarts} total restarts` });
+ const names = processStats.crashingProcesses.join(', ');
+ warnings.push({
+ type: 'restarts',
+ message: `${processStats.unstableRestarts} crash-loop restart${processStats.unstableRestarts === 1 ? '' : 's'}${names ? ` (${names})` : ''}`
+ });
}
if (!dbHealth.connected) {
diff --git a/server/services/pm2.js b/server/services/pm2.js
index 5dec4be356..9a2f73811c 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -248,6 +248,7 @@ export async function getAppStatus(name, pm2Home = null) {
memory: proc.monit?.memory || 0,
uptime: proc.pm2_env?.pm_uptime ? Date.now() - proc.pm2_env.pm_uptime : null,
restarts: proc.pm2_env?.restart_time || 0,
+ unstableRestarts: proc.pm2_env?.unstable_restarts || 0,
createdAt: proc.pm2_env?.created_at || null
};
}
@@ -339,7 +340,8 @@ export async function listProcesses(pm2Home = null) {
cpu: proc.monit?.cpu || 0,
memory: proc.monit?.memory || 0,
uptime: proc.pm2_env?.pm_uptime ? Date.now() - proc.pm2_env.pm_uptime : null,
- restarts: proc.pm2_env?.restart_time || 0
+ restarts: proc.pm2_env?.restart_time || 0,
+ unstableRestarts: proc.pm2_env?.unstable_restarts || 0
}));
}