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: unify filesystem stat parsing (#6758)
[._.]/ Adam Eivy0f78baac8baa
diff --git a/server/lib/README.md b/server/lib/README.mdindex b5e7738a5d..ee33e0ab83 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -279,7 +279,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `resolveCodeRootForModule(moduleUrl)` is the single source of truth for the "two directories above this file" depth assumption — `paths.js`'s `CODE_ROOT` and `services/userActions.js`'s data-root guard both derive through it so they cannot silently drift apart. `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. || `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. `createDownloadSlot({ codePrefix, idleStallEnvVar, exclusive, keepPartialOnCancel })` is the one transfer-slot registry a weight download claims before its first await — in-flight map, abort controller carrying a cancel/stall reason, typed `<PREFIX>_DOWNLOAD_IN_FLIGHT`/`_STALLED`/`_CANCELLED` errors, a per-chunk progress throttle, and an `isInFlight(path)` predicate covering the dest, its `.partial`, and shards under a claimed directory. Call it at module scope only. `isAnyDownloadInFlight` answers for every registered slot at once, which is how the orphaned-partial GC protects live transfers. || `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |-| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, `writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`, directory helpers, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. |+| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, `writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`, directory helpers, `parseFilesystemStats(stats)` → canonical/byte-alias metrics or `null`, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. || `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. || `portosEnv.js` | Single server-side helper for PortOS's own `.env` (`PORTOS_ENV_PATH` anchored to `installRoot` per #1947, `parseEnvContents`, `readPortosEnvValue`, `upsertPortosEnvLine` + `upsertEnvLine`), with replacer-function guard for `$`-patterns and `process.env` wins precedence; `scripts/lib/envFile.js` stays as the zero-dependency boundary copy. || `portosRootPlaceholder.js` | Expand leftover `__PORTOS_ROOT__` tokens in apps registry fields (`repoPath`, `appIconPath`, etc.) so a partial/restored `data/` tree cannot leave Apps → Git looking for a non-existent checkout. `PORTOS_ROOT_TOKEN`, `expandPortosRootToken`, `expandPortosRootInApp`, `containsPortosRootToken`. Used by `services/apps.js` on load and by `scripts/setup-data.js` / `scripts/lib/rewriteAppsPortosRoot.js` when seeding or rewriting `data/apps.json`. |diff --git a/server/lib/fileCore.js b/server/lib/fileCore.jsindex 6a53b121d6..b8960f93be 100644--- a/server/lib/fileCore.js+++ b/server/lib/fileCore.js@@ -43,6 +43,25 @@ const WIN_RENAME_LOCK_CODES = ['EPERM', 'EACCES', 'EEXIST'];const WIN_READ_LOCK_CODES = ['EPERM', 'EACCES', 'EBUSY'];const FILE_WATCH_FALLBACK_POLL_MS = 5000;+/** Normalize Node statfs block counts into byte totals and compatibility aliases. */+export function parseFilesystemStats(stats) {+ if (!stats) return null;+ const total = Number(stats.blocks) * Number(stats.bsize);+ const available = Number(stats.bavail) * Number(stats.bsize);+ if (!Number.isFinite(total) || total <= 0 || !Number.isFinite(available) || available < 0) return null;+ const free = Math.min(total, available);+ const used = total - free;+ return {+ total,+ used,+ free,+ usagePercent: Math.round((used / total) * 100),+ totalBytes: total,+ usedBytes: used,+ freeBytes: free,+ };+}+/** Watch for a file to appear without repeatedly stat'ing its parent directory. */export function watchForFile(filePath, onDetected, { settleMs = 50, pollMs = FILE_WATCH_FALLBACK_POLL_MS } = {}) {const targetName = basename(filePath);diff --git a/server/lib/fileCore.test.js b/server/lib/fileCore.test.jsnew file mode 100644index 0000000000..77e871654d--- /dev/null+++ b/server/lib/fileCore.test.js@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';+import { parseFilesystemStats } from './fileCore.js';++describe('parseFilesystemStats', () => {+ it('derives canonical byte metrics and compatibility aliases from statfs counts', () => {+ expect(parseFilesystemStats({ blocks: 100, bavail: 25, bsize: 4096 })).toEqual({+ total: 409_600,+ used: 307_200,+ free: 102_400,+ usagePercent: 75,+ totalBytes: 409_600,+ usedBytes: 307_200,+ freeBytes: 102_400,+ });+ });++ it.each([+ null,+ undefined,+ { blocks: 0, bavail: 0, bsize: 4096 },+ { blocks: 100, bavail: 25 },+ { blocks: 100, bavail: 25, bsize: 0 },+ { blocks: 100, bavail: -1, bsize: 4096 },+ { blocks: Number.NaN, bavail: 25, bsize: 4096 },+ ])('returns null for unavailable or invalid stats (%j)', (stats) => {+ expect(parseFilesystemStats(stats)).toBeNull();+ });++ it('clamps available blocks to the filesystem total', () => {+ expect(parseFilesystemStats({ blocks: 10, bavail: 11, bsize: 1024 })).toEqual({+ total: 10_240,+ used: 0,+ free: 10_240,+ usagePercent: 0,+ totalBytes: 10_240,+ usedBytes: 0,+ freeBytes: 10_240,+ });+ });++ it('preserves whole-percent rounding at the centralized boundary', () => {+ expect(parseFilesystemStats({ blocks: 1000, bavail: 2, bsize: 1 })?.usagePercent).toBe(100);+ });+});diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex e66f4b96f6..40a2e31a02 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -10,6 +10,7 @@ import { getCurrentVersion } from '../services/updateChecker.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { getMemoryStats } from '../lib/memoryStats.js';import { formatBytes, formatDuration } from '../lib/fileUtils.js';+import { parseFilesystemStats } from '../lib/fileCore.js';import { validateRequest, systemHealthWarningParamsSchema, systemHealthWarningDismissSchema } from '../lib/validation.js';import { getSettings, updateSettingsWith } from '../services/settings.js';import { checkGhHealth } from '../services/github.js';@@ -157,21 +158,13 @@ router.get('/health/details', asyncHandler(async (req, res) => {// bavail = blocks available to unprivileged users (what the user can actually fill).// Derive used/usagePercent from the same figure so `used + free === total` and// the UI's percent corresponds to the displayed `free`.- let disk = null;- if (diskStats) {- const totalDisk = diskStats.blocks * diskStats.bsize;- if (totalDisk > 0) {- const freeDisk = diskStats.bavail * diskStats.bsize;- const usedDisk = totalDisk - freeDisk;- const diskUsagePercent = Math.round((usedDisk / totalDisk) * 100);- disk = {- total: totalDisk,- used: usedDisk,- free: freeDisk,- usagePercent: diskUsagePercent- };- }- }+ const parsedDisk = parseFilesystemStats(diskStats);+ const disk = parsedDisk && {+ total: parsedDisk.total,+ used: parsedDisk.used,+ free: parsedDisk.free,+ usagePercent: parsedDisk.usagePercent,+ };// Process status summary from PM2. Processes whose exit is expected (a desktop// app the user closed) are excluded from the FAILURE-bearing counts: a quit gamediff --git a/server/services/eidoverseWorldSources.js b/server/services/eidoverseWorldSources.jsindex 4454da0229..4b58650f1b 100644--- a/server/services/eidoverseWorldSources.js+++ b/server/services/eidoverseWorldSources.js@@ -8,6 +8,7 @@import { createHash } from 'node:crypto';import { statfs } from 'node:fs/promises';+import { parseFilesystemStats } from '../lib/fileCore.js';import { getAllApps, getAppStatuses } from './apps.js';import { getStatus as getCosStatus, getAgents, getCosTasks, getTodayActivity } from './cos.js';import { getPendingCounts } from './review.js';@@ -94,10 +95,7 @@ const percentageOrNull = (value) => {async function getDiskUsagePercent() {const stats = await statfs('/').catch(() => null);- if (!stats) return null;- const total = stats.blocks * stats.bsize;- if (!(total > 0)) return null;- return Math.round(((total - stats.bavail * stats.bsize) / total) * 100);+ return parseFilesystemStats(stats)?.usagePercent ?? null;}function appSummary(apps) {diff --git a/server/services/systemResources.js b/server/services/systemResources.jsindex bae5dd6d24..ed85cb0197 100644--- a/server/services/systemResources.js+++ b/server/services/systemResources.js@@ -11,6 +11,7 @@import os from 'os';import { scanModelDuplicates } from './modelDeduplication.js';import { statfs } from 'fs/promises';+import { parseFilesystemStats } from '../lib/fileCore.js';import { join } from 'path';import { z } from 'zod';import { query } from '../lib/db.js';@@ -71,20 +72,6 @@ const sumKnownBytes = (values) => {return known.length > 0 ? sumBytes(known) : null;};-function filesystemFrom(stats) {- if (!stats) return null;- const totalBytes = finiteOrNull(stats.blocks * stats.bsize);- const freeBytes = finiteOrNull(stats.bavail * stats.bsize);- if (!totalBytes || freeBytes == null) return null;- const usedBytes = Math.max(0, totalBytes - freeBytes);- return {- totalBytes,- usedBytes,- freeBytes,- usagePercent: Math.round((usedBytes / totalBytes) * 100),- };-}-const backendState = (value) => (value == null ? 'unavailable' : 'ready');function dataCleanupCandidates(categories) {@@ -385,7 +372,13 @@ export async function buildSystemResourceReport() {scanModelDuplicates().catch(() => ({ pinokioDetected: null, items: [], totalReclaimableBytes: 0, error: 'Duplicate model scan unavailable' })),]);- const filesystem = filesystemFrom(diskStats);+ const parsedFilesystem = parseFilesystemStats(diskStats);+ const filesystem = parsedFilesystem && {+ totalBytes: parsedFilesystem.totalBytes,+ usedBytes: parsedFilesystem.usedBytes,+ freeBytes: parsedFilesystem.freeBytes,+ usagePercent: parsedFilesystem.usagePercent,+ };const databaseBytes = finiteOrNull(databaseRow?.bytes);const dependenciesBytes = sumKnownBytes(dependencySizes);const ollamaResidencyError = ollamaLoaded == null