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: keep live claim ownership through branch reconciliation and epic child selection (#10089)

Adam Eivy94e3229cf186
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index c704999930..86591e1d67 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -57,6 +57,29 @@ before merge and repeat sync, pregate and fresh current-head CI when it changes.
Admission does not grant permission to adopt another owner's branch or checkout,
does not replace reviews/CI, and does not make queued auto-merge a completed merge.
+## Claim branch ownership
+
+A claim run cuts its own `claim/…` checkout, so its registered workspace stays
+the source repository and no worktree basename names it. Ownership is the
+registry's branch/repository binding (`server/lib/claimContinuation.js`):
+a pinned run registers its target branch and is treated as possibly owning
+every claim checkout in its repository until it binds the branch it actually
+works on (a tracking epic ships a child, an oversized issue ships a slice); a
+picker or swarm parent is a possible owner until it binds its first branch.
+The claim prompt binds each branch through the host-control-gated
+`POST /api/cos/claim-ownership` (`action: "bind"`, registered agent ID, branch)
+BEFORE creating that worktree, and `release` hands a branch off mid-run. The
+run's completion releases everything; quiet diffs, cwd, or a missing basename
+never do. Bindings live on the run record in `data/cos/state.json` — no new
+store or migration; records without them keep their previous behavior.
+
+branch-reconcile applies the same owners twice: its scan holds a branch with a
+live, possible or unreadable claim owner (never dispatched as `ABANDONED_WIP`,
+never retired by cleanup), and each dispatched branch carries a `check` command
+the worker runs right before its first mutation, because a run can take the
+branch after the scan. A refusal, an unreadable registry, or a moved checkout
+leaves the branch untouched; a completed or released owner admits recovery.
+
## Task File Format
```markdown
diff --git a/server/lib/README.md b/server/lib/README.md
index 77f8962949..42a73eb158 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 `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. `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), `claimCheckoutOwnerReason(...)` names a live/possible claim owner for branch-reconcile, 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 1e0b9a741b..aa2a456c2c 100644
--- a/server/lib/claimContinuation.js
+++ b/server/lib/claimContinuation.js
@@ -45,15 +45,81 @@ function samePath(a, b) {
* - a run pinned to a target owns exactly `claim/…` for that target;
* - an unpinned run (the issue picker, including a swarm orchestrator whose
* fan-out children cut their own trees) owns a branch it chooses later, so
- * it is registered as possibly owning ANY claim branch in its repository.
+ * it is registered as possibly owning ANY claim branch in its repository
+ * until it binds the concrete ones (`bindClaimBranch`).
* Null for a task that is not a claim flow. Pure.
*
- * @returns {{ claimBranch: string|null, claimPicksOwnBranch: boolean }|null}
+ * @returns {{ claimBranch: string|null, claimPicksOwnBranch: boolean, claimSelectionPending?: true }|null}
*/
export function claimOwnershipBinding(task) {
if (!isTruthyMeta(task?.metadata?.claimFlow)) return null;
const claimBranch = claimContinuationBranch(task?.metadata?.claimTarget);
- return { claimBranch, claimPicksOwnBranch: !claimBranch };
+ // A pinned run may still check out a DIFFERENT branch: a pinned tracking epic
+ // ships its first eligible child, and an oversized issue is split and its
+ // first slice shipped. Until the run binds the branch it actually works on
+ // (`bindClaimBranch`), it may own any claim tree in its repository.
+ return { claimBranch, claimPicksOwnBranch: !claimBranch, ...(claimBranch ? { claimSelectionPending: true } : {}) };
+}
+
+/** A branch a claim run may bind to itself: `claim/…` or slashdo's `next/…`. */
+export function isClaimOwnershipBranch(name) {
+ const branch = String(name ?? '');
+ return branch.length <= 200 && /^(claim|next)\/[A-Za-z0-9._/-]+$/.test(branch)
+ && !branch.includes('..') && !branch.endsWith('/') && !branch.endsWith('.lock');
+}
+
+const ownershipList = (agent, key) => {
+ const list = agent?.metadata?.[key] ?? agent?.[key];
+ return Array.isArray(list) ? list.filter((b) => typeof b === 'string') : [];
+};
+
+/** Most branches one run may hold bound at once — a swarm binds one per child. */
+export const MAX_BOUND_CLAIM_BRANCHES = 50;
+
+/**
+ * The metadata patch that binds `branch` to a running claim run: the concrete
+ * branch it is about to check out (the pinned target, an epic's child, a split
+ * slice, or the issue a picker selected). The first binding settles the run's
+ * open selection (see `mayPickClaimBranch`). `{ refused }` when the record is
+ * not a live claim run, the branch is not claim-shaped, or the bound list is
+ * full. Pure.
+ *
+ * @returns {{ claimBranches: string[], claimReleasedBranches: string[], claimSelectionPending: false }|{ refused: string }}
+ */
+export function bindClaimBranch(agent, branch) {
+ const refused = bindingRefusal(agent, branch);
+ if (refused) return { refused };
+ const bound = ownershipList(agent, 'claimBranches');
+ if (!bound.includes(branch) && bound.length >= MAX_BOUND_CLAIM_BRANCHES) return { refused: 'too-many-branches' };
+ return {
+ claimBranches: bound.includes(branch) ? bound : [...bound, branch],
+ claimReleasedBranches: ownershipList(agent, 'claimReleasedBranches').filter((b) => b !== branch),
+ claimSelectionPending: false,
+ };
+}
+
+/**
+ * The metadata patch that explicitly releases `branch` from a running claim run
+ * that is handing it to somebody else before the run ends. Completion of the run
+ * releases everything without this. `{ refused }` on the same conditions as
+ * `bindClaimBranch`. Pure.
+ */
+export function releaseClaimBranch(agent, branch) {
+ const refused = bindingRefusal(agent, branch);
+ if (refused) return { refused };
+ const released = ownershipList(agent, 'claimReleasedBranches');
+ return {
+ claimBranches: ownershipList(agent, 'claimBranches').filter((b) => b !== branch),
+ claimReleasedBranches: released.includes(branch) ? released : [...released, branch].slice(-MAX_BOUND_CLAIM_BRANCHES),
+ };
+}
+
+// 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';
+ const claimRun = Boolean(registeredClaimBranch(agent)) || isTruthyMeta(agent?.claimPicksOwnBranch ?? agent?.metadata?.claimPicksOwnBranch);
+ if (!claimRun) return 'claim-owner-unverified';
+ return isClaimOwnershipBranch(branch) ? null : 'branch-invalid';
}
function isLiveAgent(agent) {
@@ -79,14 +145,34 @@ function registeredClaimBranch(agent) {
return agent?.claimBranch ?? agent?.metadata?.claimBranch;
}
+// Every branch the run registered — its pinned target plus each branch it bound
+// — minus the ones it explicitly released.
+function ownsClaimBranch(agent, branchName) {
+ if (ownershipList(agent, 'claimReleasedBranches').includes(branchName)) return false;
+ return registeredClaimBranch(agent) === branchName || ownershipList(agent, 'claimBranches').includes(branchName);
+}
+
+// A run that may hold a claim checkout nobody can name yet: a picker until it
+// binds its first branch, a pinned run until it binds the branch it actually
+// works on. The claim prompt binds every branch BEFORE its worktree exists, so
+// once a run has bound one, each tree it cuts is named; a run that never binds
+// (an older prompt, a provider that cannot curl) stays possible owner of every
+// claim tree in its repository until it ends.
+function mayPickClaimBranch(agent) {
+ if (isTruthyMeta(agent?.claimSelectionPending ?? agent?.metadata?.claimSelectionPending)) return true;
+ return isTruthyMeta(agent?.claimPicksOwnBranch ?? agent?.metadata?.claimPicksOwnBranch)
+ && ownershipList(agent, 'claimBranches').length === 0;
+}
+
/**
* Whether a running or paused agent other than `ignoreIds` holds, or may hold,
* the claim checkout:
- * - `active`: it works inside the directory, or registered this exact branch
- * in this repository;
- * - `ambiguous`: it is a claim run that picks its own branch, in this same
- * repository, so it might be the one that cut this tree — unprovable from
- * the registry alone.
+ * - `active`: it works inside the directory, or registered or bound this
+ * exact branch in this repository (and has not released it);
+ * - `ambiguous`: it is a claim run that picks its own branch, or a pinned run
+ * that has not yet bound the branch it works on, in this same repository,
+ * so it might be the one that cut this tree — unprovable from the registry
+ * alone.
* `active` outranks `ambiguous` across the whole list.
*
* @returns {'active'|'ambiguous'|null}
@@ -99,8 +185,8 @@ function claimHolderOccupancy({ agents, holderPath, branchName, sourceWorkspace,
const workspace = agentWorkspace(agent);
if (samePath(workspace, holderPath) || (holderPath && workspace && isPathInsideDir(holderPath, workspace))) return 'active';
if (!inRepository(agent, sourceWorkspace)) continue;
- if (registeredClaimBranch(agent) === branchName) return 'active';
- if (claimHolder && isTruthyMeta(agent.claimPicksOwnBranch ?? agent.metadata?.claimPicksOwnBranch)) ambiguous = true;
+ if (ownsClaimBranch(agent, branchName)) return 'active';
+ if (claimHolder && mayPickClaimBranch(agent)) ambiguous = true;
}
return ambiguous ? 'ambiguous' : null;
}
@@ -217,7 +303,8 @@ export function claimBranchAdmission({ branchName, preferredPath, agentId, sourc
* children cut trees PortOS never sees) might own this tree. Nothing observable
* proves it does not — git activity, the continued run's own registration, and
* the absence of a process inside the tree can all be true of a live owner — so
- * the launch stays deferred until that run ends, which is its explicit release.
+ * the launch stays deferred until that run binds the branches it works on (the
+ * claim prompt binds each before cutting it) or ends.
*
* @param {{
* metadata?: object,
@@ -239,3 +326,21 @@ export function claimContinuationAdmission({ metadata, agentId, sourceWorkspace,
ignoreIds: [metadata?.resumedFromAgentId],
});
}
+
+/**
+ * Why a live claim owner holds this branch's checkout, for a caller about to
+ * classify, dispatch or mutate it from outside that run (branch-reconcile's
+ * scan and its worker's pre-mutation recheck). The same branch/repository owner
+ * contract as `claimBranchAdmission`, without its holder-path bookkeeping: the
+ * caller already knows the checkout. An unreadable registry holds the branch.
+ *
+ * @param {{ branchName: string, holderPath?: string|null, sourceWorkspace?: string, agents: Array<object>|null, ignoreIds?: string[] }} input
+ * @returns {'claim-owner-active'|'claim-owner-ambiguous'|'claim-ownership-unreadable'|null}
+ */
+export function claimCheckoutOwnerReason({ branchName, holderPath = null, sourceWorkspace, agents, ignoreIds = [] }) {
+ if (!Array.isArray(agents) || !branchName) return 'claim-ownership-unreadable';
+ const occupancy = claimHolderOccupancy({
+ agents, holderPath, branchName, sourceWorkspace, ignoreIds: new Set(ignoreIds.filter(Boolean)),
+ });
+ return occupancy ? `claim-owner-${occupancy}` : null;
+}
diff --git a/server/lib/claimContinuation.test.js b/server/lib/claimContinuation.test.js
index 43a59f35c2..641cd97c6b 100644
--- a/server/lib/claimContinuation.test.js
+++ b/server/lib/claimContinuation.test.js
@@ -5,6 +5,9 @@ import {
claimContinuationPointer,
claimContinuationWorkspace,
claimOwnershipBinding,
+ bindClaimBranch,
+ releaseClaimBranch,
+ claimCheckoutOwnerReason,
} from './claimContinuation.js';
const ROOT = '/data/cos/worktrees';
@@ -120,7 +123,7 @@ describe('claimContinuationWorkspace', () => {
describe('claimOwnershipBinding', () => {
it('binds a pinned claim run to its exact branch', () => {
expect(claimOwnershipBinding({ metadata: { claimFlow: 'true', claimTarget: '42' } }))
- .toEqual({ claimBranch: 'claim/issue-42', claimPicksOwnBranch: false });
+ .toEqual({ claimBranch: 'claim/issue-42', claimPicksOwnBranch: false, claimSelectionPending: true });
});
it('marks an unpinned claim run (issue picker or swarm orchestrator) as picking its own branch', () => {
@@ -232,3 +235,52 @@ describe('claimContinuationAdmission', () => {
.toEqual({ admit: false, reason: 'pointer-incomplete' });
});
});
+
+// #10089: the branch a run actually checks out is not always the one it was
+// registered for — a pinned tracking epic ships a child, a picker chooses later.
+describe('claim branch binding lifecycle', () => {
+ const SOURCE = '/repos/app-x';
+ const CHILD = `${ROOT}/claim-portos-issue-101`;
+ const reason = (agents, branchName = 'claim/issue-101', holderPath = CHILD) =>
+ claimCheckoutOwnerReason({ branchName, holderPath, sourceWorkspace: SOURCE, agents });
+ const register = (task) => ({
+ id: 'agent-run', status: 'running', workspacePath: SOURCE,
+ metadata: { sourceWorkspace: SOURCE, ...claimOwnershipBinding(task) },
+ });
+ const bind = (agent, branch) => ({ ...agent, metadata: { ...agent.metadata, ...bindClaimBranch(agent, branch) } });
+
+ it('protects an epic child from a run pinned to the epic, before and after it binds the child', () => {
+ const pinned = register({ metadata: { claimFlow: true, claimTarget: '100' } });
+ // Choosing: every claim checkout in its repository may be its own.
+ expect(reason([pinned])).toBe('claim-owner-ambiguous');
+ const bound = bind(pinned, 'claim/issue-101');
+ expect(reason([bound])).toBe('claim-owner-active');
+ // Bound and settled: an unrelated claim tree is free again.
+ expect(reason([bound], 'claim/issue-55', `${ROOT}/claim-portos-issue-55`)).toBeNull();
+ // The run's end, or an explicit release, frees the child for recovery.
+ expect(reason([{ ...bound, status: 'completed' }])).toBeNull();
+ const released = { ...bound, metadata: { ...bound.metadata, ...releaseClaimBranch(bound, 'claim/issue-101') } };
+ expect(reason([released])).toBeNull();
+ });
+
+ it('keeps a picker run a possible owner until it binds its selection', () => {
+ const picker = register({ metadata: { claimFlow: true } });
+ expect(reason([picker])).toBe('claim-owner-ambiguous');
+ const bound = bind(picker, 'claim/issue-101');
+ expect(reason([bound])).toBe('claim-owner-active');
+ expect(reason([bound], 'claim/issue-55', `${ROOT}/claim-portos-issue-55`)).toBeNull();
+ });
+
+ it('refuses to bind for a finished run, a non-claim run or a non-claim branch', () => {
+ const pinned = register({ metadata: { claimFlow: true, claimTarget: '100' } });
+ expect(bindClaimBranch({ ...pinned, status: 'completed' }, 'claim/issue-101')).toEqual({ refused: 'owner-not-running' });
+ expect(bindClaimBranch({ id: 'agent-x', status: 'running', metadata: {} }, 'claim/issue-101')).toEqual({ refused: 'claim-owner-unverified' });
+ for (const branch of ['main', 'claim/../main', 'claim/issue-1 x', '']) {
+ expect(bindClaimBranch(pinned, branch)).toEqual({ refused: 'branch-invalid' });
+ }
+ });
+
+ it('holds the branch when the registry is unreadable', () => {
+ expect(reason(null)).toBe('claim-ownership-unreadable');
+ });
+});
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 28aaf83dbb..7d38e094cb 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -170,6 +170,7 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
// CoS: queue, release or steer an agent that runs shell commands in a
// worktree, or a job that runs a shell command directly.
'POST /api/cos/merge-admission',
+ 'POST /api/cos/claim-ownership',
'POST /api/cos/start',
'POST /api/cos/resume',
'POST /api/cos/evaluate',
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index d0042f246a..82687729f5 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -25,6 +25,26 @@ router.post('/merge-admission', asyncHandler(async (req, res) => {
res.json(await claimMergeAdmission(input));
}));
+// A claim run binds (or hands off) the concrete branch it checks out; a
+// branch-reconcile worker rechecks live ownership right before mutating (#10089).
+const claimBranchSchema = z.string().min(1).max(200);
+const claimOwnershipSchema = z.discriminatedUnion('action', [
+ z.object({ action: z.literal('bind'), agentId: z.string().min(1).max(200), branch: claimBranchSchema }),
+ z.object({ action: z.literal('release'), agentId: z.string().min(1).max(200), branch: claimBranchSchema }),
+ z.object({
+ action: z.literal('check'),
+ appId: z.string().min(1).max(200),
+ branch: claimBranchSchema,
+ worktreePath: z.string().min(1).max(4096).optional(),
+ agentId: z.string().min(1).max(200).optional(),
+ }),
+]);
+router.post('/claim-ownership', asyncHandler(async (req, res) => {
+ const input = validateRequest(claimOwnershipSchema, req.body ?? {});
+ const { updateClaimOwnership, checkReconcileOwnership } = await import('../services/cosClaimOwnership.js');
+ res.json(input.action === 'check' ? await checkReconcileOwnership(input) : await updateClaimOwnership(input));
+}));
+
// `reason` is persisted into task metadata + interpolated into logs; guard the
// shape so a non-string body can't store `[object Object]`.
const pauseBodySchema = z.object({ reason: z.string().max(500).optional() });
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 745c3f383b..b1b74b9fa1 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -39,6 +39,9 @@ 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 { agentApiCurl } from '../lib/agentApiToken.js';
+import { localApiBaseUrl } from '../lib/networkExposure.js';
// Never reconciled — the canonical long-lived-branch set (`main`/`master`/`dev`/
// `develop`/`release`/`gh-pages`) shared with the git branch-cleanup guards in
@@ -364,6 +367,51 @@ export function worktreeProtectionExpiresAt({ path, locked, activeAgentIds, ageM
});
}
+/**
+ * The live-owner context branch-reconcile classifies against: the runtime ids,
+ * plus every running or paused record's id and its workspace basename (a claim
+ * tree uses a branch-shaped directory name, not the run's `agent-*` id). Pure.
+ *
+ * @param {Iterable<string>} runtimeIds - `getActiveAgentIds()`
+ * @param {object[]} liveAgents - the agent registry
+ * @returns {Set<string>}
+ */
+export function buildActiveOwnerIds(runtimeIds, liveAgents) {
+ const ids = new Set(runtimeIds);
+ for (const agent of liveAgents) {
+ if (agent?.status !== 'running' && agent?.status !== 'paused') continue;
+ if (agent.id) ids.add(agent.id);
+ const worktreeId = worktreeAgentId(agent.workspacePath || agent.metadata?.workspacePath);
+ if (worktreeId) ids.add(worktreeId);
+ }
+ return ids;
+}
+
+/**
+ * A claim run that cut a `claim-*` checkout itself still lists the source
+ * repository as its workspace, so neither `activeAgentIds` nor the branch name
+ * proves it gone. The registry's branch/repository bindings do: a pinned or
+ * bound branch is `claim-owner-active`, and a picker (or a pinned run still
+ * choosing, as a tracking epic does before it picks its child) makes every
+ * claim checkout in its repository `claim-owner-ambiguous`.
+ *
+ * `claimOwners` is `{ agents }` from the caller. Omitted (undefined) means the
+ * caller does not dispatch or mutate on this answer (a read-only detector) and
+ * nothing is added; supplied but unreadable holds every branch.
+ *
+ * @param {{ branch: string, path: string|null, claimOwners?: { agents: object[]|null }, sourceWorkspace: string }} input
+ * @returns {string|null}
+ */
+export function resolveClaimOwnerReason({ branch, path, claimOwners, sourceWorkspace }) {
+ if (claimOwners === undefined) return null;
+ return claimCheckoutOwnerReason({
+ branchName: branch,
+ holderPath: path,
+ sourceWorkspace,
+ agents: claimOwners?.agents ?? null,
+ });
+}
+
/**
* Is this worktree a CoS agent workspace whose agent is no longer running?
*
@@ -785,7 +833,7 @@ async function worktreeAgeMs(worktreePath) {
* worktreeDirty, dirtyPaths, behind, ahead, collisionPaths, abandonedAgentWorktree,
* abandonedClaimWorktree, openPr }
*/
-export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIds = null, remoteHeads: providedRemoteHeads, hasOrigin: providedHasOrigin, origin: providedOrigin, forgeExec = null, forgeAccount = null } = {}) {
+export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIds = null, claimOwners = undefined, remoteHeads: providedRemoteHeads, hasOrigin: providedHasOrigin, origin: providedOrigin, forgeExec = null, forgeAccount = null } = {}) {
const protectedSet = new Set([...PROTECTED_BRANCHES, defaultBranch]);
// Read origin ONCE and use it for both facts below — `hasOrigin` (the gate on
// classifyBranch's ahead-based NEEDS_PR arm, so an origin-less repo's local work
@@ -851,6 +899,7 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId
// failure so an unreadable tip can never match a recorded one.
const tipOut = await execGit(['rev-parse', b.name], repoPath, { ignoreExitCode: true }).catch(() => null);
const tip = (tipOut?.stdout || '').trim() || null;
+ const claimOwnerReason = resolveClaimOwnerReason({ branch: b.name, path: worktreePath, claimOwners, sourceWorkspace: repoPath });
inputs.push({
branch: b.name,
tip,
@@ -880,9 +929,13 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId
// uses to refuse a teardown, reused by the classifier to refuse a DISPATCH —
// the two must agree, or the reconciler protects a worktree from deletion and
// then hands its branch to an agent that rebases underneath the live session.
+ // A registered claim owner counts too: a run that cut its own claim tree
+ // keeps the source repository as its workspace, so neither the basename
+ // set nor the branch name can see it (#10089).
liveOwnerReason: resolveLiveOwnerReason({
branch: b.name, path: worktreePath, locked: worktreeLocked, activeAgentIds
- }),
+ }) || claimOwnerReason,
+ claimOwnerReason,
behind: divergence.behind,
ahead: divergence.ahead,
collisionPaths: divergence.collisionPaths,
@@ -1145,6 +1198,9 @@ export async function reapSupersededBranches(repoPath, defaultBranch, superseded
* @returns {Promise<{ ok: true, prepared?: any } | { ok: false, reason: string, retryAt?: string }>}
*/
async function retireBranch(repoPath, b, { activeAgentIds = new Set(), staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, label, requireCleanWorktree = true, prepare }) {
+ // A live claim run may still be finishing this branch (CI wait, merge handoff,
+ // its own cleanup) — never remove its checkout or ref from under it.
+ if (b.claimOwnerReason) return { ok: false, reason: b.claimOwnerReason };
if (b.worktreePath) {
// Never tear down a worktree that's locked, a RECENT human /claim session, or
// an active CoS agent workspace. An abandoned claim worktree (clean and older
@@ -1198,6 +1254,8 @@ async function retireBranch(repoPath, b, { activeAgentIds = new Set(), staleClai
* branches left on `origin` that nothing local points at; off, they are only
* reported — see `reapOrphanedRemotes`. `activeAgentIds` protects in-use CoS
* agent worktrees and any live worktree basename tokens supplied by the caller.
+ * `claimOwners` (`{ agents }`, the agent registry) adds the registered claim
+ * owners — see `resolveClaimOwnerReason`; a dispatching caller must pass it.
* `forgeAccount` is the managed app record's explicit gh
* account pin, so an app whose repo belongs to another GitHub account is
* polled with a credential that can actually see it (#7540); unset, the
@@ -1213,7 +1271,7 @@ async function retireBranch(repoPath, b, { activeAgentIds = new Set(), staleClai
* failed mid-cycle. Either way an empty `inFlight` says nothing about the repo
* and the caller must retry rather than park on it (#3358).
*/
-export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSuperseded = cleanup, reapRemotes = false, activeAgentIds = new Set(), forgeAccount = null } = {}) {
+export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSuperseded = cleanup, reapRemotes = false, activeAgentIds = new Set(), claimOwners = undefined, forgeAccount = null } = {}) {
// Worktree cleanup is the first reconcile step, before any forge probe. It
// only removes a tree after proving both that it is completely clean and
// that every branch commit is already in the default branch (including
@@ -1272,7 +1330,7 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSup
// per cycle is the cost of each destructive step reading the remote itself.
const remoteHeads = origin?.hasOrigin ? await listRemoteHeads(repoPath) : null;
const inputs = await gatherBranchState(repoPath, {
- defaultBranch, activeAgentIds, remoteHeads, hasOrigin: Boolean(origin?.hasOrigin), origin,
+ defaultBranch, activeAgentIds, claimOwners, remoteHeads, hasOrigin: Boolean(origin?.hasOrigin), origin,
forgeExec, forgeAccount
});
// A gh failure AFTER a passing probe (a blip mid-cycle, or an unparseable
@@ -1620,10 +1678,11 @@ async function dispatchHintLineForBranch(branchName, repoPath) {
* gets one forge read for its issue's `model:`/`effort:` labels — see
* `dispatchHintLineForBranch`.
* @param {object[]} inFlight - actionable branches (post-filterActionable)
- * @param {{ defaultBranch:string, actions:object, branchesPerAgent?:number, repoPath?:string }} ctx
+ * @param {{ defaultBranch:string, actions:object, branchesPerAgent?:number, repoPath?:string, appId?:string }} ctx
+ * `appId` adds each branch's pre-mutation ownership recheck command.
* @returns {Promise<string>}
*/
-export async function formatInFlightForPrompt(inFlight, { defaultBranch, actions, branchesPerAgent, repoPath } = {}) {
+export async function formatInFlightForPrompt(inFlight, { defaultBranch, actions, branchesPerAgent, repoPath, appId } = {}) {
// One gh round-trip per issue-derived branch — resolved in parallel (not
// inline in the loop below) so N branches cost one round-trip's latency,
// not N of them in series.
@@ -1632,10 +1691,19 @@ export async function formatInFlightForPrompt(inFlight, { defaultBranch, actions
if (Number.isInteger(branchesPerAgent) && branchesPerAgent > 0) {
lines.splice(1, 0, `This coordinator run is limited to up to ${branchesPerAgent} branch(es); finish every branch listed below before reporting done.`);
}
+ // 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.');
+ }
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 } : {}) });
+ 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
// block, and the difference decides whether the push needs `-u`. State it
// rather than making the agent infer it from a missing PR link.
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 43b5e7e64b..747c1e484c 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -1297,6 +1297,79 @@ describe('reconcile', () => {
expect(git.deleteBranch).not.toHaveBeenCalled();
});
+ // #10089: a claim run that cut its own checkout keeps the SOURCE repository as
+ // its registered workspace, so the basename Set never names it. Its registered
+ // branch binding must hold the dirty tree; once the run is verifiably over the
+ // same tree is genuine abandoned work again.
+ describe('a live claim owner registered on the source repository', () => {
+ const dirtyClaim = () => {
+ git.getBranches.mockResolvedValue([
+ { name: 'claim/issue-101', isDefault: false, current: false, tracking: null, merged: true }
+ ]);
+ wt.listWorktrees.mockResolvedValue([
+ { path: '/repo/data/cos/worktrees/claim-issue-101', branch: 'refs/heads/claim/issue-101' }
+ ]);
+ git.hasBranchMergeEvidence.mockResolvedValue(true);
+ execGit.mockResolvedValue({ stdout: '?? server/services/newThing.test.js\n', exitCode: 0 });
+ };
+ // Pinned to epic 100, then bound child 101 before cutting it.
+ const owner = (status, metadata = {}) => ({
+ id: 'agent-epicrun', status, workspacePath: '/repo',
+ metadata: { claimBranch: 'claim/issue-100', claimPicksOwnBranch: false, claimBranches: ['claim/issue-101'], sourceWorkspace: '/repo', ...metadata },
+ });
+
+ it('holds its dirty child checkout instead of dispatching it as abandoned', async () => {
+ dirtyClaim();
+ for (const status of ['running', 'paused']) {
+ const res = await reconcile('/repo', { activeAgentIds: new Set(['agent-epicrun']), claimOwners: { agents: [owner(status)] } });
+ expect(res.inFlight).toEqual([]);
+ // A fresh child branch with only uncommitted work still points at a
+ // default-branch commit, so it lands in MERGED — held, never retired.
+ expect(res.skipped.map((w) => [w.branch, w.reason])).toEqual([['claim/issue-101', 'claim-owner-active']]);
+ }
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ });
+
+ it('holds every claim checkout in the repository while a pinned run has not bound its selection yet', async () => {
+ dirtyClaim();
+ const choosing = owner('running', { claimBranches: undefined, claimSelectionPending: true });
+ const res = await reconcile('/repo', { activeAgentIds: new Set(), claimOwners: { agents: [choosing] } });
+ expect(res.inFlight).toEqual([]);
+ expect(res.skipped.map((w) => w.reason)).toEqual(['claim-owner-ambiguous']);
+ });
+
+ it('defers without dispatching when the registry is unreadable', async () => {
+ dirtyClaim();
+ const res = await reconcile('/repo', { activeAgentIds: new Set(), claimOwners: { agents: null } });
+ expect(res.inFlight).toEqual([]);
+ expect(res.skipped.map((w) => w.reason)).toEqual(['claim-ownership-unreadable']);
+ });
+
+ it('recovers the tree as abandoned work once the owner completed or released the branch', async () => {
+ dirtyClaim();
+ for (const agents of [[owner('completed')], [owner('running', { claimBranches: [], claimReleasedBranches: ['claim/issue-101'] })]]) {
+ const res = await reconcile('/repo', { activeAgentIds: new Set(), claimOwners: { agents } });
+ expect(res.inFlight.map((i) => [i.branch, i.state])).toEqual([['claim/issue-101', 'ABANDONED_WIP']]);
+ }
+ });
+
+ it('never retires a merged, clean claim checkout its live owner is still handing off', async () => {
+ git.getBranches.mockResolvedValue([
+ { name: 'claim/issue-101', isDefault: false, current: false, tracking: 'origin/claim/issue-101', merged: true }
+ ]);
+ wt.listWorktrees.mockResolvedValue([
+ { path: '/repo/data/cos/worktrees/claim-issue-101', branch: 'refs/heads/claim/issue-101' }
+ ]);
+ git.hasBranchMergeEvidence.mockResolvedValue(true);
+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 });
+ const res = await reconcile('/repo', { activeAgentIds: new Set(), claimOwners: { agents: [owner('running')] } });
+ expect(res.skipped).toEqual([expect.objectContaining({ branch: 'claim/issue-101', reason: 'claim-owner-active' })]);
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ });
+ });
+
it('still leaves that branch untouched while its agent is running', async () => {
git.getBranches.mockResolvedValue([
{ name: 'cos/task-x/agent-deadbeef', isDefault: false, current: false, tracking: 'origin/main', merged: true }
@@ -1907,6 +1980,20 @@ describe('formatInFlightForPrompt', () => {
getIssueDispatchHintMock.mockResolvedValue({ status: 'unavailable', model: null, effort: null });
});
+ it('gives each branch a pre-mutation ownership recheck when the app is known (#10089)', async () => {
+ const block = await formatInFlightForPrompt([
+ { branch: 'claim/issue-101', state: 'ABANDONED_WIP', worktreePath: '/wt/claim-issue-101' },
+ { branch: 'feature/x', state: 'NEEDS_PR' }
+ ], { 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('Authorization: Bearer');
+ expect(await formatInFlightForPrompt([{ branch: 'feature/x', state: 'NEEDS_PR' }], { defaultBranch: 'main', actions: {} }))
+ .not.toContain('claim-ownership');
+ });
+
it('renders the default branch, each branch with its PR + worktree + Do line', async () => {
const block = await formatInFlightForPrompt([
{ branch: 'next/issue-1', state: 'IN_REVIEW', worktreePath: '/wt/1', openPr: { number: 42, mergeable: 'MERGEABLE', url: 'https://pr/42' } },
diff --git a/server/services/cosClaimOwnership.js b/server/services/cosClaimOwnership.js
new file mode 100644
index 0000000000..2c0b821d4f
--- /dev/null
+++ b/server/services/cosClaimOwnership.js
@@ -0,0 +1,78 @@
+/**
+ * Claim-branch ownership outside the run that holds it (#10089).
+ *
+ * A claim run cuts its own `claim/…` checkout, so its registered workspace stays
+ * the source repository and nothing on disk names the owner. Two calls close
+ * that gap:
+ * - `updateClaimOwnership` — the claim run binds the concrete branch it is
+ * about to check out (an epic's child, a split slice, a picked issue), or
+ * releases one it hands off before it ends. The run's completion releases
+ * everything; nothing here infers inactivity.
+ * - `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.
+ */
+import { resolve } from 'path';
+import { bindClaimBranch, releaseClaimBranch, 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);
+const branchOf = (wt) => String(wt?.branch || '').replace(/^refs\/heads\//, '');
+
+/**
+ * @param {{ agentId: string, action: 'bind'|'release', branch: string }} input
+ * @returns {Promise<{ bound: true, branch: string }|{ released: true, branch: string }|{ bound?: false, released?: false, reason: string }>}
+ */
+export async function updateClaimOwnership({ agentId, action, branch }) {
+ const done = action === 'bind' ? 'bound' : 'released';
+ const { withStateLock, loadState, saveState } = await import('./cosState.js');
+ const { cosEvents } = await import('./cosEvents.js');
+ return withStateLock(async () => {
+ const state = await loadState();
+ const agent = state.agents?.[agentId];
+ if (!agent || agent.id !== agentId) return { [done]: false, reason: 'owner-unknown' };
+ const patch = action === 'bind' ? bindClaimBranch(agent, branch) : releaseClaimBranch(agent, branch);
+ if (patch.refused) return { [done]: false, reason: patch.refused };
+ state.agents[agentId] = { ...agent, metadata: { ...agent.metadata, ...patch } };
+ await saveState(state);
+ cosEvents.emit('agent:updated', state.agents[agentId]);
+ console.log(`🔒 Claim ownership ${done}: ${branch} → ${agentId}`);
+ return { [done]: true, branch };
+ });
+}
+
+/**
+ * Whether a branch-reconcile worker may mutate `branch` right now. Admits only
+ * when the checkout it was dispatched at still holds the branch and no live
+ * owner (agent, lock, or registered/possible claim run) holds it.
+ *
+ * @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 = {}) {
+ 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;
+ const getActiveAgentIds = deps.getActiveAgentIds ?? (await import('./agentState.js')).getActiveAgentIds;
+ const { buildActiveOwnerIds, resolveLiveOwnerReason } = await import('./branchReconcile.js');
+
+ 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' };
+
+ 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 };
+}
diff --git a/server/services/cosClaimOwnership.test.js b/server/services/cosClaimOwnership.test.js
new file mode 100644
index 0000000000..ccc3d2de2a
--- /dev/null
+++ b/server/services/cosClaimOwnership.test.js
@@ -0,0 +1,82 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+
+const store = { state: null };
+vi.mock('./cosState.js', () => ({
+ withStateLock: (work) => work(),
+ loadState: async () => structuredClone(store.state),
+ saveState: async (next) => { store.state = structuredClone(next); },
+}));
+vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() } }));
+
+const { updateClaimOwnership, checkReconcileOwnership } = await import('./cosClaimOwnership.js');
+
+const SOURCE = '/repos/app-x';
+const CHILD = '/repos/app-x/data/cos/worktrees/claim-issue-101';
+
+beforeEach(() => {
+ store.state = {
+ agents: {
+ 'agent-epicrun': {
+ id: 'agent-epicrun', status: 'running', workspacePath: SOURCE,
+ metadata: { sourceWorkspace: SOURCE, claimBranch: 'claim/issue-100', claimPicksOwnBranch: false, claimSelectionPending: true },
+ },
+ },
+ };
+});
+
+describe('updateClaimOwnership', () => {
+ it('persists the bound child branch on the run record and settles its selection', async () => {
+ expect(await updateClaimOwnership({ agentId: 'agent-epicrun', action: 'bind', branch: 'claim/issue-101' }))
+ .toEqual({ bound: true, branch: 'claim/issue-101' });
+ expect(store.state.agents['agent-epicrun'].metadata).toMatchObject({
+ claimBranch: 'claim/issue-100', claimBranches: ['claim/issue-101'], claimSelectionPending: false,
+ });
+ expect(await updateClaimOwnership({ agentId: 'agent-epicrun', action: 'release', branch: 'claim/issue-101' }))
+ .toEqual({ released: true, branch: 'claim/issue-101' });
+ expect(store.state.agents['agent-epicrun'].metadata).toMatchObject({ claimBranches: [], claimReleasedBranches: ['claim/issue-101'] });
+ });
+
+ it('refuses an unknown or finished run without writing', async () => {
+ const before = structuredClone(store.state);
+ expect(await updateClaimOwnership({ agentId: 'agent-gone', action: 'bind', branch: 'claim/issue-101' }))
+ .toEqual({ bound: false, reason: 'owner-unknown' });
+ store.state.agents['agent-epicrun'].status = 'completed';
+ expect(await updateClaimOwnership({ agentId: 'agent-epicrun', action: 'bind', branch: 'claim/issue-101' }))
+ .toEqual({ bound: false, reason: 'owner-not-running' });
+ expect(store.state.agents['agent-epicrun'].metadata).toEqual(before.agents['agent-epicrun'].metadata);
+ });
+});
+
+// The scan that dispatched a reconcile worker is stale by the time it mutates:
+// ownership acquired in between must refuse at the worker's own recheck.
+describe('checkReconcileOwnership', () => {
+ const holder = { path: CHILD, branch: 'refs/heads/claim/issue-101' };
+ const check = (agents, overrides = {}, input = {}) => checkReconcileOwnership(
+ { appId: 'app-x', branch: 'claim/issue-101', worktreePath: CHILD, ...input },
+ {
+ getAppById: async (id) => (id === 'app-x' ? { id, repoPath: SOURCE } : null),
+ listWorktrees: async () => [holder],
+ getAgents: async () => agents,
+ getActiveAgentIds: () => [],
+ ...overrides,
+ },
+ );
+
+ it('admits a checkout no live run owns', async () => {
+ expect(await check([])).toEqual({ admitted: true });
+ });
+
+ it('refuses once a claim run bound the branch after the scan', async () => {
+ const owner = { id: 'agent-epicrun', status: 'running', workspacePath: SOURCE, metadata: { sourceWorkspace: SOURCE, claimBranches: ['claim/issue-101'] } };
+ expect(await check([owner])).toEqual({ admitted: false, reason: 'claim-owner-active' });
+ expect(await check([{ ...owner, status: 'completed' }])).toEqual({ admitted: true });
+ });
+
+ it('refuses when ownership is unreadable, the app is unknown, or the holder moved', async () => {
+ expect(await check(null)).toEqual({ admitted: false, reason: 'ownership-unreadable' });
+ expect(await check([], { listWorktrees: async () => { throw new Error('git failed'); } })).toEqual({ admitted: false, reason: 'ownership-unreadable' });
+ expect(await check([], {}, { appId: 'app-missing' })).toEqual({ admitted: false, reason: 'app-unknown' });
+ expect(await check([], { listWorktrees: async () => [] })).toEqual({ admitted: false, reason: 'holder-changed' });
+ expect(await check([], { listWorktrees: async () => [{ ...holder, locked: true }] })).toEqual({ admitted: false, reason: 'worktree-locked' });
+ });
+});
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index c3844107d7..0437e417f9 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -33,7 +33,6 @@ import { NON_ACTIONABLE_ISSUE_LABELS } from './perpetualWork.js';
import { DISPATCH_HINT_FANOUT_GUIDANCE } from '../lib/dispatchLabels.js';
import { applyAppPlaceholders } from '../lib/appPromptPlaceholders.js';
import { renderOrPrependSection } from '../lib/promptSectionRenderer.js';
-import { worktreeAgentId } from '../lib/worktreeOwnership.js';
import {
appendReviewerEffortBlock,
buildLocalReviewerInstructions,
@@ -422,26 +421,20 @@ export async function resolveReconcileDrainGate(taskSchedule, taskType, app, { s
*/
export async function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule) {
if (taskType !== 'branch-reconcile') return { skip: false, block: '' };
- const { reconcile, filterActionable, limitBranchesForAgent, formatInFlightForPrompt, actionableSignature, describeIdleReconcilePark } = await import('./branchReconcile.js');
+ const { reconcile, filterActionable, limitBranchesForAgent, formatInFlightForPrompt, actionableSignature, describeIdleReconcilePark, buildActiveOwnerIds } = await import('./branchReconcile.js');
const { formatSupersededForPrompt } = await import('./supersededLedger.js');
- const { getActiveAgentIds, isTruthyMeta } = await import('./agentState.js');
+ const { getActiveAgentIds } = await import('./agentState.js');
const { getAgents } = await import('./cos.js');
- const activeAgentIds = new Set(getActiveAgentIds());
const liveAgents = await getAgents().catch((err) => {
emitLog('warn', `branch-reconcile skipped for ${app.name}: active agent state unreadable (${err.message})`, { appId: app.id, analysisType: taskType });
return null;
});
if (!Array.isArray(liveAgents)) return { skip: true };
// Claim worktrees use a branch-shaped directory name, not the `agent-*` id
- // stored on the run. Add the live record's workspace basename to the same
- // ownership set so a branch-reconcile sub-agent cannot adopt a claim tree
- // while its original agent is still running (or paused for resume).
- for (const agent of liveAgents) {
- if (agent?.status !== 'running' && agent?.status !== 'paused') continue;
- if (agent.id) activeAgentIds.add(agent.id);
- const worktreeId = worktreeAgentId(agent.workspacePath || agent.metadata?.workspacePath);
- if (worktreeId) activeAgentIds.add(worktreeId);
- }
+ // stored on the run, so the live records' workspace basenames join the
+ // ownership set — and a run that cut its own claim tree keeps the source repo
+ // as its workspace, so its registered branch bindings are passed as well.
+ const activeAgentIds = buildActiveOwnerIds(getActiveAgentIds(), liveAgents);
// Action toggles were merged (global → per-app override) + value-constrained
// by sanitizeTaskMetadata into `metadata`; each is ON unless explicitly false.
const actions = {
@@ -454,6 +447,7 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
const result = await reconcile(app.repoPath, {
cleanup: actions.cleanupMerged !== false,
activeAgentIds,
+ claimOwners: { agents: liveAgents },
// The app's gh account pin, so a repo owned by another GitHub account is
// polled with a credential that can see it (#7540).
forgeAccount: app.forgeAccount || null
@@ -539,7 +533,8 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
defaultBranch: result.defaultBranch,
actions,
branchesPerAgent: metadata.branchesPerAgent,
- repoPath: app.repoPath
+ repoPath: app.repoPath,
+ appId: app.id
}),
supersededBlock
].filter(Boolean).join('\n');
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index 6612f88c96..4ef65f03d6 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -569,6 +569,25 @@ export function buildClaimResumeOverride({ priorAgentId, branchName, worktreePat
].join('\n');
}
+/**
+ * The run's registered claim branch is only the pinned target (or nothing, for
+ * a picker); the branch it actually checks out — an epic's child, a split
+ * slice, a picked issue — is bound here before the checkout exists, so
+ * branch-reconcile and continuations see a live owner for it (#10089).
+ */
+function buildClaimOwnershipSection(agentId) {
+ if (!agentId) return 'Claim ownership binding requires a registered agent ID. None was supplied, so PortOS treats every claim checkout in this repository as possibly yours until this run ends; do not hand a claim branch to another run while you are live.';
+ const command = (action) => agentApiCurl({ apiBase: localApiBaseUrl(), path: '/api/cos/claim-ownership',
+ payload: JSON.stringify({ agentId, action, branch: 'BRANCH' }) });
+ return [
+ '## Claim ownership binding',
+ 'Before this run (the parent, never a fan-out child) creates, adopts or checks out ANY claim worktree, bind that exact branch to this run — the pinned issue’s own `claim/…` branch, a tracking epic’s child, a slice split from an oversized issue, each issue a picker or swarm selects, or a claim worktree you are resuming. Replace BRANCH with the branch name and require a parsed JSON response with bound:true:',
+ '```bash', command('bind'), '```',
+ 'A refusal, HTTP/auth/transport error or unreadable JSON means the branch is not yours: do not create or enter that worktree; report the reason. Binding lasts until this run ends, through publication, CI, merge or leave-open handoff and cleanup — never release a branch you are still finishing. Release only a branch you deliberately leave for another owner mid-run:',
+ '```bash', command('release'), '```',
+ ].join('\n');
+}
+
/** Only the registered parent acquires; swarm workers keep authoring in parallel. */
function buildMergeAdmissionSection(agentId) {
if (!agentId) return 'Merge admission requires a registered parent agent ID. If none was supplied, leave the reviewed PR open and report this missing ownership binding; do not merge.';
@@ -596,6 +615,7 @@ export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath =
const lines = [
...(resumeOverride ? [resumeOverride, ''] : []),
...(pin ? [pin, ''] : []),
+ buildClaimOwnershipSection(agentId), '',
...(!leavePrOpen ? [buildMergeAdmissionSection(agentId), ''] : []),
'## Claim Workflow Handoff',
...(leavePrOpen ? [
diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.js
index fd333b92f1..e584c9156e 100644
--- a/server/services/promptSections/completion.test.js
+++ b/server/services/promptSections/completion.test.js
@@ -43,6 +43,19 @@ describe('review-enabled completion merge gate', () => {
});
+describe('claim ownership binding instructions (#10089)', () => {
+ it('binds every branch the run checks out before its worktree exists, whatever the completion policy', () => {
+ for (const leavePrOpen of [false, true]) {
+ const prompt = buildClaimFlowCompletionSection({ agentId: 'parent-example', leavePrOpen });
+ expect(prompt).toContain('"agentId":"parent-example","action":"bind","branch":"BRANCH"');
+ expect(prompt).toContain('a tracking epic');
+ expect(prompt).toContain('do not create or enter that worktree');
+ expect(prompt).toContain('"action":"release"');
+ }
+ expect(buildClaimFlowCompletionSection()).toContain('possibly yours until this run ends');
+ });
+});
+
describe('claim parent merge admission instructions', () => {
it('binds the parent through CI, requires resync on external base movement and releases on either outcome', () => {
const prompt = buildClaimFlowCompletionSection({ agentId: 'parent-example' });