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
fix(backup): admit runtime startup, transcript batches and removal
[._.]/ Adam Eivy2e50100495d7
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 5bc7e19d17..bf4223c5d1 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -114,7 +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 || Beeper attachment mirror (`beeperAttachments.js`) | Covered (#9982 partial): network transfer stays outside admission; content-addressed installation/dedupe and its `local_path` row commit share admission and a path queue with eviction/orphan cleanup. This also protects snapshots that opt into the normally excluded attachment bytes |-| 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 |+| 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 and CLI transcript/state batch is a short lease, including durable truncation/failure flags. Spawn prompt files/run creation/registration publish after forge preparation; old run pruning and feature-agent row/directory deletion are admitted. 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) |diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex 92f346bd98..211383d36b 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -443,7 +443,9 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([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'],+ 'services/agentTuiSpawning/sessionController.js', 'cos-runner/index.js', 'cos-runner/tuiExit.js',+ 'services/agentCliSpawning.js', 'services/agentSpawnDispatch.js',+ 'services/subAgentSpawner.js', 'services/featureAgents.js'],},{id: 'agent-run-recording-publication',diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 0d09b11d1c..c86493d6a7 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -1,3 +1,4 @@+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { maintenance } from '../lib/maintenanceAdmission.js';import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';/**@@ -16,7 +17,7 @@ import { cosEvents, emitLog } from './cosEvents.js';// The DEFINING module, not a barrel (#3450) — see the note in// `agentManagement.js`. This module is a LEAF that `agentLifecycle.js` imports,// which puts it inside the facade's closure, so the facade is out of reach here.-import { updateAgent, completeAgent, createAgentOutputBatcher } from './cosAgentLifecycle.js';+import { updateAgent, completeAgent, createAgentOutputBatcher, appendAgentOutputLines } from './cosAgentLifecycle.js';import { release } from './executionLanes.js';import { completeExecution, errorExecution } from './toolStateMachine.js';import { analyzeAgentFailure } from './agentErrorAnalysis.js';@@ -420,12 +421,22 @@ export async function spawnDirectly({// 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.)+ // handlers `await outputBatcher.flush()` so the final transcript and state+ // lines persist as one admitted batch before the agent is finalized.// Findings stay in the local transcript/report, never the shared agent stream.- const outputBatcher = isPrivateSecurityTask(task)- ? { push() {}, async flush() {} }- : createAgentOutputBatcher(agentId);+ const outputBatcher = createAgentOutputBatcher(agentId, { flushBatch: batch => {+ // Capture bytes at the same instant as this batch, before waiting for the+ // cut. Chunks received during I/O belong to the next flush, not this pair.+ const bytes = outputBuffer;+ return withBackupAssetPublication(() => Promise.all([+ writeFileGuarded(outputFile, bytes).catch(err => {+ maintenance.markResourceUnsettled('agent', agentId);+ return transcriptWriteReporter.report('output.txt', err);+ }),+ isPrivateSecurityTask(task) ? undefined : appendAgentOutputLines(agentId, batch)+ .catch(err => transcriptWriteReporter.report('state', err)),+ ]));+ } });if (ollamaContext?.warning) outputBatcher.push(ollamaContext.warning);if (ollamaContext?.applied) outputBatcher.push(`🪟 Reloaded Ollama at a ${ollamaContext.contextLength}-token context window`);@@ -442,11 +453,9 @@ export async function spawnDirectly({await outputBatcher.flush();};- // Serialize the transcript-mutating body of every stdout/stderr `data` event- // onto a single per-agent tail promise. Both handlers mutate the same shared- // `outputBuffer`/`rawStreamBuffer` and write the same `output.txt`, so their- // interleaved awaits (e.g. one chunk's `writeFile` yielding while the next- // chunk appends) would otherwise reorder the transcript (#2384). Fallback+ // Serialize stdout/stderr buffer updates before their shared debounced file+ // and state flush, so interleaved setup awaits cannot reorder the transcript+ // (#2384). Fallback// detection stays OUTSIDE this chain — it runs synchronously in the raw// listener before the enqueue, so a blocked earlier write can never delay// killing the provider on a usage-limit signal. The close/error handlers@@ -520,10 +529,6 @@ export async function spawnDirectly({const lines = streamParser.processChunk(text);for (const line of lines) outputBuffer += line + '\n';outputBatcher.push(lines);- await writeFileGuarded(outputFile, outputBuffer).catch((err) => {- maintenance.markResourceUnsettled('agent', agentId);- transcriptWriteReporter.report('output.txt', err);- });} else {// Non-stream providers: emit stdout as-is once decolored. A chunk that// was purely terminal control has nothing left to show. Unlike stderr@@ -531,10 +536,6 @@ export async function spawnDirectly({// formatting when it isn't wearing an `[stderr]` tag.if (!text) return;outputBuffer += text;- await writeFileGuarded(outputFile, outputBuffer).catch((err) => {- maintenance.markResourceUnsettled('agent', agentId);- transcriptWriteReporter.report('output.txt', err);- });outputBatcher.push(text);}});@@ -556,10 +557,6 @@ export async function spawnDirectly({const lines = codexStderrFormatter.processChunk(text);for (const line of lines) outputBuffer += line + '\n';outputBatcher.push(lines);- await writeFileGuarded(outputFile, outputBuffer).catch((err) => {- maintenance.markResourceUnsettled('agent', agentId);- transcriptWriteReporter.report('output.txt', err);- });return;}// A chunk that decolors down to whitespace was pure terminal control@@ -568,10 +565,6 @@ export async function spawnDirectly({const trimmed = text.trim();if (!trimmed || isKnownCliStderrNoise(trimmed)) return;outputBuffer += `[stderr] ${text}`;- await writeFileGuarded(outputFile, outputBuffer).catch((err) => {- maintenance.markResourceUnsettled('agent', agentId);- transcriptWriteReporter.report('output.txt', err);- });outputBatcher.push(`[stderr] ${text}`);});} catch (err) {@@ -734,11 +727,12 @@ export async function spawnDirectly({// 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 writeFileGuarded(outputFile, outputBuffer).catch((err) => {- maintenance.markResourceUnsettled('agent', agentId);- transcriptWriteReporter.report('output.txt', err);+ await withBackupAssetPublication(async () => {+ await outputBatcher.flush();+ await writeFileGuarded(outputFile, outputBuffer).catch((err) => {+ maintenance.markResourceUnsettled('agent', agentId);+ return transcriptWriteReporter.report('output.txt', err);+ });});// The teardown both in-process spawners share: paused early return, thendiff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 88429bd604..b0e39c88b0 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -2,6 +2,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { EventEmitter } from 'events';import { join } from 'path';+// This suite doubles fs.existsSync for spawn branches; it must not invent a database fence.+vi.mock('../lib/databaseMaintenanceJournal.js', () => ({ assertDatabaseAdmission() {} }));+// Heavy modules needed only by spawnDirectly — mock them all before importing.vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() }, emitLog: vi.fn() }));vi.mock('./cosAgentLifecycle.js', () => {@@ -11,7 +14,7 @@ vi.mock('./cosAgentLifecycle.js', () => {// and, on flush(), routes them through the mocked appendAgentOutputLines while// swallowing+logging failures (mirrors the real createAgentOutputBatcher in// cosAgentLifecycle.js — whose error handling is unit-tested in cosAgentLifecycle.test.js).- const createAgentOutputBatcher = vi.fn((agentId) => {+ const createAgentOutputBatcher = vi.fn((agentId, { flushBatch } = {}) => {let pending = [];return {push(lineOrLines) {@@ -22,7 +25,7 @@ vi.mock('./cosAgentLifecycle.js', () => {if (pending.length === 0) return;const batch = pending;pending = [];- await appendAgentOutputLines(agentId, batch).catch((err) =>+ await (flushBatch ? flushBatch(batch) : appendAgentOutputLines(agentId, batch)).catch((err) =>console.error(`❌ agent ${agentId} output batch flush failed: ${err.message}`));},};@@ -778,7 +781,7 @@ describe('stream error containment', () => {// Assert: error was swallowed into console.error, not an unhandled rejectionexpect(unhandledRejections).toHaveLength(0);const logged = consoleSpy.mock.calls.some(- (args) => typeof args[0] === 'string' && args[0].startsWith('❌ agent agent-test output batch flush failed:')+ (args) => typeof args[0] === 'string' && args[0].startsWith('❌ agent agent-test state write failed'));expect(logged).toBe(true);});@@ -841,11 +844,61 @@ describe('stream error containment', () => {expect(unhandledRejections).toHaveLength(0);const logged = consoleSpy.mock.calls.some(- (args) => typeof args[0] === 'string' && args[0].startsWith('❌ agent agent-test output batch flush failed:')+ (args) => typeof args[0] === 'string' && args[0].startsWith('❌ agent agent-test state write failed'));expect(logged).toBe(true);});+ it('publishes a CLI transcript flush with its state batch before admitting a snapshot', async () => {+ const fs = await vi.importActual('node:fs/promises');+ const { tmpdir } = await import('node:os');+ const { writeFileGuarded } = await import('../lib/fileUtils.js');+ const { activeAgents } = await import('./agentState.js');+ const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');+ const dir = await fs.mkdtemp(join(tmpdir(), 'cli-publication-'));+ let reached; let finish;+ const reachedPromise = new Promise(resolve => { reached = resolve; });+ const finishPromise = new Promise(resolve => { finish = resolve; });+ writeFileGuarded.mockImplementation((path, bytes) => fs.writeFile(path, bytes));+ const persistedLines = [];+ agentStateMocks.appendAgentOutputLines.mockImplementation(async (_id, batch) => {+ reached(); await finishPromise;+ persistedLines.push(...batch);+ await fs.writeFile(join(dir, 'state.json'), JSON.stringify({ lines: persistedLines }));+ });+ try {+ await spawnDirectly({ ...minimalArgs, agentDir: dir,+ cliConfig: { command: 'claude', args: [], stdinMode: 'prompt', streamFormat: 'text' } });+ fakeProcess.stdout.emit('data', Buffer.from('complete batch\n'));+ const flushing = activeAgents.get('agent-test').flushOutput();+ await reachedPromise;+ // A later chunk must not change either member of the in-flight batch.+ fakeProcess.stdout.emit('data', Buffer.from('later batch\n'));+ await new Promise(resolve => setImmediate(resolve));+ let acquired = false;+ const cut = acquireBackupSnapshotCut().then(release => { acquired = true; return release; });+ try { await new Promise(resolve => setImmediate(resolve)); expect(acquired).toBe(false); }+ finally { finish(); }+ await flushing;+ const release = await cut;+ try {+ expect(await fs.readFile(join(dir, 'output.txt'), 'utf8')).toBe('complete batch\n');+ expect(JSON.parse(await fs.readFile(join(dir, 'state.json'), 'utf8')).lines).toEqual(['complete batch\n']);+ } finally { release(); }+ await activeAgents.get('agent-test').flushOutput();+ expect(await fs.readFile(join(dir, 'output.txt'), 'utf8')).toBe('complete batch\nlater batch\n');+ expect(JSON.parse(await fs.readFile(join(dir, 'state.json'), 'utf8')).lines)+ .toEqual(['complete batch\n', 'later batch\n']);+ fakeProcess.emit('close', 0);+ await vi.waitFor(() => expect(runSpawnerCompletionCleanup).toHaveBeenCalled());+ } finally {+ finish();+ writeFileGuarded.mockResolvedValue(undefined);+ agentStateMocks.appendAgentOutputLines.mockResolvedValue(undefined);+ await fs.rm(dir, { recursive: true, force: true });+ }+ });+it('detects a fallback signal and terminates immediately even while an earlier transcript write is blocked, keeping output ordered (#2384)', async () => {killProcessTree.mockClear();diff --git a/server/services/agentSpawnDispatch.js b/server/services/agentSpawnDispatch.jsindex b99311562c..525031b332 100644--- a/server/services/agentSpawnDispatch.js+++ b/server/services/agentSpawnDispatch.js@@ -1,3 +1,4 @@+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { join } from 'path';import { existsSync } from 'fs';import { getConfig, updateTask } from './cos.js';@@ -159,24 +160,6 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {});}- const agentDir = join(AGENTS_DIR, agentId);- if (!existsSync(agentDir)) {- await ensureDir(agentDir);- }- await writeFileGuarded(join(agentDir, 'prompt.txt'), prompt);- let systemPromptFile = null;- if (systemPrompt) {- systemPromptFile = join(agentDir, 'system-prompt.md');- await writeFileGuarded(systemPromptFile, systemPrompt);- }- const { runId } = await createAgentRun({- agentId,- task,- model: selectedModel,- provider,- workspacePath,- appName: resolvedAppName,- });const executionMode = resolveExecutionMode({ spawnHeadless, useRunner: dispatchUseRunner });const sourceWorkspace = worktreeInfo? (task.metadata?.app ? await getAppWorkspace(task.metadata.app) : ROOT_DIR)@@ -195,31 +178,52 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {: resolveRepoForgeTarget(workspacePath),sourceWorkspace ? capturePrimaryCheckoutState(sourceWorkspace) : null,]);- await registerAgent(agentId, task.id, buildAgentRegistration({- task,- provider,- instanceId,- workspacePath,- sourceWorkspace,- repoIssueUrl: repoIssueUrlBase(forgeTarget),- primaryCheckoutBaseline,- worktreeInfo,- explicitWorktree,- jiraBranchName,- providerEndpoint: providerBaseUrl(provider),- localPromptBudget,- leanMode,- prOpenedBy,- claimFlowTask,- selectedModel,- effort: taskEffort,- modelSelection,- runId,- dispatchUseRunner,- executionMode,- publicReviewPosture,- resolvedAppName,- }));+ let systemPromptFile = null;+ const { runId } = await withBackupAssetPublication(async () => {+ const agentDir = join(AGENTS_DIR, agentId);+ if (!existsSync(agentDir)) {+ await ensureDir(agentDir);+ }+ await writeFileGuarded(join(agentDir, 'prompt.txt'), prompt);+ if (systemPrompt) {+ systemPromptFile = join(agentDir, 'system-prompt.md');+ await writeFileGuarded(systemPromptFile, systemPrompt);+ }+ const { runId } = await createAgentRun({+ agentId,+ task,+ model: selectedModel,+ provider,+ workspacePath,+ appName: resolvedAppName,+ });+ await registerAgent(agentId, task.id, buildAgentRegistration({+ task,+ provider,+ instanceId,+ workspacePath,+ sourceWorkspace,+ repoIssueUrl: repoIssueUrlBase(forgeTarget),+ primaryCheckoutBaseline,+ worktreeInfo,+ explicitWorktree,+ jiraBranchName,+ providerEndpoint: providerBaseUrl(provider),+ localPromptBudget,+ leanMode,+ prOpenedBy,+ claimFlowTask,+ selectedModel,+ effort: taskEffort,+ modelSelection,+ runId,+ dispatchUseRunner,+ executionMode,+ publicReviewPosture,+ resolvedAppName,+ }));+ return { runId };+ });emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });const newSpawnCount = (Number(task.metadata?.totalSpawnCount) || 0) + 1;diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex ba70fe5721..3a44e65456 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -2906,7 +2906,7 @@ describe('spawnTuiAgent runtime', () => {await spawnPromise;- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);+ await vi.waitFor(() => expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1));// The completed-agent details view reads output.txt (getAgent) and the// in-state output stream (live view / fallback). Both must carry the@@ -3024,9 +3024,9 @@ describe('spawnTuiAgent runtime', () => {await flushMicrotasks();await spawnPromise;- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ await vi.waitFor(() => expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'agent-1', success: true })- );+ ));});// The backstop for a SIGKILL'd or crashed portos-server, which never runs itsdiff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex 434425f343..5bbc84bc5e 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -322,7 +322,7 @@ const OUTPUT_FLUSH_INTERVAL_MS = 250;//// 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 } = {}) {+export function createAgentOutputBatcher(agentId, { intervalMs = OUTPUT_FLUSH_INTERVAL_MS, flushBatch } = {}) {let pending = [];let timer = null;let flushing = null;@@ -338,7 +338,7 @@ export function createAgentOutputBatcher(agentId, { intervalMs = OUTPUT_FLUSH_IN// 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) => {+ await (flushBatch ? flushBatch(batch) : appendAgentOutputLines(agentId, batch)).catch((err) => {console.error(`❌ agent ${agentId} output batch flush failed: ${err.message}`);});};diff --git a/server/services/featureAgents.js b/server/services/featureAgents.jsindex 269bab6016..8cac04c7e4 100644--- a/server/services/featureAgents.js+++ b/server/services/featureAgents.js@@ -1,3 +1,4 @@+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';/*** Feature Agents Service*@@ -138,7 +139,7 @@ export async function updateFeatureAgent(id, updates) {* Delete a feature agent and clean up resources*/export async function deleteFeatureAgent(id) {- return withLock(async () => {+ return withBackupAssetPublication(() => withLock(async () => {const data = await readData();const idx = data.agents.findIndex(a => a.id === id);if (idx === -1) return false;@@ -169,7 +170,7 @@ export async function deleteFeatureAgent(id) {console.log(`🤖 Feature agent deleted: ${agent.name} (${id})`);cosEvents.emit(`${EVT}:status`, { id, status: 'deleted', name: agent.name });return true;- });+ }));}/**diff --git a/server/services/runtimeDeletion.backupAdmission.test.js b/server/services/runtimeDeletion.backupAdmission.test.jsnew file mode 100644index 0000000000..52a9212dfe--- /dev/null+++ b/server/services/runtimeDeletion.backupAdmission.test.js@@ -0,0 +1,60 @@+import { afterAll, expect, it, vi } from 'vitest';+import { mkdir, readFile, writeFile, utimes, access } from 'node:fs/promises';+import { join } from 'node:path';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'runtime-deletion-' });+const seam = vi.hoisted(() => ({ beforeRemove: null }));+vi.mock('../lib/fileUtils.js', async original => {+ const actual = await original();+ return { ...makeProxy(actual), rmGuarded: async (...args) => { await seam.beforeRemove?.(args[0]); return actual.rmGuarded(...args); } };+});+vi.mock('./apps.js', () => ({ getAppById: async () => null }));+vi.mock('./providerStatus.js', () => ({ initProviderStatus: async () => {} }));+vi.mock('./cosRunnerClient.js', () => ({ isRunnerAvailable: async () => false, isRunnerReachable: async () => false,+ initCosRunnerConnection() {}, onCosRunnerEvent() {} }));+vi.mock('./agentManagement.js', () => ({ cleanupOrphanedAgents: async () => {} }));+vi.mock('./agentOrchestrator.js', () => ({ spawnAgentForTask: async () => {}, terminateAgent: async () => {} }));+vi.mock('./agentLifecycle.js', () => ({ handleAgentCompletion: async () => {} }));+vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: async () => {} }));+const { createFeatureAgent, deleteFeatureAgent } = await import('./featureAgents.js');+const { initSpawner } = await import('./subAgentSpawner.js');+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');+const { PATHS } = await import('../lib/fileUtils.js');+const turn = () => new Promise(resolve => setImmediate(resolve));+const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };+afterAll(cleanup);++it('drains feature-agent row removal through deletion of its run directory', async () => {+ const agent = await createFeatureAgent({ name: 'Example', appId: 'example' });+ const dir = join(tempRoot, 'cos', 'feature-agents', agent.id); await mkdir(dir, { recursive: true });+ await writeFile(join(dir, 'recording.txt'), 'example recording');+ const reached = deferred(); const finish = deferred();+ seam.beforeRemove = async path => { if (path === dir) { reached.resolve(); await finish.promise; } };+ const deletion = deleteFeatureAgent(agent.id); 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 deletion;+ const release = await cut;+ try {+ expect(JSON.parse(await readFile(join(tempRoot, 'cos', 'feature-agents.json'), 'utf8')).agents).toEqual([]);+ await expect(access(dir)).rejects.toMatchObject({ code: 'ENOENT' });+ } finally { release(); seam.beforeRemove = null; }+});++it('defers startup recording pruning until the active backup cut finishes', async () => {+ const dir = join(PATHS.runs, 'old-run'); await mkdir(dir, { recursive: true });+ await writeFile(join(dir, 'metadata.json'), JSON.stringify({ id: 'old-run', outputSize: 7 }));+ await writeFile(join(dir, 'output.txt'), 'example');+ const old = new Date(Date.now() - 40 * 24 * 3600000); await utimes(dir, old, old);+ const release = await acquireBackupSnapshotCut();+ let settled = false;+ const init = initSpawner().then(() => { settled = true; });+ try {+ await turn(); await turn();+ expect(settled).toBe(false);+ expect(await readFile(join(dir, 'output.txt'), 'utf8')).toBe('example');+ } finally { release(); }+ await init;+ await expect(access(dir)).rejects.toMatchObject({ code: 'ENOENT' });+});diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 444c3ca521..ed41cfbd51 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -1,3 +1,4 @@+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { maintenance, isMaintenanceHold } from '../lib/maintenanceAdmission.js';/*** Sub-Agent Spawner Service — the agent cluster's EVENT WIRING.@@ -261,7 +262,7 @@ async function runInitSpawner() {const runDir = join(RUNS_DIR, entry.name);const dirStat = await stat(runDir).catch(() => null);if (dirStat && dirStat.mtime.getTime() < cutoff) {- await rmGuarded(runDir, { recursive: true }).catch(() => {});+ await withBackupAssetPublication(() => rmGuarded(runDir, { recursive: true })).catch(() => {});pruned++;}}