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: retain CoS cleanup evidence when clearing agent history

Adam Eivy1ab37607ef50
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index b446a005e0..c168a46ed6 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -349,7 +349,9 @@ export default function AgentsTab({ agentsLoaded = true, agentsError = null, onR
</h3>
<button
onClick={() => setConfirmingClear(true)}
- className="flex min-h-[44px] min-w-[44px] items-center justify-center gap-1 text-sm text-gray-500 hover:text-port-error transition-colors sm:min-h-0 sm:min-w-0"
+ disabled={finalizingAgents.length > 0}
+ title={finalizingAgents.length > 0 ? 'Wait for delivery verification and cleanup to finish' : undefined}
+ className="flex min-h-[44px] min-w-[44px] items-center justify-center gap-1 text-sm text-gray-500 hover:text-port-error transition-colors disabled:opacity-50 sm:min-h-0 sm:min-w-0"
aria-label="Clear all completed agents"
>
<Trash2 size={14} aria-hidden="true" />
diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsx
index 1524d60160..e4b1fff4d2 100644
--- a/client/src/pages/ChiefOfStaff.test.jsx
+++ b/client/src/pages/ChiefOfStaff.test.jsx
@@ -1374,6 +1374,7 @@ describe('ChiefOfStaff active-agent snapshot readiness', () => {
expect(screen.getAllByText('Example system delivery')).toHaveLength(1);
expect(screen.queryByText(/No active agents/)).toBeNull();
expect(within(section).queryByRole('button', { name: /Resume|Remove agent/ })).toBeNull();
+ expect(screen.getByRole('button', { name: 'Clear all completed agents' })).toBeDisabled();
await act(async () => socketHandler('cos:agent:updated')(archived));
expect(screen.getByRole('region', { name: 'Finalizing delivery' })).toBeInTheDocument();
@@ -1385,6 +1386,7 @@ describe('ChiefOfStaff active-agent snapshot readiness', () => {
});
expect(screen.queryByRole('region', { name: 'Finalizing delivery' })).toBeNull();
expect(screen.getByText('Example system delivery')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Clear all completed agents' })).toBeEnabled();
});
it.each([true, false])('keeps unknown CoS status out of the loaded Agents UI until running=%s arrives', async (running) => {
diff --git a/server/services/cosAgentArchive.js b/server/services/cosAgentArchive.js
index ca639c3934..90131c285d 100644
--- a/server/services/cosAgentArchive.js
+++ b/server/services/cosAgentArchive.js
@@ -16,6 +16,8 @@ import { join } from 'path';
import { cosEvents } from './cosEvents.js';
import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
import { atomicWrite, ensureDir } from '../lib/fileUtils.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { isDeliveryCleanupHeld } from '../lib/taskRetryHold.js';
import { loadAgentIndex, saveAgentIndex, recordArchivedAgentOrder, moveAgentDir } from './cosAgentIndex.js';
// Archive stale completed agents from state.json.
@@ -86,6 +88,20 @@ export async function archiveStaleAgents() {
// Clear completed agents from state, cache, and disk
export async function clearCompletedAgents() {
return withBackupAssetPublication(() => withStateLock(async () => {
+ // Completion is persisted before its task hold; both records protect restart evidence.
+ const { getTaskView } = await import('./cosTaskStore.js');
+ const { readBranchCompletionPolicies } = await import('./branchCompletionPolicy.js');
+ const [tasks, agents] = await Promise.all([
+ getTaskView({ kind: 'queue' }),
+ readBranchCompletionPolicies({ repairIndex: false }),
+ ]);
+ if ([...(tasks.user?.tasks || []), ...(tasks.cos?.tasks || [])]
+ .some(task => task.status === 'in_progress' && isDeliveryCleanupHeld(task.metadata))
+ || agents.some(agent => agent.status === 'completed' && agent.metadata?.repoStateVerification?.status === 'pending')) {
+ throw new ServerError('Wait for delivery verification and cleanup before clearing completed agents.', {
+ status: 409, code: 'DELIVERY_CLEANUP_PENDING',
+ });
+ }
const state = await loadState();
const idx = await loadAgentIndex();
diff --git a/server/services/cosAgentArchives.backupAdmission.test.js b/server/services/cosAgentArchives.backupAdmission.test.js
index b2aacae48f..1cd1043c8c 100644
--- a/server/services/cosAgentArchives.backupAdmission.test.js
+++ b/server/services/cosAgentArchives.backupAdmission.test.js
@@ -7,8 +7,10 @@ const fixture = await vi.hoisted(async () => {
const { mkdtemp } = await import('node:fs/promises');
const { tmpdir } = await import('node:os');
const { join } = await import('node:path');
- return { root: await mkdtemp(join(tmpdir(), 'cos-archive-backup-')), state: null, beforeIndex: null, bypass: false };
+ const base = await mkdtemp(join(tmpdir(), 'cos-archive-backup-'));
+ return { base, root: join(base, 'agents'), state: null, tasks: null, beforeIndex: null, bypass: false };
});
+vi.mock('./cosTaskStore.js', () => ({ getTaskView: async () => fixture.tasks }));
vi.mock('./cosState.js', () => ({
AGENTS_DIR: fixture.root,
loadState: async () => structuredClone(fixture.state),
@@ -18,7 +20,7 @@ vi.mock('./cosState.js', () => ({
}));
vi.mock('../lib/fileUtils.js', async importOriginal => {
const actual = await importOriginal();
- return { ...actual, atomicWrite: async (path, data) => {
+ return { ...actual, PATHS: { ...actual.PATHS, cos: fixture.base }, atomicWrite: async (path, data) => {
if (path === join(fixture.root, 'index.json')) await fixture.beforeIndex?.();
return actual.atomicWrite(path, data);
} };
@@ -59,13 +61,56 @@ async function seed({ completed = false, indexed = false } = {}) {
beforeEach(async () => {
vi.resetModules(); fixture.beforeIndex = null; fixture.bypass = false;
fixture.state = { agents: {}, config: { completedAgentRetentionMs: 1 }, stats: { tasksCompleted: 0, errors: 0 } };
+ fixture.tasks = { user: { tasks: [] }, cos: { tasks: [] } };
await rm(fixture.root, { recursive: true, force: true }); await mkdir(fixture.root);
await writeFile(join(fixture.root, 'index.json'), '{}');
({ acquireBackupSnapshotCut: acquireCut } = await import('../lib/backupSnapshotBoundary.js'));
index = await import('./cosAgentIndex.js');
api = { ...await import('./cosAgentLifecycle.js'), ...await import('./cosAgentArchive.js') };
});
-afterAll(() => rm(fixture.root, { recursive: true, force: true }));
+afterAll(() => rm(fixture.base, { recursive: true, force: true }));
+
+it('preserves pending verification before the task hold is written and after archival', async () => {
+ await seed({ completed: true, indexed: true });
+ const agent = fixture.state.agents[id];
+ agent.result.cleanupPending = true;
+ agent.metadata.repoStateVerification = { status: 'pending' };
+ const metadataPath = join(fixture.root, date, id, 'metadata.json');
+ await writeFile(metadataPath, JSON.stringify(agent));
+
+ await expect(api.clearCompletedAgents()).rejects.toMatchObject({ code: 'DELIVERY_CLEANUP_PENDING' });
+ expect(fixture.state.agents[id]).toEqual(agent);
+ delete fixture.state.agents[id];
+ await expect(api.clearCompletedAgents()).rejects.toMatchObject({ code: 'DELIVERY_CLEANUP_PENDING' });
+ await assertIndexedTrees();
+
+ agent.metadata.repoStateVerification.status = 'completed';
+ await writeFile(metadataPath, JSON.stringify(agent));
+ expect(await api.clearCompletedAgents()).toEqual({ cleared: 1 });
+});
+
+it.each(['user', 'cos'])('preserves cleanup-owner evidence in the %s queue until delivery settles', async source => {
+ await seed({ completed: true, indexed: true });
+ // An archived owner is absent from resident state but still required after restart.
+ delete fixture.state.agents[id];
+ const task = { id: 'task-example', status: 'in_progress', metadata: {
+ deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: id,
+ } };
+ fixture.tasks[source].tasks.push(task);
+ const beforeState = structuredClone(fixture.state);
+ const beforeIndex = await readIndex();
+
+ await expect(api.clearCompletedAgents()).rejects.toMatchObject({ status: 409, code: 'DELIVERY_CLEANUP_PENDING' });
+ expect(fixture.state).toEqual(beforeState);
+ expect(await readIndex()).toEqual(beforeIndex);
+ await assertIndexedTrees();
+
+ task.status = 'completed';
+ expect(await api.clearCompletedAgents()).toEqual({ cleared: 1 });
+ expect(await readIndex()).toEqual({});
+ expect(await readdir(fixture.root)).not.toContain(date);
+});
+
const cases = [
{ name: 'completion', setup: () => seed(), run: () => api.completeAgent(id, { success: true }) },
{ name: 'zombie archive', setup: () => seed(), run: () => api.cleanupZombieAgents() },