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: inject recording publication admission into the AI toolkit

[._.]/ Adam Eivya9ce85b4355e
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 8fb73d9db5..df88c56036 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -112,6 +112,7 @@ Admission inventory (`withBackupAssetPublication`):
| CoS raw recording compression and purge (`cosAgentStorage.js`) | Covered (#9982 partial): verified gzip publication, storage manifest and plain-file removal share a lease; purge intent and unlinks also share a lease because the manifest is file-primary |
| 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 |
| 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/aiToolkit/index.js b/server/lib/aiToolkit/index.js
index 47b7d72f13..b846bb1797 100644
--- a/server/lib/aiToolkit/index.js
+++ b/server/lib/aiToolkit/index.js
@@ -52,6 +52,7 @@ export function createAIToolkit(config = {}) {
// error page). PortOS injects its own asyncHandler (→ errorMiddleware).
asyncHandler = defaultAsyncHandler,
withRunAdmission = handler => handler,
+ withAssetPublication = work => work(),
// Host-injected HTTP error class (PortOS passes its `ServerError` so route
// errors normalize into `{ error, code, timestamp, context? }`). Threaded
// to every router; routes default to the toolkit's own ToolkitHttpError
@@ -103,6 +104,7 @@ export function createAIToolkit(config = {}) {
}
const runnerService = createRunnerService({
+ withAssetPublication,
dataDir,
runsDir,
screenshotsDir,
diff --git a/server/lib/aiToolkit/internal/runFinalizer.js b/server/lib/aiToolkit/internal/runFinalizer.js
index 3e55d11a14..d38c9fa9a4 100644
--- a/server/lib/aiToolkit/internal/runFinalizer.js
+++ b/server/lib/aiToolkit/internal/runFinalizer.js
@@ -25,10 +25,15 @@ export function createRunFinalizer({
safeJsonParse,
consumeActiveStop,
onPersistenceFailure,
+ withAssetPublication = work => work(),
}) {
const pendingHooks = [];
const failed = () => onPersistenceFailure?.();
- const settleTerminal = (fn, label) => {
+ // Invoke host callbacks only after releasing the recording lease. Hooks can
+ // publish their own assets or wait for other admitted work.
+ const terminalCallbacks = [];
+ const settleTerminal = (fn, label) => terminalCallbacks.push({ fn, label });
+ const runTerminal = (fn, label) => {
try {
const result = fn();
if (result?.then) pendingHooks.push(Promise.resolve(result).catch(err => {
@@ -53,7 +58,7 @@ export function createRunFinalizer({
const openTerminalMetadata = async () => {
const state = terminalState();
- if (state.partialOutput) await atomicWrite(outputPath, state.partialOutput).catch(failed);
+ await atomicWrite(outputPath, state.partialOutput);
const metadata = await readMetadata();
metadata.endTime = new Date().toISOString();
metadata.duration = Date.now() - startTime;
@@ -81,9 +86,9 @@ export function createRunFinalizer({
await atomicWrite(metadataPath, metadata);
if (typeof providerStatusService?.markApiSuccess === 'function') {
- await providerStatusService.markApiSuccess(provider.id).catch(err => {
+ settleTerminal(() => providerStatusService.markApiSuccess(provider.id).catch(err => {
console.error(`❌ Failed to clear provider rate-limit state: ${err.message}`);
- });
+ }), `Run ${runId} provider success hook`);
}
settleTerminal(() => hooks.onRunCompleted?.(metadata, output), `Run ${runId} onRunCompleted hook`);
@@ -97,7 +102,7 @@ export function createRunFinalizer({
failMetadata.success = false;
failMetadata.error = `Run finalization failed: ${writeErr.message}`;
failMetadata.errorCategory = ERROR_CATEGORIES.UNKNOWN;
- failMetadata.outputSize = Buffer.byteLength(getOutput());
+ failMetadata.outputSize = (await readFile(outputPath).catch(() => '')).length;
await atomicWrite(metadataPath, failMetadata).catch(failed);
settleTerminal(() => hooks.onRunFailed?.(failMetadata, failMetadata.error, getOutput()), `Run ${runId} onRunFailed hook`);
settleTerminal(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);
@@ -168,7 +173,7 @@ export function createRunFinalizer({
if (errorAnalysis.hasError &&
(errorAnalysis.category === ERROR_CATEGORIES.RATE_LIMIT ||
errorAnalysis.category === ERROR_CATEGORIES.USAGE_LIMIT)) {
- await handleProviderError(provider.id, errorAnalysis, body);
+ settleTerminal(() => handleProviderError(provider.id, errorAnalysis, body), `Run ${runId} provider error hook`);
}
await atomicWrite(metadataPath, metadata);
@@ -187,7 +192,7 @@ export function createRunFinalizer({
if (errorAnalysis.hasError &&
(errorAnalysis.category === ERROR_CATEGORIES.RATE_LIMIT ||
errorAnalysis.category === ERROR_CATEGORIES.USAGE_LIMIT)) {
- await handleProviderError(provider.id, errorAnalysis, partialOutput);
+ settleTerminal(() => handleProviderError(provider.id, errorAnalysis, partialOutput), `Run ${runId} provider error hook`);
}
await atomicWrite(metadataPath, metadata);
@@ -197,11 +202,12 @@ export function createRunFinalizer({
const finalizeHandlerError = async (handlerErr) => {
const failMetadata = {
+ ...await readMetadata(),
endTime: new Date().toISOString(),
duration: Date.now() - startTime,
success: false,
error: `Run finalization failed: ${handlerErr.message}`,
- outputSize: Buffer.byteLength(getOutput()),
+ outputSize: (await readFile(outputPath).catch(() => '')).length,
};
await atomicWrite(metadataPath, failMetadata).catch(failed);
settleTerminal(() => hooks.onRunFailed?.(failMetadata, failMetadata.error, getOutput()), `Run ${runId} onRunFailed hook`);
@@ -212,24 +218,26 @@ export function createRunFinalizer({
if (!lifecycle.markSettled()) return false;
activeRuns.delete(runId);
try {
- if (cause.type === 'success') await finalizeSuccess(cause);
- else if (cause.type === 'timeout') await finalizeTimeout(cause.bound);
- else if (cause.type === 'response-error') {
- if (consumeActiveStop(runId)) await finalizeCanceled();
- else await finalizeHttpError(cause);
- }
- else if (cause.type === 'stream-error') {
- if (consumeActiveStop(runId)) await finalizeCanceled();
- else await finalizeStreamError(cause.error);
- }
- else if (cause.type === 'canceled') await finalizeCanceled();
- return true;
- } catch (handlerErr) {
- failed();
- console.error(`❌ Run ${runId} failure handler error: ${handlerErr.message}`);
- await finalizeHandlerError(handlerErr);
+ await withAssetPublication(async () => {
+ try {
+ if (cause.type === 'success') await finalizeSuccess(cause);
+ else if (cause.type === 'timeout') await finalizeTimeout(cause.bound);
+ else if (cause.type === 'response-error') {
+ if (consumeActiveStop(runId)) await finalizeCanceled();
+ else await finalizeHttpError(cause);
+ } else if (cause.type === 'stream-error') {
+ if (consumeActiveStop(runId)) await finalizeCanceled();
+ else await finalizeStreamError(cause.error);
+ } else if (cause.type === 'canceled') await finalizeCanceled();
+ } catch (handlerErr) {
+ failed();
+ console.error(`❌ Run ${runId} failure handler error: ${handlerErr.message}`);
+ await finalizeHandlerError(handlerErr);
+ }
+ });
return true;
} finally {
+ for (const { fn, label } of terminalCallbacks) runTerminal(fn, label);
await Promise.all(pendingHooks);
}
};
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index c92fed1213..c34589ca03 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -174,6 +174,8 @@ export function createRunnerService(config = {}) {
providerService,
providerStatusService = null,
hooks = {},
+ // Host-owned file-plus-record boundary; standalone toolkit has no coordinator.
+ withAssetPublication = work => work(),
maxConcurrentRuns: _maxConcurrentRuns = 5
} = config;
@@ -452,9 +454,12 @@ export function createRunnerService(config = {}) {
outputSize: 0
};
- await atomicWrite(join(runDir, 'metadata.json'), metadata);
- await atomicWrite(join(runDir, 'prompt.txt'), prompt);
- await atomicWrite(join(runDir, 'output.txt'), '');
+ await withAssetPublication(async () => {
+ // The record must never name missing prompt/output bytes after a failure.
+ await atomicWrite(join(runDir, 'prompt.txt'), prompt);
+ await atomicWrite(join(runDir, 'output.txt'), '');
+ await atomicWrite(join(runDir, 'metadata.json'), metadata);
+ });
hooks.onRunCreated?.(metadata);
console.log(`🤖 AI run [${source}]: ${provider.name}/${metadata.model}`);
@@ -570,8 +575,10 @@ export function createRunnerService(config = {}) {
let metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) metadata = {};
Object.assign(metadata, failMetadata);
- await atomicWrite(outputPath, output);
- await atomicWrite(metadataPath, metadata);
+ await withAssetPublication(async () => {
+ await atomicWrite(outputPath, output);
+ await atomicWrite(metadataPath, metadata);
+ });
Object.assign(failMetadata, metadata);
} catch (writeErr) {
console.error(`❌ Run ${runId} spawn-error finalization failed: ${writeErr.message}`);
@@ -618,30 +625,30 @@ export function createRunnerService(config = {}) {
try {
releaseRun();
- await atomicWrite(outputPath, output);
-
- const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
- metadata.endTime = new Date().toISOString();
- metadata.duration = Date.now() - startTime;
- metadata.exitCode = code;
- metadata.success = code === 0;
- metadata.outputSize = Buffer.byteLength(output);
-
- if (!metadata.success) {
- const errorAnalysis = analyzeError(output, code);
- metadata.error = errorAnalysis.message || `Process exited with code ${code}`;
- metadata.errorCategory = errorAnalysis.category;
- metadata.errorAnalysis = errorAnalysis;
-
- if (errorAnalysis.hasError &&
- (errorAnalysis.category === ERROR_CATEGORIES.RATE_LIMIT ||
- errorAnalysis.category === ERROR_CATEGORIES.USAGE_LIMIT)) {
- await handleProviderError(provider.id, errorAnalysis, output);
+ const metadata = await withAssetPublication(async () => {
+ await atomicWrite(outputPath, output);
+ const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = Date.now() - startTime;
+ metadata.exitCode = code;
+ metadata.success = code === 0;
+ metadata.outputSize = Buffer.byteLength(output);
+ if (!metadata.success) {
+ const errorAnalysis = analyzeError(output, code);
+ metadata.error = errorAnalysis.message || `Process exited with code ${code}`;
+ metadata.errorCategory = errorAnalysis.category;
+ metadata.errorAnalysis = errorAnalysis;
}
+ await atomicWrite(metadataPath, metadata);
+ return metadata;
+ });
+ const errorAnalysis = metadata.errorAnalysis;
+ if (errorAnalysis?.hasError &&
+ (errorAnalysis.category === ERROR_CATEGORIES.RATE_LIMIT ||
+ errorAnalysis.category === ERROR_CATEGORIES.USAGE_LIMIT)) {
+ await handleProviderError(provider.id, errorAnalysis, output);
}
- await atomicWrite(metadataPath, metadata);
-
// Isolate the completion hooks + onComplete from the outer catch — a
// throwing onRunCompleted must NOT be reinterpreted as a finalization
// failure that flips a successful run to success:false for the caller.
@@ -700,6 +707,7 @@ export function createRunnerService(config = {}) {
onTimeout: bound => finalizer.finalize({ type: 'timeout', bound }),
});
finalizer = createRunFinalizer({
+ withAssetPublication,
runId,
provider,
startTime,
@@ -1069,7 +1077,7 @@ export function createRunnerService(config = {}) {
const runDir = join(RUNS_PATH, runId);
if (!existsSync(runDir)) return false;
- await rm(runDir, { recursive: true });
+ await withAssetPublication(() => rm(runDir, { recursive: true }));
return true;
},
@@ -1085,7 +1093,7 @@ export function createRunnerService(config = {}) {
if (existsSync(metadataPath)) {
const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
if (metadata.success === false) {
- await rm(join(RUNS_PATH, runId), { recursive: true });
+ await withAssetPublication(() => rm(join(RUNS_PATH, runId), { recursive: true }));
deletedCount++;
}
}
diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index 6d763f251b..fecf5d171f 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -429,6 +429,14 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
status: 'admitted',
modules: ['services/games/compile.js'],
},
+ {
+ // Vendored toolkit stays self-contained: the host injects its boundary as
+ // withAssetPublication via createAIToolkit. Prompt/output creation, CLI/API
+ // completion and recording deletion use it; standalone default is a no-op.
+ id: 'toolkit-recording-publication',
+ status: 'admitted',
+ modules: ['lib/aiToolkit/runner.js', 'lib/aiToolkit/internal/runFinalizer.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/backupAssetOwners.test.js b/server/lib/backupAssetOwners.test.js
index 5d2056d115..3fdf20069a 100644
--- a/server/lib/backupAssetOwners.test.js
+++ b/server/lib/backupAssetOwners.test.js
@@ -16,8 +16,14 @@ import { blankComments } from './sourceScan.js';
const SERVER_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
const BOUNDARY_MODULE = 'lib/backupSnapshotBoundary.js';
const STATUSES = new Set(['admitted', 'reference-only', 'outstanding']);
-const takesAdmission = (path) => /\bwithBackupAssetPublication\s*\(/
- .test(blankComments(readFileSync(join(SERVER_ROOT, path), 'utf8')));
+const INJECTED_TOOLKIT_MODULES = new Set([
+ 'lib/aiToolkit/runner.js', 'lib/aiToolkit/internal/runFinalizer.js',
+]);
+const takesAdmission = (path) => {
+ const source = blankComments(readFileSync(join(SERVER_ROOT, path), 'utf8')).join('\n');
+ return /\bwithBackupAssetPublication\s*\(/.test(source)
+ || (INJECTED_TOOLKIT_MODULES.has(path) && /\bwithAssetPublication\s*\(/.test(source));
+};
const admittedModules = new Set(BACKUP_ASSET_OWNERS
.filter(owner => owner.status === 'admitted')
.flatMap(owner => owner.modules));
@@ -31,6 +37,15 @@ describe('backup asset owner inventory', () => {
}
});
+ it('admits injected toolkit writers only through the real host boundary', () => {
+ const source = path => blankComments(readFileSync(join(SERVER_ROOT, path), 'utf8')).join('\n');
+ const bootstrap = source('services/bootstrap.js');
+ expect(bootstrap).toMatch(/import\s*\{\s*withBackupAssetPublication\s*\}\s*from ['"]\.\.\/lib\/backupSnapshotBoundary\.js['"]/);
+ expect(bootstrap).toMatch(/createAIToolkit\(\{[\s\S]*?withAssetPublication:\s*withBackupAssetPublication/);
+ expect(source('lib/aiToolkit/index.js')).toMatch(/createRunnerService\(\{\s*withAssetPublication,/);
+ expect(source('lib/aiToolkit/runner.js')).toMatch(/createRunFinalizer\(\{\s*withAssetPublication,/);
+ });
+
it('lists only modules that hold the admission lease as admitted', () => {
for (const path of admittedModules) expect(takesAdmission(path), path).toBe(true);
});
diff --git a/server/services/aiToolkitBackupAdmission.test.js b/server/services/aiToolkitBackupAdmission.test.js
new file mode 100644
index 0000000000..b73e555616
--- /dev/null
+++ b/server/services/aiToolkitBackupAdmission.test.js
@@ -0,0 +1,119 @@
+/** Host injection over real toolkit files; no provider/network/child execution. */
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { EventEmitter } from 'node:events';
+import { acquireBackupSnapshotCut, withBackupAssetPublication, holdsBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
+const seam = vi.hoisted(() => ({ beforeWrite: null, child: null }));
+vi.mock('../lib/aiToolkit/internal/atomicWrite.js', async importOriginal => {
+ const actual = await importOriginal();
+ return { ...actual, atomicWrite: async (path, data) => { await seam.beforeWrite?.(path, data); return actual.atomicWrite(path, data); } };
+});
+vi.mock('child_process', async importOriginal => ({ ...await importOriginal(), spawn: () => seam.child }));
+const { createRunnerService } = await import('../lib/aiToolkit/runner.js');
+const { createRunFinalizer } = await import('../lib/aiToolkit/internal/runFinalizer.js');
+const root = await mkdtemp(join(tmpdir(), 'toolkit-backup-'));
+const dir = join(root, 'runs', 'example');
+const outputPath = join(dir, 'output.txt');
+const metadataPath = join(dir, 'metadata.json');
+const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };
+const settle = () => new Promise(resolve => setImmediate(resolve));
+const provider = { id: 'example', name: 'Example', enabled: true, command: 'synthetic' };
+const runner = (injected = withBackupAssetPublication, hooks = {}) => createRunnerService({ dataDir: root, withAssetPublication: injected, hooks,
+ providerService: { getProviderById: async () => provider } });
+const capture = async () => ({ output: await readFile(outputPath, 'utf8'), metadata: JSON.parse(await readFile(metadataPath, 'utf8')) });
+const assertPair = async () => { const pair = await capture(); expect(pair.metadata.outputSize).toBe(Buffer.byteLength(pair.output)); };
+beforeEach(async () => {
+ seam.beforeWrite = null;
+ await rm(root, { recursive: true, force: true }); await mkdir(dir, { recursive: true });
+ await writeFile(outputPath, ''); await writeFile(metadataPath, JSON.stringify({ id: 'example', outputSize: 0 }));
+});
+afterAll(() => rm(root, { recursive: true, force: true }));
+function apiFinalizer(injected = withBackupAssetPublication, hooks = {}) {
+ let settled = false;
+ return createRunFinalizer({ runId: 'example', provider, startTime: Date.now(), activeRuns: new Map(),
+ lifecycle: { markSettled: () => { if (settled) return false; settled = true; return true; } },
+ stallTimeout: 5, absoluteTimeout: 10, outputPath, metadataPath, getOutput: () => 'Example output', getReasoning: () => '',
+ hooks, safeJsonParse: JSON.parse, consumeActiveStop: () => false, handleProviderError: async () => {},
+ withAssetPublication: injected });
+}
+const causes = [{ type: 'success' }, { type: 'timeout', bound: 'stall' }, { type: 'canceled' }, { type: 'stream-error', error: new Error('Example stream failure') }];
+describe.each(causes)('API $type recording', cause => {
+ it('does not replace output or metadata during a cut', async () => {
+ const before = await capture(); const release = await acquireBackupSnapshotCut();
+ const work = apiFinalizer().finalize(cause);
+ try { await settle(); await settle(); expect(await capture()).toEqual(before); } finally { release(); }
+ await work; await assertPair();
+ });
+ it('drains output through metadata and invokes hooks outside admission', async () => {
+ const reached = deferred(); const commit = deferred();
+ seam.beforeWrite = async path => { if (path === metadataPath) { reached.resolve(); await commit.promise; } };
+ const leaseStates = [];
+ const check = () => leaseStates.push(holdsBackupAssetPublication());
+ const work = apiFinalizer(withBackupAssetPublication, { onRunCompleted: check, onRunFailed: check, onRunCanceled: check }).finalize(cause);
+ 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 { await assertPair(); expect(leaseStates).toEqual([false]); } finally { release(); }
+ });
+});
+it('negative control exposes copied output differing from later completion metadata', async () => {
+ const release = await acquireBackupSnapshotCut();
+ try {
+ const copied = (await capture()).output;
+ await apiFinalizer(work => work()).finalize({ type: 'success' });
+ expect((await capture()).metadata.outputSize).not.toBe(Buffer.byteLength(copied));
+ } finally { release(); }
+});
+it.each(causes)('keeps persisted outputSize truthful on $type output-write failure', async cause => {
+ seam.beforeWrite = async path => { if (path === outputPath) throw new Error('synthetic output write failure'); };
+ await apiFinalizer().finalize(cause); await assertPair();
+});
+it('creation drains prompt and output before publishing metadata', async () => {
+ const reached = deferred(); const commit = deferred(); let newDir;
+ seam.beforeWrite = async path => { if (path.endsWith('metadata.json')) { newDir = join(path, '..'); reached.resolve(); await commit.promise; } };
+ const work = runner().createRun({ providerId: provider.id, prompt: 'Example prompt' });
+ await reached.promise;
+ expect(await readFile(join(newDir, 'prompt.txt'), 'utf8')).toBe('Example prompt');
+ let ready = false; const cut = acquireBackupSnapshotCut().then(release => { ready = true; return release; });
+ try { await settle(); expect(ready).toBe(false); } finally { commit.resolve(); }
+ const created = await work; const release = await cut;
+ try { expect((await readdir(created.runDir)).sort()).toEqual(['metadata.json', 'output.txt', 'prompt.txt']); } finally { release(); }
+});
+it('creation cannot publish metadata when prompt persistence fails', async () => {
+ seam.beforeWrite = async path => { if (path.endsWith('prompt.txt')) throw new Error('synthetic prompt failure'); };
+ await expect(runner().createRun({ providerId: provider.id, prompt: 'Example' })).rejects.toThrow('synthetic prompt failure');
+ for (const id of (await readdir(join(root, 'runs'))).filter(id => id !== 'example')) {
+ expect(await readdir(join(root, 'runs', id))).not.toContain('metadata.json');
+ }
+});
+it.each(['close', 'error'])('CLI %s drains the actual output/metadata tail', async event => {
+ const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); seam.child = child;
+ const reached = deferred(); const commit = deferred(); const complete = deferred();
+ seam.beforeWrite = async path => { if (path === metadataPath) { reached.resolve(); await commit.promise; } };
+ const leaseStates = [];
+ await runner().executeCliRun({ runId: 'example', provider, prompt: 'Example', timeout: 10000,
+ onComplete: () => { leaseStates.push(holdsBackupAssetPublication()); complete.resolve(); } });
+ child.stdout.emit('data', 'Example CLI output'); child.emit(event, event === 'error' ? new Error('Example spawn error') : 0);
+ 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 complete.promise; const release = await cut;
+ try { await assertPair(); expect(leaseStates).toEqual([false]); } finally { release(); }
+});
+it('deletion waits for the cut before removing a recording tree', async () => {
+ const release = await acquireBackupSnapshotCut(); const work = runner().deleteRun('example');
+ try { await settle(); await assertPair(); } finally { release(); }
+ expect(await work).toBe(true); expect(await readdir(join(root, 'runs'))).toEqual([]);
+});
+
+it('creation waits out an open cut before publishing any file in its new run', async () => {
+ const release = await acquireBackupSnapshotCut();
+ let writes = 0; seam.beforeWrite = async () => { writes++; };
+ const work = runner().createRun({ providerId: provider.id, prompt: 'Example' });
+ try { await settle(); await settle(); expect(writes).toBe(0); }
+ finally { release(); }
+ await work; expect(writes).toBe(3);
+});