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: admit agent usage recording file pairs

[._.]/ Adam Eivy6bd97213a292
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index b0ee39ef60..04ededbd88 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -114,6 +114,7 @@ Admission inventory (`withBackupAssetPublication`):
| 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 |
+| Agent usage run creation and completion (`agentRunTracking.js`) | Covered: prompt/output creation precedes metadata inside one lease; completion holds output replacement through terminal metadata, with usage and event callbacks after release |
| 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/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index 7cbd8ece54..0e9aba114e 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -445,6 +445,11 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
modules: ['lib/runtimeFilePublication.js', 'services/agentTuiSpawning/outputSpooler.js',
'services/agentTuiSpawning/sessionController.js', 'cos-runner/index.js', 'cos-runner/tuiExit.js'],
},
+ {
+ id: 'agent-run-recording-publication',
+ status: 'admitted',
+ modules: ['services/agentRunTracking.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/services/agentRunTracking.backupAdmission.test.js b/server/services/agentRunTracking.backupAdmission.test.js
new file mode 100644
index 0000000000..ea8fc1f022
--- /dev/null
+++ b/server/services/agentRunTracking.backupAdmission.test.js
@@ -0,0 +1,64 @@
+import { afterAll, beforeEach, expect, it, vi } from 'vitest';
+import { mkdir, readFile, readdir, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+let beforeWrite = async () => {};
+let bypass = false;
+vi.mock('../lib/fileUtils.js', async importOriginal => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, { dataRoot: () => lazyTempDataRoot('agent-recording-backup-'), overrides: {
+ atomicWrite: async (path, data) => { await beforeWrite(path); return actual.atomicWrite(path, data); },
+ } });
+});
+vi.mock('../lib/backupSnapshotBoundary.js', async importOriginal => {
+ const actual = await importOriginal();
+ return { ...actual, withBackupAssetPublication: work => bypass ? work() : actual.withBackupAssetPublication(work) };
+});
+vi.mock('./usage.js', () => ({ recordSession: async () => {} }));
+vi.mock('./usageReconciler.js', () => ({ recordCompletedRunUsage: () => {} }));
+vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent: async () => {} }));
+vi.mock('../lib/gitCommitProbe.js', () => ({ committedDuringRun: async () => false }));
+const { PATHS } = await import('../lib/fileUtils.js');
+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+const { createAgentRun, completeAgentRun } = await import('./agentRunTracking.js');
+const create = () => createAgentRun({ agentId: 'example-agent', task: { id: 'example-task', description: 'Example prompt' }, provider: { id: 'example-provider', name: 'Example', defaultModel: 'example-model' } });
+const capture = async dir => ({ output: await readFile(join(dir, 'output.txt'), 'utf8'), metadata: JSON.parse(await readFile(join(dir, 'metadata.json'), 'utf8')) });
+const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };
+const settle = () => new Promise(resolve => setImmediate(resolve));
+beforeEach(async () => { beforeWrite = async () => {}; bypass = false; await rm(PATHS.data, { recursive: true, force: true }); await mkdir(PATHS.runs, { recursive: true }); });
+afterAll(cleanupTempDataRoots);
+it('does not publish creation files during a cut', async () => {
+ const release = await acquireBackupSnapshotCut(); let writes = 0;
+ beforeWrite = async () => { writes++; };
+ const work = create();
+ try { await settle(); await settle(); expect(writes).toBe(0); } finally { release(); }
+ const { runDir } = await work;
+ expect((await readdir(runDir)).sort()).toEqual(['metadata.json', 'output.txt', 'prompt.txt']);
+});
+it('blocks completion output and metadata during a cut', async () => {
+ const { runId, runDir } = await create(); const before = await capture(runDir);
+ const release = await acquireBackupSnapshotCut(); const work = completeAgentRun(runId, 'Example output', 0, 10);
+ try { await settle(); await settle(); expect(await capture(runDir)).toEqual(before); } finally { release(); }
+ await work; const after = await capture(runDir); expect(after.metadata.outputSize).toBe(Buffer.byteLength(after.output));
+});
+it('drains the actual output write through terminal metadata', async () => {
+ const { runId, runDir } = await create(); const reached = deferred(); const commit = deferred();
+ beforeWrite = async path => { if (path.endsWith('metadata.json')) { reached.resolve(); await commit.promise; } };
+ const work = completeAgentRun(runId, 'Example output', 0, 10); await reached.promise;
+ let ready = false; const cut = acquireBackupSnapshotCut().then(release => { ready = true; return release; });
+ try { await settle(); expect(ready).toBe(false); } finally { commit.resolve(); }
+ await work; const release = await cut;
+ try { const after = await capture(runDir); expect(after.metadata.outputSize).toBe(Buffer.byteLength(after.output)); } finally { release(); }
+});
+it('negative control exposes terminal metadata for output absent from the earlier copy', async () => {
+ const { runId, runDir } = await create(); bypass = true;
+ const release = await acquireBackupSnapshotCut();
+ try { const copied = (await capture(runDir)).output; await completeAgentRun(runId, 'Example output', 0, 10); expect((await capture(runDir)).metadata.outputSize).not.toBe(Buffer.byteLength(copied)); }
+ finally { release(); }
+});
+it('does not stamp terminal metadata when output persistence fails', async () => {
+ const { runId, runDir } = await create(); const before = await capture(runDir);
+ beforeWrite = async path => { if (path.endsWith('output.txt')) throw new Error('synthetic write failure'); };
+ await expect(completeAgentRun(runId, 'Example output', 0, 10)).rejects.toThrow('synthetic write failure');
+ expect(await capture(runDir)).toEqual(before);
+});
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index 567f0a6477..a0b25d922b 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -5,6 +5,7 @@
*/
import { join } from 'path';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { mkdir } from 'fs/promises';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { recordSession } from './usage.js';
@@ -58,9 +59,11 @@ export async function createAgentRun({ agentId, task, model, provider, workspace
outputSize: 0
};
- await atomicWrite(join(runDir, 'metadata.json'), metadata);
- await atomicWrite(join(runDir, 'prompt.txt'), task.description || '');
- await atomicWrite(join(runDir, 'output.txt'), '');
+ await withBackupAssetPublication(async () => {
+ await atomicWrite(join(runDir, 'prompt.txt'), task.description || '');
+ await atomicWrite(join(runDir, 'output.txt'), '');
+ await atomicWrite(join(runDir, 'metadata.json'), metadata);
+ });
// Record usage session for CoS agent
recordSession(provider.id, provider.name, model || provider.defaultModel).catch(err => {
@@ -151,8 +154,10 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA
// Persist output first so endTime remains the durable completion marker. If
// this write fails, the still-open metadata lets recovery retry the whole
// operation; once metadata lands, every run artifact is already complete.
- await atomicWrite(join(runDir, 'output.txt'), output || '');
- await atomicWrite(metaPath, metadata);
+ await withBackupAssetPublication(async () => {
+ await atomicWrite(join(runDir, 'output.txt'), output || '');
+ await atomicWrite(metaPath, metadata);
+ });
// Record usage for every completed CoS agent run: failed and interrupted
// providers still consumed tokens. Prefers the provider CLI's own