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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: admit assigned branch reconciliation coordinators (#13294)
[._.]/ Adam Eivye0e4d0dc9759
diff --git a/server/lib/README.md b/server/lib/README.mdindex 0be87a0d63..09e9661a00 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -579,7 +579,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 pinned run is also "still choosing" until it binds) a claim run registers on its agent record; `bindClaimBranch` / `releaseClaimBranch` patch the concrete branches a run binds before cutting them (an epic's child, a picked issue), `ownsClaimBranch(agent, branch)` is explicit registered/bound ownership only (never a picker's "may pick"), `claimCheckoutOwnerReason(...)` names a live/possible claim owner for branch-reconcile (`claimCheckoutOwner(...)` adds the holder run ids a blocked cleanup records), 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). |+| `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. `reconcileAssignmentForTask`, `reconcileAssignedTarget`, and `reconcileMergeTarget` preserve scheduler assignments and match their registered/live branch, checkout, and completion policy for reconciliation admission; `claimOwnershipBinding(task)` is the branch (or "picks its own", for a swarm orchestrator; a pinned run is also "still choosing" until it binds) a claim run registers on its agent record; `bindClaimBranch` / `releaseClaimBranch` patch the concrete branches a run binds before cutting them (an epic's child, a picked issue), `ownsClaimBranch(agent, branch)` is explicit registered/bound ownership only (never a picker's "may pick"), `claimCheckoutOwnerReason(...)` names a live/possible claim owner for branch-reconcile (`claimCheckoutOwner(...)` adds the holder run ids a blocked cleanup records), 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. || `taskTypeBucket.js` | CoS task-learning bucket classifier (`extractTaskType`, `classifyUntypedTask`, `isSandboxedTaskType`); browser-safe, shared with the client ETA lookup via `client/src/lib/cosTaskType.js`. || `taskTypeRenames.js` | Dependency-free retired-task-name map (`TASK_TYPE_RENAMES`, `currentTaskTypeName`); re-exported by `scheduledTaskTypes.js`. |diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.jsindex 4880674ed7..6bec608dfc 100644--- a/server/lib/agentRegistrationRecord.js+++ b/server/lib/agentRegistrationRecord.js@@ -24,7 +24,7 @@ import { processAuditRecoveryOriginSchema } from './persistentMindProcessAudit.j// pure helper (server/AGENTS.md, "Import scoping").import { normalizeReviewers } from './reviewerConfig.js';import { quotaBurnAgentMetadata } from './quotaBurnOrigin.js';-import { claimOwnershipBinding } from './claimContinuation.js';+import { claimOwnershipBinding, reconcileAssignmentForTask } from './claimContinuation.js';import { explicitPrCompletion } from './prDisposition.js';import { repositoryCleanupMergeTarget } from './recoveryMergeTarget.js';@@ -300,6 +300,7 @@ export function buildAgentRegistration({// Repository-cleanup recovery (#12251): the parent PR this run was filed to// land, snapshotted so a later task edit reads as a changed target.recoveryMergeTarget: repositoryCleanupMergeTarget(task),+ reconcileAssignment: reconcileAssignmentForTask(task),configSimplify: isTruthyMeta(task.metadata?.simplify),configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),configReviewers: normalizeReviewers(task.metadata),diff --git a/server/lib/claimContinuation.js b/server/lib/claimContinuation.jsindex c0f7af5c98..5b988303ab 100644--- a/server/lib/claimContinuation.js+++ b/server/lib/claimContinuation.js@@ -14,7 +14,9 @@* git listing and the agent list stay with the caller.*/-import { resolve } from 'path';+import { isAbsolute, resolve } from 'path';+import { isPlainObject } from './objects.js';+import { prStaysOpen } from './prDisposition.js';import { isPathInsideDir } from './pathSafety.js';import { isHumanClaimWorktree, worktreeAgentId } from './worktreeOwnership.js';import { hasClaimFlowContract } from './claimFlowTaskTypes.js';@@ -120,6 +122,7 @@ export function releaseClaimBranch(agent, branch) {const released = ownershipList(agent, 'claimReleasedBranches');return {claimBranches: ownershipList(agent, 'claimBranches').filter((b) => b !== branch),+ ...(agent.metadata?.reconcileMergeReservation?.branch === branch ? { reconcileMergeReservation: null } : {}),claimReleasedBranches: released.includes(branch) ? released : [...released, branch].slice(-MAX_BOUND_CLAIM_BRANCHES),};}@@ -146,6 +149,49 @@ export function reserveReconcileBranch(agent, branch) {};}+/** Scheduler-derived reconciliation assignment; never inferred from prompt text.+ * Kept as structured task metadata across persistence and snapshotted at launch.+ * A reservation selects one exact target; the assignment itself grants no lease.+ */+export function reconcileAssignmentForTask(task) {+ const meta = task?.metadata;+ const assignment = meta?.reconcileAssignment;+ if (task?.taskType !== 'internal' || meta?.analysisType !== 'branch-reconcile'+ || !isPlainObject(assignment) || assignment.appId !== meta.app+ || typeof assignment.appId !== 'string' || !assignment.appId+ || typeof assignment.repoPath !== 'string' || !isAbsolute(assignment.repoPath) || !isPlainObject(assignment.origin)+ || typeof assignment.origin.host !== 'string' || !assignment.origin.host+ || typeof assignment.origin.fullName !== 'string' || !assignment.origin.fullName+ || !Array.isArray(assignment.targets) || !assignment.targets.length+ || assignment.targets.some(target => !isPlainObject(target)+ || typeof target.branch !== 'string' || !target.branch+ || (target.workspacePath !== null && (typeof target.workspacePath !== 'string' || !isAbsolute(target.workspacePath)))+ || typeof target.merge !== 'boolean')) return null;+ return structuredClone(assignment);+}++/** Match an exact target against both the registered and live assignment. */+export function reconcileAssignedTarget(agent, task, target) {+ const assignment = reconcileAssignmentForTask(task);+ const meta = agent?.metadata;+ if (!assignment || agent.status !== 'running' || agent.taskId !== task.id+ || ['completed', 'failed', 'cancelled'].includes(task.status)+ || 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;+}++/** 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)+ && agent.metadata.prCompletionPolicy !== 'leave-open' && !prStaysOpen(task) && !isTruthyMeta(task.metadata.reviewLoopLeaveOpen)+ && ![false, 'false'].includes(task.metadata.autoMerge) ? proof : null;+}+/** 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}"`;@@ -167,6 +213,7 @@ 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) && ownershipList(agent, 'claimBranches').includes(branch)) {return isClaimOwnershipBranch(branch) ? null : 'branch-invalid';}@@ -252,7 +299,7 @@ function scanClaimHolders({ agents, holderPath, branchName, sourceWorkspace, ignreturn { occupancy: 'active', holderIds: [agent.id].filter(Boolean) };}if (!inRepository(agent, sourceWorkspace)) continue;- if (ownsClaimBranch(agent, branchName)) return { occupancy: 'active', holderIds: [agent.id].filter(Boolean) };+ if (agent.metadata?.reconcileMergeReservation?.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.jsindex 4eafc04e99..722ab08d5c 100644--- a/server/services/cosClaimOwnership.js+++ b/server/services/cosClaimOwnership.js@@ -17,7 +17,7 @@* while the worker mutates it; the run's completion releases it.*/import { resolve } from 'path';-import { bindClaimBranch, releaseClaimBranch, reserveReconcileBranch, claimCheckoutOwnerReason } from '../lib/claimContinuation.js';+import { bindClaimBranch, releaseClaimBranch, reserveReconcileBranch, reconcileAssignedTarget, reconcileMergeTarget, claimCheckoutOwnerReason } from '../lib/claimContinuation.js';import { withClaimOwnershipLock, readClaimOwnershipAgents, checkoutRetirementFenceReason } from './cosClaimOwnershipState.js';@@ -176,7 +176,7 @@ export async function checkReconcileOwnership(input, deps = {}) {return reason ? { admitted: false, reason } : { admitted: true };};const { withCheckoutPublication } = await import('../lib/checkoutRetirementAdmission.js');- if (!agentId) return withCheckoutPublication(repoPath, admit)+ if (!agentId || deps.reserve === false) return withCheckoutPublication(repoPath, admit).catch(() => ({ admitted: false, reason: 'checkout-retirement-reserved' }));const { cosEvents } = await import('./cosEvents.js');@@ -187,8 +187,21 @@ export async function checkReconcileOwnership(input, deps = {}) {if (!admission.admitted) return admission;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;+ let reservation = null;+ 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 { 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 patch = { ...reserveReconcileBranch(agent, branch), ...reservation };+ if (!Object.keys(patch).length) return admission;if (patch.refused) return { admitted: false, reason: patch.refused };state.agents[agentId] = { ...agent, metadata: { ...agent.metadata, ...patch } };await save();diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.jsindex c93aa40e66..29db677788 100644--- a/server/services/cosMergeAdmission.js+++ b/server/services/cosMergeAdmission.js@@ -284,12 +284,37 @@ async function verifiedCleanupRecovery(agent, repository, agents) {return repositoryKey(await getOriginInfo(parent.metadata.sourceWorkspace).catch(() => null)) === repository;}+// A source-checkout coordinator owns only its scheduler-assigned targets. A+// successful ownership check selects one target; acquire/check re-read all live+// holds under the state lock, so an old reservation cannot outlive a policy or+// checkout change. No caller-supplied admission fields participate in this proof.+async function verifiedReconcileCoordinator(agent, repository, agents) {+ if (!agent.metadata?.reconcileMergeReservation) return false;+ const { reconcileMergeTarget } = await import('../lib/claimContinuation.js');+ const task = await liveTask(agent);+ const proof = reconcileMergeTarget(agent, task, agent.metadata.reconcileMergeReservation);+ if (!proof || repositoryKey(proof.assignment.origin) !== repository+ || !await checkoutOnBranch(proof.target.workspacePath, proof.target.branch, repository)) return false;+ const { checkReconcileOwnership } = await import('./cosClaimOwnership.js');+ const admission = await checkReconcileOwnership({ agentId: agent.id, appId: proof.assignment.appId,+ branch: proof.target.branch, worktreePath: proof.target.workspacePath }, {+ reserve: false, getAgents: async () => Object.values(agents),+ getAppById: async (appId) => {+ const { getAppById } = await import('./apps.js');+ const app = await getAppById(appId);+ return app?.repoPath === proof.assignment.repoPath ? app : null;+ },+ });+ return admission.admitted ? { reconcileTarget: proof.target } : false;+}+// Claim parents carry their registered claim binding; every other participant// must prove its registered target against live task and checkout state.async function verifiedParticipant(agent, repository, agents) {if (isTruthyMeta(agent.metadata?.claimPicksOwnBranch) || agent.metadata?.claimBranch) return true;if (isCleanupRecovery(agent)) return verifiedCleanupRecovery(agent, repository, agents);- return await verifiedReviewCoordinator(agent, repository) || verifiedWorktreeDelivery(agent, repository);+ return await verifiedReviewCoordinator(agent, repository) || await verifiedWorktreeDelivery(agent, repository)+ || verifiedReconcileCoordinator(agent, repository, agents);}/**@@ -324,6 +349,9 @@ export async function resolveMergeHandoffOwner(agentId) {if (await verifiedWorktreeDelivery(agent, repository)) {return { ...owner, owns: (branch) => branch === meta.prDeliveryTarget.branch, workspacePath: meta.prDeliveryTarget.workspacePath };}+ const reconcile = await verifiedReconcileCoordinator(agent, repository, snapshot.agents);+ if (reconcile) return { ...owner, owns: branch => branch === reconcile.reconcileTarget.branch,+ workspacePath: reconcile.reconcileTarget.workspacePath };return { refused: 'handoff-owner-unverified' };}@@ -402,7 +430,10 @@ export async function claimMergeAdmission({ agentId, action, token, outcome }) {}const held = state.mergeAdmissions[repository];if (participant.headSha && held?.agentId === agentId && !expired(held) && held.headSha !== participant.headSha) return refuse('lease-head-changed');+ if (held?.agentId === agentId && !expired(held)+ && JSON.stringify(held.reconcileTarget) !== JSON.stringify(participant.reconcileTarget)) return refuse('lease-target-changed');return admit(state, save, repository, { kind: 'agent', ...binding(agent),+ ...(participant.reconcileTarget ? { reconcileTarget: participant.reconcileTarget } : {}),...(participant.headSha ? { headSha: participant.headSha } : {}) }, measure);}const lease = state.mergeAdmissions[repository];@@ -412,6 +443,7 @@ export async function claimMergeAdmission({ agentId, action, token, outcome }) {// An expired holder must stop and re-acquire before merging; releasing// its own still-unclaimed lease stays permitted.if (action === 'check' && participant.headSha && lease.headSha !== participant.headSha) return refuse('lease-head-changed');+ if (action === 'check' && JSON.stringify(lease.reconcileTarget) !== JSON.stringify(participant.reconcileTarget)) return refuse('lease-target-changed');if (action === 'check') return expired(lease) ? refuse('lease-expired') : { admitted: true, token, repository };if (action !== 'release' || !MERGE_ADMISSION_OUTCOMES.includes(outcome)) return refuse('outcome-required');delete state.mergeAdmissions[repository];diff --git a/server/services/cosTaskPreStepBlocks.compose.test.js b/server/services/cosTaskPreStepBlocks.compose.test.jsindex 59a9ad6bd1..b899675f3a 100644--- a/server/services/cosTaskPreStepBlocks.compose.test.js+++ b/server/services/cosTaskPreStepBlocks.compose.test.js@@ -20,6 +20,9 @@*/import { describe, it, expect, beforeEach, vi } from 'vitest';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { buildAgentRegistration } from '../lib/agentRegistrationRecord.js';+import { generateTasksMarkdown, parseTasksMarkdown } from '../lib/taskParser.js';import { retainRetirementObligations } from '../lib/reconcileRetirementEvidence.js';const BRANCH_RECONCILE_TEMPLATE = [@@ -62,6 +65,7 @@ vi.mock('./appActivity.js', async (importActual) => ({vi.mock('./apps.js', async (importActual) => ({...(await importActual()),getAppTaskTypeOverrides: vi.fn(async () => ({})),+ getAppById: async () => admissionFixture.app,}));vi.mock('./codeReview.js', async (importActual) => ({@@ -107,9 +111,27 @@ vi.mock('./agentState.js', async (importActual) => ({getActiveAgentIds: vi.fn(() => []),}));+const admissionFixture = vi.hoisted(() => ({ state: null, task: null, app: null, trees: [], hold: null,+ branch: 'claim/issue-42', origin: { host: 'github.com', fullName: 'example/repo' } }));vi.mock('./cosState.js', () => ({+ AGENTS_DIR: '/tmp/synthetic-agents',readAgentsStateForSafetyCheck: vi.fn(async () => ({ trusted: true, agents: {} })),+ readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: true, ...structuredClone(admissionFixture.state) }),+ withStateLock: createFileWriteQueue(),+ loadState: async () => admissionFixture.state,+ saveState: async state => { admissionFixture.state = structuredClone(state); },}));+vi.mock('./cosTaskStore.js', async original => ({ ...await original(), getTaskById: async () => admissionFixture.task }));+vi.mock('../lib/gitRemote.js', async original => ({ ...await original(), getOriginInfo: async () => admissionFixture.origin }));+vi.mock('./worktreeManager.js', async original => ({ ...await original(), listWorktrees: async () => admissionFixture.trees }));+vi.mock('../lib/execGit.js', async original => ({ ...await original(), execGit: async () => ({ stdout: admissionFixture.branch }) }));+vi.mock('./branchCompletionPolicy.js', async original => ({ ...await original(), readBranchCompletionHold: async () => admissionFixture.hold }));+// The test's repository is synthetic; durable retirement fencing has real-filesystem coverage.+vi.mock('../lib/checkoutRetirementAdmission.js', () => ({ withCheckoutPublication: (_repo, work) => work() }));++import { registerAgent } from './cosAgentLifecycle.js';+import { claimMergeAdmission, resolveMergeHandoffOwner } from './cosMergeAdmission.js';+import { checkReconcileOwnership } from './cosClaimOwnership.js';import { emitLog } from './cosEvents.js';import { inspectOpenDeliveryRepair } from './repoCleanupObservation.js';@@ -414,3 +436,157 @@ describe('prepareManagedAppImprovementTask composes the extracted pre-step layer});});+++// Regression: prompt-only branch assignments formerly reserved claimBranches+// successfully but never survived registration as a merge participant.+describe('scheduled reconciliation registration through merge admission', () => {+ const workspacePath = '/tmp/example-checkout';+ const branch = 'claim/issue-42';+ const ownership = (over = {}) => checkReconcileOwnership({ agentId: 'agent-reconcile', appId: APP.id,+ branch, worktreePath: workspacePath, ...over });+ const acquire = () => claimMergeAdmission({ agentId: 'agent-reconcile', action: 'acquire' });+ const owner = () => admissionFixture.state.agents['agent-reconcile'];+ const register = async task => {+ admissionFixture.task = { ...parseTasksMarkdown(generateTasksMarkdown([{ ...task, description: task.description.split('\n')[0],+ metadata: { ...task.metadata, prompt: task.description } }], true))[0], taskType: 'internal' };+ await registerAgent('agent-reconcile', task.id, buildAgentRegistration({ task: admissionFixture.task,+ provider: { id: 'example-provider' }, workspacePath: APP.repoPath, sourceWorkspace: APP.repoPath,+ modelSelection: { tier: 'heavy', reason: 'test' }, prOpenedBy: 'portos', claimFlowTask: false }));+ };+ beforeEach(async () => {+ vi.clearAllMocks();+ Object.assign(admissionFixture, { state: { agents: {}, mergeAdmissions: {}, stats: { agentsSpawned: 0 } }, task: null, app: APP,+ trees: [{ path: workspacePath, branch: `refs/heads/${branch}`, locked: false }], hold: null, branch,+ origin: { host: 'github.com', fullName: 'example/repo' } });+ readAgentsStateForSafetyCheck.mockImplementation(async () => ({ trusted: true, agents: structuredClone(admissionFixture.state.agents) }));+ getBranchReconcileOutcome.mockResolvedValue(null);+ recordBranchReconcileOutcome.mockImplementation(async (_id, update) => ({ ...update, retirementObligations: [] }));+ getPerpetualDrainState.mockResolvedValue({ signature: null, dispatchCount: 0 });+ recordPerpetualDispatch.mockResolvedValue(1);+ getTaskInterval.mockResolvedValue({ type: 'on-demand', taskMetadata: { branchesPerAgent: 1 } });+ reconcileMock.mockResolvedValue(scan({ inFlight: [{ branch, worktreePath: workspacePath, state: 'NEEDS_PR' },+ { branch: 'claim/issue-99', worktreePath: '/tmp/other-checkout', state: 'NEEDS_PR' }] }));+ await register(await generate());+ });++ it('persists only the selected assignment, reserves it, and acquires/checks/releases the shared lease', async () => {+ expect(owner().metadata.reconcileAssignment.targets).toEqual([{ branch, workspacePath, merge: true }]);+ expect(owner().metadata).toMatchObject({ configClaimFlow: false, isWorktree: false, configOpenPR: false, prOpenedBy: 'portos' });+ expect((await acquire()).admitted).toBe(false);+ expect(await ownership()).toEqual({ admitted: true });+ const lease = await acquire();+ expect(lease.admitted).toBe(true);+ expect(await claimMergeAdmission({ agentId: owner().id, action: 'check', token: lease.token })).toMatchObject({ admitted: true });+ const handoff = await resolveMergeHandoffOwner(owner().id);+ expect(handoff.workspacePath).toBe(workspacePath);+ expect(handoff.owns(branch)).toBe(true);+ expect(handoff.owns('claim/issue-99')).toBe(false);+ // Successful merge may remove the checkout and complete the task before release.+ admissionFixture.trees = [];+ admissionFixture.task.status = 'completed';+ expect(await claimMergeAdmission({ agentId: owner().id, action: 'release', token: lease.token, outcome: 'merged' }))+ .toMatchObject({ released: true });+ expect(admissionFixture.state.mergeAdmissions).toEqual({});+ });++ it('refuses an unassigned branch even when caller paths and copied prose describe it', async () => {+ admissionFixture.trees.push({ path: '/tmp/other-checkout', branch: 'refs/heads/claim/issue-99' });+ expect(await ownership({ branch: 'claim/issue-99', worktreePath: '/tmp/other-checkout' }))+ .toMatchObject({ admitted: false, reason: 'reconcile-target-unverified' });+ delete owner().metadata.reconcileAssignment;+ delete admissionFixture.task.metadata.reconcileAssignment;+ expect(await ownership()).toMatchObject({ admitted: true });+ expect(owner().metadata.claimBranches).toEqual([branch]);+ expect(await claimMergeAdmission({ agentId: owner().id, action: 'acquire', branch, worktreePath: workspacePath }))+ .toMatchObject({ admitted: false, reason: 'claim-owner-unverified' });+ });++ it.each(['task-completed', 'task-missing', 'owner-completed', 'owner-missing', 'assignment-changed', 'checkout-changed',+ 'repository-changed', 'app-changed', 'read-only', 'human-handoff', 'auto-merge-disabled', 'retirement-only',+ 'policy-hold', 'policy-review', 'policy-unreadable', 'live-owner', 'locked-checkout', 'ownership-unreadable'])+ ('refuses %s after a successful reservation', async mode => {+ expect((await ownership()).admitted).toBe(true);+ const lease = await acquire();+ expect(lease.admitted).toBe(true);+ if (mode === 'task-missing') admissionFixture.task = null;+ if (mode === 'task-completed') admissionFixture.task.status = 'completed';+ if (mode === 'owner-completed') owner().status = 'completed';+ if (mode === 'owner-missing') delete admissionFixture.state.agents['agent-reconcile'];+ if (mode === 'assignment-changed') admissionFixture.task.metadata.reconcileAssignment.targets[0].workspacePath = '/tmp/changed';+ if (mode === 'checkout-changed') admissionFixture.branch = 'main';+ if (mode === 'repository-changed') admissionFixture.origin = { host: 'github.com', fullName: 'example/other' };+ if (mode === 'app-changed') admissionFixture.app = { ...APP, repoPath: '/tmp/changed' };+ if (mode === 'read-only') admissionFixture.task.metadata.readOnly = 'true';+ if (mode === 'human-handoff') admissionFixture.task.metadata.prCompletion = 'leave-open';+ if (mode === 'auto-merge-disabled') admissionFixture.task.metadata.autoMerge = 'false';+ if (mode === 'retirement-only') {+ admissionFixture.task.metadata.reconcileAssignment.targets[0].merge = false;+ owner().metadata.reconcileAssignment.targets[0].merge = false;+ }+ if (mode === 'policy-hold') admissionFixture.hold = 'pr-completion-human-handoff';+ if (mode === 'policy-review') admissionFixture.hold = 'pr-completion-review-required';+ if (mode === 'policy-unreadable') admissionFixture.hold = 'pr-completion-policy-unavailable';+ if (mode === 'live-owner') admissionFixture.state.agents['agent-other'] = { id: 'agent-other', status: 'running',+ metadata: { sourceWorkspace: APP.repoPath, claimBranches: [branch] } };+ if (mode === 'locked-checkout') admissionFixture.trees[0].locked = true;+ if (mode === 'ownership-unreadable') admissionFixture.trees = null;+ expect((await acquire()).admitted).toBe(false);+ expect((await claimMergeAdmission({ agentId: 'agent-reconcile', action: 'check', token: lease.token })).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);+ expect(task.metadata.reconcileAssignment.targets).toEqual([{ branch, workspacePath, merge: true }]);+ });++ it('allows non-merging reconciliation work with auto-merge disabled without minting merge authority', async () => {+ getTaskInterval.mockResolvedValue({ type: 'on-demand', taskMetadata: { autoMerge: false, branchesPerAgent: 1 } });+ await register(await generate());+ expect(owner().metadata.reconcileAssignment.targets[0].merge).toBe(false);+ expect((await ownership()).admitted).toBe(true);+ expect(owner().metadata.reconcileMergeReservation).toBeNull();+ expect((await acquire()).admitted).toBe(false);+ });++ it('does not retarget an acquired lease when another assigned branch is reserved', async () => {+ getTaskInterval.mockResolvedValue({ type: 'on-demand', taskMetadata: { branchesPerAgent: 2 } });+ await register(await generate());+ expect((await ownership()).admitted).toBe(true);+ const lease = await acquire();+ admissionFixture.trees.push({ path: '/tmp/other-checkout', branch: 'refs/heads/claim/issue-99' });+ expect((await ownership({ branch: 'claim/issue-99', worktreePath: '/tmp/other-checkout' })).admitted).toBe(true);+ admissionFixture.branch = 'claim/issue-99';+ expect(await acquire()).toMatchObject({ admitted: false, reason: 'lease-target-changed' });+ expect(await claimMergeAdmission({ agentId: owner().id, action: 'check', token: lease.token }))+ .toMatchObject({ admitted: false, reason: 'lease-target-changed' });+ expect(await claimMergeAdmission({ agentId: owner().id, action: 'release', token: lease.token, outcome: 'resync' }))+ .toMatchObject({ released: true });+ expect((await acquire()).admitted).toBe(true);+ });++ it('reserves and releases a non-claim branch without granting other coordinators its checkout', async () => {+ const ordinaryBranch = 'fix/example';+ reconcileMock.mockResolvedValue(scan({ inFlight: [{ branch: ordinaryBranch, worktreePath: workspacePath, state: 'ABANDONED_WIP' }] }));+ await register(await generate());+ admissionFixture.branch = ordinaryBranch;+ admissionFixture.trees[0].branch = `refs/heads/${ordinaryBranch}`;+ expect((await ownership({ branch: ordinaryBranch })).admitted).toBe(true);+ expect((await acquire()).admitted).toBe(true);+ expect(await checkReconcileOwnership({ appId: APP.id, branch: ordinaryBranch, worktreePath: workspacePath }))+ .toMatchObject({ admitted: false, reason: 'claim-owner-active' });+ const { updateClaimOwnership } = await import('./cosClaimOwnership.js');+ expect(await updateClaimOwnership({ agentId: owner().id, action: 'release', branch: ordinaryBranch })).toMatchObject({ released: true });+ expect((await acquire()).admitted).toBe(false);+ });++ it('preserves repository lease exclusion for a different live participant', async () => {+ expect((await ownership()).admitted).toBe(true);+ admissionFixture.state.agents['agent-other'] = { id: 'agent-other', status: 'running', taskId: 'other-task',+ startedAt: '2026-01-01T00:00:00Z', metadata: { sourceWorkspace: APP.repoPath, claimPicksOwnBranch: true, claimBranches: ['claim/issue-100'] } };+ const other = await claimMergeAdmission({ agentId: 'agent-other', action: 'acquire' });+ expect(other.admitted).toBe(true);+ expect(await acquire()).toMatchObject({ admitted: false, reason: 'owner-active-or-unverified' });+ });+});diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.jsindex 020b2978b4..4403a8c04b 100644--- a/server/services/cosTaskPreStepBlocks.js+++ b/server/services/cosTaskPreStepBlocks.js@@ -670,6 +670,17 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskSemitLog('info', `🔀 branch-reconcile parked for ${app.name}: all ${allActionable.length} branch(es) were attempted without further progress`, { appId: app.id });return { skip: true };}+ // Only this deterministic scan writes the assignment. Schedule/run overrides+ // cannot supply it; registration snapshots it before any coordinator executes.+ const { getOriginInfo } = await import('../lib/gitRemote.js');+ const origin = await getOriginInfo(app.repoPath).catch(() => null);+ metadata.reconcileAssignment = origin ? {+ appId: app.id, repoPath: app.repoPath,+ origin: { host: origin.host, fullName: origin.fullName },+ targets: actionable.map(branch => ({ branch: branch.branch, workspacePath: branch.worktreePath || null,+ merge: actions.autoMerge !== false && !branch.retirement+ && ['NEEDS_PR', 'IN_REVIEW', 'CONFLICTED', 'ABANDONED_WIP'].includes(branch.state) })),+ } : null;metadata.perpetual = true;metadata.reconcileRetirements = actionable.filter(branch => branch.retirement).map(branch => ({...branch.retirement,