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: archiving a stale CoS agent no longer corrupts its gzip recording or deletes files it failed to copy

Adam Eivyddd4e49c0e22
diff --git a/server/services/cosAgentArchive.js b/server/services/cosAgentArchive.js
index 693da08cd8..ca639c3934 100644
--- a/server/services/cosAgentArchive.js
+++ b/server/services/cosAgentArchive.js
@@ -10,13 +10,13 @@
*/
import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
-import { writeFile, rename, readdir, rm } from 'fs/promises';
+import { rm } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { cosEvents } from './cosEvents.js';
import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
-import { atomicWrite, ensureDir, tryReadFile } from '../lib/fileUtils.js';
-import { loadAgentIndex, saveAgentIndex, recordArchivedAgentOrder } from './cosAgentIndex.js';
+import { atomicWrite, ensureDir } from '../lib/fileUtils.js';
+import { loadAgentIndex, saveAgentIndex, recordArchivedAgentOrder, moveAgentDir } from './cosAgentIndex.js';
// Archive stale completed agents from state.json.
// Completed agents are already persisted to per-agent metadata files on disk
@@ -54,17 +54,11 @@ export async function archiveStaleAgents() {
const targetDir = join(bucketDir, id);
if (existsSync(flatDir) && !existsSync(targetDir)) {
- // Write metadata then move (with cross-filesystem fallback)
+ // Write metadata then move (byte-safe fallback that never deletes the
+ // source unless the whole copy landed)
await atomicWrite(join(flatDir, 'metadata.json'), agentWithoutOutput).catch(() => {});
- await rename(flatDir, targetDir).catch(async () => {
- await ensureDir(targetDir);
- const files = await readdir(flatDir).catch(() => []);
- for (const file of files) {
- const content = await tryReadFile(join(flatDir, file), null);
- if (content !== null) await writeFile(join(targetDir, file), content);
- }
- await rm(flatDir, { recursive: true }).catch(() => {});
- });
+ await moveAgentDir(flatDir, targetDir)
+ .catch(err => console.error(`❌ Failed to archive agent ${id}: ${err.message}`));
if (!existsSync(targetDir)) continue; // Skip index update if move failed
} else if (!existsSync(targetDir)) {
await ensureDir(targetDir);
diff --git a/server/services/cosAgentIndex.js b/server/services/cosAgentIndex.js
index 9898dfd9d6..a15ea32564 100644
--- a/server/services/cosAgentIndex.js
+++ b/server/services/cosAgentIndex.js
@@ -11,7 +11,7 @@
*/
import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
-import { readFile, writeFile, rename, readdir, rm, stat } from 'fs/promises';
+import { readFile, writeFile, rename, readdir, rm, stat, cp } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { AGENTS_DIR } from './cosState.js';
@@ -168,6 +168,38 @@ export function getAgentDir(agentId, dateString) {
return join(AGENTS_DIR, agentId);
}
+/**
+ * Move an agent's run directory (output, prompt, metadata, raw.txt.gz) to `targetDir`.
+ *
+ * `rename` is atomic but can fail (EXDEV across mounts, EPERM/EBUSY on Windows
+ * while a handle is open). The fallback copies BYTES (`cp`, so the gzip
+ * recording is not re-encoded as UTF-8 text and subdirectories survive) and
+ * removes the source only after the whole copy succeeded. A failed copy rolls
+ * back the partial target that this call created — `existsSync(targetDir)` is
+ * what every later archive attempt reads as "already archived", so leaving it
+ * would strand the rest of the run's files — and rethrows with the source
+ * intact. Callers guarantee `targetDir` did not exist before the call.
+ */
+export async function moveAgentDir(flatDir, targetDir) {
+ try {
+ await rename(flatDir, targetDir);
+ return;
+ } catch {
+ // Fall through to the copy-then-remove path.
+ }
+ const targetExisted = existsSync(targetDir);
+ try {
+ await cp(flatDir, targetDir, { recursive: true, force: false, errorOnExist: true });
+ } catch (err) {
+ if (!targetExisted) {
+ await rm(targetDir, { recursive: true, force: true })
+ .catch(rmErr => console.error(`❌ Failed to roll back partial archive ${targetDir}: ${rmErr.message}`));
+ }
+ throw err;
+ }
+ await rm(flatDir, { recursive: true, force: true });
+}
+
// Migrate flat agent-* directories into YYYY-MM-DD date buckets
// Runs once when index.json doesn't exist. Idempotent — no-op if already migrated.
async function migrateAgentsToDateBuckets() {
diff --git a/server/services/cosAgentIndex.moveAgentDir.test.js b/server/services/cosAgentIndex.moveAgentDir.test.js
new file mode 100644
index 0000000000..5a4b3a9368
--- /dev/null
+++ b/server/services/cosAgentIndex.moveAgentDir.test.js
@@ -0,0 +1,74 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdir, rm, writeFile, readFile, readdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+
+// Isolated file: `rename` is forced to fail (EXDEV / a Windows open handle) so the
+// copy fallback runs, and `cp` can be made to fail halfway.
+const mock = vi.hoisted(() => ({
+ agentsDir: `${process.env.TMPDIR || process.env.TEMP || process.env.TMP || '/tmp'}/portos-cos-movedir-${process.pid}`,
+ failCp: false,
+}));
+
+vi.mock('./cosState.js', () => ({
+ AGENTS_DIR: mock.agentsDir,
+ loadState: vi.fn(),
+ saveState: vi.fn(),
+ withStateLock: async (fn) => fn(),
+}));
+vi.mock('./domainUsage.js', () => ({ recordDomainUsage: vi.fn(async () => {}) }));
+vi.mock('fs/promises', async () => {
+ const actual = await vi.importActual('fs/promises');
+ return {
+ ...actual,
+ rename: vi.fn(async () => { throw Object.assign(new Error('cross-device link not permitted'), { code: 'EXDEV' }); }),
+ cp: vi.fn(async (from, to, opts) => {
+ if (!mock.failCp) return actual.cp(from, to, opts);
+ // Copy one file, then fail — a half-copied target.
+ await actual.mkdir(to, { recursive: true });
+ await actual.writeFile(`${to}/metadata.json`, await actual.readFile(`${from}/metadata.json`));
+ throw Object.assign(new Error('no space left on device'), { code: 'ENOSPC' });
+ }),
+ };
+});
+
+import { moveAgentDir } from './cosAgentIndex.js';
+
+// Not valid UTF-8: a text round-trip would replace these with U+FFFD.
+const GZIP_BYTES = Buffer.from([0x1f, 0x8b, 0x08, 0x00, 0xff, 0xfe, 0x80, 0x81, 0xc3, 0x28]);
+
+describe('moveAgentDir copy fallback (rename failed)', () => {
+ const flatDir = join(mock.agentsDir, 'agent-1');
+ const targetDir = join(mock.agentsDir, '2026-01-02', 'agent-1');
+
+ beforeEach(async () => {
+ mock.failCp = false;
+ await rm(mock.agentsDir, { recursive: true, force: true });
+ await mkdir(join(flatDir, 'nested'), { recursive: true });
+ await mkdir(join(mock.agentsDir, '2026-01-02'), { recursive: true });
+ await writeFile(join(flatDir, 'metadata.json'), '{"id":"agent-1"}');
+ await writeFile(join(flatDir, 'raw.txt.gz'), GZIP_BYTES);
+ await writeFile(join(flatDir, 'nested', 'extra.txt'), 'kept');
+ });
+ afterEach(async () => {
+ await rm(mock.agentsDir, { recursive: true, force: true });
+ });
+
+ it('copies binary recordings byte-for-byte and subdirectories, then removes the source', async () => {
+ await moveAgentDir(flatDir, targetDir);
+
+ expect(Buffer.compare(await readFile(join(targetDir, 'raw.txt.gz')), GZIP_BYTES)).toBe(0);
+ expect(await readFile(join(targetDir, 'nested', 'extra.txt'), 'utf8')).toBe('kept');
+ expect(existsSync(flatDir)).toBe(false);
+ });
+
+ it('keeps the source intact and rolls back the partial target when the copy fails', async () => {
+ mock.failCp = true;
+
+ await expect(moveAgentDir(flatDir, targetDir)).rejects.toThrow('no space left on device');
+
+ expect(existsSync(targetDir)).toBe(false);
+ expect((await readdir(flatDir)).sort()).toEqual(['metadata.json', 'nested', 'raw.txt.gz']);
+ expect(Buffer.compare(await readFile(join(flatDir, 'raw.txt.gz')), GZIP_BYTES)).toBe(0);
+ });
+});
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index 5bbc84bc5e..2b7beb3e3d 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -11,7 +11,7 @@
*/
import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
-import { readFile, writeFile, rename, readdir, rm, stat } from 'fs/promises';
+import { readFile, rm, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { cosEvents } from './cosEvents.js';
@@ -21,7 +21,7 @@ import { atomicWrite, ensureDir, readFileTail, safeJSONParse, tryReadFile } from
import { runnerEntryShieldsRunningRecord } from '../lib/runnerAgentLiveness.js';
import { recordDomainUsage } from './domainUsage.js';
import { repairCodexTaskSummary } from './codexSummaryRepair.js';
-import { loadAgentIndex, saveAgentIndex, getAgentDir, recordArchivedAgentOrder } from './cosAgentIndex.js';
+import { loadAgentIndex, saveAgentIndex, getAgentDir, recordArchivedAgentOrder, moveAgentDir } from './cosAgentIndex.js';
import { isAgentHandoff } from '../lib/agentOutcome.js';
export async function registerAgent(agentId, taskId, metadata = {}) {
@@ -81,14 +81,6 @@ export async function updateAgent(agentId, updates) {
});
}
-async function copyDirContents(fromDir, toDir) {
- const files = await readdir(fromDir);
- for (const file of files) {
- const content = await readFile(join(fromDir, file));
- await writeFile(join(toDir, file), content);
- }
-}
-
/**
* Move a completed agent's directory into its `YYYY-MM-DD` bucket and index it.
* Split out of `completeAgent` and made idempotent so the duplicate-completion
@@ -115,20 +107,10 @@ async function archiveCompletedAgent(agentId, agent) {
await atomicWrite(join(flatDir, 'metadata.json'), agentWithoutOutput);
// Move entire agent dir into date bucket (atomic on same filesystem)
- await rename(flatDir, targetDir).catch(async () => {
- // Fallback for cross-filesystem: copy files then remove
- await ensureDir(targetDir);
- await copyDirContents(flatDir, targetDir).catch(async (err) => {
- // Roll the half-copied target back. `existsSync(targetDir)` is what every
- // later archive attempt (including the duplicate-completion repair) reads
- // as "already archived", so leaving a partial directory behind would
- // strand the rest of the run's output.txt/prompt.txt permanently.
- await rm(targetDir, { recursive: true, force: true })
- .catch(rmErr => console.error(`❌ Failed to roll back partial archive for ${agentId}: ${rmErr.message}`));
- throw err;
- });
- await rm(flatDir, { recursive: true });
- });
+ // Cross-filesystem / Windows-handle fallback copies bytes and rolls back a
+ // partial target (the duplicate-completion repair reads an existing
+ // `targetDir` as "already archived", so a partial one would strand the run).
+ await moveAgentDir(flatDir, targetDir);
}
// Update index — deliberately NOT gated on the in-memory map already holding
@@ -772,17 +754,7 @@ export async function cleanupZombieAgents() {
// Move to date bucket
const targetDir = join(bucketDir, agentId);
- if (!existsSync(targetDir)) {
- await rename(flatDir, targetDir).catch(async () => {
- await ensureDir(targetDir);
- const files = await readdir(flatDir);
- for (const file of files) {
- const content = await readFile(join(flatDir, file));
- await writeFile(join(targetDir, file), content);
- }
- await rm(flatDir, { recursive: true });
- });
- }
+ if (!existsSync(targetDir)) await moveAgentDir(flatDir, targetDir);
idx.set(agentId, dateStr);
archived.push({ ...agent, id: agentId });
diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.js
index f7ac5cc998..aecff73658 100644
--- a/server/services/cosAgentLifecycle.test.js
+++ b/server/services/cosAgentLifecycle.test.js
@@ -47,9 +47,14 @@ vi.mock('fs/promises', async (importOriginal) => {
if (failsFor(to)) throw Object.assign(new Error('EXDEV: cross-device link'), { code: 'EXDEV' });
return actual.rename(from, to, ...rest);
},
- writeFile: async (path, ...rest) => {
- if (failsFor(path)) throw new Error('simulated copy failure');
- return actual.writeFile(path, ...rest);
+ // The archive fallback copies with `cp`; the destination dir is created
+ // before the failure so the rollback has a half-copied target to remove.
+ cp: async (from, to, ...rest) => {
+ if (failsFor(to)) {
+ await actual.mkdir(to, { recursive: true });
+ throw new Error('simulated copy failure');
+ }
+ return actual.cp(from, to, ...rest);
}
};
});