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(backup): admit runtime recording completion and spool transactions

[._.]/ Adam Eivy8aab5fe3df21
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index df88c56036..b0ee39ef60 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -113,6 +113,7 @@ Admission inventory (`withBackupAssetPublication`):
| CoS agent archive/index publication (`cosAgentLifecycle.js`, `cosAgentArchive.js`, `cosAgentIndex.js`) | Covered (#9982 partial): completion, zombie/stale archival, deletion and legacy layout migration lease directory changes through state and index publication; state-locked workflows acquire admission first |
| Game compiled manifests (`games/compile.js`) | Covered (#9982 partial): versioned manifest and game compiled/history pointers hold one lease before the per-game queue |
| Toolkit run creation, CLI/API terminal recording and deletion (`aiToolkit/runner.js`, `internal/runFinalizer.js`) | Covered through the host-injected `withAssetPublication` boundary. Standalone toolkit defaults to direct execution. Terminal hooks run after release; output failures retain truthful persisted byte counts. This does not itself coordinate a separate runner process |
+| Runtime recording completion tails (`runtimeFilePublication.js`, server runner/TUI finalizers, CoS runner completion, loop iterations, TUI spooler) | Covered (#9982 partial): output and completion metadata are admitted together with rollback on write failure; CoS completion retains admission through runner ownership removal. Each parsed/raw spool flush is a short lease, including durable truncation/failure flags. Model execution stays outside. Uses the shared process admission protocol when installed; startup/other runtime lanes remain separately outstanding below |
| Active runtime transcript/metadata pairs (`runner.js`, `tuiPromptRunner.js`, `agentTuiSpawning/outputSpooler.js`, `sessionController.js`) | Outstanding (#9982): output replacement and completion metadata, parsed output/state batches and raw-spool truncation flags span writes and may execute in the separate runner process. The server-local lease cannot establish a cross-process recording cut; requires a coordinated barrier before claiming global consistency |
| Durable replacement/deletion owners not yet classified | Outstanding (#9982) |
| Snapshot consistency claim (`backupAssetOwners.js`, see below) | Covered (#9982 partial) |
diff --git a/server/cos-runner/completion.js b/server/cos-runner/completion.js
new file mode 100644
index 0000000000..f9103debb2
--- /dev/null
+++ b/server/cos-runner/completion.js
@@ -0,0 +1,29 @@
+import { join } from 'path';
+import { readFile } from 'fs/promises';
+import { ensureDir, atomicWrite } from '../lib/fileUtils.js';
+import { publishRuntimeFiles } from '../lib/runtimeFilePublication.js';
+
+export async function persistRunnerCompletion(agentsDir, agentId, output, metadata) {
+ const agentDir = join(agentsDir, agentId);
+ return publishRuntimeFiles([join(agentDir, 'output.txt'), join(agentDir, 'metadata.json')], async () => {
+ await ensureDir(agentDir);
+ // atomicWrite (temp + rename): a crash mid-write must not leave a torn file
+ // that the next completion attempt then chokes on.
+ await atomicWrite(join(agentDir, 'output.txt'), output);
+ if (!metadata) return;
+ const metadataPath = join(agentDir, 'metadata.json');
+ const existing = await readFile(metadataPath, 'utf-8').then(JSON.parse).catch(err => {
+ if (err.code === 'ENOENT') return {};
+ // Unreadable/corrupt prior metadata must not block recording the terminal
+ // result — the new fields below are the authoritative completion evidence.
+ if (err instanceof SyntaxError) {
+ console.warn(`⚠️ Agent ${agentId} metadata.json is corrupt (${err.message}) — rewriting from completion data`);
+ return {};
+ }
+ throw err;
+ });
+ await atomicWrite(metadataPath, {
+ ...existing, agentId, ...metadata, outputSize: Buffer.byteLength(output),
+ });
+ });
+}
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 0f8e7f2ccd..0918fb7d41 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -1,3 +1,5 @@
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
+import { persistRunnerCompletion } from './completion.js';
import { maintenance } from '../lib/maintenanceAdmission.js';
import '../services/databaseBootFence.js';
/**
@@ -19,7 +21,7 @@ import { writeFile, readFile } from 'fs/promises';
import { existsSync } from 'fs';
import http from 'http';
import { Server as SocketServer } from 'socket.io';
-import { ensureDir, atomicWrite, PATHS } from '../lib/fileUtils.js';
+import { ensureDir, PATHS } from '../lib/fileUtils.js';
import { prepareCliSpawn, killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
@@ -128,28 +130,7 @@ registerRunnerShutdownSignals(process, lifecycle);
// commands and new namespace connections as soon as shutdown starts.
io.use((socket, next) => next(lifecycle.isStopping() ? new Error('Runner is shutting down') : undefined));
-async function persistCompletion(agentId, output, metadata) {
- const agentDir = join(AGENTS_DIR, agentId);
- await ensureDir(agentDir);
- // atomicWrite (temp + rename): a crash mid-write must not leave a torn file
- // that the next completion attempt then chokes on.
- await atomicWrite(join(agentDir, 'output.txt'), output);
- if (!metadata) return;
- const metadataPath = join(agentDir, 'metadata.json');
- const existing = await readFile(metadataPath, 'utf-8').then(JSON.parse).catch(err => {
- if (err.code === 'ENOENT') return {};
- // Unreadable/corrupt prior metadata must not block recording the terminal
- // result — the new fields below are the authoritative completion evidence.
- if (err instanceof SyntaxError) {
- console.warn(`⚠️ Agent ${agentId} metadata.json is corrupt (${err.message}) — rewriting from completion data`);
- return {};
- }
- throw err;
- });
- await atomicWrite(metadataPath, {
- ...existing, agentId, ...metadata, outputSize: Buffer.byteLength(output),
- });
-}
+const persistCompletion = (agentId, output, metadata) => persistRunnerCompletion(AGENTS_DIR, agentId, output, metadata);
/**
* Emit event to connected portos-server instances
@@ -692,35 +673,36 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
// Persist output and terminal evidence before publishing completion or
// removing durable ownership. Failed writes leave recovery evidence intact.
- await persistCompletion(agentId, output, paused ? null : {
- taskId,
- completedAt: new Date().toISOString(),
- exitCode: code,
- success: code === 0,
- duration,
- });
- if (paused) {
- activeAgents.delete(agentId);
- return;
- }
+ await withBackupAssetPublication(async () => {
+ await persistCompletion(agentId, output, paused ? null : {
+ taskId,
+ completedAt: new Date().toISOString(),
+ exitCode: code,
+ success: code === 0,
+ duration,
+ });
+ if (paused) {
+ activeAgents.delete(agentId);
+ return;
+ }
- // Emit completion event
- emitToServer('agent:completed', {
- agentId,
- taskId,
- exitCode: code,
- success: code === 0,
- duration,
- outputLength: output.length
- });
+ // Emit completion event
+ emitToServer('agent:completed', {
+ agentId,
+ taskId,
+ exitCode: code,
+ success: code === 0,
+ duration,
+ outputLength: output.length
+ });
- // Update state — serialize with the spawn write path via withState.
- await withState((state) => {
- state.stats.completed++;
- if (code !== 0) state.stats.failed++;
- delete state.agents[agentId];
+ // Update state — serialize with the spawn write path via withState.
+ await withState((state) => {
+ state.stats.completed++;
+ if (code !== 0) state.stats.failed++;
+ delete state.agents[agentId];
+ });
});
-
activeAgents.delete(agentId);
} catch (err) {
lifecycle.reportFailure(err);
diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.js
index ba5cb5cee3..a4c6b1fc8e 100644
--- a/server/cos-runner/index.test.js
+++ b/server/cos-runner/index.test.js
@@ -214,21 +214,3 @@ describe('cos-runner output — ANSI decoloring parity with spawnDirectly', () =
expect(RUNNER_SRC).toMatch(/if \(!trimmedDecolored \|\| isKnownCliStderrNoise\(trimmedDecolored\)\) return;/);
});
});
-
-describe('cos-runner persistCompletion — crash-safe completion evidence', () => {
- const body = RUNNER_SRC.slice(
- RUNNER_SRC.indexOf('async function persistCompletion'),
- RUNNER_SRC.indexOf('Emit event to connected')
- );
-
- it('writes output.txt and metadata.json atomically, not via in-place writeFile', () => {
- expect(body).toMatch(/atomicWrite\(join\(agentDir, 'output\.txt'\)/);
- expect(body).toMatch(/atomicWrite\(metadataPath,/);
- expect(body).not.toMatch(/\bwriteFile\(/);
- });
-
- it('tolerates a corrupt prior metadata.json instead of throwing on JSON.parse', () => {
- expect(body).toMatch(/\.then\(JSON\.parse\)\.catch\(/);
- expect(body).toMatch(/err instanceof SyntaxError/);
- });
-});
diff --git a/server/cos-runner/tuiExit.js b/server/cos-runner/tuiExit.js
index 87a94ef18d..080d348e42 100644
--- a/server/cos-runner/tuiExit.js
+++ b/server/cos-runner/tuiExit.js
@@ -1,3 +1,4 @@
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
/** Finish a runner TUI on observed process exit, even after force-kill reaping. */
import { stripAnsi } from '../lib/ansiStrip.js';
import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';
@@ -49,35 +50,37 @@ export function createTuiExitHandler({ agentId, taskId, sessionId, agent, active
// The terminal buffer contains TUI thinking/repaints. A validated
// sentinel owns the durable user-facing output once it is available.
const completionOutput = resolveCompletionOutput(current);
- await persistCompletion(agentId, completionOutput, current.paused ? null : {
- taskId, completedAt: new Date().toISOString(), exitCode: effectiveExitCode,
- signal: effectiveSignal, success: !!success, duration,
- completionReason: success ? 'agent-signaled-done' : 'tui-exit',
- });
- io.emit('tui:exit', {
- sessionId,
- agentId,
- exitCode: effectiveExitCode,
- signal: effectiveSignal,
- ...(outputTail ? { outputTail } : {}),
- });
- // A pause still needs the transport exit: the server consumes it to
- // release its process map and unblock worktree adoption. Preserve the
- // durable paused record and omit the task-completion verdict.
- if (current.paused === true) return;
- emitToServer('agent:completed', {
- agentId,
- taskId,
- exitCode: effectiveExitCode,
- success,
- duration,
- outputLength: completionOutput.length,
- completionReason: current.completedBySentinel ? 'agent-signaled-done' : 'tui-exit',
- });
- await withState((state) => {
- state.stats.completed++;
- if (!success) state.stats.failed++;
- delete state.agents[agentId];
+ await withBackupAssetPublication(async () => {
+ await persistCompletion(agentId, completionOutput, current.paused ? null : {
+ taskId, completedAt: new Date().toISOString(), exitCode: effectiveExitCode,
+ signal: effectiveSignal, success: !!success, duration,
+ completionReason: success ? 'agent-signaled-done' : 'tui-exit',
+ });
+ io.emit('tui:exit', {
+ sessionId,
+ agentId,
+ exitCode: effectiveExitCode,
+ signal: effectiveSignal,
+ ...(outputTail ? { outputTail } : {}),
+ });
+ // A pause still needs the transport exit: the server consumes it to
+ // release its process map and unblock worktree adoption. Preserve the
+ // durable paused record and omit the task-completion verdict.
+ if (current.paused === true) return;
+ emitToServer('agent:completed', {
+ agentId,
+ taskId,
+ exitCode: effectiveExitCode,
+ success,
+ duration,
+ outputLength: completionOutput.length,
+ completionReason: current.completedBySentinel ? 'agent-signaled-done' : 'tui-exit',
+ });
+ await withState((state) => {
+ state.stats.completed++;
+ if (!success) state.stats.failed++;
+ delete state.agents[agentId];
+ });
});
} catch (err) {
console.error(`❌ TUI agent ${agentId} exit handler error: ${err.message}`);
diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index fecf5d171f..7cbd8ece54 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -437,6 +437,14 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
status: 'admitted',
modules: ['lib/aiToolkit/runner.js', 'lib/aiToolkit/internal/runFinalizer.js'],
},
+ {
+ // Bounded output/metadata replacement, spool ticks and terminal ownership
+ // settlement delegate to the shared process-aware publication boundary.
+ id: 'runtime-recording-publication-tails',
+ status: 'admitted',
+ modules: ['lib/runtimeFilePublication.js', 'services/agentTuiSpawning/outputSpooler.js',
+ 'services/agentTuiSpawning/sessionController.js', 'cos-runner/index.js', 'cos-runner/tuiExit.js'],
+ },
{
// Active run transcripts and their file-primary completion metadata are
// mutated by server and separate CoS/TUI runner processes. Final output
diff --git a/server/lib/runtimeFilePublication.js b/server/lib/runtimeFilePublication.js
new file mode 100644
index 0000000000..d4dd5c2b17
--- /dev/null
+++ b/server/lib/runtimeFilePublication.js
@@ -0,0 +1,26 @@
+import { readFile } from 'fs/promises';
+import { atomicWrite, unlinkGuarded } from './fileUtils.js';
+import { withBackupAssetPublication } from './backupSnapshotBoundary.js';
+import { createKeyCachedQueue } from './createKeyCachedQueue.js';
+
+const queues = createKeyCachedQueue();
+
+/** Publish a bounded runtime recording pair; failure restores its prior bytes. */
+export function publishRuntimeFiles(paths, work) {
+ return withBackupAssetPublication(() => queues(paths[0], async () => {
+ const previous = await Promise.all(paths.map(path => readFile(path).catch(error => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ })));
+ try {
+ return await work();
+ } catch (error) {
+ const rollback = await Promise.allSettled(paths.map((path, i) => previous[i] === null
+ ? unlinkGuarded(path).catch(err => { if (err.code !== 'ENOENT') throw err; })
+ : atomicWrite(path, previous[i])));
+ const failures = rollback.filter(result => result.status === 'rejected').map(result => result.reason);
+ if (failures.length) throw new AggregateError([error, ...failures], 'Runtime recording publication and rollback failed');
+ throw error;
+ }
+ }));
+}
diff --git a/server/services/agentTuiSpawning/outputSpooler.js b/server/services/agentTuiSpawning/outputSpooler.js
index b2c92b3189..68aee6cb21 100644
--- a/server/services/agentTuiSpawning/outputSpooler.js
+++ b/server/services/agentTuiSpawning/outputSpooler.js
@@ -1,3 +1,4 @@
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
/**
* Agent TUI output spooler
*
@@ -49,7 +50,7 @@ export function createTranscriptWriteReporter({ agentId }) {
console.error(`❌ agent ${agentId} ${fileLabel} write failed (${err.code || 'error'}): ${err.message}`);
// Update agent metadata to flag transcript as incomplete
- updateAgent(agentId, { metadata: { transcriptWriteFailed: { file: fileLabel, code: err.code || 'unknown' } } })
+ return updateAgent(agentId, { metadata: { transcriptWriteFailed: { file: fileLabel, code: err.code || 'unknown' } } })
.catch(metaErr => console.error(`❌ agent ${agentId} transcriptWriteFailed metadata write failed: ${metaErr.message}`));
},
};
@@ -96,7 +97,7 @@ export function createOutputSpooler({ agentId, outputFile, rawFile }) {
const reporter = createTranscriptWriteReporter({ agentId });
- const flushPendingLines = async () => {
+ const flushPendingLines = () => withBackupAssetPublication(async () => {
if (flushTimer) { clearTimeout(flushTimer); flushTimer = null; }
if (pendingLines.length === 0) return;
const batch = pendingLines;
@@ -105,13 +106,13 @@ export function createOutputSpooler({ agentId, outputFile, rawFile }) {
appendAgentOutputLines(agentId, batch).catch((err) => reporter.report('state', err)),
appendFile(outputFile, batch.map(l => `${l}\n`).join('')).catch((err) => reporter.report('output.txt', err))
]);
- };
+ });
const scheduleFlush = () => {
if (flushTimer || flushing) return;
flushTimer = setTimeout(() => {
flushTimer = null;
- flushing = flushPendingLines().finally(() => {
+ flushing = flushPendingLines().catch(err => reporter.report('state', err)).finally(() => {
flushing = null;
// Catch chunks that arrived during the in-flight flush — without
// this, a producer that goes quiet right after the flush starts
@@ -131,7 +132,7 @@ export function createOutputSpooler({ agentId, outputFile, rawFile }) {
// scheduleRawFlush is gated by rawFlushing); join() runs once per flush
// tick, so peak in-memory raw data is bounded by one debounce-plus-IO
// window of TUI output (typically hundreds of KB on a chatty agent).
- const flushPendingRawChunks = async () => {
+ const flushPendingRawChunks = () => withBackupAssetPublication(async () => {
if (rawFlushTimer) { clearTimeout(rawFlushTimer); rawFlushTimer = null; }
if (pendingRawChunks.length === 0) return;
const batch = pendingRawChunks.join('');
@@ -159,33 +160,34 @@ export function createOutputSpooler({ agentId, outputFile, rawFile }) {
}
const writeBytes = typeof writeBuf === 'string' ? batchBytes : writeBuf.length;
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}`));
+ // Publish the warning before dropping bytes; if this fails, preserve
+ // the previous spool and retry the warning on the next flush.
+ await updateAgent(agentId, { metadata: { rawSpoolTruncated: true } });
+ rawSpoolTruncationWarned = true;
}
// Only update the byte counter on successful write — a failed write
// would otherwise inflate rawBytesWritten and make subsequent flush
// decisions race the actual on-disk state.
- const wrote = await writeFile(rawFile, writeBuf).then(() => true).catch((err) => {
- reporter.report('raw.txt', err);
+ const wrote = await writeFile(rawFile, writeBuf).then(() => true).catch(async (err) => {
+ await reporter.report('raw.txt', err);
return false;
});
if (wrote) rawBytesWritten = writeBytes;
return;
}
- const wrote = await appendFile(rawFile, batch).then(() => true).catch((err) => {
- reporter.report('raw.txt', err);
+ const wrote = await appendFile(rawFile, batch).then(() => true).catch(async (err) => {
+ await reporter.report('raw.txt', err);
return false;
});
if (wrote) rawBytesWritten += batchBytes;
- };
+ });
const scheduleRawFlush = () => {
if (rawFlushTimer || rawFlushing) return;
rawFlushTimer = setTimeout(() => {
rawFlushTimer = null;
- rawFlushing = flushPendingRawChunks().finally(() => {
+ rawFlushing = flushPendingRawChunks().catch(err => reporter.report('raw.txt', err)).finally(() => {
rawFlushing = null;
// Same re-schedule guard as scheduleFlush: chunks that arrived
// during the in-flight appendFile would otherwise sit until
diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.js
index 85f656b9bd..ecf25e2a2f 100644
--- a/server/services/agentTuiSpawning/sessionController.js
+++ b/server/services/agentTuiSpawning/sessionController.js
@@ -1,3 +1,4 @@
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
/**
* Agent TUI session controller
*
@@ -1197,12 +1198,12 @@ export function createTuiSessionController({
// the metadata patch — and the two that share the state lock still serialize
// on it. `phase` is a breadcrumb only: the record stays `running` on purpose,
// because boot recovery owns the transition.
- await Promise.all([
+ await withBackupAssetPublication(() => Promise.all([
drainLines().catch(() => {}),
drainRaw().catch(() => {}),
persistence.updateAgent(agentId, { metadata: { phase: 'interrupted', interruptedBy: HOST_SHUTDOWN_REASON } })
.catch(err => emitLog('warn', `Could not mark TUI agent ${agentId} interrupted: ${err.message}`, { agentId })),
- ]);
+ ]));
// NOTE: the active-run entry is intentionally left in place — the shutdown
// handler reads that map to name the agents in the host-shutdown marker, and
// there is no reason to shrink it on the way out.
diff --git a/server/services/loops.backupAdmission.test.js b/server/services/loops.backupAdmission.test.js
new file mode 100644
index 0000000000..ed89adeb94
--- /dev/null
+++ b/server/services/loops.backupAdmission.test.js
@@ -0,0 +1,54 @@
+import { afterAll, expect, it, vi } from 'vitest';
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+
+const state = vi.hoisted(() => ({ root: null, beforeWrite: null, providerFinish: null, providerReached: null }));
+state.root = await mkdtemp(join(tmpdir(), 'loop-recording-publication-'));
+const provider = { id: 'example', name: 'Example', defaultModel: 'example-model' };
+vi.mock('../lib/fileUtils.js', async original => {
+ const actual = await original();
+ return { ...actual, PATHS: { ...actual.PATHS, data: state.root }, atomicWrite: async (path, data) => {
+ await state.beforeWrite?.(path, data); return actual.atomicWrite(path, data);
+ } };
+});
+vi.mock('./runner.js', () => ({ createRun: async () => ({ metadata: { id: 'example-run' }, provider }) }));
+vi.mock('./providers.js', () => ({ getActiveProvider: async () => provider, listSelectableProviders: async () => [provider] }));
+vi.mock('./promptRunner.js', () => ({
+ assertProvider() {}, resolveProviderAndModel: async () => ({ provider }),
+ runPromptThroughProvider: async ({ onData }) => {
+ state.providerReached(); await state.providerFinish;
+ onData('example result'); return { text: 'example result', model: 'example-model' };
+ },
+}));
+const { createLoop, triggerLoop, stopLoop, loopEvents } = await import('./loops.js');
+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };
+const turn = () => new Promise(resolve => setImmediate(resolve));
+afterAll(async () => { await rm(state.root, { recursive: true, force: true }); });
+
+it('allows backup during the model run, then drains the loop result through iteration metadata', async () => {
+ const providerReached = deferred(); const providerFinish = deferred();
+ state.providerReached = providerReached.resolve; state.providerFinish = providerFinish.promise;
+ const loop = await createLoop({ prompt: 'example', interval: '1h', runImmediately: false });
+ const reached = deferred(); const finish = deferred();
+ const completed = new Promise(resolve => loopEvents.once('iteration:complete', resolve));
+ try {
+ await triggerLoop(loop.id); await providerReached.promise;
+ const releaseDuringModel = await acquireBackupSnapshotCut(); releaseDuringModel();
+ state.beforeWrite = async (path, data) => {
+ if (path.endsWith('loops.json') && data[0]?.iterationCount === 1) { reached.resolve(); await finish.promise; }
+ };
+ providerFinish.resolve(); await reached.promise;
+ let acquired = false;
+ const cut = acquireBackupSnapshotCut().then(release => { acquired = true; return release; });
+ try { await turn(); expect(acquired).toBe(false); } finally { finish.resolve(); }
+ await completed;
+ const release = await cut;
+ try {
+ expect(await readFile(join(state.root, 'loops', `${loop.id}-1.txt`), 'utf8')).toBe('example result');
+ const loops = JSON.parse(await readFile(join(state.root, 'loops.json'), 'utf8'));
+ expect(loops[0]).toMatchObject({ iterationCount: 1, lastExitCode: 0 });
+ } finally { release(); }
+ } finally { state.beforeWrite = null; await stopLoop(loop.id); }
+});
diff --git a/server/services/loops.js b/server/services/loops.js
index 9684ba0f3b..e519cbec0a 100644
--- a/server/services/loops.js
+++ b/server/services/loops.js
@@ -1,3 +1,4 @@
+import { publishRuntimeFiles } from '../lib/runtimeFilePublication.js';
/**
* Loops Service
*
@@ -141,15 +142,13 @@ async function executeIteration(loopId) {
active.runId = null;
const outputPath = join(LOOPS_OUTPUT_DIR, `${id}-${iterationNum}.txt`);
- // atomicWrite (not a bare writeFile, which is no longer imported) — a bare
- // writeFile here throws ReferenceError synchronously, before .catch() can
- // attach, skipping updatePersistedLoop so lastRun/iterationCount never persist.
- await atomicWrite(outputPath, result).catch(() => {});
-
- await updatePersistedLoop(id, {
- lastRun: Date.now(),
- iterationCount: active.iterationCount,
- lastExitCode: metadata.exitCode
+ await publishRuntimeFiles([outputPath], async () => {
+ await atomicWrite(outputPath, result);
+ await updatePersistedLoop(id, {
+ lastRun: Date.now(),
+ iterationCount: active.iterationCount,
+ lastExitCode: metadata.exitCode
+ });
}).finally(() => {
// Notify after persistence settles, including failures: live execution
// has ended either way, and consumers must leave the running state.
diff --git a/server/services/runner.js b/server/services/runner.js
index 823a1bd9a0..edb9c0ebbf 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -1,3 +1,4 @@
+import { publishRuntimeFiles } from '../lib/runtimeFilePublication.js';
import { maintenance } from '../lib/maintenanceAdmission.js';
/**
* Compatibility shim for PortOS services that import from runner.js
@@ -6,7 +7,7 @@ import { maintenance } from '../lib/maintenanceAdmission.js';
import { spawn } from '../lib/childProcess.js';
import { readFile } from 'fs/promises';
import { join } from 'path';
-import { atomicWrite, ensureDir, tryReadFile, writeFileGuarded, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, tryReadFile, PATHS } from '../lib/fileUtils.js';
import { resolveSpawnCwd } from '../lib/spawnCwd.js';
import { hasModelFlag, extractBakedModel, isCodexProvider } from '../lib/providerModels.js';
import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';
@@ -115,68 +116,71 @@ export async function finalizeRunRecord({ runId, output, exitCode, success, erro
const outputPath = join(runDir, 'output.txt');
const metadataPath = join(runDir, 'metadata.json');
- await writeFileGuarded(outputPath, output).catch(() => maintenance.markCurrentUnsettled());
-
- const metadataStr = await readFile(metadataPath, 'utf-8').catch(() => '{}');
- let metadata = {};
- try { metadata = JSON.parse(metadataStr); } catch { console.log('⚠️ Corrupted metadata for run, using fresh'); }
- // A caller that never went through toolkit `createRun` — or whose run record
- // was lost — leaves `{}` here, and the completion fields below then describe a
- // run with no id, provider or model. That anonymous record still reaches the
- // `onRunFailed` hook, which published an investigation task literally titled
- // "Investigate AI provider failure: undefined (undefined)" and keyed its
- // dedupe + circuit breaker on `undefined-undefined` — one bucket every such
- // failure collapses into, suppressing unrelated real ones for the window.
- // Backfill what the caller already handed us.
- if (!metadata.id) metadata.id = runId;
- for (const [key, value] of Object.entries(identity || {})) {
- if (metadata[key] === undefined && value !== undefined) metadata[key] = value;
- }
- metadata.endTime = new Date().toISOString();
- metadata.duration = Date.now() - startTime;
- metadata.exitCode = exitCode;
- metadata.success = success;
- metadata.outputSize = Buffer.byteLength(output);
- if (error) metadata.error = error;
- if (extras && typeof extras === 'object') Object.assign(metadata, extras);
- const canceled = metadata.canceled === true;
-
- if (!success && canceled) {
- // Cancellation is an operator/host lifecycle outcome, not evidence about
- // provider health. Keep it explicit for /runs without scanning story text
- // (which may contain quota-like words) or firing the provider-failure hook.
- metadata.errorCategory = ERROR_CATEGORIES.CANCELED;
- } else if (!success && toolkit.services.errorDetection) {
- // Exit 124 is the host's authoritative wall-clock timeout. Do not scan the
- // model's entire TUI screen/prompt for a competing category in that case:
- // story text can legitimately contain words such as "credit" or
- // "billing", which used to turn a plain timeout into quota-exceeded and
- // bench a healthy provider for an hour. Other failures still analyze the
- // output because their provider banner is often the only useful signal.
- const analyzeError = toolkit.services.errorDetection.analyzeError;
- const analysisInput = exitCode === 124 ? (error || 'Process timed out') : output;
- let errorAnalysis = analyzeError(analysisInput, exitCode);
- // When that scan lands on nothing, the caller's own `error` is the better
- // evidence — and the run that proved it was a local-LLM playground timeout:
- // the host aborted its OWN deadline, finalized with exit 1 + `Timed out after
- // Nms`, and handed over the partial generation as `output`. Scanning a
- // generation that carries no failure signal returns UNKNOWN with its first
- // line lifted as the "error message", so a plain timeout reached the
- // provider-failure hook as an uncategorized Tier-4 failure titled with the
- // story's own headline. Consulted only as a fallback, so a scan that already
- // found a real category (the CLI/TUI banner case) keeps it.
- if (error && (!errorAnalysis.category || errorAnalysis.category === ERROR_CATEGORIES.UNKNOWN)) {
- const statedAnalysis = analyzeError(error, exitCode);
- if (statedAnalysis.category && statedAnalysis.category !== ERROR_CATEGORIES.UNKNOWN) {
- errorAnalysis = statedAnalysis;
+ const metadata = await publishRuntimeFiles([outputPath, metadataPath], async () => {
+ const metadataStr = await readFile(metadataPath, 'utf-8').catch(() => '{}');
+ let metadata = {};
+ try { metadata = JSON.parse(metadataStr); } catch { console.log('⚠️ Corrupted metadata for run, using fresh'); }
+ // A caller that never went through toolkit `createRun` — or whose run record
+ // was lost — leaves `{}` here, and the completion fields below then describe a
+ // run with no id, provider or model. That anonymous record still reaches the
+ // `onRunFailed` hook, which published an investigation task literally titled
+ // "Investigate AI provider failure: undefined (undefined)" and keyed its
+ // dedupe + circuit breaker on `undefined-undefined` — one bucket every such
+ // failure collapses into, suppressing unrelated real ones for the window.
+ // Backfill what the caller already handed us.
+ if (!metadata.id) metadata.id = runId;
+ for (const [key, value] of Object.entries(identity || {})) {
+ if (metadata[key] === undefined && value !== undefined) metadata[key] = value;
+ }
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = Date.now() - startTime;
+ metadata.exitCode = exitCode;
+ metadata.success = success;
+ metadata.outputSize = Buffer.byteLength(output);
+ if (error) metadata.error = error;
+ if (extras && typeof extras === 'object') Object.assign(metadata, extras);
+ const canceled = metadata.canceled === true;
+
+ if (!success && canceled) {
+ // Cancellation is an operator/host lifecycle outcome, not evidence about
+ // provider health. Keep it explicit for /runs without scanning story text
+ // (which may contain quota-like words) or firing the provider-failure hook.
+ metadata.errorCategory = ERROR_CATEGORIES.CANCELED;
+ } else if (!success && toolkit.services.errorDetection) {
+ // Exit 124 is the host's authoritative wall-clock timeout. Do not scan the
+ // model's entire TUI screen/prompt for a competing category in that case:
+ // story text can legitimately contain words such as "credit" or
+ // "billing", which used to turn a plain timeout into quota-exceeded and
+ // bench a healthy provider for an hour. Other failures still analyze the
+ // output because their provider banner is often the only useful signal.
+ const analyzeError = toolkit.services.errorDetection.analyzeError;
+ const analysisInput = exitCode === 124 ? (error || 'Process timed out') : output;
+ let errorAnalysis = analyzeError(analysisInput, exitCode);
+ // When that scan lands on nothing, the caller's own `error` is the better
+ // evidence — and the run that proved it was a local-LLM playground timeout:
+ // the host aborted its OWN deadline, finalized with exit 1 + `Timed out after
+ // Nms`, and handed over the partial generation as `output`. Scanning a
+ // generation that carries no failure signal returns UNKNOWN with its first
+ // line lifted as the "error message", so a plain timeout reached the
+ // provider-failure hook as an uncategorized Tier-4 failure titled with the
+ // story's own headline. Consulted only as a fallback, so a scan that already
+ // found a real category (the CLI/TUI banner case) keeps it.
+ if (error && (!errorAnalysis.category || errorAnalysis.category === ERROR_CATEGORIES.UNKNOWN)) {
+ const statedAnalysis = analyzeError(error, exitCode);
+ if (statedAnalysis.category && statedAnalysis.category !== ERROR_CATEGORIES.UNKNOWN) {
+ errorAnalysis = statedAnalysis;
+ }
}
+ metadata.error = metadata.error || errorAnalysis.message || `Process exited with code ${exitCode}`;
+ metadata.errorCategory = errorAnalysis.category;
+ metadata.errorAnalysis = errorAnalysis;
}
- metadata.error = metadata.error || errorAnalysis.message || `Process exited with code ${exitCode}`;
- metadata.errorCategory = errorAnalysis.category;
- metadata.errorAnalysis = errorAnalysis;
- }
- await atomicWrite(metadataPath, metadata).catch(() => maintenance.markCurrentUnsettled());
+ await atomicWrite(outputPath, output);
+ await atomicWrite(metadataPath, metadata);
+ return metadata;
+ }).catch(error => { maintenance.markCurrentUnsettled(); throw error; });
+ const canceled = metadata.canceled === true;
// Guarded: these hooks are host-supplied, and every caller of this function
// runs outside the request lifecycle — the /runs route never awaits its
@@ -582,8 +586,6 @@ async function executeAdmittedCliRun({ runId, provider, prompt, workspacePath, s
await cleanupVisionFiles().catch((error) => console.error(`❌ Failed to clean CLI vision files: ${error.message}`));
if (spawnError) console.error(`❌ Run ${runId} spawn error: ${spawnError.message}`);
- await writeFileGuarded(outputPath, output);
-
metadata.endTime = new Date().toISOString();
metadata.duration = Date.now() - startTime;
metadata.exitCode = exitCode;
@@ -628,7 +630,10 @@ async function executeAdmittedCliRun({ runId, provider, prompt, workspacePath, s
metadata.errorAnalysis = errorAnalysis;
}
- await atomicWrite(metadataPath, metadata);
+ await publishRuntimeFiles([outputPath, metadataPath], async () => {
+ await atomicWrite(outputPath, output);
+ await atomicWrite(metadataPath, metadata);
+ });
// Isolate lifecycle hooks from onComplete so a hook failure never changes
// the terminal result or prevents the caller from settling.
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index b3ba9ca0cc..ddc3d9d160 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -263,7 +263,7 @@ describe('finalizeRunRecord — authoritative timeout classification', () => {
});
it('never lets identity overwrite what the stored run record already says', async () => {
- readFile.mockResolvedValueOnce(JSON.stringify({
+ readFile.mockResolvedValue(JSON.stringify({
id: 'run-real', providerId: 'claude-cli', providerName: 'Claude Code', model: 'claude-opus-5',
}));
@@ -277,6 +277,7 @@ describe('finalizeRunRecord — authoritative timeout classification', () => {
identity: { providerId: 'wrong', providerName: 'Wrong', model: 'wrong-model' },
});
+ readFile.mockResolvedValue('{}');
expect(metadata).toMatchObject({
id: 'run-real', providerId: 'claude-cli', providerName: 'Claude Code', model: 'claude-opus-5',
});
@@ -1118,9 +1119,10 @@ describe('executeCliRun — close handler crash guard', () => {
await vi.waitFor(() => expect(onComplete).toHaveBeenCalledTimes(1));
expect(onRunFailed).toHaveBeenCalledTimes(1);
- expect(atomicWrite).toHaveBeenCalledTimes(1);
+ const metadataWrites = atomicWrite.mock.calls.filter(([path]) => path.endsWith('metadata.json'));
+ expect(metadataWrites).toHaveLength(1);
- const persisted = atomicWrite.mock.calls[0][1];
+ const persisted = metadataWrites[0][1];
expect(persisted).toMatchObject({
id: 'run-spawn-error',
providerId: 'configured-provider',
diff --git a/server/services/runtimeRecordings.backupAdmission.test.js b/server/services/runtimeRecordings.backupAdmission.test.js
new file mode 100644
index 0000000000..c0d4d67bbc
--- /dev/null
+++ b/server/services/runtimeRecordings.backupAdmission.test.js
@@ -0,0 +1,138 @@
+import { afterAll, beforeEach, expect, it, vi } from 'vitest';
+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+
+const state = vi.hoisted(() => ({ beforeWrite: null, root: null }));
+state.root = await mkdtemp(join(tmpdir(), 'runtime-recording-publication-'));
+vi.mock('../lib/fileUtils.js', async original => {
+ const actual = await original();
+ return { ...actual, atomicWrite: async (path, data) => {
+ await state.beforeWrite?.(path, data);
+ return actual.atomicWrite(path, data);
+ } };
+});
+vi.mock('./cosAgentLifecycle.js', () => ({
+ appendAgentOutputLines: async (_id, lines) => {
+ const { atomicWrite } = await import('../lib/fileUtils.js');
+ await atomicWrite(join(state.root, 'state.json'), { lines });
+ },
+ updateAgent: async (_id, patch) => {
+ const { atomicWrite } = await import('../lib/fileUtils.js');
+ await atomicWrite(join(state.root, 'state.json'), patch);
+ },
+}));
+vi.mock('../lib/tuiHandshake.js', () => ({ OUTPUT_BUFFER_CAP: 50, OUTPUT_BUFFER_HEADROOM: 100, RAW_SPOOL_MAX_BYTES: 10 }));
+
+const { finalizeRunRecord, setAIToolkit } = await import('./runner.js');
+const { persistRunnerCompletion } = await import('../cos-runner/completion.js');
+const { createTuiExitHandler } = await import('../cos-runner/tuiExit.js');
+const { createOutputSpooler } = await import('./agentTuiSpawning/outputSpooler.js');
+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+const { atomicWrite } = await import('../lib/fileUtils.js');
+const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };
+const turn = () => new Promise(resolve => setImmediate(resolve));
+const readJson = async path => JSON.parse(await readFile(path, 'utf8'));
+
+beforeEach(async () => {
+ state.beforeWrite = null;
+ await rm(state.root, { recursive: true, force: true }); await mkdir(state.root);
+ setAIToolkit({ services: { runner: {} } }, { dataDir: state.root });
+});
+afterAll(async () => { await rm(state.root, { recursive: true, force: true }); });
+
+async function snapshotAfterDraining(work, reached, finish, verify) {
+ await reached;
+ let acquired = false;
+ const cut = acquireBackupSnapshotCut().then(release => { acquired = true; return release; });
+ try { await turn(); expect(acquired, 'the snapshot must drain the whole recording publication').toBe(false); }
+ finally { finish(); }
+ await work;
+ const release = await cut;
+ try { await verify(); } finally { release(); }
+}
+
+it('drains the host TUI/failed-run finalizer through output plus metadata', async () => {
+ const dir = join(state.root, 'runs', 'example'); await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'output.txt'), 'old');
+ await writeFile(join(dir, 'metadata.json'), JSON.stringify({ id: 'example', outputSize: 3 }));
+ const reached = deferred(); const finish = deferred();
+ state.beforeWrite = async path => { if (path.endsWith('metadata.json')) { reached.resolve(); await finish.promise; } };
+ const work = finalizeRunRecord({ runId: 'example', output: 'new result', success: true, exitCode: 0, startTime: Date.now() });
+ await snapshotAfterDraining(work, reached.promise, finish.resolve, async () => {
+ expect(await readFile(join(dir, 'output.txt'), 'utf8')).toBe('new result');
+ expect(await readJson(join(dir, 'metadata.json'))).toMatchObject({ success: true, outputSize: 10 });
+ });
+});
+
+it('rolls back the previous recording when completion metadata fails', async () => {
+ const dir = join(state.root, 'runs', 'example'); await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'output.txt'), 'old');
+ await writeFile(join(dir, 'metadata.json'), JSON.stringify({ id: 'example', outputSize: 3 }));
+ state.beforeWrite = async (path, data) => {
+ if (path.endsWith('metadata.json') && data.success === true) throw new Error('injected metadata failure');
+ };
+ await expect(finalizeRunRecord({ runId: 'example', output: 'new result', success: true, exitCode: 0, startTime: Date.now() }))
+ .rejects.toThrow('injected metadata failure');
+ const release = await acquireBackupSnapshotCut();
+ try {
+ expect(await readFile(join(dir, 'output.txt'), 'utf8')).toBe('old');
+ expect(await readJson(join(dir, 'metadata.json'))).toEqual({ id: 'example', outputSize: 3 });
+ } finally { release(); }
+});
+
+it('keeps a separate-runner TUI recording and durable ownership removal in one cut', async () => {
+ const reached = deferred(); const finish = deferred();
+ const runnerState = { agents: { example: {} }, stats: { completed: 0, failed: 0 } };
+ const runnerStatePath = join(state.root, 'runner-state.json');
+ await writeFile(runnerStatePath, JSON.stringify(runnerState));
+ state.beforeWrite = async path => { if (path === runnerStatePath) { reached.resolve(); await finish.promise; } };
+ const agent = { startedAt: Date.now(), outputBuffer: 'terminal tail', completedBySentinel: true, completionOutput: 'finished' };
+ const exit = createTuiExitHandler({ agentId: 'example', taskId: 'task', sessionId: 'session', agent,
+ activeAgents: new Map([['example', agent]]), io: { emit() {} }, emitToServer() {},
+ persistCompletion: (...args) => persistRunnerCompletion(state.root, ...args),
+ withState: async work => { await work(runnerState); await atomicWrite(runnerStatePath, runnerState); },
+ });
+ await snapshotAfterDraining(exit({ exitCode: 0 }), reached.promise, finish.resolve, async () => {
+ expect(await readFile(join(state.root, 'example', 'output.txt'), 'utf8')).toBe('finished');
+ expect(await readJson(join(state.root, 'example', 'metadata.json'))).toMatchObject({ success: true, outputSize: 8 });
+ expect((await readJson(runnerStatePath)).agents).toEqual({});
+ });
+});
+
+it('holds parsed spool bytes and state through the same snapshot drain', async () => {
+ const reached = deferred(); const finish = deferred();
+ state.beforeWrite = async path => { if (path.endsWith('state.json')) { reached.resolve(); await finish.promise; } };
+ const spool = createOutputSpooler({ agentId: 'example', outputFile: join(state.root, 'output.txt'), rawFile: join(state.root, 'raw.txt') });
+ spool.appendLine('example line');
+ await snapshotAfterDraining(spool.drainLines(), reached.promise, finish.resolve, async () => {
+ expect(await readFile(join(state.root, 'output.txt'), 'utf8')).toBe('example line\n');
+ expect(await readJson(join(state.root, 'state.json'))).toEqual({ lines: ['example line'] });
+ });
+});
+
+it('holds raw truncation and its durable warning through the same snapshot drain', async () => {
+ const reached = deferred(); const finish = deferred();
+ const spool = createOutputSpooler({ agentId: 'example', outputFile: join(state.root, 'output.txt'), rawFile: join(state.root, 'raw.txt') });
+ spool.pushRaw('old bytes'); await spool.drainRaw();
+ state.beforeWrite = async path => { if (path.endsWith('state.json')) { reached.resolve(); await finish.promise; } };
+ spool.pushRaw('new bytes');
+ await snapshotAfterDraining(spool.drainRaw(), reached.promise, finish.resolve, async () => {
+ expect(await readFile(join(state.root, 'raw.txt'), 'utf8')).toBe('new bytes');
+ expect(await readJson(join(state.root, 'state.json'))).toEqual({ metadata: { rawSpoolTruncated: true } });
+ });
+});
+
+
+it('preserves the old raw spool when the truncation warning cannot persist', async () => {
+ const spool = createOutputSpooler({ agentId: 'example', outputFile: join(state.root, 'output.txt'), rawFile: join(state.root, 'raw.txt') });
+ spool.pushRaw('old bytes'); await spool.drainRaw();
+ state.beforeWrite = async path => { if (path.endsWith('state.json')) throw new Error('warning write refused'); };
+ spool.pushRaw('new bytes');
+ await expect(spool.drainRaw()).rejects.toThrow('warning write refused');
+ expect(await readFile(join(state.root, 'raw.txt'), 'utf8')).toBe('old bytes');
+ state.beforeWrite = null;
+ spool.pushRaw('retry'); await spool.drainRaw();
+ expect(await readFile(join(state.root, 'raw.txt'), 'utf8')).toBe('retry');
+ expect(await readJson(join(state.root, 'state.json'))).toEqual({ metadata: { rawSpoolTruncated: true } });
+});