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

address review: 256MB disk safety valve on raw.txt + clarify finalize-guard comment

Adam Eivy94c5e8ce672d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 60b22f36cd..9ddff13536 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,4 +17,4 @@
- Federated peer-sync category toggles for **Universe** and **Pipeline** silently no-op'd. The Zod `syncCategoriesSchema` in `server/routes/instances.js` was missing both keys; Zod's default object parsing strips unknown keys, so the PATCH validated as an empty `syncCategories` object, the service-side merge became a no-op, and the checkbox stayed unchecked with no server-side error. Added `universe` and `pipeline` to the schema to restore parity with `DEFAULT_SYNC_CATEGORIES` and the UI's `SYNC_CATEGORY_META`.
- Auto-run the world → universe data rename on server boot. The conversion previously shipped as a manual CLI script (`server/scripts/migrateWorldToUniverse.js`) that nobody knew to invoke, so installs upgrading from the World Builder era kept stale `data/world-builder.json` files and never saw their worlds appear as universes. The new migration `031-world-to-universe-data-rename.js` does the file rename, top-level key rename (`worlds`→`universes`), `worldId`→`universeId` rewrite in `pipeline-series.json`, `worldRun`→`universeRun` rewrite in `media-jobs.json`, and also relinks any `"World: <name>"` render collections in `media-collections.json` to their universe by canonical-name match.
- Universe Builder picker dropdown rendered beneath the tab subnav and downstream section cards in Lumen Glass / Blueprint Ops themes. Those themes ship a non-`none` `--port-backdrop-filter`, and the global rule in `index.css` applies it to every `.bg-port-card.border.rounded*` — which turns each such card into its own stacking context. The picker's `absolute z-30` dropdown was trapped inside the header card's context and couldn't paint over later sibling cards. Adding `relative z-30` to the picker's `<header>` lets that stacking context win against subsequent siblings so the dropdown overlays them as intended.
-- TUI agent raw-PTY buffer no longer truncates the head at ~640KB ("⚠️ raw PTY buffer exceeded 1MB — head dropped"). The buffer feeds `analyzeAgentFailure` at finalize, so silently slicing the head was the exact behavior the warning admitted to ("failure analysis may miss earlier symptoms"). `server/services/agentTuiSpawning.js` now spools raw PTY bytes to a per-agent `raw.txt` file in 250ms-debounced batches (mirroring the existing parsed-output pipeline that writes `output.txt`), so the in-memory footprint stays bounded regardless of run length. `analyzeAgentFailure` reads the file on failure — successful runs skip the read entirely. The paste-marker poll keeps only a small post-paste accumulator that lives for the paste window (a few seconds). The `rawBufferTruncated` agent-metadata flag is gone with the truncation logic.
+- TUI agent raw-PTY buffer no longer truncates the head at ~640KB ("⚠️ raw PTY buffer exceeded 1MB — head dropped"). The buffer feeds `analyzeAgentFailure` at finalize, so silently slicing the head was the exact behavior the warning admitted to ("failure analysis may miss earlier symptoms"). `server/services/agentTuiSpawning.js` now spools raw PTY bytes to a per-agent `raw.txt` file in 250ms-debounced batches (mirroring the existing parsed-output pipeline that writes `output.txt`), so the in-memory footprint stays bounded regardless of run length. `analyzeAgentFailure` reads the **tail** of the file (last 1MB) on failure via a non-throwing `readFileTail` helper; successful runs skip the read entirely. The paste-marker poll keeps only a short-lived post-paste accumulator that lives for the paste window. A 256MB disk safety valve truncates `raw.txt` if a runaway agent exceeds the cap (preserves the most-recent bytes that `readFileTail` actually consumes; warns once and sets a `rawSpoolTruncated` agent-metadata flag). The old `rawBufferTruncated` flag is gone with the in-memory truncation logic.
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index db72b35075..112459acc6 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -8,7 +8,7 @@
import { join } from 'path';
import { existsSync } from 'fs';
-import { appendFile, readFile, rm, open, stat as fsStat } from 'fs/promises';
+import { appendFile, readFile, rm, open, stat as fsStat, writeFile } from 'fs/promises';
import * as shellService from './shell.js';
import { emitLog } from './cosEvents.js';
import { appendAgentOutputLines, updateAgent } from './cosAgents.js';
@@ -45,6 +45,16 @@ const DEFAULT_TUI_MIN_RUNTIME_MS = 15000;
// realistic PTY stream while keeping peak finalize memory bounded.
const RAW_TAIL_ANALYSIS_BYTES = 1024 * 1024;
+// Disk safety valve for the raw PTY spool. A misbehaving (or compromised)
+// TUI agent could in principle emit MB/sec forever and fill the volume —
+// realistic agents idle out at 180s and emit <10MB total, but no operator
+// wants ONE runaway agent eating all disk. At this threshold the spool is
+// truncated (rewritten with the current batch) so the most-recent data
+// remains, which is what readFileTail at finalize needs anyway. Warn fires
+// once per agent run; the `rawSpoolTruncated` metadata flag persists in
+// the agent record so the operator can spot the affected runs after the fact.
+const RAW_SPOOL_MAX_BYTES = 256 * 1024 * 1024;
+
/**
* Read at most `maxBytes` from the end of a file. Returns null when the file
* doesn't exist or can't be opened; an empty string for a zero-byte file.
@@ -200,6 +210,8 @@ export async function spawnTuiAgent({
let pendingRawChunks = [];
let rawFlushTimer = null;
let rawFlushing = null;
+ let rawBytesWritten = 0;
+ let rawSpoolTruncationWarned = false;
let pasteEnterTimer = null;
const streamingStrip = createStreamingAnsiStripper();
@@ -244,7 +256,24 @@ export async function spawnTuiAgent({
if (pendingRawChunks.length === 0) return;
const batch = pendingRawChunks.join('');
pendingRawChunks = [];
+ if (rawBytesWritten + batch.length > RAW_SPOOL_MAX_BYTES) {
+ // Safety valve: rewrite the file with just this batch instead of
+ // appending. The tail-read at finalize wants the MOST RECENT bytes,
+ // not the oldest, so truncating preserves what analyzeAgentFailure
+ // actually uses while bounding disk usage at ~RAW_SPOOL_MAX_BYTES
+ // plus one debounce window.
+ if (!rawSpoolTruncationWarned) {
+ rawSpoolTruncationWarned = true;
+ console.warn(`⚠️ TUI agent ${agentId} raw PTY spool reached ${Math.round(RAW_SPOOL_MAX_BYTES / 1024 / 1024)}MB — truncating spool (oldest bytes dropped; tail-read still reflects most recent)`);
+ updateAgent(agentId, { metadata: { rawSpoolTruncated: true } })
+ .catch(err => console.error(`❌ TUI agent ${agentId} rawSpoolTruncated metadata write failed: ${err.message}`));
+ }
+ await writeFile(rawFile, batch).catch(() => {});
+ rawBytesWritten = batch.length;
+ return;
+ }
await appendFile(rawFile, batch).catch(() => {});
+ rawBytesWritten += batch.length;
};
const scheduleRawFlush = () => {
@@ -394,10 +423,10 @@ export async function spawnTuiAgent({
};
const handleData = async (data) => {
- // The PTY can emit chunks between finalize starting and the shell session
- // actually being killed in the finally block. Once finalized, skip them —
- // disk-spool would race the rm of raw.txt (if we did remove it), and the
- // post-paste accumulator + state mutations are pointless after finish.
+ // node-pty can deliver chunks between finalize starting and the shell
+ // session being killed in finalize's finally block. Once finalized, drop
+ // them — appending to the spool, growing the post-paste accumulator, or
+ // mutating timing state is all pointless after finish has settled.
if (finalized) return;
// node-pty surfaces output as already-decoded UTF-8 strings via
// shellService's onData hook (StringDecoder handles multi-byte
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 8dc9d449e0..4be4fb4a49 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -543,6 +543,54 @@ describe('spawnTuiAgent runtime', () => {
expect(closeMock).toHaveBeenCalled();
});
+ // ── 8b. Disk safety valve at 256MB ──────────────────────────────────────────
+ // The raw spool truncates rather than appends once it crosses the cap so
+ // a runaway agent can't fill the volume. Test by feeding chunks that push
+ // past the threshold and asserting writeFile (truncate) is preferred over
+ // appendFile for the overflow batch, plus the rawSpoolTruncated metadata
+ // flag fires once.
+ it('raw spool: truncates instead of appending once it crosses the 256MB safety cap', async () => {
+ const fsPromises = await import('fs/promises');
+ runSpawn();
+ await flushMicrotasks();
+
+ // Push three 100MB chunks: total 300MB, well past the 256MB cap.
+ // Buffer.alloc(size, byte) keeps allocations cheap (single fill).
+ const HUNDRED_MB = 100 * 1024 * 1024;
+ await capturedOnData(Buffer.alloc(HUNDRED_MB, 0x61));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(300);
+ await flushMicrotasks();
+
+ await capturedOnData(Buffer.alloc(HUNDRED_MB, 0x62));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(300);
+ await flushMicrotasks();
+
+ await capturedOnData(Buffer.alloc(HUNDRED_MB, 0x63));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(300);
+ await flushMicrotasks();
+
+ // Third chunk should have crossed the 256MB threshold → writeFile, not
+ // appendFile. Earlier chunks went through appendFile.
+ const writeFileRawCalls = vi.mocked(fsPromises.writeFile).mock.calls.filter(
+ ([p]) => typeof p === 'string' && p.endsWith('raw.txt')
+ );
+ expect(writeFileRawCalls.length).toBeGreaterThan(0);
+
+ const truncWarns = warnSpy.mock.calls.filter(args =>
+ typeof args[0] === 'string' && args[0].includes('raw PTY spool reached')
+ );
+ expect(truncWarns).toHaveLength(1);
+
+ const truncMetaCalls = vi.mocked(cosAgents.updateAgent).mock.calls.filter(
+ ([_id, payload]) => payload?.metadata?.rawSpoolTruncated === true
+ );
+ expect(truncMetaCalls).toHaveLength(1);
+ expect(truncMetaCalls[0][0]).toBe('agent-1');
+ });
+
// ── 9. Success-path skips the tail read ─────────────────────────────────────
// Successful finalize must not touch raw.txt — that's what makes the
// disk-spool's bounded-memory guarantee hold for healthy long runs.