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: preserve swarm claim ownership through merge handoff (#10035)

[._.]/ Adam Eivy5e5673bdd67e
diff --git a/server/lib/README.md b/server/lib/README.md
index 502822e693..4b418f7d0d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -508,7 +508,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, and the orphan sweep. `retryHoldMetadata(agentId, now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isRetryHoldOwner(metadata, agentId)` gate the spawn and the owner-scoped release; `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. |
| `taskStatusTransition.js` | The CoS task STATUS TRANSITION vocabulary (#6620) — `resolveTaskStatusTransition(previousStatus, nextStatus)` classifies one update's status pair ONCE and returns `{ action, isRevive, isRequeue, entersInProgress, leavesInProgress, leavesBlocked, isTerminal }`, so `writeTaskUpdate`'s blocked/pause clear, resume-pointer drop, retry-hold retire, claim release, requeue stamp and emitted `tasks:changed` action all read one answer instead of re-deriving seven. A falsy `nextStatus` means "this patch carries no status" (a lease-renewal heartbeat) and releases nothing. `isTerminalTaskStatus(status)` is the shared `completed`/`blocked` predicate `cosTaskStore` and `cosTaskMerge` both read. Pure — metadata predicates (is this block a pause?) stay at the application site. |
| `taskTargetBranch.js` | Pure task-branch contract: `resolveTaskTargetBranch(metadata)` reads a retry's legacy `existingBranch` or a review-loop follow-up's canonical `reviewLoopPRBranch`; `shouldStripTaskTargetBranch(metadata)` identifies only retry-owned pointers for terminal cleanup. |
-| `claimContinuation.js` | Claim-flow relaunch pointer. `claimContinuationBranch(claimTarget)` is the `claim/issue-<n>` or `claim/<key>` branch a pinned target checks out. `claimContinuationPointer(...)` names the `claim-*` worktree already holding that branch when a relaunch should finish it in place (locked, prunable, unmanaged, or occupied by another running/paused agent → null). `claimContinuationWorkspace(...)` turns a still-on-disk pointer into the cwd the next agent uses without moving the directory. `claimOwnershipBinding(task)` is the branch (or "picks its own", for a swarm orchestrator) a claim run registers on its agent record, and `claimContinuationAdmission(...)` is the launch-time ownership check that re-reads holder, branch and live owners before a cached pointer may be entered (anything unreadable or changed → refuse, the caller defers; a possible swarm owner holds the launch until that run ends). |
+| `claimContinuation.js` | Claim-flow relaunch pointer. `claimContinuationBranch(claimTarget)` is the `claim/issue-<n>` or `claim/<key>` branch a pinned target checks out. `claimContinuationPointer(...)` names the `claim-*` worktree already holding that branch when a relaunch should finish it in place (locked, prunable, unmanaged, or occupied by another running/paused agent → null). `claimContinuationWorkspace(...)` turns a still-on-disk pointer into the cwd the next agent uses without moving the directory. `claimOwnershipBinding(task)` is the branch (or "picks its own", for a swarm orchestrator) a claim run registers on its agent record, and `claimBranchAdmission(...)` gates coordinator adoption and detach with the same branch/repository owners; `claimContinuationAdmission(...)` is the launch-time ownership check that re-reads holder, branch and live owners before a cached pointer may be entered (anything unreadable or changed → refuse, the caller defers; a possible swarm owner holds the launch until that run ends). |
| `scheduledTaskTypes.js` | Registered scheduled task names (`SELF_IMPROVEMENT_TASK_TYPES`), shared by schedule configuration and authoritative skill routing; plus the retired-name map (`TASK_TYPE_RENAMES`, `currentTaskTypeName`, `taskExecutionKey`) for tasks and records written before a task rename. |
| `scheduleExecutionFieldsValidation.js` | `scheduleExecutionFieldsSchema` validates optional prompt and provider/model selections before schedule writes, preserving null/empty clears. |
| `scheduleRunOrder.js` | Storage rules for a task's advisory `suggestedAfter` list — which OTHER scheduled tasks to run first. `normalizeSuggestedAfter` drops blanks, duplicates and self-references and caps at `SUGGESTED_AFTER_MAX`; the shipped order it defaults to is `auditCatalog.AUDIT_SUGGESTED_AFTER`, layered at read time in `getScheduleStatus`. Advisory only — the ENFORCED dependency field is `runAfter`. Pure — no I/O. |
diff --git a/server/lib/claimContinuation.js b/server/lib/claimContinuation.js
index 12b1448c3e..1e0b9a741b 100644
--- a/server/lib/claimContinuation.js
+++ b/server/lib/claimContinuation.js
@@ -93,13 +93,14 @@ function registeredClaimBranch(agent) {
*/
function claimHolderOccupancy({ agents, holderPath, branchName, sourceWorkspace, ignoreIds }) {
let ambiguous = false;
+ const claimHolder = /^(claim|next)\//.test(branchName) || isHumanClaimWorktree(worktreeAgentId(holderPath));
for (const agent of agents) {
if (!agent || ignoreIds.has(agent.id) || !isLiveAgent(agent)) continue;
const workspace = agentWorkspace(agent);
- if (samePath(workspace, holderPath) || (workspace && isPathInsideDir(holderPath, workspace))) return 'active';
+ if (samePath(workspace, holderPath) || (holderPath && workspace && isPathInsideDir(holderPath, workspace))) return 'active';
if (!inRepository(agent, sourceWorkspace)) continue;
if (registeredClaimBranch(agent) === branchName) return 'active';
- if (isTruthyMeta(agent.claimPicksOwnBranch ?? agent.metadata?.claimPicksOwnBranch)) ambiguous = true;
+ if (claimHolder && isTruthyMeta(agent.claimPicksOwnBranch ?? agent.metadata?.claimPicksOwnBranch)) ambiguous = true;
}
return ambiguous ? 'ambiguous' : null;
}
@@ -177,6 +178,32 @@ export function claimContinuationWorkspace({ metadata, pathExists = () => false,
};
}
+/**
+ * Shared admission for coordinator adoption/release and claim continuations.
+ * A missing cache may discover the holder; a supplied cache must still match.
+ * With no holder, branch/repository owners still prevent a new checkout from
+ * taking over publication while the original run is between worktrees.
+ */
+export function claimBranchAdmission({ branchName, preferredPath, agentId, sourceWorkspace, worktrees, agents, ignoreIds = [] }) {
+ if (!Array.isArray(worktrees) || !Array.isArray(agents)) return { admit: false, reason: 'ownership-unreadable' };
+ if (!branchName) return { admit: false, reason: 'pointer-incomplete' };
+ const holder = preferredPath
+ ? worktrees.find(wt => samePath(wt?.path, preferredPath))
+ : worktrees.find(wt => String(wt?.branch || '').replace(/^refs\/heads\//, '') === branchName);
+ if (preferredPath && !holder) return { admit: false, reason: 'holder-missing' };
+ if (holder && String(holder.branch || '').replace(/^refs\/heads\//, '') !== branchName) {
+ return { admit: false, reason: 'branch-changed' };
+ }
+ if (holder?.locked || holder?.prunable) return { admit: false, reason: 'holder-locked' };
+ const occupancy = claimHolderOccupancy({
+ agents, holderPath: holder?.path, branchName, sourceWorkspace,
+ ignoreIds: new Set([agentId, ...ignoreIds].filter(Boolean)),
+ });
+ if (occupancy === 'active') return { admit: false, reason: 'owner-active' };
+ if (occupancy === 'ambiguous') return { admit: false, reason: 'owner-ambiguous' };
+ return { admit: true };
+}
+
/**
* Launch-time ownership admission for an in-place continuation. A pointer is a
* cached answer from when the previous run died; another owner can appear after
@@ -207,16 +234,8 @@ export function claimContinuationAdmission({ metadata, agentId, sourceWorkspace,
const worktreePath = metadata?.resumeWorktreePath;
if (!branchName || !worktreePath) return { admit: false, reason: 'pointer-incomplete' };
- const holder = worktrees.find((wt) => samePath(wt?.path, worktreePath));
- if (!holder) return { admit: false, reason: 'holder-missing' };
- if (String(holder.branch || '').replace(/^refs\/heads\//, '') !== branchName) {
- return { admit: false, reason: 'branch-changed' };
- }
- if (holder.locked || holder.prunable) return { admit: false, reason: 'holder-locked' };
-
- const ignoreIds = new Set([agentId, metadata?.resumedFromAgentId].filter(Boolean));
- const occupancy = claimHolderOccupancy({ agents, holderPath: holder.path, branchName, sourceWorkspace, ignoreIds });
- if (occupancy === 'active') return { admit: false, reason: 'owner-active' };
- if (occupancy === 'ambiguous') return { admit: false, reason: 'owner-ambiguous' };
- return { admit: true };
+ return claimBranchAdmission({
+ branchName, preferredPath: worktreePath, agentId, sourceWorkspace, worktrees, agents,
+ ignoreIds: [metadata?.resumedFromAgentId],
+ });
}
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index c1e68b478c..07c3cf0ad4 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -44,7 +44,7 @@ import { getAppWorkspace, getAppDataForTask } from './agentAppWorkspace.js';
import { createJiraTicketForTask } from './promptSections/appContext.js';
import { INVESTIGATION_TASK_DELIVERY, isInvestigationTask } from '../lib/investigationTasks.js';
import { isNonCommittingCoordinatorTask, resolveTaskHookType } from './taskTypeHooks.js';
-import { claimContinuationAdmission, claimContinuationWorkspace } from '../lib/claimContinuation.js';
+import { claimBranchAdmission, claimContinuationAdmission, claimContinuationWorkspace } from '../lib/claimContinuation.js';
const ROOT_DIR = PATHS.root;
@@ -104,10 +104,10 @@ export { resolveTaskTargetBranch as resolveTaskExistingBranch } from '../lib/tas
* The one caller-gated exception is `allowLiveClaim`: a non-committing
* coordinator follow-up (`isNonCommittingCoordinatorTask` — a review-loop
* resolve-and-merge or a PR-remediation follow-up) may take over a `claim-*`
- * holder too, because its whole deliverable names that exact branch as the one
- * to finish and land.
+ * holder too, but only after branch/repository admission verifies that no
+ * running or paused claim owner still controls publication and cleanup.
*
- * @returns {Promise<{ worktreeInfo: object, adoptedFrom: string }|null>}
+ * @returns {Promise<{ worktreeInfo: object, adoptedFrom: string }|{ refused: string }|null>}
*/
async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName, preferredPath = null, taskId, allowLiveClaim = false }) {
// Fail CLOSED on an unreadable agent list: an empty protected set would read as
@@ -118,10 +118,16 @@ async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName,
emitLog('warn', `🌳 Skipping worktree adoption for task ${taskId} — could not read the agent list: ${err.message}`, { taskId });
return null;
});
- if (!agents) return null;
+ if (!Array.isArray(agents)) return { refused: 'ownership-unreadable' };
+ const worktrees = await listWorktrees(workspacePath).catch(() => null);
+ const admission = claimBranchAdmission({
+ branchName, preferredPath: allowLiveClaim ? preferredPath : null,
+ agentId, sourceWorkspace: workspacePath, agents, worktrees,
+ });
+ if (!admission.admit) return { refused: admission.reason };
const activeAgentIds = protectedAgentIds(agents);
- const holder = await findAdoptableWorktreeForBranch(workspacePath, branchName, { activeAgentIds, preferredPath, allowLiveClaim });
+ const holder = await findAdoptableWorktreeForBranch(workspacePath, branchName, { activeAgentIds, agents, requestingAgentId: agentId, preferredPath, allowLiveClaim });
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`
@@ -130,7 +136,7 @@ async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName,
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 => {
+ const released = await releaseIdleSiblingNextHolder(workspacePath, branchName, { activeWorkspacePaths, agents, requestingAgentId: agentId }).catch(err => {
emitLog('warn', `🌳 Could not release ${branchName} for task ${taskId}: ${err.message}`, { taskId });
return null;
});
@@ -173,16 +179,8 @@ async function prepareRequestedWorktree({
// same safe adoption path review-loop follow-ups use, rather than cutting a
// fresh branch merely because a cached path could not be moved.
const resumeWorktreePath = existingBranch ? task.metadata?.resumeWorktreePath : null;
- // A review-loop / PR-remediation follow-up's whole purpose is landing THIS
- // branch, and the user's own "resolve and merge" trigger (or pr-reviewer's own
- // dispatch) is the signal to finish whatever a `/do:next` claim left on it — so
- // these are the callers allowed to take over a `claim-*` holder instead of
- // retrying against it until the task gives up (#6243). `isNonCommittingCoordinatorTask`
- // is the shared predicate for exactly this "same shape" set (taskTypeHooks.js) —
- // reused here rather than re-listing the flags, so a future follow-up type of the
- // same shape inherits the carve-out too. A plain resume never targets a claim tree
- // (its pointer names a CoS `agent-*` worktree) and doesn't set either follow-up
- // flag, so the predicate is a no-op there.
+ // Coordinator follow-ups may recover a claim directory only after its owner
+ // releases it. Review-only posture never grants another run's merge ownership.
const takeoverPromise = existingBranch
? adoptWorktreeHoldingBranch({
agentId,
@@ -206,14 +204,19 @@ async function prepareRequestedWorktree({
}
const takeover = await takeoverPromise;
+ const attempt = (Number(task.metadata?.worktreeBusyAttempts) || 0) + 1;
+ if (takeover?.refused) {
+ const reason = `Branch ownership prevents worktree takeover (${takeover.refused}); retrying after a short cooldown`;
+ await blockTask(task, reason, attempt <= WORKTREE_BUSY_MAX_ATTEMPTS ? 'worktree-busy' : 'worktree-failed',
+ attempt <= WORKTREE_BUSY_MAX_ATTEMPTS ? {
+ cooldownUntil: new Date(Date.now() + WORKTREE_BUSY_COOLDOWN_MS).toISOString(),
+ worktreeBusyAttempts: attempt,
+ } : {});
+ return { outcome: 'blocked', reason };
+ }
- // Both read only by the block/pause decision below: the failure REASON
- // decides whether the task is unrunnable or merely early, and `attempt` is
- // which branch-busy wait this would be (TASKS.md round-trips metadata as
- // strings, hence the coercion; never reset on revive, so the cap is the
- // task's whole patience budget rather than a per-attempt one).
+ // The failure reason decides whether the task is unrunnable or merely early.
let worktreeError = null;
- const attempt = (Number(task.metadata?.worktreeBusyAttempts) || 0) + 1;
const worktreeInfo = takeover?.worktreeInfo || await createWorktree(agentId, workspacePath, task.id, {
baseBranch: detectedBase || undefined,
existingBranch: existingBranch || undefined,
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index e093333c5e..2fb21684b0 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -76,7 +76,7 @@ import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, listWork
import { ensureDir, PATHS } from '../lib/fileUtils.js';
import { creativeDirectorScratchCwd } from '../lib/spawnCwd.js';
-beforeEach(() => { vi.clearAllMocks(); });
+beforeEach(() => { vi.clearAllMocks(); listWorktrees.mockResolvedValue([]); });
describe('prepareAgentWorkspace — Creative Director scratch cwd (#4650)', () => {
it('pins a CD no-worktree task to an isolated scratch dir and skips the git pull', async () => {
@@ -700,7 +700,7 @@ describe('prepareAgentWorkspace — the branch is checked out in another worktre
const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask() });
- expect(releaseIdleSiblingNextHolder).toHaveBeenCalledWith(expect.any(String), 'cos/task-x/agent-y', { activeWorkspacePaths: ['/elsewhere/live'] });
+ expect(releaseIdleSiblingNextHolder).toHaveBeenCalledWith(expect.any(String), 'cos/task-x/agent-y', expect.objectContaining({ activeWorkspacePaths: ['/elsewhere/live'], agents: expect.any(Array), requestingAgentId: 'agent-new' }));
expect(r.outcome).toBe('ready');
expect(updateTask).not.toHaveBeenCalled();
});
@@ -747,6 +747,50 @@ describe('prepareAgentWorkspace — the branch is checked out in another worktre
expect(r.outcome).toBe('blocked');
});
+ it('recovers an unrelated ordinary agent branch while a swarm owns claim branches', async () => {
+ const path = '/mock/worktrees/agent-y';
+ const branch = 'cos/task-x/agent-y';
+ listWorktrees.mockResolvedValue([{ path, branch: `refs/heads/${branch}` }]);
+ getAgents.mockResolvedValue([{ id: 'agent-parent', status: 'running', claimPicksOwnBranch: true }]);
+ findAdoptableWorktreeForBranch.mockResolvedValue({ path, agentId: 'agent-y' });
+ adoptWorktree.mockResolvedValue({ worktreePath: '/mock/worktrees/agent-new', branchName: branch, adopted: true });
+ const result = await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask() });
+ expect(result.outcome).toBe('ready');
+ expect(adoptWorktree).toHaveBeenCalled();
+ });
+
+ it.each(['claim/issue-42', 'next/issue-42'])('defers coordinator takeover of %s through the child completion and merge window', async branch => {
+ const path = '/mock/worktrees/claim-issue-42';
+ listWorktrees.mockResolvedValue([{ path, branch: `refs/heads/${branch}` }]);
+ getAgents.mockResolvedValue([
+ { id: 'agent-parent', status: 'running', claimPicksOwnBranch: true },
+ { id: 'agent-child', status: 'completed', claimBranch: branch },
+ ]);
+ // Without owner admission this route moves the selected checkout, or
+ // detaches a sibling holder and creates a new one. Neither is authorized.
+ findAdoptableWorktreeForBranch.mockResolvedValue({ path, agentId: 'claim-issue-42' });
+ adoptWorktree.mockResolvedValue({ worktreePath: '/mock/worktrees/agent-new', branchName: branch, adopted: true });
+ const result = await prepareAgentWorkspace({
+ agentId: 'agent-new', task: followUpTask({ reviewLoopPRBranch: branch }),
+ });
+ expect(result).toMatchObject({ outcome: 'blocked', reason: expect.stringContaining('owner-ambiguous') });
+ expect(adoptWorktree).not.toHaveBeenCalled();
+ expect(releaseIdleSiblingNextHolder).not.toHaveBeenCalled();
+ expect(createWorktree).not.toHaveBeenCalled();
+ });
+
+ it.each(['unreadable', 'missing', 'changed'])('refuses %s coordinator ownership without taking a fallback', async fault => {
+ const path = '/mock/worktrees/claim-issue-42';
+ listWorktrees.mockResolvedValue(fault === 'unreadable' ? null : fault === 'missing' ? [] : [{ path, branch: 'refs/heads/claim/issue-99' }]);
+ const result = await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask({
+ reviewLoopPRBranch: 'claim/issue-42', resumeWorktreePath: path,
+ }) });
+ expect(result.outcome).toBe('blocked');
+ expect(adoptWorktree).not.toHaveBeenCalled();
+ expect(releaseIdleSiblingNextHolder).not.toHaveBeenCalled();
+ expect(createWorktree).not.toHaveBeenCalled();
+ });
+
it('falls back to the cooldown pause when the adoption is refused', async () => {
findAdoptableWorktreeForBranch.mockResolvedValue({ path: '/mock/worktrees/agent-y', agentId: 'agent-y' });
adoptWorktree.mockResolvedValue(null);
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 57417d1ad2..3ef60838bc 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -9,6 +9,7 @@
* and the branch cleaned up.
*/
+import { claimBranchAdmission } from '../lib/claimContinuation.js';
import { existsSync, realpathSync } from 'fs';
import { lstat, readlink, readdir, rm, stat, symlink, unlink } from 'fs/promises';
import { dirname, isAbsolute, join, resolve } from 'path';
@@ -750,25 +751,26 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options
* @param {object} [options]
* @param {Set<string>} [options.activeAgentIds] - agents currently running
* @param {string} [options.preferredPath] - cached holder path to validate first
- * @param {boolean} [options.allowLiveClaim=false] - treat a `claim-*` holder as
- * adoptable rather than off-limits. The claim flow keeps no durable agent id
- * for its branch, so this can't distinguish an idle claim tree from a live
- * `/do:next` session in it — pass it only for a task whose whole purpose IS
- * that exact branch (a review-loop resolve-and-merge follow-up, or a PR-
- * remediation follow-up — `isNonCommittingCoordinatorTask` in taskTypeHooks.js),
- * where the task's own deliverable is the signal that the claim's work should
- * be finished and landed. Mirrors `branchReconcile.resolveLiveOwnerReason`'s
- * dispatch-side carve-out for the same directory shape (#6243).
+ * @param {boolean} [options.allowLiveClaim=false] - recover a claim holder only
+ * after the supplied full registry passes branch/repository owner admission.
+ * @param {Array<object>|null} [options.agents] - required for claim recovery
+ * @param {string|null} [options.requestingAgentId] - the requesting run, not its predecessor
* @returns {Promise<{ path: string, agentId: string }|null>}
*/
export async function findAdoptableWorktreeForBranch(sourceWorkspace, branchName, {
activeAgentIds = new Set(),
preferredPath = null,
allowLiveClaim = false,
+ agents = null,
+ requestingAgentId = null,
} = {}) {
if (!sourceWorkspace || !branchName) return null;
- const worktrees = await listWorktrees(sourceWorkspace).catch(() => []);
+ const worktrees = await listWorktrees(sourceWorkspace).catch(() => null);
+ if (!worktrees) return null;
+ if (allowLiveClaim && !claimBranchAdmission({
+ branchName, preferredPath, agentId: requestingAgentId, sourceWorkspace, worktrees, agents,
+ }).admit) return null;
// Git permits one holder per branch. A resume pointer is merely a cache of that
// answer, so validate it against the current worktree list first and then fall
// back to discovery when the cached path went stale or was moved.
@@ -794,7 +796,7 @@ export async function findAdoptableWorktreeForBranch(sourceWorkspace, branchName
// 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.
+// say) goes quiet for far longer; owner admission must pass independently.
export const SIBLING_NEXT_HOLDER_IDLE_MS = 10 * 60 * 1000;
/**
@@ -811,23 +813,28 @@ export const SIBLING_NEXT_HOLDER_IDLE_MS = 10 * 60 * 1000;
*
* 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
+ * unlocked; the readable registry has no branch/repository owner or running/paused
+ * agent 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]
+ * @param {{ activeWorkspacePaths?: string[], agents?: object[], requestingAgentId?: string, idleMs?: number, nowMs?: number }} [options]
* @returns {Promise<{ path: string }|null>} the released holder, or null
*/
export async function releaseIdleSiblingNextHolder(sourceWorkspace, branchName, {
activeWorkspacePaths = [],
+ agents = null,
+ requestingAgentId = null,
idleMs = SIBLING_NEXT_HOLDER_IDLE_MS,
nowMs = Date.now(),
} = {}) {
if (!sourceWorkspace || !branchName?.startsWith('next/')) return null;
- const worktrees = await listWorktrees(sourceWorkspace).catch(() => []);
+ const worktrees = await listWorktrees(sourceWorkspace).catch(() => null);
+ if (!claimBranchAdmission({
+ branchName, agentId: requestingAgentId, sourceWorkspace, worktrees, agents,
+ }).admit) return null;
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;
diff --git a/server/services/worktreeManager.releaseNextHolder.test.js b/server/services/worktreeManager.releaseNextHolder.test.js
index cdf07346b0..5a7c293a1e 100644
--- a/server/services/worktreeManager.releaseNextHolder.test.js
+++ b/server/services/worktreeManager.releaseNextHolder.test.js
@@ -40,40 +40,54 @@ afterEach(async () => {
describe('releaseIdleSiblingNextHolder', () => {
it('detaches an idle, clean, pushed sibling tree in place so the branch can be checked out', async () => {
// git reports forward-slash paths on Windows, so compare resolved paths.
- const released = await releaseIdleSiblingNextHolder(repo, BRANCH, { nowMs: LATER() });
+ const released = await releaseIdleSiblingNextHolder(repo, BRANCH, { agents: [], nowMs: LATER() });
expect(resolve(released.path)).toBe(resolve(holder));
expect(existsSync(holder)).toBe(true);
expect(await holderBranch()).toBe('');
await git(['worktree', 'add', '-q', join(root, 'follow-up'), BRANCH]);
});
+ it('preserves an idle pushed branch while its swarm parent owns the merge, including unreadable ownership', async () => {
+ const parent = { id: 'agent-parent', status: 'running', sourceWorkspace: repo, claimPicksOwnBranch: true };
+ const head = await git(['rev-parse', 'HEAD'], holder);
+ for (const agents of [[parent], null]) {
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, { agents, nowMs: LATER() })).resolves.toBeNull();
+ expect(await holderBranch()).toBe(BRANCH);
+ expect(await git(['rev-parse', 'HEAD'], holder)).toBe(head);
+ }
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, {
+ agents: [{ ...parent, status: 'completed' }], nowMs: LATER(),
+ })).resolves.toEqual({ path: holder });
+ expect(await git(['rev-parse', 'HEAD'], holder)).toBe(head);
+ });
+
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();
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, { agents: [], 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();
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, { agents: [], 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();
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, { agents: [] })).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();
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, { agents: [], 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();
+ await expect(releaseIdleSiblingNextHolder(repo, BRANCH, { agents: [], nowMs: LATER() })).resolves.toBeNull();
expect(await git(['branch', '--show-current'])).toBe(BRANCH);
- await expect(releaseIdleSiblingNextHolder(repo, 'feature/x', { nowMs: LATER() })).resolves.toBeNull();
+ await expect(releaseIdleSiblingNextHolder(repo, 'feature/x', { agents: [], nowMs: LATER() })).resolves.toBeNull();
});
});
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index 46910ad794..5bfa8f9ecf 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -623,10 +623,27 @@ describe('findAdoptableWorktreeForBranch (take over the tree that holds the bran
it('adopts a human /claim worktree when the caller opts into allowLiveClaim', async () => {
scriptWorktrees([{ path: cosTree('claim-issue-42'), branch: `refs/heads/${BRANCH}` }]);
- expect(await findAdoptableWorktreeForBranch(REPO, BRANCH, { allowLiveClaim: true }))
+ expect(await findAdoptableWorktreeForBranch(REPO, BRANCH, { allowLiveClaim: true, agents: [] }))
.toEqual({ path: cosTree('claim-issue-42'), agentId: 'claim-issue-42' });
});
+ it('keeps a swarm claim through the child-idle merge handoff, then allows inactive-owner recovery', async () => {
+ const path = cosTree('claim-issue-42');
+ scriptWorktrees([{ path, branch: `refs/heads/${BRANCH}` }]);
+ const parent = { id: 'agent-parent', status: 'running', sourceWorkspace: REPO, claimPicksOwnBranch: true };
+ const child = { id: 'agent-child', status: 'completed', sourceWorkspace: REPO, claimBranch: BRANCH };
+ const opts = { allowLiveClaim: true, activeAgentIds: new Set([parent.id]), agents: [parent, child] };
+ expect(await findAdoptableWorktreeForBranch(REPO, BRANCH, opts)).toBeNull();
+ expect(await findAdoptableWorktreeForBranch(REPO, BRANCH, { ...opts, agents: null })).toBeNull();
+ expect(await findAdoptableWorktreeForBranch(REPO, BRANCH, {
+ ...opts, agents: [{ ...parent, status: 'completed' }, child],
+ })).toEqual({ path, agentId: 'claim-issue-42' });
+ // A stale pointer must not silently select a different claim holder.
+ expect(await findAdoptableWorktreeForBranch(REPO, BRANCH, {
+ ...opts, agents: [], preferredPath: cosTree('claim-issue-99'),
+ })).toBeNull();
+ });
+
it('refuses a non-agent directory in the managed root', async () => {
scriptWorktrees([{ path: cosTree('next-issue-42'), branch: `refs/heads/${BRANCH}` }]);