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: reserve a claim branch for an admitted branch-reconcile worker so a claim run cannot bind it mid-mutation (#10096)

Adam Eivy1c725899c19d
diff --git a/server/lib/claimContinuation.js b/server/lib/claimContinuation.js
index caf8dee1f7..cb410cedf2 100644
--- a/server/lib/claimContinuation.js
+++ b/server/lib/claimContinuation.js
@@ -114,7 +114,7 @@ export function bindClaimBranch(agent, branch, agents = []) {
* `bindClaimBranch`. Pure.
*/
export function releaseClaimBranch(agent, branch) {
- const refused = bindingRefusal(agent, branch);
+ const refused = releaseRefusal(agent, branch);
if (refused) return { refused };
const released = ownershipList(agent, 'claimReleasedBranches');
return {
@@ -123,6 +123,55 @@ export function releaseClaimBranch(agent, branch) {
};
}
+/**
+ * The metadata patch that reserves `branch` for a live branch-reconcile
+ * coordinator whose worker was just admitted to mutate it (#10096). It lands in
+ * the same `claimBranches` list a claim run's bindings use, so
+ * `claimHolderOccupancy` reports the coordinator as an `active` owner to `bind`,
+ * continuation and adoption until its run ends. Null when `branch` is not a
+ * claim-shaped name — no claim run can bind it, so there is nothing to reserve.
+ * `{ refused }` when the record is not a live run or its bound list is full. Pure.
+ *
+ * @returns {{ claimBranches: string[], claimReleasedBranches: string[] }|{ refused: string }|null}
+ */
+export function reserveReconcileBranch(agent, branch) {
+ if (!isClaimOwnershipBranch(branch)) return null;
+ if (!isLiveAgent(agent)) return { refused: 'owner-not-running' };
+ const held = ownershipList(agent, 'claimBranches');
+ if (!held.includes(branch) && held.length >= MAX_BOUND_CLAIM_BRANCHES) return { refused: 'too-many-branches' };
+ return {
+ claimBranches: held.includes(branch) ? held : [...held, branch],
+ claimReleasedBranches: ownershipList(agent, 'claimReleasedBranches').filter((b) => b !== branch),
+ };
+}
+
+/** Where the coordinator prompt's recheck command carries the run's own agent id. */
+export const RECONCILE_AGENT_ID_PLACEHOLDER = '{agentId}';
+const RECONCILE_AGENT_ID_FIELD = `,"agentId":"${RECONCILE_AGENT_ID_PLACEHOLDER}"`;
+
+/**
+ * Fill a coordinator prompt's `{agentId}` slot at spawn time, once the run has an
+ * id (the in-flight block is generated before spawn). Without a usable id the
+ * field is dropped, so the recheck stays the read-only answer instead of sending
+ * a literal placeholder. Pure.
+ */
+export function injectReconcileAgentId(text, agentId) {
+ if (typeof text !== 'string' || !text.includes(RECONCILE_AGENT_ID_PLACEHOLDER)) return text;
+ const usable = typeof agentId === 'string' && /^[A-Za-z0-9_-]{1,200}$/.test(agentId);
+ return usable
+ ? text.replaceAll(RECONCILE_AGENT_ID_PLACEHOLDER, agentId)
+ : text.replaceAll(RECONCILE_AGENT_ID_FIELD, '');
+}
+
+// A release may also come from a run that holds the branch by reservation rather
+// than as a claim run (a branch-reconcile coordinator).
+function releaseRefusal(agent, branch) {
+ if (isLiveAgent(agent) && ownershipList(agent, 'claimBranches').includes(branch)) {
+ return isClaimOwnershipBranch(branch) ? null : 'branch-invalid';
+ }
+ return bindingRefusal(agent, branch);
+}
+
// Only a live claim run may change its own bindings, and only for a claim branch.
function bindingRefusal(agent, branch) {
if (!isLiveAgent(agent)) return 'owner-not-running';
diff --git a/server/lib/claimContinuation.test.js b/server/lib/claimContinuation.test.js
index 8345840d61..84248502a8 100644
--- a/server/lib/claimContinuation.test.js
+++ b/server/lib/claimContinuation.test.js
@@ -8,6 +8,7 @@ import {
bindClaimBranch,
releaseClaimBranch,
claimCheckoutOwnerReason,
+ injectReconcileAgentId,
} from './claimContinuation.js';
const ROOT = '/data/cos/worktrees';
@@ -301,3 +302,20 @@ describe('claim branch binding lifecycle', () => {
expect(reason(null)).toBe('claim-ownership-unreadable');
});
});
+
+describe('injectReconcileAgentId', () => {
+ const text = `curl -d '{"action":"check","branch":"b","agentId":"{agentId}"}' and again '{"agentId":"{agentId}"}'`;
+
+ it('fills every slot with the run id', () => {
+ expect(injectReconcileAgentId(text, 'agent-1a2b')).toBe(
+ `curl -d '{"action":"check","branch":"b","agentId":"agent-1a2b"}' and again '{"agentId":"agent-1a2b"}'`,
+ );
+ });
+
+ it('drops the field, keeping the read-only check, when there is no usable id', () => {
+ for (const id of [undefined, '', "x'; rm -rf /"]) {
+ expect(injectReconcileAgentId(text, id)).toBe(`curl -d '{"action":"check","branch":"b"}' and again '{"agentId":"{agentId}"}'`);
+ }
+ expect(injectReconcileAgentId(undefined, 'agent-1')).toBeUndefined();
+ });
+});
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 048e020303..12b69736b0 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -19,7 +19,8 @@ import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { doneSentinelName } from '../lib/agentSentinel.js';
import { canTypeSlashCommands, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';
import { getDigitalTwinForPrompt } from './digital-twin.js';
-import { taskContextBlock } from '../lib/cosTaskPrompt.js';
+import { TASK_PROMPT_KEY, taskContextBlock } from '../lib/cosTaskPrompt.js';
+import { injectReconcileAgentId } from '../lib/claimContinuation.js';
import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';
// Shared with cosTaskGenerator.js, which stamps the same set as metadata.claimFlow.
import { isClaimFlowDispatch, resolveTaskHookType } from './taskTypeHooks.js';
@@ -289,6 +290,16 @@ async function prepareReviewLoopRecipe(task, {
};
}
+function fillReconcileAgentId(task, agentId) {
+ const description = injectReconcileAgentId(task.description, agentId);
+ const prompt = injectReconcileAgentId(task.metadata?.[TASK_PROMPT_KEY], agentId);
+ if (description === task.description && prompt === task.metadata?.[TASK_PROMPT_KEY]) return task;
+ return {
+ ...task, description,
+ ...(prompt !== task.metadata?.[TASK_PROMPT_KEY] ? { metadata: { ...task.metadata, [TASK_PROMPT_KEY]: prompt } } : {}),
+ };
+}
+
/**
* Build the agent prompt.
*
@@ -342,6 +353,11 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
// full-path fallback below.
task = reconcileSplitContext(task);
+ // A branch-reconcile coordinator's recheck commands carry its own agent id so
+ // a successful check reserves the branch for it (#10096). The block was built
+ // before the run had an id; fill the slot now, wherever the prompt travels.
+ task = fillReconcileAgentId(task, options.agentId);
+
// Feature-agent tasks carry only a compact queue description. Expand the
// persisted persona briefing at spawn time so scheduled and manually
// triggered runs share the same feature-specific goals, constraints, branch
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 50b5e04eff..b3d3120ea5 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -39,7 +39,7 @@ import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';
import { ledgerPath, readVerdictLedger, partitionSuperseded, recordVerdictInstruction, recordVerdict, sameDirtyPaths } from './supersededLedger.js';
import { backupSupersededBranch } from './supersededBackup.js';
-import { claimCheckoutOwnerReason } from '../lib/claimContinuation.js';
+import { claimCheckoutOwnerReason, RECONCILE_AGENT_ID_PLACEHOLDER } from '../lib/claimContinuation.js';
import { withClaimOwnershipLock } from './cosClaimOwnership.js';
import { agentApiCurl } from '../lib/agentApiToken.js';
import { localApiBaseUrl } from '../lib/networkExposure.js';
@@ -1714,14 +1714,18 @@ export async function formatInFlightForPrompt(inFlight, { defaultBranch, actions
// This list is a scan from before dispatch; a claim run can take a branch
// after it. Each branch's own recheck runs right before its first mutation (#10089).
if (appId) {
- lines.splice(lines.length - 1, 0, '', 'Ownership recheck: immediately before the FIRST edit, commit, rebase, push, merge, PR change, move or removal on a branch below (and again before its merge), run that branch\'s "Recheck" command and require a parsed JSON response with admitted:true. On admitted:false, an HTTP/auth/transport error or unreadable JSON, leave that branch and its checkout untouched and report it as held by a live owner with the returned reason — a live claim run owns it now.');
+ lines.splice(lines.length - 1, 0, '', 'Ownership recheck: immediately before the FIRST edit, commit, rebase, push, merge, PR change, move or removal on a branch below (and again before its merge), run that branch\'s "Recheck" command and require a parsed JSON response with admitted:true. On admitted:false, an HTTP/auth/transport error or unreadable JSON, leave that branch and its checkout untouched and report it as held by a live owner with the returned reason — a live claim run owns it now. A successful Recheck also reserves that branch for this run until it ends, so no claim run can take it mid-mutation.');
}
inFlight.forEach((b, i) => {
const pr = b.openPr ? ` — PR #${b.openPr.number} (${b.openPr.mergeable})${b.openPr.url ? ` ${b.openPr.url}` : ''}` : ' — no PR';
lines.push(`### \`${b.branch}\` [${b.state}]${pr}`);
if (b.worktreePath) lines.push(`- Worktree: \`${b.worktreePath}\`${b.state === 'ABANDONED_WIP' ? ' (holds UNCOMMITTED work — read it before doing anything)' : ''}`);
if (appId) {
- const payload = JSON.stringify({ action: 'check', appId, branch: b.branch, ...(b.worktreePath ? { worktreePath: b.worktreePath } : {}) });
+ // `{agentId}` is filled at spawn (`injectReconcileAgentId`): the run has no id yet.
+ const payload = JSON.stringify({
+ action: 'check', appId, branch: b.branch, ...(b.worktreePath ? { worktreePath: b.worktreePath } : {}),
+ agentId: RECONCILE_AGENT_ID_PLACEHOLDER,
+ });
lines.push(`- Recheck: \`${agentApiCurl({ apiBase: localApiBaseUrl(), path: '/api/cos/claim-ownership', payload })}\``);
}
// A never-pushed NEEDS_PR branch reads identically to a pushed one in this
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index f65137225f..ceec5da013 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -2005,8 +2005,8 @@ describe('formatInFlightForPrompt', () => {
], { defaultBranch: 'main', actions: {}, appId: 'app-x' });
expect(block).toContain('Ownership recheck: immediately before the FIRST edit');
expect(block).toContain('/api/cos/claim-ownership');
- expect(block).toContain('{"action":"check","appId":"app-x","branch":"claim/issue-101","worktreePath":"/wt/claim-issue-101"}');
- expect(block).toContain('{"action":"check","appId":"app-x","branch":"feature/x"}');
+ expect(block).toContain('{"action":"check","appId":"app-x","branch":"claim/issue-101","worktreePath":"/wt/claim-issue-101","agentId":"{agentId}"}');
+ expect(block).toContain('{"action":"check","appId":"app-x","branch":"feature/x","agentId":"{agentId}"}');
expect(block).toContain('Authorization: Bearer');
expect(await formatInFlightForPrompt([{ branch: 'feature/x', state: 'NEEDS_PR' }], { defaultBranch: 'main', actions: {} }))
.not.toContain('claim-ownership');
diff --git a/server/services/cosClaimOwnership.js b/server/services/cosClaimOwnership.js
index a154ec27fa..42bc577dac 100644
--- a/server/services/cosClaimOwnership.js
+++ b/server/services/cosClaimOwnership.js
@@ -11,10 +11,13 @@
* - `checkReconcileOwnership` — a branch-reconcile worker re-reads the live
* owners immediately before it edits, rebases, pushes, merges, moves or
* removes a checkout, because ownership can be acquired after the scan that
- * dispatched it. Anything unreadable or changed refuses.
+ * dispatched it. Anything unreadable or changed refuses. When the caller
+ * names its agent, a successful check also RESERVES the branch on that run's
+ * record under the binding lock, so a claim run cannot bind or adopt it
+ * while the worker mutates it; the run's completion releases it.
*/
import { resolve } from 'path';
-import { bindClaimBranch, releaseClaimBranch, claimCheckoutOwnerReason } from '../lib/claimContinuation.js';
+import { bindClaimBranch, releaseClaimBranch, reserveReconcileBranch, claimCheckoutOwnerReason } from '../lib/claimContinuation.js';
const normalize = (p) => (process.platform === 'win32' ? resolve(p).toLowerCase() : resolve(p));
const samePath = (a, b) => typeof a === 'string' && typeof b === 'string' && normalize(a) === normalize(b);
@@ -56,11 +59,19 @@ export async function updateClaimOwnership({ agentId, action, branch }) {
* when the checkout it was dispatched at still holds the branch and no live
* owner (agent, lock, or registered/possible claim run) holds it.
*
+ * With `agentId` the admission is also an acquire: under the same lock `bind`
+ * takes, the branch is recorded on that coordinator's run record, so every other
+ * caller (claim `bind`, continuation, adoption, a later reconcile scan) sees a
+ * live owner until the run ends or releases it. Without `agentId` the answer is
+ * read-only. A named run that is not a live registered agent is refused: the
+ * reservation could not be recorded.
+ *
* @param {{ appId: string, branch: string, worktreePath?: string, agentId?: string }} input
* @param {object} [deps] - injected for tests
* @returns {Promise<{ admitted: true }|{ admitted: false, reason: string }>}
*/
-export async function checkReconcileOwnership({ appId, branch, worktreePath, agentId }, deps = {}) {
+export async function checkReconcileOwnership(input, deps = {}) {
+ const { appId, branch, worktreePath, agentId } = input;
const getAppById = deps.getAppById ?? (await import('./apps.js')).getAppById;
const listWorktrees = deps.listWorktrees ?? (await import('./worktreeManager.js')).listWorktrees;
const getAgents = deps.getAgents ?? (await import('./cosAgentLifecycle.js')).getAgents;
@@ -70,18 +81,41 @@ export async function checkReconcileOwnership({ appId, branch, worktreePath, age
const app = await getAppById(appId).catch(() => null);
const repoPath = app?.repoPath;
if (!repoPath) return { admitted: false, reason: 'app-unknown' };
- const [worktrees, agents] = await Promise.all([
- listWorktrees(repoPath).catch(() => null),
- getAgents().catch(() => null),
- ]);
- if (!Array.isArray(worktrees) || !Array.isArray(agents)) return { admitted: false, reason: 'ownership-unreadable' };
+ // The git read stays outside the lock; only the agent registry — the half a
+ // concurrent bind changes — is re-read where the reservation is decided.
+ const worktrees = await listWorktrees(repoPath).catch(() => null);
+
+ const admit = async () => {
+ const agents = await getAgents().catch(() => null);
+ if (!Array.isArray(worktrees) || !Array.isArray(agents)) return { admitted: false, reason: 'ownership-unreadable' };
+ const holder = worktrees.find((wt) => branchOf(wt) === branch) || null;
+ if (worktreePath && !samePath(holder?.path, worktreePath)) return { admitted: false, reason: 'holder-changed' };
+ const others = agentId ? agents.filter((a) => a?.id !== agentId) : agents;
+ const reason = resolveLiveOwnerReason({
+ branch, path: holder?.path || null, locked: Boolean(holder?.locked),
+ activeAgentIds: buildActiveOwnerIds(getActiveAgentIds().filter((id) => id !== agentId), others),
+ }) || claimCheckoutOwnerReason({ branchName: branch, holderPath: holder?.path || null, sourceWorkspace: repoPath, agents: others });
+ return reason ? { admitted: false, reason } : { admitted: true };
+ };
+ if (!agentId) return admit();
- const holder = worktrees.find((wt) => branchOf(wt) === branch) || null;
- if (worktreePath && !samePath(holder?.path, worktreePath)) return { admitted: false, reason: 'holder-changed' };
- const others = agentId ? agents.filter((a) => a?.id !== agentId) : agents;
- const reason = resolveLiveOwnerReason({
- branch, path: holder?.path || null, locked: Boolean(holder?.locked),
- activeAgentIds: buildActiveOwnerIds(getActiveAgentIds().filter((id) => id !== agentId), others),
- }) || claimCheckoutOwnerReason({ branchName: branch, holderPath: holder?.path || null, sourceWorkspace: repoPath, agents: others });
- return reason ? { admitted: false, reason } : { admitted: true };
+ const { withStateLock, loadState, saveState } = await import('./cosState.js');
+ const { cosEvents } = await import('./cosEvents.js');
+ // Decided inside the lock a bind takes, so no bind can land between
+ // "admitted" and "reserved".
+ return withClaimOwnershipLock(() => withStateLock(async () => {
+ const admission = await admit();
+ if (!admission.admitted) return admission;
+ const state = await loadState();
+ const agent = state.agents?.[agentId];
+ if (!agent || agent.id !== agentId) return { admitted: false, reason: 'owner-unknown' };
+ const patch = reserveReconcileBranch(agent, branch);
+ if (!patch) return admission;
+ if (patch.refused) return { admitted: false, reason: patch.refused };
+ state.agents[agentId] = { ...agent, metadata: { ...agent.metadata, ...patch } };
+ await saveState(state);
+ cosEvents.emit('agent:updated', state.agents[agentId]);
+ console.log(`🔒 Reconcile reservation: ${branch} → ${agentId}`);
+ return admission;
+ }));
}
diff --git a/server/services/cosClaimOwnership.test.js b/server/services/cosClaimOwnership.test.js
index ccc3d2de2a..0130f97a08 100644
--- a/server/services/cosClaimOwnership.test.js
+++ b/server/services/cosClaimOwnership.test.js
@@ -9,6 +9,7 @@ vi.mock('./cosState.js', () => ({
vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() } }));
const { updateClaimOwnership, checkReconcileOwnership } = await import('./cosClaimOwnership.js');
+const { claimContinuationAdmission, claimBranchAdmission } = await import('../lib/claimContinuation.js');
const SOURCE = '/repos/app-x';
const CHILD = '/repos/app-x/data/cos/worktrees/claim-issue-101';
@@ -80,3 +81,80 @@ describe('checkReconcileOwnership', () => {
expect(await check([], { listWorktrees: async () => [{ ...holder, locked: true }] })).toEqual({ admitted: false, reason: 'worktree-locked' });
});
});
+
+// A successful check by a named coordinator is an acquire (#10096): the claim run
+// that binds mid-mutation would otherwise be handed the same checkout.
+describe('checkReconcileOwnership reservation', () => {
+ const holder = { path: CHILD, branch: 'refs/heads/claim/issue-101' };
+ const admit = (agentId, input = {}) => checkReconcileOwnership(
+ { appId: 'app-x', branch: 'claim/issue-101', worktreePath: CHILD, agentId, ...input },
+ {
+ getAppById: async (id) => ({ id, repoPath: SOURCE }),
+ listWorktrees: async () => [holder],
+ getAgents: async () => Object.values(store.state.agents),
+ getActiveAgentIds: () => [],
+ },
+ );
+ const bind = () => updateClaimOwnership({ agentId: 'agent-picker', action: 'bind', branch: 'claim/issue-101' });
+
+ beforeEach(() => {
+ store.state.agents['agent-recon'] = {
+ id: 'agent-recon', status: 'running', workspacePath: SOURCE, metadata: { sourceWorkspace: SOURCE },
+ };
+ store.state.agents['agent-picker'] = {
+ id: 'agent-picker', status: 'running', workspacePath: SOURCE,
+ metadata: { sourceWorkspace: SOURCE, claimBranch: 'claim/issue-100', claimPicksOwnBranch: false },
+ };
+ delete store.state.agents['agent-epicrun'];
+ });
+
+ it('refuses a claim bind, continuation and adoption of an admitted branch until the coordinator ends', async () => {
+ expect(await admit('agent-recon')).toEqual({ admitted: true });
+ expect(store.state.agents['agent-recon'].metadata.claimBranches).toEqual(['claim/issue-101']);
+
+ expect(await bind()).toEqual({ bound: false, reason: 'owner-active' });
+ const agents = Object.values(store.state.agents);
+ const metadata = { existingBranch: 'claim/issue-101', resumeWorktreePath: CHILD };
+ expect(claimContinuationAdmission({ metadata, agentId: 'agent-picker', sourceWorkspace: SOURCE, worktrees: [holder], agents }))
+ .toEqual({ admit: false, reason: 'owner-active' });
+ expect(claimBranchAdmission({ branchName: 'claim/issue-101', preferredPath: CHILD, agentId: 'agent-picker', sourceWorkspace: SOURCE, worktrees: [holder], agents }))
+ .toEqual({ admit: false, reason: 'owner-active' });
+
+ store.state.agents['agent-recon'].status = 'completed';
+ expect(await bind()).toEqual({ bound: true, branch: 'claim/issue-101' });
+ });
+
+ it('lets the coordinator re-admit its own branch and release it explicitly', async () => {
+ expect(await admit('agent-recon')).toEqual({ admitted: true });
+ expect(await admit('agent-recon')).toEqual({ admitted: true });
+ expect(store.state.agents['agent-recon'].metadata.claimBranches).toEqual(['claim/issue-101']);
+
+ expect(await updateClaimOwnership({ agentId: 'agent-recon', action: 'release', branch: 'claim/issue-101' }))
+ .toEqual({ released: true, branch: 'claim/issue-101' });
+ expect(await bind()).toEqual({ bound: true, branch: 'claim/issue-101' });
+ });
+
+ it('stays read-only without an agent id and writes nothing when refused', async () => {
+ const before = structuredClone(store.state);
+ expect(await admit(undefined)).toEqual({ admitted: true });
+ expect(store.state).toEqual(before);
+
+ expect(await admit('agent-gone')).toEqual({ admitted: false, reason: 'owner-unknown' });
+ store.state.agents['agent-recon'].status = 'completed';
+ expect(await admit('agent-recon')).toEqual({ admitted: false, reason: 'owner-not-running' });
+ store.state.agents['agent-recon'].status = 'running';
+ store.state.agents['agent-picker'].metadata.claimBranches = ['claim/issue-101'];
+ expect(await admit('agent-recon')).toEqual({ admitted: false, reason: 'claim-owner-active' });
+ expect(store.state.agents['agent-recon'].metadata.claimBranches).toBeUndefined();
+ });
+
+ it('reserves nothing for a branch no claim run can bind', async () => {
+ const before = structuredClone(store.state);
+ const feature = { path: '/repos/app-x/other', branch: 'refs/heads/feature/x' };
+ expect(await checkReconcileOwnership(
+ { appId: 'app-x', branch: 'feature/x', worktreePath: feature.path, agentId: 'agent-recon' },
+ { getAppById: async (id) => ({ id, repoPath: SOURCE }), listWorktrees: async () => [feature], getAgents: async () => [], getActiveAgentIds: () => [] },
+ )).toEqual({ admitted: true });
+ expect(store.state).toEqual(before);
+ });
+});