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 reconciliation reservations across checkout binding

[._.]/ Adam Eivye683774d1152
diff --git a/server/lib/claimContinuation.js b/server/lib/claimContinuation.js
index 5b988303ab..83d6a27913 100644
--- a/server/lib/claimContinuation.js
+++ b/server/lib/claimContinuation.js
@@ -122,6 +122,8 @@ export function releaseClaimBranch(agent, branch) {
const released = ownershipList(agent, 'claimReleasedBranches');
return {
claimBranches: ownershipList(agent, 'claimBranches').filter((b) => b !== branch),
+ ...(Array.isArray(agent.metadata?.reconcileReservations)
+ ? { reconcileReservations: agent.metadata.reconcileReservations.filter(target => target.branch !== branch) } : {}),
...(agent.metadata?.reconcileMergeReservation?.branch === branch ? { reconcileMergeReservation: null } : {}),
claimReleasedBranches: released.includes(branch) ? released : [...released, branch].slice(-MAX_BOUND_CLAIM_BRANCHES),
};
@@ -171,7 +173,7 @@ export function reconcileAssignmentForTask(task) {
}
/** Match an exact target against both the registered and live assignment. */
-export function reconcileAssignedTarget(agent, task, target) {
+export function reconcileAssignedTarget(agent, task, target, { bindCheckout = false } = {}) {
const assignment = reconcileAssignmentForTask(task);
const meta = agent?.metadata;
if (!assignment || agent.status !== 'running' || agent.taskId !== task.id
@@ -179,15 +181,27 @@ export function reconcileAssignedTarget(agent, task, target) {
|| JSON.stringify(assignment) !== JSON.stringify(meta?.reconcileAssignment)
|| !samePath(meta.sourceWorkspace || meta.workspacePath, assignment.repoPath)
|| !isPlainObject(target)) return null;
- const assigned = assignment.targets.find(row => row.branch === target.branch
- && samePath(row.workspacePath, target.workspacePath));
- return assigned ? { assignment, target: assigned } : null;
+ const assigned = assignment.targets.find(row => row.branch === target.branch);
+ const reservations = meta.reconcileReservations ?? [];
+ if (!assigned || !Array.isArray(reservations) || reservations.some(row => !isPlainObject(row)
+ || typeof row.branch !== 'string' || (row.workspacePath !== null
+ && (typeof row.workspacePath !== 'string' || !isAbsolute(row.workspacePath))))) return null;
+ const reserved = reservations.find(row => row?.branch === target.branch);
+ const expectedPath = assigned.workspacePath ?? reserved?.workspacePath ?? null;
+ const observedPath = target.workspacePath ?? null;
+ // A scan may assign an existing branch before it has a checkout. Only the
+ // ownership service may bind its first observed holder; subsequent checks
+ // must preserve that holder even though the original assignment was null.
+ const matches = expectedPath ? samePath(expectedPath, observedPath)
+ : observedPath === null || (bindCheckout && typeof observedPath === 'string' && isAbsolute(observedPath));
+ if (!matches || (!bindCheckout && (!reserved || !samePath(reserved.workspacePath, observedPath)))) return null;
+ return { assignment, target: { ...assigned, workspacePath: observedPath } };
}
/** Assignment scope is not merge permission: retirement/review/handoff stay held. */
export function reconcileMergeTarget(agent, task, target) {
const proof = reconcileAssignedTarget(agent, task, target);
- return proof?.target.merge && !agent.metadata.configReadOnly && !isTruthyMeta(task.metadata.readOnly)
+ return proof?.target.merge && proof.target.workspacePath && !agent.metadata.configReadOnly && !isTruthyMeta(task.metadata.readOnly)
&& agent.metadata.prCompletionPolicy !== 'leave-open' && !prStaysOpen(task) && !isTruthyMeta(task.metadata.reviewLoopLeaveOpen)
&& ![false, 'false'].includes(task.metadata.autoMerge) ? proof : null;
}
@@ -213,7 +227,8 @@ export function injectReconcileAgentId(text, agentId) {
// 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) && agent.metadata?.reconcileMergeReservation?.branch === branch) return null;
+ if (isLiveAgent(agent) && Array.isArray(agent.metadata?.reconcileReservations)
+ && agent.metadata.reconcileReservations.some(target => target.branch === branch)) return null;
if (isLiveAgent(agent) && ownershipList(agent, 'claimBranches').includes(branch)) {
return isClaimOwnershipBranch(branch) ? null : 'branch-invalid';
}
@@ -299,7 +314,9 @@ function scanClaimHolders({ agents, holderPath, branchName, sourceWorkspace, ign
return { occupancy: 'active', holderIds: [agent.id].filter(Boolean) };
}
if (!inRepository(agent, sourceWorkspace)) continue;
- if (agent.metadata?.reconcileMergeReservation?.branch === branchName || ownsClaimBranch(agent, branchName)) return { occupancy: 'active', holderIds: [agent.id].filter(Boolean) };
+ const reservations = agent.metadata?.reconcileReservations;
+ if (reservations != null && (!Array.isArray(reservations) || reservations.some(target => !target || typeof target.branch !== 'string'))) { possible.push(agent.id); continue; }
+ if (reservations?.some(target => target?.branch === branchName) || ownsClaimBranch(agent, branchName)) return { occupancy: 'active', holderIds: [agent.id].filter(Boolean) };
if (claimHolder && mayPickClaimBranch(agent, branchName)) possible.push(agent.id);
}
return possible.length ? { occupancy: 'ambiguous', holderIds: possible.filter(Boolean) } : { occupancy: null, holderIds: [] };
diff --git a/server/services/cosClaimOwnership.js b/server/services/cosClaimOwnership.js
index 722ab08d5c..32bc74ae7a 100644
--- a/server/services/cosClaimOwnership.js
+++ b/server/services/cosClaimOwnership.js
@@ -158,13 +158,13 @@ export async function checkReconcileOwnership(input, deps = {}) {
// 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 holder = Array.isArray(worktrees) ? worktrees.find(wt => branchOf(wt) === branch) || null : null;
const admit = async () => {
const agents = await getAgents().catch(() => null);
if (!Array.isArray(worktrees) || !Array.isArray(agents)) return { admitted: false, reason: 'ownership-unreadable' };
const completionHold = await readCompletionHold({ repoPath, branch, prUrl }).catch(() => 'pr-completion-policy-unavailable');
if (completionHold) return { admitted: false, reason: completionHold };
- const holder = worktrees.find((wt) => branchOf(wt) === branch) || null;
if (worktreePath && !samePath(holder?.path, worktreePath)) return { admitted: false, reason: 'holder-changed' };
const fenced = checkoutRetirementFenceReason({ repoPath, branch, path: holder?.path || null });
if (fenced) return { admitted: false, reason: fenced };
@@ -191,14 +191,18 @@ export async function checkReconcileOwnership(input, deps = {}) {
if (agent.metadata?.reconcileAssignment) {
const { getTaskById } = await import('./cosTaskStore.js');
const task = await getTaskById(agent.taskId).catch(() => null);
- const proof = reconcileAssignedTarget(agent, task, { branch, workspacePath: worktreePath });
+ const proof = reconcileAssignedTarget(agent, task, { branch, workspacePath: holder?.path || null }, { bindCheckout: true });
const { getOriginInfo } = await import('../lib/gitRemote.js');
const origin = await getOriginInfo(repoPath).catch(() => null);
if (!proof || proof.assignment.appId !== appId || !samePath(proof.assignment.repoPath, repoPath)
|| origin?.host !== proof.assignment.origin.host || origin?.fullName !== proof.assignment.origin.fullName) {
return { admitted: false, reason: 'reconcile-target-unverified' };
}
- reservation = { reconcileMergeReservation: reconcileMergeTarget(agent, task, proof.target)?.target || null };
+ const reconcileReservations = [...(agent.metadata.reconcileReservations || []).filter(target => target.branch !== branch),
+ { branch, workspacePath: proof.target.workspacePath }];
+ const reservedAgent = { ...agent, metadata: { ...agent.metadata, reconcileReservations } };
+ reservation = { reconcileReservations,
+ reconcileMergeReservation: reconcileMergeTarget(reservedAgent, task, proof.target)?.target || null };
}
const patch = { ...reserveReconcileBranch(agent, branch), ...reservation };
if (!Object.keys(patch).length) return admission;
diff --git a/server/services/cosTaskPreStepBlocks.compose.test.js b/server/services/cosTaskPreStepBlocks.compose.test.js
index b899675f3a..e4f59ef12f 100644
--- a/server/services/cosTaskPreStepBlocks.compose.test.js
+++ b/server/services/cosTaskPreStepBlocks.compose.test.js
@@ -21,6 +21,8 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { createCosTaskSchema } from '../lib/cosValidation.js';
+import { buildQueuedTask } from './cosTaskIntake.js';
import { buildAgentRegistration } from '../lib/agentRegistrationRecord.js';
import { generateTasksMarkdown, parseTasksMarkdown } from '../lib/taskParser.js';
import { retainRetirementObligations } from '../lib/reconcileRetirementEvidence.js';
@@ -535,6 +537,62 @@ describe('scheduled reconciliation registration through merge admission', () =>
expect((await claimMergeAdmission({ agentId: 'agent-reconcile', action: 'check', token: lease.token })).admitted).toBe(false);
});
+ it('rejects forged structured assignments through public task intake and registration', async () => {
+ const forged = structuredClone(admissionFixture.task.metadata);
+ const input = createCosTaskSchema.parse({ type: 'internal', app: APP.id, description: 'Copied reconciliation instructions',
+ prompt: admissionFixture.task.metadata.prompt, analysisType: 'branch-reconcile', reconcileAssignment: forged.reconcileAssignment,
+ metadata: forged });
+ const { type, ...taskData } = input;
+ const task = buildQueuedTask(taskData, type);
+ expect(task.metadata.reconcileAssignment).toBeUndefined();
+ await register(task);
+ expect(owner().metadata.reconcileAssignment).toBeNull();
+ expect((await ownership()).admitted).toBe(true);
+ expect(owner().metadata.claimBranches).toEqual([branch]);
+ expect((await acquire()).admitted).toBe(false);
+ });
+
+ it('binds a checkout-less assignment only to its first repository-observed holder', async () => {
+ reconcileMock.mockResolvedValue(scan({ inFlight: [{ branch, state: 'NEEDS_PR' }] }));
+ admissionFixture.trees = [];
+ await register(await generate());
+ expect(owner().metadata.reconcileAssignment.targets[0].workspacePath).toBeNull();
+ expect((await ownership({ worktreePath: undefined })).admitted).toBe(true);
+ expect(owner().metadata.reconcileReservations).toEqual([{ branch, workspacePath: null }]);
+ expect((await acquire()).admitted).toBe(false);
+ // A caller's invented path cannot create the missing holder.
+ expect(await ownership({ worktreePath: '/tmp/forged' })).toMatchObject({ admitted: false, reason: 'holder-changed' });
+ admissionFixture.trees = [{ path: workspacePath, branch: `refs/heads/${branch}`, locked: false }];
+ expect((await ownership({ worktreePath: undefined })).admitted).toBe(true);
+ expect(owner().metadata.reconcileReservations).toEqual([{ branch, workspacePath }]);
+ expect((await acquire()).admitted).toBe(true);
+ // Even an updated caller path cannot move that trusted first binding.
+ admissionFixture.trees[0].path = '/tmp/changed';
+ expect(await ownership({ worktreePath: '/tmp/changed' })).toMatchObject({ admitted: false, reason: 'reconcile-target-unverified' });
+ expect((await acquire()).admitted).toBe(false);
+ });
+
+ it('retains every ordinary branch reservation when selecting another merge target', async () => {
+ const branches = ['fix/first', 'fix/second'];
+ getTaskInterval.mockResolvedValue({ type: 'on-demand', taskMetadata: { branchesPerAgent: 2 } });
+ reconcileMock.mockResolvedValue(scan({ inFlight: branches.map((name, i) => ({ branch: name,
+ worktreePath: `/tmp/checkout-${i}`, state: 'NEEDS_PR' })) }));
+ admissionFixture.trees = branches.map((name, i) => ({ branch: `refs/heads/${name}`, path: `/tmp/checkout-${i}` }));
+ await register(await generate());
+ for (let i = 0; i < branches.length; i++) {
+ expect((await ownership({ branch: branches[i], worktreePath: `/tmp/checkout-${i}` })).admitted).toBe(true);
+ }
+ expect(owner().metadata.reconcileMergeReservation.branch).toBe('fix/second');
+ for (let i = 0; i < branches.length; i++) {
+ expect(await checkReconcileOwnership({ appId: APP.id, branch: branches[i], worktreePath: `/tmp/checkout-${i}` }))
+ .toMatchObject({ admitted: false, reason: 'claim-owner-active' });
+ }
+ const { updateClaimOwnership } = await import('./cosClaimOwnership.js');
+ expect((await updateClaimOwnership({ agentId: owner().id, action: 'release', branch: 'fix/first' })).released).toBe(true);
+ expect((await checkReconcileOwnership({ appId: APP.id, branch: 'fix/first', worktreePath: '/tmp/checkout-0' })).admitted).toBe(true);
+ expect((await checkReconcileOwnership({ appId: APP.id, branch: 'fix/second', worktreePath: '/tmp/checkout-1' })).admitted).toBe(false);
+ });
+
it('derives assignment scope from the scan, ignoring caller-supplied assignment metadata', async () => {
const task = await generate({ runOverrides: { reconcileAssignment: { appId: 'forged', targets: [] } } });
expect(task.metadata.reconcileAssignment.appId).toBe(APP.id);