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: re-check claim ownership at launch before continuing a claim worktree in place (#10015)
Adam Eivy488ba549d357
diff --git a/server/lib/README.md b/server/lib/README.mdindex fbc28ef921..cd8d1e8adf 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. |+| `claimContinuation.js` | Claim-flow relaunch pointer. `claimContinuationBranch(claimTarget)` is the `claim/issue-<n>` or `claim/<key>` branch a pinned target checks out. `claimContinuationPointer(...)` names the `claim-*` worktree already holding that branch when a relaunch should finish it in place (locked, prunable, unmanaged, or occupied by another running/paused agent → null). `claimContinuationWorkspace(...)` turns a still-on-disk pointer into the cwd the next agent uses without moving the directory. `claimOwnershipBinding(task)` is the branch (or "picks its own", for a swarm orchestrator) a claim run registers on its agent record, and `claimContinuationAdmission(...)` is the launch-time ownership check that re-reads holder, branch and live owners before a cached pointer may be entered (anything unreadable or changed → refuse, the caller defers). || `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/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.jsindex 909172756c..7f340fc94d 100644--- a/server/lib/agentRegistrationRecord.js+++ b/server/lib/agentRegistrationRecord.js@@ -24,6 +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';/*** How this run is dispatched, as one closed vocabulary rather than the nested@@ -259,6 +260,11 @@ export function buildAgentRegistration({// the run record so completion diagnostics cannot mistake the claim path// for the generic commit-only handoff.configClaimFlow: claimFlowTask,+ // The claim branch this run owns (or `claimPicksOwnBranch` when it picks one+ // itself, as a swarm orchestrator does). The `claim-*` tree is cut by the+ // agent, so `workspacePath` never names it; a later relaunch of that claim+ // reads these at launch to see that a live owner holds the checkout.+ ...claimOwnershipBinding(task),configSimplify: isTruthyMeta(task.metadata?.simplify),configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),configReviewers: normalizeReviewers(task.metadata),diff --git a/server/lib/agentRegistrationRecord.test.js b/server/lib/agentRegistrationRecord.test.jsindex 6f8d9861cd..b51e8cd8f4 100644--- a/server/lib/agentRegistrationRecord.test.js+++ b/server/lib/agentRegistrationRecord.test.js@@ -99,3 +99,25 @@ it('preserves scheduled reconciliation identity through persistence and registraexpect(record.taskAnalysisType).toBe('branch-reconcile');expect(record.isWorktree).toBe(false);});++describe('buildAgentRegistration — claim ownership', () => {+ // The claim tree is cut by the agent, so a relaunch can only see who holds it+ // from the branch the run registered here.+ it('registers the exact branch a pinned claim run owns', () => {+ const record = buildAgentRegistration({ ...args({ claimFlow: true, claimTarget: '42' }), claimFlowTask: true });+ expect(record.claimBranch).toBe('claim/issue-42');+ expect(record.claimPicksOwnBranch).toBe(false);+ });++ it('registers an unpinned claim run (swarm orchestrator) as picking its own branch', () => {+ const record = buildAgentRegistration({ ...args({ claimFlow: true, swarmCount: 3 }), claimFlowTask: true });+ expect(record.claimBranch).toBeNull();+ expect(record.claimPicksOwnBranch).toBe(true);+ });++ it('registers no claim ownership for an ordinary task', () => {+ const record = buildAgentRegistration(args({}));+ expect(record.claimBranch).toBeUndefined();+ expect(record.claimPicksOwnBranch).toBeUndefined();+ });+});diff --git a/server/lib/claimContinuation.js b/server/lib/claimContinuation.jsindex 9e033a760c..140a24f63f 100644--- a/server/lib/claimContinuation.js+++ b/server/lib/claimContinuation.js@@ -17,9 +17,19 @@import { resolve } from 'path';import { isPathInsideDir } from './pathSafety.js';import { isHumanClaimWorktree, worktreeAgentId } from './worktreeOwnership.js';+import { isTruthyMeta } from './metadataFlags.js';const CASE_FOLD = process.platform === 'win32';+/**+ * How long a claim checkout must sit untouched before a claim-flow agent that+ * has NOT named its branch (an unpinned or swarm orchestrator run, whose+ * children cut `claim/issue-<n>` trees PortOS never sees) stops counting as the+ * possible owner. Matches `SIBLING_NEXT_HOLDER_IDLE_MS`: a live session touches+ * its index constantly, a finished one waiting on CI goes quiet for longer.+ */+export const CLAIM_AMBIGUOUS_OWNER_IDLE_MS = 10 * 60 * 1000;+/** Branch a pinned claim target checks out, or null when the ref is not a claim name. */export function claimContinuationBranch(claimTarget) {const ref = String(claimTarget ?? '').trim();@@ -37,6 +47,61 @@ function samePath(a, b) {return CASE_FOLD ? left.toLowerCase() === right.toLowerCase() : left === right;}+/**+ * The claim ownership a claim-flow run registers on its agent record. PortOS does+ * not provision the `claim-*` directory the agent cuts, so `workspacePath` never+ * names it; the branch is the only identity both sides know:+ * - 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.+ * Null for a task that is not a claim flow. Pure.+ *+ * @returns {{ claimBranch: string|null, claimPicksOwnBranch: boolean }|null}+ */+export function claimOwnershipBinding(task) {+ if (!isTruthyMeta(task?.metadata?.claimFlow)) return null;+ const claimBranch = claimContinuationBranch(task?.metadata?.claimTarget);+ return { claimBranch, claimPicksOwnBranch: !claimBranch };+}++function isLiveAgent(agent) {+ return agent?.status === 'running' || agent?.status === 'paused';+}++function agentWorkspace(agent) {+ return agent.workspacePath || agent.metadata?.workspacePath;+}++function agentRepository(agent) {+ return agent.sourceWorkspace || agent.metadata?.sourceWorkspace || agentWorkspace(agent);+}++/**+ * 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;+ * - `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` outranks `ambiguous` across the whole list.+ *+ * @returns {'active'|'ambiguous'|null}+ */+function claimHolderOccupancy({ agents, holderPath, branchName, sourceWorkspace, ignoreIds }) {+ let ambiguous = false;+ for (const agent of agents) {+ if (!agent || ignoreIds.has(agent.id) || !isLiveAgent(agent)) continue;+ const workspace = agentWorkspace(agent);+ if (samePath(workspace, holderPath) || (workspace && isPathInsideDir(holderPath, workspace))) return 'active';+ const registeredBranch = agent.claimBranch ?? agent.metadata?.claimBranch;+ if (registeredBranch === branchName) return 'active';+ const picksOwn = agent.claimPicksOwnBranch ?? agent.metadata?.claimPicksOwnBranch;+ if (isTruthyMeta(picksOwn) && samePath(agentRepository(agent), sourceWorkspace)) ambiguous = true;+ }+ return ambiguous ? 'ambiguous' : null;+}+/*** The claim worktree this task's previous run left on its own branch, when* PortOS may hand it to the relaunch. Null when there is nothing to continue:@@ -47,12 +112,13 @@ function samePath(a, b) {* task: object,* agentId: string,* worktrees?: Array<{path?: string, branch?: string, locked?: boolean, prunable?: boolean}>,- * agents?: Array<{id?: string, status?: string, workspacePath?: string, metadata?: {workspacePath?: string}}>,+ * agents?: Array<{id?: string, status?: string, workspacePath?: string, metadata?: object}>,* worktreesRoot: string,+ * sourceWorkspace?: string,* }} input* @returns {{ existingBranch: string, resumedFromAgentId: string, resumeWorktreePath: string, claimResumeInPlace: true }|null}*/-export function claimContinuationPointer({ task, agentId, worktrees = [], agents = [], worktreesRoot }) {+export function claimContinuationPointer({ task, agentId, worktrees = [], agents = [], worktreesRoot, sourceWorkspace }) {if (task?.metadata?.claimFlow !== true && task?.metadata?.claimFlow !== 'true') return null;const branchName = claimContinuationBranch(task?.metadata?.claimTarget);if (!branchName || !agentId || !worktreesRoot) return null;@@ -66,13 +132,13 @@ export function claimContinuationPointer({ task, agentId, worktrees = [], agentsif (!isHumanClaimWorktree(worktreeAgentId(holder.path))) return null;if (!isPathInsideDir(worktreesRoot, holder.path)) return null;- const occupied = agents.some((agent) => {- if (!agent || agent.id === agentId) return false;- if (agent.status !== 'running' && agent.status !== 'paused') return false;- const workspace = agent.workspacePath || agent.metadata?.workspacePath;- return samePath(workspace, holder.path);+ // Only a definite owner withholds the pointer. A possible one (a picker run+ // in the same repository) is left to `claimContinuationAdmission`, which sees+ // the checkout's activity at the moment of launch.+ const occupancy = claimHolderOccupancy({+ agents, holderPath: holder.path, branchName, sourceWorkspace, ignoreIds: new Set([agentId]),});- if (occupied) return null;+ if (occupancy === 'active') return null;return {existingBranch: branchName,@@ -108,3 +174,51 @@ export function claimContinuationWorkspace({ metadata, pathExists = () => false,},};}++/**+ * Launch-time ownership admission for an in-place continuation. A pointer is a+ * cached answer from when the previous run died; another owner can appear after+ * that, so the pointer alone is not authority to enter the checkout. Re-reads+ * the holder and the agent registry as supplied by the caller and admits only+ * when the same branch is still checked out in the same directory and no other+ * live owner holds it. Anything unreadable or changed refuses — the caller+ * defers the launch and touches neither ref nor tree.+ *+ * `holderIdleMs` is how long the checkout has been untouched (null when it+ * cannot be read). It only matters for a possible owner that picks its own+ * branch; a registered owner refuses at any idleness.+ *+ * @param {{+ * metadata?: object,+ * agentId: string,+ * sourceWorkspace?: string,+ * worktrees: Array<object>|null,+ * agents: Array<object>|null,+ * holderIdleMs?: number|null,+ * idleMs?: number,+ * }} input+ * @returns {{ admit: true }|{ admit: false, reason: string }}+ */+export function claimContinuationAdmission({+ metadata, agentId, sourceWorkspace, worktrees, agents, holderIdleMs = null, idleMs = CLAIM_AMBIGUOUS_OWNER_IDLE_MS,+}) {+ if (!Array.isArray(worktrees) || !Array.isArray(agents)) return { admit: false, reason: 'ownership-unreadable' };+ const branchName = metadata?.existingBranch;+ const worktreePath = metadata?.resumeWorktreePath;+ if (!branchName || !worktreePath) return { admit: false, reason: 'pointer-incomplete' };++ const holder = worktrees.find((wt) => samePath(wt?.path, worktreePath));+ if (!holder) return { admit: false, reason: 'holder-missing' };+ if (String(holder.branch || '').replace(/^refs\/heads\//, '') !== branchName) {+ return { admit: false, reason: 'branch-changed' };+ }+ if (holder.locked || holder.prunable) return { admit: false, reason: 'holder-locked' };++ const ignoreIds = new Set([agentId, metadata?.resumedFromAgentId].filter(Boolean));+ const occupancy = claimHolderOccupancy({ agents, holderPath: holder.path, branchName, sourceWorkspace, ignoreIds });+ if (occupancy === 'active') return { admit: false, reason: 'owner-active' };+ if (occupancy === 'ambiguous' && !(Number.isFinite(holderIdleMs) && holderIdleMs >= idleMs)) {+ return { admit: false, reason: 'owner-ambiguous' };+ }+ return { admit: true };+}diff --git a/server/lib/claimContinuation.test.js b/server/lib/claimContinuation.test.jsindex 05a15311cd..180473e5ec 100644--- a/server/lib/claimContinuation.test.js+++ b/server/lib/claimContinuation.test.js@@ -1,5 +1,12 @@import { describe, expect, it } from 'vitest';-import { claimContinuationBranch, claimContinuationPointer, claimContinuationWorkspace } from './claimContinuation.js';+import {+ CLAIM_AMBIGUOUS_OWNER_IDLE_MS,+ claimContinuationAdmission,+ claimContinuationBranch,+ claimContinuationPointer,+ claimContinuationWorkspace,+ claimOwnershipBinding,+} from './claimContinuation.js';const ROOT = '/data/cos/worktrees';const CLAIM = `${ROOT}/claim-portos-issue-42`;@@ -65,6 +72,16 @@ describe('claimContinuationPointer', () => {})).toBeNull();});+ it('leaves the relaunch clean when a live agent registered this claim branch', () => {+ expect(claimContinuationPointer({+ task,+ agentId: 'agent-old',+ worktrees: [holder],+ agents: [{ id: 'agent-other', status: 'running', metadata: { claimBranch: 'claim/issue-42' } }],+ worktreesRoot: ROOT,+ })).toBeNull();+ });+it('does nothing for a task that is not a pinned claim', () => {expect(claimContinuationPointer({task: { metadata: { claimFlow: true } },@@ -100,3 +117,105 @@ describe('claimContinuationWorkspace', () => {})).toBeNull();});});++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 });+ });++ it('marks an unpinned claim run (issue picker or swarm orchestrator) as picking its own branch', () => {+ expect(claimOwnershipBinding({ metadata: { claimFlow: true, swarmCount: 4 } }))+ .toEqual({ claimBranch: null, claimPicksOwnBranch: true });+ });++ it('registers nothing for a task that is not a claim flow', () => {+ expect(claimOwnershipBinding({ metadata: { claimTarget: '42' } })).toBeNull();+ });+});++// The ownership race from the swarm collision: a pointer is made while the+// checkout is idle, then an owner appears. Each case is a synthetic two-owner+// lifecycle — no live process or instance data.+describe('claimContinuationAdmission', () => {+ const SOURCE = '/repos/app-x';+ const task = { id: 'task-1', metadata: { claimFlow: true, claimTarget: '42' } };+ const holder = { path: CLAIM, branch: 'refs/heads/claim/issue-42' };+ const pointer = claimContinuationPointer({+ task, agentId: 'agent-dead', worktrees: [holder], agents: [], worktreesRoot: ROOT, sourceWorkspace: SOURCE,+ });+ const metadata = { ...pointer, resumedFromAgentId: 'agent-dead' };+ const admit = (overrides = {}) => claimContinuationAdmission({+ metadata, agentId: 'agent-new', sourceWorkspace: SOURCE, worktrees: [holder], agents: [], holderIdleMs: null, ...overrides,+ });++ it('admits a surviving claim whose previous owner is gone', () => {+ expect(pointer).not.toBeNull();+ expect(admit()).toEqual({ admit: true });+ expect(admit({+ agents: [{ id: 'agent-dead', status: 'paused', metadata: { claimBranch: 'claim/issue-42' } }],+ })).toEqual({ admit: true });+ });++ it('refuses once a running or paused owner registers the branch after the pointer was made', () => {+ for (const status of ['running', 'paused']) {+ expect(admit({+ agents: [{ id: 'agent-other', status, metadata: { claimBranch: 'claim/issue-42', sourceWorkspace: SOURCE } }],+ })).toEqual({ admit: false, reason: 'owner-active' });+ }+ });++ it('refuses when another agent works inside the checkout', () => {+ expect(admit({+ agents: [{ id: 'agent-other', status: 'running', metadata: { workspacePath: `${CLAIM}/server` } }],+ })).toEqual({ admit: false, reason: 'owner-active' });+ });++ it('ignores a completed owner and one bound to a different branch', () => {+ expect(admit({+ agents: [+ { id: 'agent-a', status: 'completed', metadata: { claimBranch: 'claim/issue-42' } },+ { id: 'agent-b', status: 'running', metadata: { claimBranch: 'claim/issue-43' } },+ ],+ })).toEqual({ admit: true });+ });++ describe('a swarm orchestrator whose children cut their own trees', () => {+ const orchestrator = {+ id: 'agent-swarm', status: 'running', metadata: { claimPicksOwnBranch: true, sourceWorkspace: SOURCE },+ };++ it('refuses while the checkout shows recent activity or its idleness is unknown', () => {+ expect(admit({ agents: [orchestrator], holderIdleMs: 30_000 })).toEqual({ admit: false, reason: 'owner-ambiguous' });+ expect(admit({ agents: [orchestrator], holderIdleMs: null })).toEqual({ admit: false, reason: 'owner-ambiguous' });+ });++ it('admits once the checkout has been quiet past the idle window', () => {+ expect(admit({ agents: [orchestrator], holderIdleMs: CLAIM_AMBIGUOUS_OWNER_IDLE_MS })).toEqual({ admit: true });+ });++ it('does not suspect an orchestrator working in a different repository', () => {+ const elsewhere = { ...orchestrator, metadata: { ...orchestrator.metadata, sourceWorkspace: '/repos/other' } };+ expect(admit({ agents: [elsewhere] })).toEqual({ admit: true });+ });++ it('refuses a registered owner at any idleness', () => {+ expect(admit({+ agents: [orchestrator, { id: 'agent-other', status: 'running', metadata: { claimBranch: 'claim/issue-42' } }],+ holderIdleMs: Number.MAX_SAFE_INTEGER,+ })).toEqual({ admit: false, reason: 'owner-active' });+ });+ });++ it('fails closed on unreadable ownership, a vanished holder, or a changed branch', () => {+ expect(admit({ agents: null })).toEqual({ admit: false, reason: 'ownership-unreadable' });+ expect(admit({ worktrees: null })).toEqual({ admit: false, reason: 'ownership-unreadable' });+ expect(admit({ worktrees: [] })).toEqual({ admit: false, reason: 'holder-missing' });+ expect(admit({ worktrees: [{ path: CLAIM, branch: 'refs/heads/claim/issue-43' }] }))+ .toEqual({ admit: false, reason: 'branch-changed' });+ expect(admit({ worktrees: [{ path: CLAIM, detached: true }] })).toEqual({ admit: false, reason: 'branch-changed' });+ expect(admit({ worktrees: [{ ...holder, locked: true }] })).toEqual({ admit: false, reason: 'holder-locked' });+ expect(admit({ metadata: { ...metadata, resumeWorktreePath: undefined } }))+ .toEqual({ admit: false, reason: 'pointer-incomplete' });+ });+});diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex fddfa590d4..158ac9f882 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -35,7 +35,7 @@ import { isTruthyMeta, isFalsyMeta, protectedAgentIds } from './agentState.js';import { PATHS, ensureDir } from '../lib/fileUtils.js';import * as git from './git.js';import { detectConflicts } from './taskConflict.js';-import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies } from './worktreeManager.js';+import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError, listWorktrees, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies, worktreeIdleMs } from './worktreeManager.js';import { resolveSpawnCwd, usesCreativeDirectorScratchCwd, creativeDirectorScratchCwd } from '../lib/spawnCwd.js';import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';@@ -44,7 +44,7 @@ import { getAppWorkspace, getAppDataForTask } from './agentAppWorkspace.js';import { createJiraTicketForTask } from './promptSections/appContext.js';import { INVESTIGATION_TASK_DELIVERY, isInvestigationTask } from '../lib/investigationTasks.js';import { isNonCommittingCoordinatorTask, resolveTaskHookType } from './taskTypeHooks.js';-import { claimContinuationWorkspace } from '../lib/claimContinuation.js';+import { claimContinuationAdmission, claimContinuationWorkspace } from '../lib/claimContinuation.js';const ROOT_DIR = PATHS.root;@@ -282,6 +282,25 @@ async function prepareRequestedWorktree({return { outcome: 'blocked', reason };}+/**+ * Re-check, at launch, that the claim worktree a cached continuation pointer names+ * is still free to enter. The pointer was written when the previous run died;+ * another owner may have taken the checkout since. Every read fails closed — an+ * unreadable agent list or worktree list is "unknown", never "nobody is there".+ * Read-only: nothing here rebases, commits, pushes, moves or removes.+ */+async function admitClaimContinuation({ task, agentId, sourceWorkspace, claimWorkspace }) {+ const { getAgents } = await import('./cos.js');+ const [agents, worktrees] = await Promise.all([+ getAgents().catch(() => null),+ listWorktrees(sourceWorkspace).catch(() => null),+ ]);+ const holderIdleMs = await worktreeIdleMs(claimWorkspace.workspacePath).catch(() => null);+ return claimContinuationAdmission({+ metadata: task.metadata, agentId, sourceWorkspace, worktrees, agents, holderIdleMs,+ });+}+/*** Prepare the workspace (and any worktree/JIRA branch) for an agent task.*@@ -403,6 +422,25 @@ export async function prepareAgentWorkspace({ agentId, task }) {worktreesRoot: PATHS.worktrees,});if (claimWorkspace) {+ // The pointer is a cached answer, not authority: confirm the holder, the+ // branch and the absence of another live owner NOW, and wait (bounded) when+ // that cannot be established rather than entering someone's checkout.+ const admission = await admitClaimContinuation({ task, agentId, sourceWorkspace: workspacePath, claimWorkspace });+ if (!admission.admit) {+ const attempt = (Number(task.metadata?.worktreeBusyAttempts) || 0) + 1;+ const detail = `The claim worktree for ${claimWorkspace.worktreeInfo.branchName} cannot be confirmed free (${admission.reason}); nothing in it was touched`;+ if (attempt <= WORKTREE_BUSY_MAX_ATTEMPTS) {+ emitLog('info', `🌳 ${detail}; retrying after a short cooldown (attempt ${attempt}/${WORKTREE_BUSY_MAX_ATTEMPTS})`, { taskId: task.id, branch: claimWorkspace.worktreeInfo.branchName, reason: admission.reason });+ await blockTask(task, `${detail}; retrying after a short cooldown`, 'worktree-busy', {+ cooldownUntil: new Date(Date.now() + WORKTREE_BUSY_COOLDOWN_MS).toISOString(),+ worktreeBusyAttempts: attempt,+ });+ return { outcome: 'blocked', reason: detail };+ }+ emitLog('warn', `🌳 ${detail}; giving up after ${WORKTREE_BUSY_MAX_ATTEMPTS} attempts`, { taskId: task.id, branch: claimWorkspace.worktreeInfo.branchName, reason: admission.reason });+ await blockTask(task, `${detail}. Resolve who owns the checkout, then re-run this task.`, 'worktree-failed');+ return { outcome: 'blocked', reason: detail };+ }workspacePath = claimWorkspace.workspacePath;worktreeInfo = claimWorkspace.worktreeInfo;emitLog('info', `🌳 Agent ${agentId} is continuing the claim worktree ${worktreeInfo.branchName}`, {diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex cc275e67d0..340cbc6e7c 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -47,6 +47,8 @@ vi.mock('./worktreeManager.js', async (importOriginal) => ({unlinkWorktreeDependencies: vi.fn().mockResolvedValue(undefined),findAdoptableWorktreeForBranch: vi.fn().mockResolvedValue(null),releaseIdleSiblingNextHolder: vi.fn().mockResolvedValue(null),+ listWorktrees: vi.fn().mockResolvedValue([]),+ worktreeIdleMs: vi.fn().mockResolvedValue(null),mergeBaseIntoFeatureWorktree: vi.fn(),}));vi.mock('./agentAppWorkspace.js', () => ({@@ -71,7 +73,7 @@ import { ensureLatest } from './git.js';import { execGit } from '../lib/execGit.js';import { detectConflicts } from './taskConflict.js';import { getAppWorkspace } from './agentAppWorkspace.js';-import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies } from './worktreeManager.js';+import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, listWorktrees, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies } from './worktreeManager.js';import { ensureDir, PATHS } from '../lib/fileUtils.js';import { creativeDirectorScratchCwd } from '../lib/spawnCwd.js';@@ -473,38 +475,105 @@ describe('prepareAgentWorkspace — resuming an interrupted run', () => {expect(r.outcome).toBe('blocked');});- it('continues a relaunched claim inside the existing claim worktree', async () => {- claimContinuationWorkspace.mockReturnValueOnce({- workspacePath: '/mock/worktrees/claim-portos-issue-42',- worktreeInfo: {- worktreePath: '/mock/worktrees/claim-portos-issue-42',- branchName: 'claim/issue-42',- baseBranch: null,- existingBranch: true,- adopted: true,- claimResumeInPlace: true,- },- });- const task = {+ describe('a relaunched claim continuing in place', () => {+ const CLAIM_DIR = '/mock/worktrees/claim-portos-issue-42';+ const claimTask = (extra = {}) => ({id: 't-claim', taskType: 'user',metadata: {claimFlow: true,claimTarget: '42',claimResumeInPlace: true,existingBranch: 'claim/issue-42',- resumeWorktreePath: '/mock/worktrees/claim-portos-issue-42',+ resumedFromAgentId: 'agent-dead',+ resumeWorktreePath: CLAIM_DIR,useWorktree: false,+ ...extra,},- };+ });+ const pointerWorkspace = () => ({+ workspacePath: CLAIM_DIR,+ worktreeInfo: {+ worktreePath: CLAIM_DIR,+ branchName: 'claim/issue-42',+ baseBranch: null,+ existingBranch: true,+ adopted: true,+ claimResumeInPlace: true,+ },+ });+ const holder = { path: CLAIM_DIR, branch: 'refs/heads/claim/issue-42' };- const r = await prepareAgentWorkspace({ agentId: 'agent-new', task });+ beforeEach(() => {+ claimContinuationWorkspace.mockReturnValueOnce(pointerWorkspace());+ listWorktrees.mockResolvedValue([holder]);+ });- expect(r.outcome).toBe('ready');- expect(r.workspacePath).toBe('/mock/worktrees/claim-portos-issue-42');- expect(r.worktreeInfo.claimResumeInPlace).toBe(true);- expect(createWorktree).not.toHaveBeenCalled();- expect(adoptWorktree).not.toHaveBeenCalled();- expect(ensureLatest).not.toHaveBeenCalled();+ it('continues inside the existing claim worktree when no other owner holds it', async () => {+ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: claimTask() });++ expect(r.outcome).toBe('ready');+ expect(r.workspacePath).toBe(CLAIM_DIR);+ expect(r.worktreeInfo.claimResumeInPlace).toBe(true);+ expect(createWorktree).not.toHaveBeenCalled();+ expect(adoptWorktree).not.toHaveBeenCalled();+ expect(ensureLatest).not.toHaveBeenCalled();+ });++ it('defers the launch when a live owner registered the branch after the pointer was made', async () => {+ getAgents.mockResolvedValue([+ { id: 'agent-other', status: 'running', metadata: { claimBranch: 'claim/issue-42', sourceWorkspace: '/repos/app-x' } },+ ]);++ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: claimTask() });++ expect(r.outcome).toBe('blocked');+ expect(r.workspacePath).toBeUndefined();+ expect(updateTask).toHaveBeenCalledWith('t-claim', expect.objectContaining({+ status: 'blocked',+ metadata: expect.objectContaining({+ blockedCategory: 'worktree-busy',+ worktreeBusyAttempts: 1,+ existingBranch: 'claim/issue-42',+ claimResumeInPlace: true,+ }),+ }), 'user');+ expect(createWorktree).not.toHaveBeenCalled();+ expect(adoptWorktree).not.toHaveBeenCalled();+ });++ it('fails closed when the agent registry cannot be read', async () => {+ getAgents.mockRejectedValue(new Error('state unreadable'));++ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: claimTask() });++ expect(r.outcome).toBe('blocked');+ expect(updateTask).toHaveBeenCalledWith('t-claim', expect.objectContaining({+ metadata: expect.objectContaining({ blockedCategory: 'worktree-busy' }),+ }), 'user');+ });++ it('fails closed when the checkout now holds a different branch', async () => {+ listWorktrees.mockResolvedValue([{ path: CLAIM_DIR, branch: 'refs/heads/claim/issue-43' }]);++ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: claimTask() });++ expect(r.outcome).toBe('blocked');+ expect(createWorktree).not.toHaveBeenCalled();+ });++ it('stops waiting after the retry budget and blocks for a human instead of entering', async () => {+ listWorktrees.mockResolvedValue([]);++ const r = await prepareAgentWorkspace({+ agentId: 'agent-new', task: claimTask({ worktreeBusyAttempts: 5 }),+ });++ expect(r.outcome).toBe('blocked');+ expect(updateTask).toHaveBeenCalledWith('t-claim', expect.objectContaining({+ metadata: expect.objectContaining({ blockedCategory: 'worktree-failed' }),+ }), 'user');+ expect(createWorktree).not.toHaveBeenCalled();+ });});it('ignores a stale worktree pointer with no branch to resume', async () => {diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex a617ab5cdd..32ac5a5d1c 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -737,7 +737,7 @@ async function resolveClaimContinuationPatch({ task, agentId, agentMetadata }) {if (!agents) return null;const worktrees = await listWorktrees(source).catch(() => []);const pointer = claimContinuationPointer({- task, agentId, worktrees, agents, worktreesRoot: PATHS.worktrees,+ task, agentId, worktrees, agents, worktreesRoot: PATHS.worktrees, sourceWorkspace: source,});if (!pointer) return null;emitLog('info', `🔁 Task ${task.id} will resume in the claim worktree ${pointer.resumeWorktreePath} (${pointer.existingBranch}) instead of starting clean`, {diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 9a3a65695c..bbc8d341ac 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -792,6 +792,22 @@ export async function findAdoptableWorktreeForBranch(sourceWorkspace, branchNamereturn { path: holder.path, agentId };}+/**+ * How long a worktree's git state has sat untouched, in ms — the newest mtime of+ * its index, HEAD and HEAD reflog. A live session touches its index constantly;+ * a finished one goes quiet. Null when nothing could be read (no git dir, or no+ * file stat-able), which callers must treat as "unknown", never as "idle".+ * Read-only: it only stats files, so reading never resets the clock.+ */+export async function worktreeIdleMs(worktreePath, nowMs = Date.now()) {+ const gitDir = await execGit(['rev-parse', '--absolute-git-dir'], worktreePath).then(r => r.stdout.trim(), () => null);+ if (!gitDir) return null;+ const mtimes = await Promise.all(['index', 'HEAD', join('logs', 'HEAD')]+ .map(f => stat(join(gitDir, f)).then(st => st.mtimeMs, () => 0)));+ const newest = Math.max(...mtimes);+ return newest > 0 ? nowMs - newest : null;+}+// How long a sibling `/do:next` tree must sit untouched before a follow-up may// release its branch. An agent that finished and kept its tree (waiting on CI,// say) goes quiet for far longer; a live session touches its index constantly.@@ -837,13 +853,10 @@ export async function releaseIdleSiblingNextHolder(sourceWorkspace, branchName,if (activeWorkspacePaths.some(p => p && (pathsEqual(p, holder.path) || isPathInsideDir(holder.path, p)))) return null;const git = (args) => execGit(args, holder.path).then(r => r.stdout.trim());- // Idleness first; `--no-optional-locks` keeps `status` from refreshing the- // index and so resetting the very clock this reads on a refused attempt.- const gitDir = await git(['rev-parse', '--absolute-git-dir']).catch(() => null);- if (!gitDir) return null;- const mtimes = await Promise.all(['index', 'HEAD', join('logs', 'HEAD')]- .map(f => stat(join(gitDir, f)).then(s => s.mtimeMs, () => 0)));- if (nowMs - Math.max(...mtimes) < idleMs) return null;+ // Idleness first; the `--no-optional-locks` status below keeps a refused attempt+ // from refreshing the index and so resetting the very clock this reads.+ const idle = await worktreeIdleMs(holder.path, nowMs);+ if (idle === null || idle < idleMs) return null;// Stricter than `classifyWorktreeDirt` on purpose: this tree isn't PortOS's,// so no path counts as disposable scratch.