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([cos-agent-output-write-amplification]): batch streamed agent output to end per-line state-file rewrites

[._.]/ Adam Eivy0562bed886bf
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 978858c558..40d427571c 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -11,7 +11,7 @@ import { existsSync } from 'fs';
import { spawn } from 'child_process';
import { homedir } from 'os';
import { cosEvents, emitLog } from './cosEvents.js';
-import { updateAgent, completeAgent, appendAgentOutput, appendAgentOutputLines } from './cosAgents.js';
+import { updateAgent, completeAgent, createAgentOutputBatcher } from './cosAgents.js';
import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';
import { release } from './executionLanes.js';
import { completeExecution, errorExecution } from './toolStateMachine.js';
@@ -415,6 +415,14 @@ export async function spawnDirectly({
let immediateFallbackAnalysis = null;
const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();
+ // Debounced state-write batcher for streamed output. stdout/stderr `data`
+ // events fire per chunk (and stream-json yields many lines per chunk), so a
+ // per-line/per-chunk appendAgentOutput would round-trip a full state
+ // load+save each time. The batcher coalesces a ~250ms window; the close/error
+ // handlers `await outputBatcher.flush()` so the final lines persist before
+ // the agent is finalized. (output.txt is written separately below.)
+ const outputBatcher = createAgentOutputBatcher(agentId);
+
const stopForImmediateFallbackSignal = (text) => {
if (immediateFallbackAnalysis || claudeProcess.killed) return;
const analysis = detectImmediateFallbackSignal(text);
@@ -457,13 +465,13 @@ export async function spawnDirectly({
}
const lines = streamParser.processChunk(text);
for (const line of lines) outputBuffer += line + '\n';
- await appendAgentOutputLines(agentId, lines);
+ outputBatcher.push(lines);
await writeFile(outputFile, outputBuffer).catch(() => {});
} else {
// Non-stream providers: emit raw stdout as before
outputBuffer += text;
await writeFile(outputFile, outputBuffer).catch(() => {});
- await appendAgentOutput(agentId, text);
+ outputBatcher.push(text);
}
} catch (err) {
console.error(`❌ agentCli stdout handler failed: ${err.message}`);
@@ -478,13 +486,13 @@ export async function spawnDirectly({
if (codexStderrFormatter) {
const lines = codexStderrFormatter.processChunk(text);
for (const line of lines) outputBuffer += line + '\n';
- await appendAgentOutputLines(agentId, lines);
+ outputBatcher.push(lines);
await writeFile(outputFile, outputBuffer).catch(() => {});
return;
}
outputBuffer += `[stderr] ${text}`;
await writeFile(outputFile, outputBuffer).catch(() => {});
- await appendAgentOutput(agentId, `[stderr] ${text}`);
+ outputBatcher.push(`[stderr] ${text}`);
} catch (err) {
console.error(`❌ agentCli stderr handler failed: ${err.message}`);
}
@@ -512,6 +520,7 @@ export async function spawnDirectly({
}
cosEvents.emit('agent:error', { agentId, error: err.message });
+ await outputBatcher.flush();
await completeAgent(agentId, { success: false, error: err.message });
await completeAgentRun(runId, outputBuffer, 1, 0, { message: err.message, category: 'spawn-error' });
unregisterSpawnedAgent(claudeProcess.pid);
@@ -551,7 +560,7 @@ export async function spawnDirectly({
const remaining = streamParser.flush();
for (const line of remaining) {
outputBuffer += line + '\n';
- await appendAgentOutput(agentId, line);
+ outputBatcher.push(line);
}
// Use the parsed final result for the output file if available
const finalResult = streamParser.getFinalResult();
@@ -562,10 +571,15 @@ export async function spawnDirectly({
if (codexStderrFormatter) {
for (const line of codexStderrFormatter.flush()) {
outputBuffer += line + '\n';
- await appendAgentOutput(agentId, line);
+ outputBatcher.push(line);
}
}
+ // Drain pending output to state before finalize so the transcript tail
+ // lands before the agent's terminal record (covers the paused early-return
+ // below too, since output.txt is written next).
+ await outputBatcher.flush();
+
await writeFile(outputFile, outputBuffer).catch(() => {});
// Paused agents are finalized in `markAgentPaused` (which already released
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index 6461fa3287..e3bd407cdc 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -3,12 +3,37 @@ import { EventEmitter } from 'events';
// Heavy modules needed only by spawnDirectly — mock them all before importing.
vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() }, emitLog: vi.fn() }));
-vi.mock('./cosAgents.js', () => ({
- updateAgent: vi.fn().mockResolvedValue(undefined),
- completeAgent: vi.fn().mockResolvedValue(undefined),
- appendAgentOutput: vi.fn().mockResolvedValue(undefined),
- appendAgentOutputLines: vi.fn().mockResolvedValue(undefined),
-}));
+vi.mock('./cosAgents.js', () => {
+ const appendAgentOutput = vi.fn().mockResolvedValue(undefined);
+ const appendAgentOutputLines = vi.fn().mockResolvedValue(undefined);
+ // Faithful stand-in for the real debounced batcher: accumulates pushed lines
+ // and, on flush(), routes them through the mocked appendAgentOutputLines while
+ // swallowing+logging failures (mirrors the real createAgentOutputBatcher in
+ // cosAgents.js — whose error handling is unit-tested in cosAgents.test.js).
+ const createAgentOutputBatcher = vi.fn((agentId) => {
+ let pending = [];
+ return {
+ push(lineOrLines) {
+ if (Array.isArray(lineOrLines)) pending.push(...lineOrLines);
+ else pending.push(lineOrLines);
+ },
+ async flush() {
+ if (pending.length === 0) return;
+ const batch = pending;
+ pending = [];
+ await appendAgentOutputLines(agentId, batch).catch((err) =>
+ console.error(`❌ agent ${agentId} output batch flush failed: ${err.message}`));
+ },
+ };
+ });
+ return {
+ updateAgent: vi.fn().mockResolvedValue(undefined),
+ completeAgent: vi.fn().mockResolvedValue(undefined),
+ appendAgentOutput,
+ appendAgentOutputLines,
+ createAgentOutputBatcher,
+ };
+});
vi.mock('./agents.js', () => ({
registerSpawnedAgent: vi.fn(),
unregisterSpawnedAgent: vi.fn(),
@@ -215,10 +240,10 @@ describe('stream error containment', () => {
vi.restoreAllMocks();
});
- it('stdout handler catches appendAgentOutputLines rejection and logs ❌ prefix — no unhandled rejection escapes', async () => {
- // Arrange: make appendAgentOutputLines reject so the handler's catch is exercised.
- // Use mockRejectedValueOnce so only the first call (during data event) throws;
- // subsequent calls in the close handler are unaffected.
+ it('drains stdout output on close and a failed batch flush is logged, not leaked as an unhandled rejection', async () => {
+ // stdout output is now batched: the data handler pushes lines to the output
+ // batcher and the close handler drains it. Make the drain's state write fail
+ // and assert the batcher swallows+logs it with a ❌ prefix — no escape.
cosAgentsMocks.appendAgentOutputLines.mockRejectedValueOnce(new Error('db write failed'));
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -234,13 +259,16 @@ describe('stream error containment', () => {
// Yield to let the await inside spawnDirectly resolve so listeners are registered.
await new Promise((r) => setTimeout(r, 10));
- // Emit data on stdout to trigger the async handler
- fakeProcess.stdout.emit('data', Buffer.from('{"type":"result","result":"ok"}\n'));
+ // Emit a stream-json text delta on stdout so the parser yields a line the
+ // handler enqueues into the batcher.
+ fakeProcess.stdout.emit('data', Buffer.from(
+ '{"type":"stream_event","event":{"type":"content_block_delta","delta":{"type":"text_delta","text":"hello\\n"}}}\n'
+ ));
// Give the microtask queue a chance to drain so the async handler runs.
await new Promise((r) => setTimeout(r, 50));
- // Trigger close so spawnDirectly resolves
+ // Trigger close so the batcher drains and spawnDirectly resolves.
fakeProcess.emit('close', 0);
await spawnPromise.catch(() => {});
@@ -249,13 +277,13 @@ describe('stream error containment', () => {
// Assert: error was swallowed into console.error, not an unhandled rejection
expect(unhandledRejections).toHaveLength(0);
const logged = consoleSpy.mock.calls.some(
- (args) => typeof args[0] === 'string' && args[0].startsWith('❌ agentCli stdout handler failed:')
+ (args) => typeof args[0] === 'string' && args[0].startsWith('❌ agent agent-test output batch flush failed:')
);
expect(logged).toBe(true);
});
- it('stderr handler catches appendAgentOutput rejection and logs ❌ prefix — no unhandled rejection escapes', async () => {
- cosAgentsMocks.appendAgentOutput.mockRejectedValueOnce(new Error('stderr db write failed'));
+ it('drains stderr output on close and a failed batch flush is logged, not leaked as an unhandled rejection', async () => {
+ cosAgentsMocks.appendAgentOutputLines.mockRejectedValueOnce(new Error('stderr db write failed'));
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const unhandledRejections = [];
@@ -267,7 +295,7 @@ describe('stream error containment', () => {
// Yield to let the await inside spawnDirectly resolve so listeners are registered.
await new Promise((r) => setTimeout(r, 10));
- // Emit data on stderr to trigger the async stderr handler
+ // Emit data on stderr to enqueue a batched `[stderr] …` line.
fakeProcess.stderr.emit('data', Buffer.from('some stderr output\n'));
await new Promise((r) => setTimeout(r, 50));
@@ -279,7 +307,7 @@ describe('stream error containment', () => {
expect(unhandledRejections).toHaveLength(0);
const logged = consoleSpy.mock.calls.some(
- (args) => typeof args[0] === 'string' && args[0].startsWith('❌ agentCli stderr handler failed:')
+ (args) => typeof args[0] === 'string' && args[0].startsWith('❌ agent agent-test output batch flush failed:')
);
expect(logged).toBe(true);
});
diff --git a/server/services/cosAgents.js b/server/services/cosAgents.js
index 0c891bde44..83aa646c43 100644
--- a/server/services/cosAgents.js
+++ b/server/services/cosAgents.js
@@ -389,6 +389,78 @@ export async function appendAgentOutputLines(agentId, lines) {
return result;
}
+// Debounce window for batching streamed agent output to state. A chatty
+// producer (CoS Runner stream events, non-stream CLI stdout) can emit dozens
+// of lines/sec; without batching, each line round-trips a full state
+// load+save (see appendAgentOutput). 250ms is invisible to the live tail but
+// cuts state I/O by 1-2 orders of magnitude. Matches OUTPUT_FLUSH_INTERVAL_MS
+// in agentTuiSpawning.js.
+const OUTPUT_FLUSH_INTERVAL_MS = 250;
+
+// Debounced per-agent output batcher. Wraps appendAgentOutputLines with a
+// ~250ms flush window so a hot streaming producer triggers one state load+save
+// per window instead of per line — the write-amplification guard documented in
+// CLAUDE.md ("High-frequency state writes must batch"). The TUI spawner rolls
+// its own equivalent inline because it co-flushes an output.txt appendFile in
+// the same batch; producers that only need the state write should use this.
+//
+// Callers MUST `await flush()` in their finish/cleanup path before the
+// completion event so the final lines land before the agent is marked done.
+export function createAgentOutputBatcher(agentId, { intervalMs = OUTPUT_FLUSH_INTERVAL_MS } = {}) {
+ let pending = [];
+ let timer = null;
+ let flushing = null;
+
+ const drain = async () => {
+ if (timer) { clearTimeout(timer); timer = null; }
+ if (pending.length === 0) return;
+ const batch = pending;
+ pending = [];
+ // Swallow+log state-write failures so neither the debounced timer nor a
+ // caller's `await flush()` ever rejects — this runs in child-process /
+ // timer callbacks where an uncaught throw would crash Node (CLAUDE.md "No
+ // try/catch" exception). The authoritative transcript lives in output.txt;
+ // a dropped live-tail batch is non-fatal. Mirrors the TUI spawner's
+ // `.catch(() => {})` on its own batched append.
+ await appendAgentOutputLines(agentId, batch).catch((err) => {
+ console.error(`❌ agent ${agentId} output batch flush failed: ${err.message}`);
+ });
+ };
+
+ const schedule = () => {
+ if (timer || flushing) return;
+ timer = setTimeout(() => {
+ timer = null;
+ flushing = drain().finally(() => {
+ flushing = null;
+ // Catch lines that arrived during the in-flight drain — without this a
+ // producer that goes quiet right after the timer fires strands its last
+ // batch in `pending` until flush().
+ if (pending.length > 0) schedule();
+ });
+ }, intervalMs);
+ };
+
+ return {
+ push(lineOrLines) {
+ if (Array.isArray(lineOrLines)) {
+ if (lineOrLines.length === 0) return;
+ pending.push(...lineOrLines);
+ } else {
+ pending.push(lineOrLines);
+ }
+ schedule();
+ },
+ // Wait for any in-flight drain, then synchronously empty `pending`. A push
+ // can race in during the awaited drain, so drain once more to be sure.
+ async flush() {
+ if (flushing) await flushing;
+ await drain();
+ if (pending.length > 0) await drain();
+ },
+ };
+}
+
// Get all agents from in-memory state (includes running and recently completed; archived agents loaded via getAgentsByDate)
export async function getAgents() {
const state = await loadState();
diff --git a/server/services/cosAgents.test.js b/server/services/cosAgents.test.js
index 869dfe197c..93782b0760 100644
--- a/server/services/cosAgents.test.js
+++ b/server/services/cosAgents.test.js
@@ -19,7 +19,8 @@ vi.mock('./cosState.js', () => ({
withStateLock: async (fn) => fn()
}));
-import { getAgent } from './cosAgents.js';
+import { getAgent, createAgentOutputBatcher } from './cosAgents.js';
+import { saveState } from './cosState.js';
describe('cosAgents', () => {
beforeEach(async () => {
@@ -54,3 +55,64 @@ describe('cosAgents', () => {
]);
});
});
+
+describe('createAgentOutputBatcher', () => {
+ const agentId = 'agent-batch';
+
+ beforeEach(() => {
+ saveState.mockClear();
+ mockCosState.state = { agents: { [agentId]: { id: agentId, output: [] } } };
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('coalesces many pushed lines into a single state write on flush', async () => {
+ const batcher = createAgentOutputBatcher(agentId);
+ batcher.push('line 1');
+ batcher.push('line 2');
+ batcher.push(['line 3', 'line 4']); // array push appends each line
+ await batcher.flush();
+
+ // Write-amplification guard: 4 lines, one load+save — not one per line.
+ expect(saveState).toHaveBeenCalledTimes(1);
+ expect(mockCosState.state.agents[agentId].output.map((o) => o.line)).toEqual([
+ 'line 1', 'line 2', 'line 3', 'line 4'
+ ]);
+ });
+
+ it('flush() is a no-op (no state write) when nothing was pushed', async () => {
+ const batcher = createAgentOutputBatcher(agentId);
+ await batcher.flush();
+ expect(saveState).not.toHaveBeenCalled();
+ });
+
+ it('captures lines pushed during an in-flight drain', async () => {
+ const batcher = createAgentOutputBatcher(agentId);
+ batcher.push('first');
+ const flushing = batcher.flush();
+ batcher.push('raced-in'); // arrives while the first drain is awaiting
+ await flushing;
+ await batcher.flush(); // second flush picks up the raced-in line
+
+ expect(mockCosState.state.agents[agentId].output.map((o) => o.line)).toEqual([
+ 'first', 'raced-in'
+ ]);
+ });
+
+ it('swallows + logs a state-write failure so flush() never rejects', async () => {
+ saveState.mockRejectedValueOnce(new Error('disk full'));
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const batcher = createAgentOutputBatcher(agentId);
+ batcher.push('doomed line');
+
+ await expect(batcher.flush()).resolves.toBeUndefined();
+ const logged = consoleSpy.mock.calls.some(
+ (args) => typeof args[0] === 'string' &&
+ args[0].startsWith(`❌ agent ${agentId} output batch flush failed:`)
+ );
+ expect(logged).toBe(true);
+ });
+});
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 84011168dd..7fc51a3d35 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -10,7 +10,7 @@ import { join } from 'path';
import { readFile, readdir, rm, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { emitLog, cosEvents } from './cosEvents.js';
-import { appendAgentOutput, updateAgent, completeAgent } from './cosAgents.js';
+import { createAgentOutputBatcher, updateAgent, completeAgent } from './cosAgents.js';
import { initProviderStatus } from './providerStatus.js';
import { onCosRunnerEvent, initCosRunnerConnection, isRunnerAvailable } from './cosRunnerClient.js';
import { ensureDir, loadSlashdoFile, PATHS } from '../lib/fileUtils.js';
@@ -32,6 +32,29 @@ export { processAgentCompletion } from './agentCompletion.js';
const ROOT_DIR = PATHS.root;
const RUNS_DIR = PATHS.runs;
+// Per-agent debounced output batchers for the CoS Runner stream path. The
+// runner emits `agent:output` per parsed line (see cos-runner/index.js), so a
+// chatty agent would otherwise trigger a full state load+save per line. Each
+// batcher coalesces a ~250ms window; we drain + drop it when the agent
+// completes/errors so the final lines persist before the completion event.
+const runnerOutputBatchers = new Map();
+
+function getRunnerOutputBatcher(agentId) {
+ let batcher = runnerOutputBatchers.get(agentId);
+ if (!batcher) {
+ batcher = createAgentOutputBatcher(agentId);
+ runnerOutputBatchers.set(agentId, batcher);
+ }
+ return batcher;
+}
+
+async function flushRunnerOutputBatcher(agentId) {
+ const batcher = runnerOutputBatchers.get(agentId);
+ if (!batcher) return;
+ runnerOutputBatchers.delete(agentId);
+ await batcher.flush();
+}
+
/**
* Load a slashdo command from the bundled submodule, resolving !`cat` lib includes inline.
@@ -95,7 +118,7 @@ export async function initSpawner() {
// Set up event handlers for runner events
onCosRunnerEvent('agent:output', async (data) => {
const { agentId, text } = data;
- await appendAgentOutput(agentId, text);
+ getRunnerOutputBatcher(agentId).push(text);
// Update phase on first output
const agent = runnerAgents.get(agentId);
@@ -113,6 +136,9 @@ export async function initSpawner() {
if (agent) {
clearTimeout(agent.initializationTimeout);
}
+ // Drain pending output before completion so the final lines land in
+ // state before handleAgentCompletion writes the terminal record.
+ await flushRunnerOutputBatcher(agentId);
await handleAgentCompletion(agentId, exitCode, success, duration);
});
@@ -125,6 +151,7 @@ export async function initSpawner() {
if (agent) {
clearTimeout(agent.initializationTimeout);
}
+ await flushRunnerOutputBatcher(orphan.agentId);
await handleAgentCompletion(orphan.agentId, orphan.exitCode, orphan.success, 0);
}
});
@@ -133,6 +160,7 @@ export async function initSpawner() {
const { agentId, error } = data;
console.error(`❌ Agent ${agentId} error from runner: ${error}`);
cosEvents.emit('agent:error', { agentId, error });
+ await flushRunnerOutputBatcher(agentId);
const agent = runnerAgents.get(agentId);
if (agent) {
clearTimeout(agent.initializationTimeout);