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

handle a half-done archive on the idempotent completion path

[._.]/ Adam Eivy373ccf9208c9
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index 49c97331fc..c4954085ec 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -77,6 +77,48 @@ export async function updateAgent(agentId, updates) {
});
}
+/**
+ * Move a completed agent's directory into its `YYYY-MM-DD` bucket and index it.
+ * Split out of `completeAgent` so the duplicate-completion path can finish an
+ * archive a prior call left half-done (an fs failure between the state write and
+ * the move) without touching the recorded verdict — every step is a no-op when
+ * the destination already exists.
+ */
+async function archiveCompletedAgent(agentId, agent) {
+ // Determine date bucket from completedAt
+ const dateStr = agent.completedAt.slice(0, 10);
+ const bucketDir = join(AGENTS_DIR, dateStr);
+ await ensureDir(bucketDir);
+
+ // Write metadata to flat dir first (may already have output.txt/prompt.txt there)
+ const flatDir = join(AGENTS_DIR, agentId);
+ if (!existsSync(flatDir)) {
+ await ensureDir(flatDir);
+ }
+ const { output: _output, ...agentWithoutOutput } = agent;
+ await atomicWrite(join(flatDir, 'metadata.json'), agentWithoutOutput);
+
+ // Move entire agent dir into date bucket (atomic on same filesystem)
+ const targetDir = join(bucketDir, agentId);
+ if (!existsSync(targetDir)) {
+ await rename(flatDir, targetDir).catch(async () => {
+ // Fallback for cross-filesystem: copy files then remove
+ 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 });
+ });
+ }
+
+ // Update index
+ const idx = await loadAgentIndex();
+ idx.set(agentId, dateStr);
+ await saveAgentIndex();
+}
+
export async function completeAgent(agentId, result = {}) {
// Set inside the lock when the record is already terminal, so the post-lock
// tail below (budget ledger + `agent:completed`) is skipped too — see #3384.
@@ -99,6 +141,15 @@ export async function completeAgent(agentId, result = {}) {
// are legitimately completed on resume.
if (state.agents[agentId].status === 'completed') {
alreadyCompleted = true;
+ // One exception to "do nothing": if a prior completion threw between its
+ // state write and the archive move, the record says completed but its
+ // directory never made it into the date bucket. Finish that with the
+ // ALREADY-RECORDED result, so the retry repairs the archive without
+ // adopting the second caller's (typically bogus) verdict.
+ const { completedAt } = state.agents[agentId];
+ if (completedAt && !existsSync(join(AGENTS_DIR, completedAt.slice(0, 10), agentId))) {
+ await archiveCompletedAgent(agentId, state.agents[agentId]);
+ }
return state.agents[agentId];
}
@@ -127,38 +178,7 @@ export async function completeAgent(agentId, result = {}) {
// stays inside the lock.
cosEvents.emit('agent:updated', state.agents[agentId]);
- // Determine date bucket from completedAt
- const dateStr = state.agents[agentId].completedAt.slice(0, 10);
- const bucketDir = join(AGENTS_DIR, dateStr);
- await ensureDir(bucketDir);
-
- // Write metadata to flat dir first (may already have output.txt/prompt.txt there)
- const flatDir = join(AGENTS_DIR, agentId);
- if (!existsSync(flatDir)) {
- await ensureDir(flatDir);
- }
- const { output: _output, ...agentWithoutOutput } = state.agents[agentId];
- await atomicWrite(join(flatDir, 'metadata.json'), agentWithoutOutput);
-
- // Move entire agent dir into date bucket (atomic on same filesystem)
- const targetDir = join(bucketDir, agentId);
- if (!existsSync(targetDir)) {
- await rename(flatDir, targetDir).catch(async () => {
- // Fallback for cross-filesystem: copy files then remove
- 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 });
- });
- }
-
- // Update index
- const idx = await loadAgentIndex();
- idx.set(agentId, dateStr);
- await saveAgentIndex();
+ await archiveCompletedAgent(agentId, state.agents[agentId]);
return state.agents[agentId];
});
diff --git a/server/services/cosAgents.test.js b/server/services/cosAgents.test.js
index 16a99143fa..87aa2ca3e1 100644
--- a/server/services/cosAgents.test.js
+++ b/server/services/cosAgents.test.js
@@ -238,6 +238,41 @@ describe('completeAgent idempotence (#3384)', () => {
expect(archived.result.exitCode).toBe(0);
});
+ it('finishes a half-done archive using the already-recorded verdict', async () => {
+ // A prior completion that threw between its state write and the directory
+ // move leaves the record `completed` but never archived. The duplicate call
+ // repairs the archive — with the FIRST verdict, not the caller's.
+ const agentId = 'agent-half-archived';
+ const completedAt = '2026-05-25T12:00:00.000Z';
+ mockCosState.state.agents[agentId] = {
+ id: agentId,
+ status: 'completed',
+ completedAt,
+ result: { validationPassed: null, success: true, exitCode: 0 },
+ metadata: { taskType: 'scheduled' },
+ output: []
+ };
+ const flatDir = join(mockCosState.agentsDir, agentId);
+ await mkdir(flatDir, { recursive: true });
+ await writeFile(join(flatDir, 'output.txt'), 'the run that finished\n');
+
+ const returned = await completeAgent(agentId, { success: false, exitCode: 143 });
+
+ const archiveDir = join(mockCosState.agentsDir, '2026-05-25', agentId);
+ const archived = JSON.parse(await readFile(join(archiveDir, 'metadata.json'), 'utf8'));
+ expect(archived.result.success).toBe(true);
+ expect(archived.result.exitCode).toBe(0);
+ expect(existsSync(join(archiveDir, 'output.txt'))).toBe(true);
+ expect(existsSync(flatDir)).toBe(false);
+
+ // Repairing the archive is NOT a re-completion: verdict, ledger and the
+ // scheduler hand-off all stay untouched.
+ expect(returned.result.success).toBe(true);
+ expect(recordDomainUsage).not.toHaveBeenCalled();
+ expect(emittedCompletions).toEqual([]);
+ expect(mockCosState.state.stats).toEqual({ tasksCompleted: 0, errors: 0 });
+ });
+
it('completes a still-paused agent (the guard is completed-only, not running-only)', async () => {
const agentId = 'agent-paused-completion';
mockCosState.state.agents[agentId] = {