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(cos): stop CoS cleanup from removing human /claim worktrees

Adam Eivy43b4c8be6c4c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ad882c450e..56b51395b4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -29,6 +29,8 @@
## Fixed
+- **Background agent cleanup no longer removes an in-progress manual claim's workspace.** A long-running hands-on task could have its isolated workspace deleted out from under it by the periodic agent-cleanup sweep, which mistook the human-owned workspace for an abandoned agent one. The sweep now leaves manual-claim workspaces alone and only reaps truly abandoned agent workspaces, and it runs on the daily maintenance schedule instead of every 15 minutes.
+
- **Federated media-collection sync reconciliation + resolution UX.** Follow-up to the federated-media-collections feature, fixing issues found running it across two machines. (1) **Universe/series-linked collections now reconcile across peers.** Each machine used to mint a random UUID for its "Universe: X" / "Series: Y" collection, so per-record sync (keyed on `id`) treated each machine's copy as distinct — integrity reported both sides "local only" and the merge created a *duplicate* on every peer. Linked collections now derive a deterministic id (`uc-<universeId>` / `sc-<seriesId>`); create paths reclaim the id when a tombstone holds it (re-creating a deleted collection). Migration 038 canonicalizes existing ids on each machine, merging (union of items) any same-owner duplicates and rewriting `mediaCollection` subscription recordIds — idempotent; both machines converge independently. (2) **New "Pull from peer" action** (`GET /api/peer-sync/record` + `POST /api/peer-sync/pull-record`) lets a machine that is *behind* on a record fetch it and background-pull its asset bytes via `applyIncomingPush`, instead of "Sync to peer" being push-only; the Sync Details drawer is now direction-aware (Pull for peer-only, Sync for local-only, both for diverged/assets-missing). (3) **The Sync Details drawer can no longer hang on "Loading…"** — the record fetch gets a 12s timeout + explicit error state. (4) **Removed the unbounded "Live-pushed records" per-record list** from the Instances page (the Sync Details drawer covers per-record status). `mediaCollections` sync remains opt-in per peer — enable the "Media Collections" category on the Instances page for collections to sync.
- **[upcoming-tasks-widget-drop-catch-to-empty] Upcoming Tasks widget no longer blanks on a transient hiccup** — a momentary failure of the dashboard's Upcoming Tasks background refresh now keeps the last-loaded tasks on screen instead of clearing the list.
- **[propagate-runner-errorAnalysis-into-onRunFailed-context] Propagate `metadata.errorAnalysis` into the `onRunFailed` event context.** Runner-provided error analysis now rides the failed run result into `promptRunner`, so fallback provider marking reuses the category and wait-time already computed by the runner instead of analyzing the wrapper error again. The emitted `AI_PROVIDER_EXECUTION_FAILED` context also includes `errorAnalysis` for downstream auto-fix and diagnostics consumers.
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 59fd46c08c..61da8d401d 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -15,7 +15,6 @@ import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
import { activeAgents, runnerAgents, userTerminatedAgents, useRunner } from './agentState.js';
import { cleanupAgentWorktree, syncRunnerAgents } from './agentLifecycle.js';
-import { cleanupOrphanedWorktrees } from './worktreeManager.js';
import { checkForTaskCommit } from './agentRunTracking.js';
import { PATHS } from '../lib/fileUtils.js';
@@ -371,17 +370,16 @@ export async function cleanupOrphanedAgents() {
}
}
- // Clean up worktrees for orphaned agents
+ // Clean up worktrees for the specific agents detected as orphaned this cycle.
+ // The blanket "reap every worktree dir with no live agent" sweep lives in the
+ // scheduled `agent-data-cleanup` job (autonomousJobs.js), NOT here — running it
+ // on the 15-min health-check hot path gave it a wide window to remove a human's
+ // in-flight `/claim` worktree mid-review. Targeted cleanup of a known-dead
+ // agent's own worktree is safe and stays.
for (const { agentId } of orphanedTaskIds) {
await cleanupAgentWorktree(agentId, false);
}
- // Also clean up any orphaned worktrees not tracked by any agent
- const activeIds = new Set([...activeAgents.keys(), ...runnerAgents.keys()]);
- await cleanupOrphanedWorktrees(ROOT_DIR, activeIds).catch(err => {
- console.log(`⚠️ Orphaned worktree cleanup failed: ${err.message}`);
- });
-
// Handle orphaned tasks - reset for retry or create investigation task
for (const { taskId, agentId } of orphanedTaskIds) {
await handleOrphanedTask(taskId, agentId, getTask);
diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.js
index 889291c5da..1c69d22533 100644
--- a/server/services/autonomousJobs.js
+++ b/server/services/autonomousJobs.js
@@ -28,6 +28,7 @@ import { runGoalCheckIn } from './goalCheckIn.js'
import { validateCommand, redactOutput, ALLOWED_COMMANDS_SORTED } from '../lib/commandSecurity.js'
import { getUserTimezone, getLocalParts, nextLocalTime } from '../lib/timezone.js'
import { parseCronToNextRun } from './eventScheduler.js'
+import { cleanupOrphanedWorktrees } from './worktreeManager.js'
/**
* Run the moltworld-explore.mjs script as a child process (no AI agent needed).
@@ -73,36 +74,51 @@ function runMoltworldExploration() {
* instead of spawning AI agents. Key is the scriptHandler name, value is the function.
*/
/**
- * Remove completed agent data directories older than 7 days.
+ * Remove completed agent data directories older than 7 days, and reap leaked
+ * CoS agent worktrees (dirs whose agent is no longer live).
+ *
+ * The worktree sweep lives here, on the daily scheduled cadence, rather than on
+ * the 15-min CoS health-check hot path — running it that often gave it a wide
+ * window to remove a human's in-flight `/claim` worktree mid-review.
+ * `cleanupOrphanedWorktrees` itself also skips `claim-*` worktrees outright, so
+ * the daily cadence is purely about reaping abandoned `agent-*` trees.
*/
async function agentDataCleanup() {
- const agentsDir = join(PATHS.cos, 'agents')
- if (!existsSync(agentsDir)) return { cleaned: 0 }
-
- const entries = await readdir(agentsDir)
- const cutoff = Date.now() - 7 * DAY
- let cleaned = 0
-
- // Get active agent IDs so we never delete data for running agents
+ // Get active agent IDs so we never delete data / worktrees for running agents
const { getActiveAgentIds } = await import('./subAgentSpawner.js')
const activeIds = new Set(getActiveAgentIds())
- for (const entry of entries) {
- if (activeIds.has(entry)) continue
- const entryPath = join(agentsDir, entry)
- const info = await stat(entryPath).catch(() => null)
- if (!info?.isDirectory()) continue
- if (info.mtimeMs < cutoff) {
- const removed = await rm(entryPath, { recursive: true, force: true }).then(() => true, (err) => {
- console.warn(`⚠️ Failed to clean agent dir ${entry}: ${err.message}`)
- return false
- })
- if (removed) cleaned++
+ const agentsDir = join(PATHS.cos, 'agents')
+ let cleaned = 0
+ if (existsSync(agentsDir)) {
+ const entries = await readdir(agentsDir)
+ const cutoff = Date.now() - 7 * DAY
+
+ for (const entry of entries) {
+ if (activeIds.has(entry)) continue
+ const entryPath = join(agentsDir, entry)
+ const info = await stat(entryPath).catch(() => null)
+ if (!info?.isDirectory()) continue
+ if (info.mtimeMs < cutoff) {
+ const removed = await rm(entryPath, { recursive: true, force: true }).then(() => true, (err) => {
+ console.warn(`⚠️ Failed to clean agent dir ${entry}: ${err.message}`)
+ return false
+ })
+ if (removed) cleaned++
+ }
}
}
- console.log(`🧹 Agent data cleanup: removed ${cleaned} directories older than 7 days`)
- return { cleaned }
+ // Reap orphaned agent worktrees not tracked by any live agent (moved off the
+ // CoS hot path). The helper guards `claim-*` worktrees, so this can't touch a
+ // human's in-flight claim.
+ const worktreesReaped = await cleanupOrphanedWorktrees(PATHS.root, activeIds).catch((err) => {
+ console.warn(`⚠️ Orphaned worktree cleanup failed: ${err.message}`)
+ return 0
+ })
+
+ console.log(`🧹 Agent data cleanup: removed ${cleaned} dir(s) older than 7 days, reaped ${worktreesReaped} orphaned worktree(s)`)
+ return { cleaned, worktreesReaped }
}
const SCRIPT_HANDLERS = {
@@ -364,7 +380,7 @@ Phase 4 — Report:
{
id: 'job-agent-data-cleanup',
name: 'Agent Data Cleanup',
- description: 'Remove completed agent data older than 7 days.',
+ description: 'Remove completed agent data older than 7 days and reap orphaned agent worktrees.',
category: 'agent-data-cleanup',
interval: 'daily',
intervalMs: DAY,
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 8471771453..d25475a981 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -19,6 +19,24 @@ const WORKTREES_DIR = PATHS.worktrees;
// Lockfiles that npm/yarn/pnpm modify as a side-effect — safe to discard during worktree cleanup
const AUTO_GENERATED_LOCKFILES = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
+/**
+ * True when a worktree directory belongs to a human-driven `/claim` TUI
+ * session, not a CoS agent.
+ *
+ * The `/claim` command creates its worktree at `data/cos/worktrees/claim-<slug>`
+ * — the SAME directory CoS uses for agent worktrees (`agent-<uuid>`). CoS
+ * agent IDs are always `agent-<8-char-uuid>` (see `agentLifecycle.js`), so the
+ * `claim-` prefix is unambiguous. These worktrees are owned by the `/claim`
+ * command's own Phase 7 cleanup; CoS orphan-cleanup MUST skip them. Otherwise
+ * every cleanup cycle (boot + each evaluation) sees a `claim-<slug>` dir with
+ * no matching active agent, treats it as orphaned, and removes it — pruning a
+ * human's in-flight claim mid-review (and, with `{ merge: true }`, even
+ * fast-forwarding the `claim/<slug>` branch into the default branch).
+ */
+export function isHumanClaimWorktree(agentId) {
+ return typeof agentId === 'string' && agentId.startsWith('claim-');
+}
+
/**
* Decide whether an auto-merge into `currentBranch` should be refused.
*
@@ -463,6 +481,9 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds)
const agentId = wt.path.split('/').pop();
handledAgentIds.add(agentId);
+ // Never reap human-driven `/claim` worktrees (`claim-<slug>`) — they belong
+ // to the `/claim` command's own Phase 7 cleanup, not CoS. See isHumanClaimWorktree.
+ if (isHumanClaimWorktree(agentId)) continue;
if (!activeAgentIds.has(agentId)) {
const branchName = wt.branch?.replace('refs/heads/', '') || '';
// Attempt merge so committed work from preserved worktrees (e.g., PR/push failures) isn't lost.
@@ -500,6 +521,8 @@ async function cleanupExternalRepoWorktrees(activeAgentIds, alreadyHandled) {
if (!entry.isDirectory()) continue;
const agentId = entry.name;
if (alreadyHandled.has(agentId) || activeAgentIds.has(agentId)) continue;
+ // Human-driven `/claim` worktrees are not CoS agents — never reap them.
+ if (isHumanClaimWorktree(agentId)) continue;
const worktreePath = join(WORKTREES_DIR, agentId);
const gitFile = join(worktreePath, '.git');
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index 23a04cba3f..518e52ebd6 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import { join } from 'path';
-import { shouldRefuseDefaultBranchMerge } from './worktreeManager.js';
+import { shouldRefuseDefaultBranchMerge, isHumanClaimWorktree } from './worktreeManager.js';
/**
* Tests for the worktree manager service.
@@ -290,6 +290,9 @@ describe('Orphaned Worktree Detection', () => {
return worktrees.filter(wt => {
if (!wt.path.startsWith(worktreesDir)) return false;
const agentId = wt.path.split('/').pop();
+ // Mirror the real cleanup guard: human-driven `/claim` worktrees are
+ // never CoS orphans.
+ if (isHumanClaimWorktree(agentId)) return false;
return !activeAgentIds.has(agentId);
});
}
@@ -327,6 +330,38 @@ describe('Orphaned Worktree Detection', () => {
expect(orphans).toHaveLength(0);
});
+
+ it('never flags a human-driven /claim worktree as orphaned', () => {
+ const worktrees = [
+ { path: '/data/cos/worktrees/agent-bbb', branch: 'refs/heads/cos/task-2/agent-bbb' },
+ { path: '/data/cos/worktrees/claim-extract-compare-helpers', branch: 'refs/heads/claim/extract-compare-helpers' }
+ ];
+ // No active agents at all — the dead CoS agent IS an orphan, but the claim
+ // worktree must be left alone (it's owned by /claim's own cleanup).
+ const orphans = findOrphanedWorktrees(worktrees, '/data/cos/worktrees', new Set());
+
+ expect(orphans).toHaveLength(1);
+ expect(orphans[0].path).toContain('agent-bbb');
+ expect(orphans.some(o => o.path.includes('claim-'))).toBe(false);
+ });
+});
+
+describe('isHumanClaimWorktree', () => {
+ it('is true for /claim worktree dir names', () => {
+ expect(isHumanClaimWorktree('claim-extract-compare-helpers')).toBe(true);
+ expect(isHumanClaimWorktree('claim-codex5-onboarding-capability-map')).toBe(true);
+ });
+
+ it('is false for CoS agent worktree dir names', () => {
+ expect(isHumanClaimWorktree('agent-1a2b3c4d')).toBe(false);
+ expect(isHumanClaimWorktree('cos-task-xyz')).toBe(false);
+ });
+
+ it('is false for non-string / empty input (fail safe)', () => {
+ expect(isHumanClaimWorktree(undefined)).toBe(false);
+ expect(isHumanClaimWorktree(null)).toBe(false);
+ expect(isHumanClaimWorktree('')).toBe(false);
+ });
});
describe('Default-Branch Merge Gate (defense-in-depth)', () => {