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: a review loop blocked on a leftover /do:next worktree now recovers

[._.]/ Adam Eivy4d2679f5725b
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index dd4fe18c5b..e3ff6c2fe6 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -35,7 +35,7 @@ import { isTruthyMeta, isFalsyMeta, protectedAgentIds } from './agentState.js';
import { PATHS, ensureDir } from '../lib/fileUtils.js';
import * as git from './git.js';
import { detectConflicts } from './taskConflict.js';
-import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError } from './worktreeManager.js';
+import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError, releaseIdleSiblingNextHolder } from './worktreeManager.js';
import { resolveSpawnCwd, usesCreativeDirectorScratchCwd, creativeDirectorScratchCwd } from '../lib/spawnCwd.js';
import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';
import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';
@@ -86,12 +86,6 @@ const WORKTREE_BUSY_MAX_ATTEMPTS = 5;
// service before the shared task-target-branch contract existed.
export { resolveTaskTargetBranch as resolveTaskExistingBranch } from '../lib/taskTargetBranch.js';
-/** `protectedAgentIds` over a freshly-read agent list — see agentState.js. */
-async function getProtectedAgentIds() {
- const { getAgents } = await import('./cos.js');
- return protectedAgentIds(await getAgents());
-}
-
/**
* Take over the worktree that already holds `branchName`, for a task whose whole
* purpose is to run ON that branch (a merge/review-loop follow-up, a resume).
@@ -117,14 +111,31 @@ async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName,
// Fail CLOSED on an unreadable agent list: an empty protected set would read as
// "nothing is running", which is the one wrong answer here — it would move a
// live run's directory. The caller's timed pause is the safe outcome instead.
- const activeAgentIds = await getProtectedAgentIds().catch(err => {
+ const { getAgents } = await import('./cos.js');
+ const agents = await getAgents().catch(err => {
emitLog('warn', `🌳 Skipping worktree adoption for task ${taskId} — could not read the agent list: ${err.message}`, { taskId });
return null;
});
- if (!activeAgentIds) return null;
+ if (!agents) return null;
+ const activeAgentIds = protectedAgentIds(agents);
const holder = await findAdoptableWorktreeForBranch(workspacePath, branchName, { activeAgentIds, preferredPath, allowLiveClaim });
- if (!holder) return null;
+ if (!holder) {
+ // Not adoptable, but a coordinator follow-up may still free the branch from an
+ // idle `/do:next` sibling tree by detaching it in place — `createWorktree`
+ // then attaches normally instead of waiting out a holder that never leaves.
+ if (allowLiveClaim) {
+ const activeWorkspacePaths = agents
+ .filter(a => activeAgentIds.has(a.id))
+ .map(a => a.workspacePath || a.metadata?.workspacePath);
+ const released = await releaseIdleSiblingNextHolder(workspacePath, branchName, { activeWorkspacePaths }).catch(err => {
+ emitLog('warn', `🌳 Could not release ${branchName} for task ${taskId}: ${err.message}`, { taskId });
+ return null;
+ });
+ if (released) emitLog('info', `🌳 Released ${branchName} from idle worktree ${released.path} for task ${taskId}`, { taskId, branch: branchName });
+ }
+ return null;
+ }
const worktreeInfo = await adoptWorktree(agentId, workspacePath, holder.path, branchName).catch(err => {
emitLog('warn', `🌳 Could not adopt ${holder.path} holding ${branchName} for task ${taskId}: ${err.message}`, { taskId });
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index d49d72e2b4..c4944225f1 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -45,6 +45,7 @@ vi.mock('./worktreeManager.js', async (importOriginal) => ({
createWorktree: vi.fn(),
adoptWorktree: vi.fn(),
findAdoptableWorktreeForBranch: vi.fn().mockResolvedValue(null),
+ releaseIdleSiblingNextHolder: vi.fn().mockResolvedValue(null),
mergeBaseIntoFeatureWorktree: vi.fn(),
}));
vi.mock('./agentAppWorkspace.js', () => ({
@@ -69,7 +70,7 @@ import { ensureLatest } from './git.js';
import { execGit } from '../lib/execGit.js';
import { detectConflicts } from './taskConflict.js';
import { getAppWorkspace } from './agentAppWorkspace.js';
-import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch } from './worktreeManager.js';
+import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, releaseIdleSiblingNextHolder } from './worktreeManager.js';
import { ensureDir, PATHS } from '../lib/fileUtils.js';
import { creativeDirectorScratchCwd } from '../lib/spawnCwd.js';
@@ -566,6 +567,21 @@ describe('prepareAgentWorkspace — the branch is checked out in another worktre
expect(r.outcome).toBe('ready');
});
+ // A `/do:next` run keeps its tree in a sibling directory outside the managed
+ // root, which adoption refuses. Releasing that idle holder lets the follow-up
+ // attach instead of pausing until its busy budget runs out.
+ it('releases an idle /do:next sibling holder for a review-loop follow-up, then attaches', async () => {
+ getAgents.mockResolvedValue([{ id: 'agent-live', status: 'running', metadata: { workspacePath: '/elsewhere/live' } }]);
+ releaseIdleSiblingNextHolder.mockResolvedValueOnce({ path: '/repos/next-issue-1' });
+ createWorktree.mockResolvedValueOnce({ worktreePath: '/mock/worktrees/agent-new', branchName: 'cos/task-x/agent-y', baseBranch: null });
+
+ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask() });
+
+ expect(releaseIdleSiblingNextHolder).toHaveBeenCalledWith(expect.any(String), 'cos/task-x/agent-y', { activeWorkspacePaths: ['/elsewhere/live'] });
+ expect(r.outcome).toBe('ready');
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
// A plain resume never targets a claim tree — its pointer names a CoS
// `agent-*` worktree — so it must not carry the same carve-out.
it('does not opt into live-claim adoption for a plain resume', async () => {
@@ -576,6 +592,7 @@ describe('prepareAgentWorkspace — the branch is checked out in another worktre
const [, , opts] = findAdoptableWorktreeForBranch.mock.calls.at(-1);
expect(opts.allowLiveClaim).toBe(false);
+ expect(releaseIdleSiblingNextHolder).not.toHaveBeenCalled();
});
// Adoption MOVES the directory, so the protected set has to cover every agent
diff --git a/server/services/cos.js b/server/services/cos.js
index df65b9a6bb..a292043bd0 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -143,7 +143,8 @@ import {
countRunningAgentsByProject,
isWithinProjectLimit,
checkStagePrecondition,
- applyAppWorktreeDefault
+ applyAppWorktreeDefault,
+ unblockExpiredCooldowns
} from './cosTaskGenerator.js';
export { evaluateTasks, checkStagePrecondition, applyAppWorktreeDefault };
@@ -435,6 +436,16 @@ async function runStart() {
emitLog('info', `🧹 Periodic cleanup: ${cleaned} orphaned agent(s)`);
}
await resetOrphanedTasks();
+ // Evaluation is event-driven, so without this cadence a timed pause
+ // (`worktree-busy`, `orphan-cooldown`) whose `cooldownUntil` lapsed would
+ // sit blocked until the next restart or manual evaluate.
+ const revived = await getAllTasks()
+ .then(({ user, cos: internal }) => unblockExpiredCooldowns(user, internal))
+ .catch((err) => {
+ console.warn(`⚠️ unblockExpiredCooldowns failed: ${err?.message || err}`);
+ return 0;
+ });
+ if (revived > 0) scheduleDequeue();
const { archived } = await _archiveStaleAgents().catch(err => {
console.warn(`⚠️ _archiveStaleAgents failed: ${err?.message || err}`, err?.stack || '');
return { archived: 0 };
diff --git a/server/services/cosTaskGenerator.cooldown.test.js b/server/services/cosTaskGenerator.cooldown.test.js
index e73adb8bcb..956b35946b 100644
--- a/server/services/cosTaskGenerator.cooldown.test.js
+++ b/server/services/cosTaskGenerator.cooldown.test.js
@@ -57,10 +57,11 @@ beforeEach(() => {
describe('unblockExpiredCooldowns', () => {
it('routes each revived task back to the store it was read from', async () => {
- await unblockExpiredCooldowns(
+ // The count drives the health timer's follow-up dequeue.
+ await expect(unblockExpiredCooldowns(
store([cooldownTask('u1', EXPIRED)]),
store([cooldownTask('c1', EXPIRED)])
- );
+ )).resolves.toBe(2);
expect(updateTaskMock).toHaveBeenCalledTimes(2);
expect(updateTaskMock.mock.calls.map(([id, , taskType]) => [id, taskType])).toEqual([
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index ea690e5f5e..31aacec509 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -691,6 +691,7 @@ export function isWithinProjectLimit(task, agentsByProject, perProjectLimit) {
* otherwise sit blocked forever.
*/
async function unblockExpiredCooldownsInQueue(blocked, defaultTaskType) {
+ let revived = 0;
for (const task of blocked || []) {
if (!TIMED_COOLDOWN_BLOCKED_CATEGORIES.has(task.metadata?.blockedCategory) || !task.metadata?.cooldownUntil) continue;
// An unparseable `cooldownUntil` yields NaN, and NaN loses BOTH comparisons —
@@ -710,7 +711,9 @@ async function unblockExpiredCooldownsInQueue(blocked, defaultTaskType) {
cooldownUntil: undefined
}
}, task.taskType || defaultTaskType);
+ revived++;
}
+ return revived;
}
/**
@@ -723,10 +726,13 @@ async function unblockExpiredCooldownsInQueue(blocked, defaultTaskType) {
* version re-derived the queue of origin with `userBlocked.includes(task)` per
* task, an O(N) scan inside an O(N) loop (#3500). Passing the origin down makes
* classification O(1) and the whole pass linear.
+ *
+ * @returns {Promise<number>} how many tasks were revived
*/
export async function unblockExpiredCooldowns(userTaskData, cosTaskData) {
- await unblockExpiredCooldownsInQueue(userTaskData.grouped?.blocked, 'user');
- await unblockExpiredCooldownsInQueue(cosTaskData.grouped?.blocked, 'internal');
+ const user = await unblockExpiredCooldownsInQueue(userTaskData.grouped?.blocked, 'user');
+ const internal = await unblockExpiredCooldownsInQueue(cosTaskData.grouped?.blocked, 'internal');
+ return user + internal;
}
/**
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 5388a8024d..02b1554560 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -675,6 +675,80 @@ export async function findAdoptableWorktreeForBranch(sourceWorkspace, branchName
return { path: holder.path, agentId };
}
+// How long a sibling `/do:next` tree must sit untouched before a follow-up may
+// release its branch. An agent that finished and kept its tree (waiting on CI,
+// say) goes quiet for far longer; a live session touches its index constantly.
+export const SIBLING_NEXT_HOLDER_IDLE_MS = 10 * 60 * 1000;
+
+/**
+ * Free `branchName` from an idle slashdo `/do:next` worktree that sits OUTSIDE
+ * `data/cos/worktrees/`, by DETACHING that tree's HEAD in place.
+ *
+ * `/do:next` cuts `next/<slug>` into a sibling directory of the repo
+ * (`../next-issue-<n>`). A run that finished but kept its tree still holds the
+ * branch, and the review-loop follow-up for that PR then cannot `worktree add`
+ * it — adoption refuses any tree outside the managed root, so the follow-up
+ * waits out its whole `worktree-busy` budget and blocks. Unlike adoption this
+ * never moves or deletes the directory: a detached HEAD at the same commit keeps
+ * every file, and `git switch <branch>` restores it.
+ *
+ * Refuses (returns false) unless ALL hold: the branch is `next/…`; the holder is
+ * a linked worktree (never the primary checkout) outside the managed root,
+ * unlocked; no running/paused agent works inside it; nothing in it changed for
+ * `idleMs`; the tree is clean, untracked files included; and HEAD is already on
+ * the remote, so nothing is left only in that tree.
+ *
+ * @param {string} sourceWorkspace
+ * @param {string} branchName
+ * @param {{ activeWorkspacePaths?: string[], idleMs?: number, nowMs?: number }} [options]
+ * @returns {Promise<{ path: string }|null>} the released holder, or null
+ */
+export async function releaseIdleSiblingNextHolder(sourceWorkspace, branchName, {
+ activeWorkspacePaths = [],
+ idleMs = SIBLING_NEXT_HOLDER_IDLE_MS,
+ nowMs = Date.now(),
+} = {}) {
+ if (!sourceWorkspace || !branchName?.startsWith('next/')) return null;
+
+ const worktrees = await listWorktrees(sourceWorkspace).catch(() => []);
+ const holderIndex = worktrees.findIndex(wt => wt.branch?.replace('refs/heads/', '') === branchName);
+ // Index 0 is the main worktree — the user's own checkout is never released.
+ if (holderIndex <= 0) return null;
+ const holder = worktrees[holderIndex];
+ if (holder.locked || holder.prunable || !existsSync(holder.path)) return null;
+ if (isPathInsideDir(WORKTREES_DIR, holder.path)) return null;
+ if (activeWorkspacePaths.some(p => p && (pathsEqual(p, holder.path) || isPathInsideDir(holder.path, p)))) return null;
+
+ const git = (args) => execGit(args, holder.path).then(r => r.stdout.trim());
+ // Idleness first; `--no-optional-locks` keeps `status` from refreshing the
+ // index and so resetting the very clock this reads on a refused attempt.
+ const gitDir = await git(['rev-parse', '--absolute-git-dir']).catch(() => null);
+ if (!gitDir) return null;
+ const mtimes = await Promise.all(['index', 'HEAD', join('logs', 'HEAD')]
+ .map(f => stat(join(gitDir, f)).then(s => s.mtimeMs, () => 0)));
+ if (nowMs - Math.max(...mtimes) < idleMs) return null;
+
+ // Stricter than `classifyWorktreeDirt` on purpose: this tree isn't PortOS's,
+ // so no path counts as disposable scratch.
+ const porcelain = await git(['--no-optional-locks', 'status', '--porcelain', '--untracked-files=all']).catch(() => null);
+ if (porcelain !== '') return null;
+ const remoteRef = await git(['rev-parse', '--verify', '--quiet', `${branchName}@{upstream}`])
+ .catch(() => git(['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branchName}`]))
+ .catch(() => null);
+ if (!remoteRef) return null;
+ const pushed = await execGit(['merge-base', '--is-ancestor', 'HEAD', remoteRef], holder.path)
+ .then(() => true, () => false);
+ if (!pushed) return null;
+
+ const detached = await execGit(['switch', '--detach', '--quiet'], holder.path).then(() => true, (err) => {
+ console.warn(`⚠️ Could not detach ${holder.path} to release ${branchName}: ${err.message}`);
+ return false;
+ });
+ if (!detached) return null;
+ console.log(`🌳 Released ${branchName} from idle /do:next worktree ${holder.path} (HEAD detached in place)`);
+ return { path: holder.path };
+}
+
/**
* Adopt an INTERRUPTED agent's surviving worktree on behalf of the agent that is
* retrying its task, instead of building a fresh one from the default branch.
diff --git a/server/services/worktreeManager.releaseNextHolder.test.js b/server/services/worktreeManager.releaseNextHolder.test.js
new file mode 100644
index 0000000000..5cf20e66f3
--- /dev/null
+++ b/server/services/worktreeManager.releaseNextHolder.test.js
@@ -0,0 +1,77 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtemp, rm, writeFile, realpath } from 'fs/promises';
+import { existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { execGit } from '../lib/execGit.js';
+import { releaseIdleSiblingNextHolder } from './worktreeManager.js';
+
+// Real git, because the guard's whole job is reading real repo state (porcelain,
+// upstream ancestry, git-dir mtimes) before it detaches someone's tree.
+const BRANCH = 'next/issue-1';
+const LATER = () => Date.now() + 60 * 60 * 1000;
+
+let root, repo, holder;
+const git = (args, cwd = repo) => execGit(args, cwd).then(r => r.stdout.trim());
+const holderBranch = () => git(['branch', '--show-current'], holder);
+
+beforeEach(async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ root = await realpath(await mkdtemp(join(tmpdir(), 'release-next-')));
+ const remote = join(root, 'remote.git');
+ repo = join(root, 'repo');
+ holder = join(root, 'next-issue-1');
+ await git(['init', '--bare', '-b', 'main', remote], root);
+ await git(['init', '-b', 'main', repo], root);
+ for (const [k, v] of [['user.email', '[email protected]'], ['user.name', 'Test'], ['commit.gpgsign', 'false']]) await git(['config', k, v]);
+ await git(['remote', 'add', 'origin', remote]);
+ await git(['commit', '--allow-empty', '-m', 'init']);
+ await git(['push', '-q', '-u', 'origin', 'main']);
+ await git(['worktree', 'add', '-q', '-b', BRANCH, holder, 'main']);
+ await git(['commit', '--allow-empty', '-m', 'work'], holder);
+ await git(['push', '-q', '-u', 'origin', BRANCH], holder);
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await rm(root, { recursive: true, force: true });
+});
+
+describe('releaseIdleSiblingNextHolder', () => {
+ it('detaches an idle, clean, pushed sibling tree in place so the branch can be checked out', async () => {
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, { nowMs: LATER() })).resolves.toEqual({ path: holder });
+ expect(existsSync(holder)).toBe(true);
+ expect(await holderBranch()).toBe('');
+ await git(['worktree', 'add', '-q', join(root, 'follow-up'), BRANCH]);
+ });
+
+ it('refuses a tree with a commit that exists only locally', async () => {
+ await git(['commit', '--allow-empty', '-m', 'unpushed'], holder);
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, { nowMs: LATER() })).resolves.toBeNull();
+ expect(await holderBranch()).toBe(BRANCH);
+ });
+
+ it('refuses a tree with an untracked file', async () => {
+ await writeFile(join(holder, 'notes.txt'), 'draft');
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, { nowMs: LATER() })).resolves.toBeNull();
+ expect(await holderBranch()).toBe(BRANCH);
+ });
+
+ it('refuses a tree touched within the idle window', async () => {
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH)).resolves.toBeNull();
+ expect(await holderBranch()).toBe(BRANCH);
+ });
+
+ it('refuses a tree a running agent works in', async () => {
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, { nowMs: LATER(), activeWorkspacePaths: [holder] })).resolves.toBeNull();
+ expect(await holderBranch()).toBe(BRANCH);
+ });
+
+ it('never touches the primary checkout or a non-/do:next branch', async () => {
+ await git(['switch', '-q', '--detach'], holder);
+ await git(['switch', '-q', BRANCH]);
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, { nowMs: LATER() })).resolves.toBeNull();
+ expect(await git(['branch', '--show-current'])).toBe(BRANCH);
+ await expect(releaseIdleSiblingNextHolder(repo, 'feature/x', { nowMs: LATER() })).resolves.toBeNull();
+ });
+});