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
feat([issue-1563]): federated single-claim execution for CoS tasks
[._.]/ Adam Eivy1af9a34f688e
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex e59d39b153..3acb3cd7cf 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -27,7 +27,8 @@ import { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';import { processAgentCompletion } from './agentCompletion.js';import { releaseAppReviewMarker } from './appActivity.js';-import { getInstanceId, ensureSelf, UNKNOWN_INSTANCE_ID } from './instances.js';+import { ensureInstanceId } from './instances.js';+import { isClaimableBy, buildClaim, getClaimOwner } from './cosTaskClaim.js';import { runnerAgents, pausedAgents, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';import { v4 as uuidv4 } from '../lib/uuid.js';@@ -118,6 +119,19 @@ export async function spawnAgentForTask(task) {return null;}+ // Cross-instance claim guard (issue #1563, acceptance criterion 2). When this+ // task list is shared with a federated peer (full-sync mode, #1561), the peer+ // may already be working this task. Refuse to spawn while another instance+ // holds a live lease — otherwise both peers spawn an agent for the same task,+ // create conflicting `cos/<taskId>/<agentId>` worktrees on the same repo, and+ // race the orphan-reset. This is a no-op for a non-federated install (no claim+ // metadata) and for re-claiming our own task on retry/resume.+ const instanceId = await ensureInstanceId();+ if (!isClaimableBy(task.metadata, instanceId)) {+ console.log(`🔒 Task ${task.id} is claimed by instance ${getClaimOwner(task.metadata)} (live lease) — skipping spawn on ${instanceId}`);+ return null;+ }+// Check total spawn count across all retry types to prevent runaway respawningconst totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;if (totalSpawns >= MAX_TOTAL_SPAWNS) {@@ -267,18 +281,8 @@ export async function spawnAgentForTask(task) {// node pair can attribute each agent + its worktree branch to the instance// that produced it.//- // `getInstanceId()` returns the `UNKNOWN_INSTANCE_ID` sentinel (and never- // throws) before the local identity has been created — which can happen on a- // boot-time always-on auto-start that spawns an agent before the startup- // chain's `ensureSelf()` runs. Persisting that sentinel would leave the- // archived agent permanently unattributable, so on the cold path we create- // (or load) the real identity here before stamping. The warm path stays a- // cheap cached read — `ensureSelf()` only runs the once, when identity is- // genuinely missing.- let instanceId = await getInstanceId();- if (instanceId === UNKNOWN_INSTANCE_ID) {- instanceId = (await ensureSelf())?.instanceId || instanceId;- }+ // `instanceId` was resolved up front via `ensureInstanceId()` for the claim+ // guard, and is reused here so the warm-path cached read happens once.await registerAgent(agentId, task.id, {instanceId,workspacePath,@@ -321,14 +325,20 @@ export async function spawnAgentForTask(task) {emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });- // Mark the task as in_progress and increment total spawn count+ // Mark the task as in_progress, increment the total spawn count, and stamp+ // the federation claim (issue #1563). `buildClaim` records this instance as+ // `claimedBy` with a fresh lease, so a federated peer sharing this task list+ // sees the task as live-claimed and backs off (the orphan-reset honors the+ // same lease). The lease is renewed on the health-check heartbeat while the+ // agent runs and released when the task leaves `in_progress`.const newSpawnCount = (Number(task.metadata?.totalSpawnCount) || 0) + 1;const updateResult = await updateTask(task.id, {status: 'in_progress',metadata: {...task.metadata,totalSpawnCount: newSpawnCount,- lastSpawnedAt: new Date().toISOString()+ lastSpawnedAt: new Date().toISOString(),+ ...buildClaim(instanceId)}}, task.taskType || 'user').catch(err => {diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex e7375dbb6b..19caca2bdc 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -658,34 +658,37 @@ describe('spawnAgentForTask — cleanupOnError error recovery', () => {// serializes `.metadata`. These source-level assertions break loudly if a// future refactor drops the stamp.describe('agentLifecycle — instance provenance stamping (#1563)', () => {- it('source: imports the identity helpers from the instances service', () => {+ it('source: imports the identity resolver from the instances service', () => {expect(AGENT_LIFECYCLE_SRC).toMatch(- /import\s*\{\s*getInstanceId\s*,\s*ensureSelf\s*,\s*UNKNOWN_INSTANCE_ID\s*\}\s*from\s*'\.\/instances\.js';/+ /import\s*\{\s*ensureInstanceId\s*\}\s*from\s*'\.\/instances\.js';/);});- it('source: resolves instanceId via getInstanceId() before registering the agent', () => {+ it('source: resolves instanceId via ensureInstanceId() before registering the agent', () => {+ // Resolution is delegated to the shared `ensureInstanceId()` helper in+ // instances.js (which handles the boot-time `unknown` sentinel cold path)+ // and is reused by the #1563 claim guard at the top of the spawn. The+ // contract is unchanged: the id is resolved before registerAgent stamps it.const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);- const resolveIdx = fnBody.indexOf('await getInstanceId()');+ const resolveIdx = fnBody.indexOf('await ensureInstanceId()');const registerIdx = fnBody.indexOf('registerAgent(agentId, task.id, {');- expect(resolveIdx, '`await getInstanceId()` must exist inside spawnAgentForTask').toBeGreaterThan(-1);+ expect(resolveIdx, '`await ensureInstanceId()` must exist inside spawnAgentForTask').toBeGreaterThan(-1);expect(registerIdx, '`registerAgent(...)` must exist inside spawnAgentForTask').toBeGreaterThan(-1);expect(resolveIdx, 'instanceId must be resolved BEFORE registerAgent is called').toBeLessThan(registerIdx);});- it('source: falls back to ensureSelf() when identity is the unknown sentinel (never archives "unknown")', () => {- // Boot-time always-on auto-start can spawn an agent before the startup- // chain's ensureSelf() runs, so getInstanceId() can return the sentinel.- // The cold path must create/load the real identity rather than persist it.+ it('source: refuses to spawn a task under another instance\'s live lease (claim guard)', () => {const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);- const guardIdx = fnBody.indexOf('=== UNKNOWN_INSTANCE_ID');- const ensureIdx = fnBody.indexOf('await ensureSelf()');+ const guardIdx = fnBody.indexOf('isClaimableBy(task.metadata, instanceId)');const registerIdx = fnBody.indexOf('registerAgent(agentId, task.id, {');- expect(guardIdx, 'must guard on the UNKNOWN_INSTANCE_ID sentinel').toBeGreaterThan(-1);- expect(ensureIdx, 'must call ensureSelf() on the cold path').toBeGreaterThan(guardIdx);- expect(ensureIdx, 'the sentinel fallback must run BEFORE registerAgent').toBeLessThan(registerIdx);+ expect(guardIdx, 'must gate the spawn on isClaimableBy').toBeGreaterThan(-1);+ expect(guardIdx, 'the claim guard must run BEFORE registering the agent').toBeLessThan(registerIdx);+ });++ it('source: stamps the federation claim into the in_progress task update', () => {+ expect(AGENT_LIFECYCLE_SRC).toMatch(/\.\.\.buildClaim\(instanceId\)/);});it('source: stamps instanceId into the registerAgent metadata', () => {diff --git a/server/services/cos.js b/server/services/cos.jsindex 51af657c34..ee78b17d53 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -56,6 +56,8 @@ export { runHealthCheck, getHealthStatus };// dequeueNextTask so the spawn-side logic stays here, not in the store.import { firstLine, PRIORITY_VALUES, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask } from './cosTaskStore.js';export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask };+import { ensureInstanceId } from './instances.js';+import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';const AGENT_ARCHIVE_RETENTION_DAYS = 90;const RESUME_DEQUEUE_DELAY_MS = 500;@@ -482,6 +484,12 @@ async function resetOrphanedTasks() {const state = await loadState();const { user: userTaskData, cos: cosTaskData } = await getAllTasks();+ // This machine's federation identity, for the cross-instance lease checks+ // below (issue #1563). `ensureInstanceId()` resolves the real id on the cold+ // path so a boot-time orphan-reset never compares against the `unknown`+ // sentinel.+ const instanceId = await ensureInstanceId();+const runningAgentTaskIds = Object.values(state.agents).filter(a => a.status === 'running').map(a => a.taskId);@@ -515,7 +523,23 @@ async function resetOrphanedTasks() {const processOrphanedTasks = async (tasks) => {for (const task of tasks) {- if (runningAgentTaskIds.includes(task.id)) continue;+ if (runningAgentTaskIds.includes(task.id)) {+ // A local agent is actively working this task — renew its federation+ // lease (the heartbeat, issue #1563) so a peer sharing this task list+ // keeps seeing it as live-claimed across a long run instead of treating+ // it as orphaned once the original lease window elapses. We can only+ // hold a lease we own (or freshly claim an unclaimed legacy task); never+ // steal a lease another instance owns.+ const owner = getClaimOwner(task.metadata);+ const renewal = owner === instanceId+ ? buildRenewal(task.metadata, instanceId)+ : (owner === null ? buildClaim(instanceId) : null);+ if (renewal) {+ const taskType = task.taskType || (isInternalTaskId(task.id) ? 'internal' : 'user');+ await updateTask(task.id, { metadata: { ...task.metadata, ...renewal } }, taskType).catch(() => {});+ }+ continue;+ }// Skip tasks whose agent just completed — updateTask will set them to// completed shortly; treating them as orphaned causes spurious retriesif (recentlyCompletedTaskIds.has(task.id)) {@@ -530,6 +554,15 @@ async function resetOrphanedTasks() {await updateTask(task.id, { status: 'completed' }, task.taskType || (isInternalTaskId(task.id) ? 'internal' : 'user'));continue;}+ // Cross-instance lease guard (issue #1563, acceptance criterion 3): a+ // federated peer holds a live claim on this task, so it is being worked on+ // the other machine — not orphaned here. Resetting it to pending would+ // race a second agent onto work the peer is already doing. Leave it; the+ // lease expires on its own if the peer actually died.+ if (isHeldByOther(task.metadata, instanceId)) {+ emitLog('debug', `Skipping task ${task.id} — live lease held by instance ${getClaimOwner(task.metadata)}`, { taskId: task.id });+ continue;+ }emitLog('info', `Found orphaned in_progress task ${task.id}, routing through retry handler`, { taskId: task.id });await handleOrphanedTask(task.id, 'unknown-reset', getTaskById);}diff --git a/server/services/cosTaskClaim.js b/server/services/cosTaskClaim.jsnew file mode 100644index 0000000000..03bf882174--- /dev/null+++ b/server/services/cosTaskClaim.js@@ -0,0 +1,122 @@+/**+ * CoS Task Claim + Lease — federated single-claim execution (issue #1563)+ *+ * When two federated peers share the same task backlog (see #1561 full-sync+ * peer mode), both would otherwise parse the same `pending` task and each spawn+ * an agent for it — creating conflicting worktrees/branches on the same repo and+ * racing the orphan-reset. This module is the safety primitive that prevents+ * that: a task carries claim metadata (`claimedBy` = the producing instance's+ * federation id, `claimedAt`, and a `leaseExpiresAt` lease), and a peer only+ * spawns a task whose lease is unset/expired or already owned by itself.+ *+ * The lease is time-bounded so a crashed claimant can't block its peer forever:+ * the owning instance renews the lease on a heartbeat (folded into the periodic+ * health-check sweep) while its agent runs, and the claim is released when the+ * task leaves `in_progress`. A peer treats a task whose lease has expired as+ * free to claim.+ *+ * Pure + side-effect-free: every function operates on a plain task-metadata+ * object and returns either a boolean or a partial-metadata patch to merge via+ * `cosTaskStore.updateTask`. Persistence, sync, and scheduling live in the+ * callers (agentLifecycle.js spawn guard, cos.js orphan-reset + heartbeat,+ * cosTaskStore.js release-on-transition).+ */++// Lease duration. A claim stays "live" for this long after it was last set or+// renewed. Sized well above the health-check renewal cadence (15 min) so a+// long-running agent's lease never lapses mid-run, while a crashed instance's+// stale claim frees up for its peer within one lease window.+export const LEASE_DURATION_MS = 30 * 60 * 1000; // 30 minutes++// The metadata keys this module owns on a task. Exported so the store can strip+// them in one place when a task leaves `in_progress` (release-on-transition).+export const CLAIM_METADATA_KEYS = Object.freeze(['claimedBy', 'claimedAt', 'leaseExpiresAt']);++/**+ * Parse `leaseExpiresAt` (an ISO string after the markdown round-trip, or a+ * Date/number in-memory) to epoch ms, or null when absent/unparseable. A null+ * here means "no live lease" — never "lease in the past".+ */+function leaseExpiryMs(metadata) {+ const raw = metadata?.leaseExpiresAt;+ if (raw === undefined || raw === null || raw === '') return null;+ const ms = typeof raw === 'number' ? raw : Date.parse(raw);+ return Number.isFinite(ms) ? ms : null;+}++/**+ * Is there a live (unexpired) lease on this task right now?+ */+export function isLeaseLive(metadata, now = Date.now()) {+ const expiry = leaseExpiryMs(metadata);+ return expiry !== null && expiry > now;+}++/**+ * The instance currently holding the task's claim, or null. Note this reflects+ * the recorded `claimedBy` even if the lease has since expired — pair with+ * `isLeaseLive` when you need "actively held".+ */+export function getClaimOwner(metadata) {+ const owner = metadata?.claimedBy;+ return owner === undefined || owner === null || owner === '' ? null : owner;+}++/**+ * May `instanceId` spawn this task? True unless a DIFFERENT instance holds a+ * live lease. An unset/expired lease, or a live lease this instance already+ * owns (re-claim on retry / resume-after-restart), are both claimable.+ */+export function isClaimableBy(metadata, instanceId, now = Date.now()) {+ if (!isLeaseLive(metadata, now)) return true;+ return getClaimOwner(metadata) === instanceId;+}++/**+ * Is the task actively held by some OTHER instance (live lease, different+ * owner)? The orphan-reset uses this to leave a peer's in-flight work alone+ * rather than resetting it to pending and racing a second agent onto it.+ */+export function isHeldByOther(metadata, instanceId, now = Date.now()) {+ if (!isLeaseLive(metadata, now)) return false;+ const owner = getClaimOwner(metadata);+ return owner !== null && owner !== instanceId;+}++/**+ * Build the claim patch for a FRESH claim by `instanceId`. Stamps `claimedBy`,+ * a fresh `claimedAt`, and a lease `leaseMs` into the future. Merge the result+ * into the task's metadata.+ */+export function buildClaim(instanceId, { now = Date.now(), leaseMs = LEASE_DURATION_MS } = {}) {+ return {+ claimedBy: instanceId,+ claimedAt: new Date(now).toISOString(),+ leaseExpiresAt: new Date(now + leaseMs).toISOString()+ };+}++/**+ * Build the lease-renewal patch (heartbeat) for a task already owned by+ * `instanceId`. Extends `leaseExpiresAt` but preserves the original+ * `claimedAt`. Returns null when the task is NOT owned by this instance — a+ * peer must never renew another instance's lease (that would silently steal a+ * live claim); the caller should skip such tasks.+ */+export function buildRenewal(metadata, instanceId, { now = Date.now(), leaseMs = LEASE_DURATION_MS } = {}) {+ if (getClaimOwner(metadata) !== instanceId) return null;+ return {+ claimedBy: instanceId,+ claimedAt: metadata?.claimedAt || new Date(now).toISOString(),+ leaseExpiresAt: new Date(now + leaseMs).toISOString()+ };+}++/**+ * Build the release patch. Sets every claim key to `undefined` so+ * `cosTaskStore.updateTask`'s undefined-stripping drops them from the persisted+ * metadata, leaving the task freely claimable by either instance.+ */+export function buildRelease() {+ return Object.fromEntries(CLAIM_METADATA_KEYS.map((k) => [k, undefined]));+}diff --git a/server/services/cosTaskClaim.test.js b/server/services/cosTaskClaim.test.jsnew file mode 100644index 0000000000..2efffef82a--- /dev/null+++ b/server/services/cosTaskClaim.test.js@@ -0,0 +1,165 @@+import { describe, it, expect } from 'vitest';+import {+ LEASE_DURATION_MS,+ CLAIM_METADATA_KEYS,+ isLeaseLive,+ getClaimOwner,+ isClaimableBy,+ isHeldByOther,+ buildClaim,+ buildRenewal,+ buildRelease+} from './cosTaskClaim.js';++const A = 'instance-aaaa';+const B = 'instance-bbbb';+const T0 = 1_700_000_000_000; // fixed epoch for deterministic lease math++describe('isLeaseLive', () => {+ it('false when no lease present', () => {+ expect(isLeaseLive({}, T0)).toBe(false);+ expect(isLeaseLive({ leaseExpiresAt: null }, T0)).toBe(false);+ expect(isLeaseLive({ leaseExpiresAt: '' }, T0)).toBe(false);+ });+ it('true when lease is in the future, false when in the past', () => {+ const future = { leaseExpiresAt: new Date(T0 + 1000).toISOString() };+ const past = { leaseExpiresAt: new Date(T0 - 1000).toISOString() };+ expect(isLeaseLive(future, T0)).toBe(true);+ expect(isLeaseLive(past, T0)).toBe(false);+ });+ it('accepts a numeric (in-memory) lease as well as an ISO string', () => {+ expect(isLeaseLive({ leaseExpiresAt: T0 + 1000 }, T0)).toBe(true);+ });+ it('false for an unparseable lease value (never throws)', () => {+ expect(isLeaseLive({ leaseExpiresAt: 'not-a-date' }, T0)).toBe(false);+ });+});++describe('getClaimOwner', () => {+ it('returns the owner or null', () => {+ expect(getClaimOwner({ claimedBy: A })).toBe(A);+ expect(getClaimOwner({})).toBeNull();+ expect(getClaimOwner({ claimedBy: '' })).toBeNull();+ });+});++describe('isClaimableBy', () => {+ it('claimable when no live lease', () => {+ expect(isClaimableBy({}, A, T0)).toBe(true);+ });+ it('claimable by the lease owner (re-claim on retry/resume)', () => {+ const mine = buildClaim(A, { now: T0 });+ expect(isClaimableBy(mine, A, T0)).toBe(true);+ });+ it('NOT claimable by a different instance while the lease is live', () => {+ const held = buildClaim(A, { now: T0 });+ expect(isClaimableBy(held, B, T0)).toBe(false);+ });+ it('claimable by anyone once the lease has expired', () => {+ const expired = buildClaim(A, { now: T0, leaseMs: 1000 });+ expect(isClaimableBy(expired, B, T0 + 2000)).toBe(true);+ });+});++describe('isHeldByOther', () => {+ it('true only for a live lease owned by a different instance', () => {+ const held = buildClaim(A, { now: T0 });+ expect(isHeldByOther(held, B, T0)).toBe(true); // B sees A's live claim+ expect(isHeldByOther(held, A, T0)).toBe(false); // A owns it+ });+ it('false when no lease or lease expired', () => {+ expect(isHeldByOther({}, B, T0)).toBe(false);+ const expired = buildClaim(A, { now: T0, leaseMs: 1000 });+ expect(isHeldByOther(expired, B, T0 + 2000)).toBe(false);+ });+});++describe('buildClaim', () => {+ it('stamps owner, claimedAt, and a lease LEASE_DURATION_MS in the future', () => {+ const patch = buildClaim(A, { now: T0 });+ expect(patch.claimedBy).toBe(A);+ expect(Date.parse(patch.claimedAt)).toBe(T0);+ expect(Date.parse(patch.leaseExpiresAt)).toBe(T0 + LEASE_DURATION_MS);+ });+});++describe('buildRenewal', () => {+ it('extends the lease but preserves the original claimedAt', () => {+ const claim = buildClaim(A, { now: T0 });+ const renewal = buildRenewal(claim, A, { now: T0 + 60_000 });+ expect(renewal.claimedAt).toBe(claim.claimedAt); // unchanged+ expect(Date.parse(renewal.leaseExpiresAt)).toBe(T0 + 60_000 + LEASE_DURATION_MS);+ });+ it('refuses to renew a lease owned by another instance', () => {+ const claim = buildClaim(A, { now: T0 });+ expect(buildRenewal(claim, B, { now: T0 + 60_000 })).toBeNull();+ });+});++describe('buildRelease', () => {+ it('sets every claim key to undefined so the store strips them', () => {+ const patch = buildRelease();+ for (const key of CLAIM_METADATA_KEYS) {+ expect(key in patch).toBe(true);+ expect(patch[key]).toBeUndefined();+ }+ });+});++// Criterion 5: two peers sharing one task list provably never both spawn the+// same task. This simulates the spawn-time decision each instance makes against+// the shared (synced) task record, applying claim patches as the store would.+describe('two-instance claim simulation (#1563 acceptance criterion 5)', () => {+ // mimic cosTaskStore.updateTask's metadata merge + undefined-stripping+ const applyPatch = (metadata, patch) => {+ const merged = { ...metadata, ...patch };+ for (const k of Object.keys(merged)) if (merged[k] === undefined) delete merged[k];+ return merged;+ };++ it('only one instance claims a free task; the other backs off', () => {+ let task = { id: 'task-1', metadata: {} };+ // Both peers evaluate the task at the same instant against the same record.+ const aCanClaim = isClaimableBy(task.metadata, A, T0);+ const bCanClaim = isClaimableBy(task.metadata, B, T0);+ expect(aCanClaim).toBe(true);+ expect(bCanClaim).toBe(true); // both *see* it free before either writes++ // A wins the write race (its claim syncs first). B re-reads the synced+ // record before spawning — the real guard is the re-check against the+ // freshest record, exactly as spawnAgentForTask does.+ task.metadata = applyPatch(task.metadata, buildClaim(A, { now: T0 }));+ expect(isClaimableBy(task.metadata, A, T0)).toBe(true); // A proceeds+ expect(isClaimableBy(task.metadata, B, T0)).toBe(false); // B must back off+ });++ it('the lease holder keeps the task across a long run via heartbeat renewal', () => {+ let task = { id: 'task-1', metadata: buildClaim(A, { now: T0 }) };+ // Half an hour later, without renewal the lease would have lapsed and B+ // could steal the task. A renews on the health-check heartbeat first.+ const renewAt = T0 + LEASE_DURATION_MS - 60_000; // renew 1 min before expiry+ const renewal = buildRenewal(task.metadata, A, { now: renewAt });+ task.metadata = applyPatch(task.metadata, renewal);+ // Well past the ORIGINAL expiry, B still cannot claim — the lease moved.+ const afterOriginalExpiry = T0 + LEASE_DURATION_MS + 1000;+ expect(isHeldByOther(task.metadata, B, afterOriginalExpiry)).toBe(true);+ expect(isClaimableBy(task.metadata, B, afterOriginalExpiry)).toBe(false);+ });++ it('a crashed claimant (no renewal) frees the task for its peer after the lease window', () => {+ let task = { id: 'task-1', metadata: buildClaim(A, { now: T0 }) };+ // A crashes; no renewal happens. After the lease window B may take over.+ const afterExpiry = T0 + LEASE_DURATION_MS + 1;+ expect(isHeldByOther(task.metadata, B, afterExpiry)).toBe(false);+ expect(isClaimableBy(task.metadata, B, afterExpiry)).toBe(true);+ task.metadata = applyPatch(task.metadata, buildClaim(B, { now: afterExpiry }));+ expect(getClaimOwner(task.metadata)).toBe(B);+ });++ it('release frees the task immediately for either instance', () => {+ let task = { id: 'task-1', metadata: buildClaim(A, { now: T0 }) };+ task.metadata = applyPatch(task.metadata, buildRelease());+ for (const key of CLAIM_METADATA_KEYS) expect(key in task.metadata).toBe(false);+ expect(isClaimableBy(task.metadata, B, T0)).toBe(true);+ });+});diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 187027d846..342a2511d1 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -19,6 +19,7 @@ import { parseTasksMarkdown, groupTasksByStatus, getAutoApprovedTasks, getAwaitiimport { REVIEW_STOP_MODES, normalizeReviewers } from '../lib/validation.js';import { loadState, withStateLock, ROOT_DIR } from './cosState.js';import { cosEvents } from './cosEvents.js';+import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';// First non-empty line of a string. Used by addTask dedup: stored descriptions// are flattened to a single line by generateTasksMarkdown, so the comparison@@ -262,6 +263,19 @@ export async function updateTask(taskId, updates, taskType = 'user') {}}+ // Release the federation claim/lease when a task leaves `in_progress` (issue+ // #1563). A claim only protects in-flight work; once the task completes, fails+ // back to pending, or is blocked, it must become freely claimable by either+ // peer — leaving a stale lease behind would block a legitimate retry (by this+ // instance or its peer) for a full lease window. The spawn's own+ // in_progress update carries `status: 'in_progress'` and is exempt, and a+ // lease-renewal heartbeat passes no `status` at all, so neither is stripped.+ if (updates.status && updates.status !== 'in_progress') {+ for (const key of CLAIM_METADATA_KEYS) {+ delete updatedMetadata[key];+ }+ }+// Clean undefined values from metadataObject.keys(updatedMetadata).forEach(key => {if (updatedMetadata[key] === undefined) delete updatedMetadata[key];diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex ba5beff852..0255360d26 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -215,6 +215,35 @@ describe('cosTaskStore.updateTask', () => {expect(reopened.metadata.blockedCategory).toBeUndefined();});+ it('releases the federation claim/lease when a task leaves in_progress (#1563)', async () => {+ await addTask({ description: 'claimed', id: 'task-claimed' }, 'user');+ // Spawn-time claim: status in_progress carries the claim metadata.+ const claimed = await updateTask('task-claimed', {+ status: 'in_progress',+ metadata: { claimedBy: 'instance-a', claimedAt: '2026-01-01T00:00:00.000Z', leaseExpiresAt: '2026-01-01T00:30:00.000Z' }+ }, 'user');+ expect(claimed.metadata.claimedBy).toBe('instance-a');+ // Completing the task strips the claim so it is freely re-claimable.+ const done = await updateTask('task-claimed', { status: 'completed' }, 'user');+ expect(done.metadata.claimedBy).toBeUndefined();+ expect(done.metadata.claimedAt).toBeUndefined();+ expect(done.metadata.leaseExpiresAt).toBeUndefined();+ });++ it('keeps the claim while the task stays in_progress (lease renewal, no status change) (#1563)', async () => {+ await addTask({ description: 'renew', id: 'task-renew' }, 'user');+ await updateTask('task-renew', {+ status: 'in_progress',+ metadata: { claimedBy: 'instance-a', claimedAt: '2026-01-01T00:00:00.000Z', leaseExpiresAt: '2026-01-01T00:30:00.000Z' }+ }, 'user');+ // A heartbeat renewal passes no status — the claim must survive and update.+ const renewed = await updateTask('task-renew', {+ metadata: { claimedBy: 'instance-a', claimedAt: '2026-01-01T00:00:00.000Z', leaseExpiresAt: '2026-01-01T01:00:00.000Z' }+ }, 'user');+ expect(renewed.metadata.claimedBy).toBe('instance-a');+ expect(renewed.metadata.leaseExpiresAt).toBe('2026-01-01T01:00:00.000Z');+ });+it('returns an error object when the file is missing', async () => {const result = await updateTask('task-x', { status: 'completed' }, 'user');expect(result.error).toBe('Task file not found');diff --git a/server/services/instances.js b/server/services/instances.jsindex cc9165d295..1df505a240 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -169,6 +169,25 @@ export async function getInstanceId() {return cachedInstanceId;}+/**+ * Resolve this machine's real federation instance id, creating the local+ * identity on the cold path. `getInstanceId()` returns the+ * `UNKNOWN_INSTANCE_ID` sentinel (and never throws) before the identity exists+ * — which can happen on a boot-time always-on auto-start that runs before the+ * startup chain's `ensureSelf()` does. Callers that stamp the id onto durable+ * records (agent provenance, worktree metadata) or compare it for cross-machine+ * task claims (#1563) must never persist/compare the sentinel, so this creates+ * (or loads) the real identity before returning. The warm path is the cheap+ * cached `getInstanceId()` read; `ensureSelf()` only runs the once.+ */+export async function ensureInstanceId() {+ let instanceId = await getInstanceId();+ if (instanceId === UNKNOWN_INSTANCE_ID) {+ instanceId = (await ensureSelf())?.instanceId || instanceId;+ }+ return instanceId;+}+export async function updateSelf(name, { defaultPeerFullSync } = {}) {return withData(async (data) => {if (!data.self) return null;diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex ef77102eb0..e35c8b0969 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -148,6 +148,32 @@ describe('instances.js', () => {});});+ describe('ensureInstanceId (#1563)', () => {+ // getInstanceId caches the resolved id at module scope, so isolate each+ // case with a fresh module instance to exercise the cold path deterministically.+ it('returns the existing id without creating a new identity (warm path)', async () => {+ readJSONFile.mockResolvedValue({ self: { instanceId: 'warm-id', name: 'host' }, peers: [] });+ vi.resetModules();+ const fresh = await import('./instances.js');+ const id = await fresh.ensureInstanceId();+ expect(id).toBe('warm-id');+ // No write — the identity already existed.+ expect(atomicWrite).not.toHaveBeenCalled();+ });++ it('creates a real identity on the cold path instead of returning the unknown sentinel', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });+ vi.resetModules();+ const fresh = await import('./instances.js');+ const id = await fresh.ensureInstanceId();+ expect(id).not.toBe('unknown');+ expect(typeof id).toBe('string');+ expect(id.length).toBeGreaterThan(0);+ // ensureSelf persisted the freshly-created identity.+ expect(atomicWrite).toHaveBeenCalled();+ });+ });+describe('updateSelf', () => {it('should update name when self exists', async () => {readJSONFile.mockResolvedValue({diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex eee631420e..7287007bca 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -14,6 +14,7 @@ import { readdir, rm, stat } from 'fs/promises';import { join } from 'path';import { ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';import { execGit } from '../lib/execGit.js';+import { ensureInstanceId } from './instances.js';const WORKTREES_DIR = PATHS.worktrees;// Lockfiles that npm/yarn/pnpm modify as a side-effect — safe to discard during worktree cleanup@@ -167,6 +168,14 @@ export async function createWorktree(agentId, sourceWorkspace, taskId, options =const worktreePath = join(WORKTREES_DIR, agentId);+ // Stamp the producing machine's federation identity onto the worktree+ // metadata (issue #1563, acceptance criterion 1). The branch is named+ // `cos/<taskId>/<agentId>`, so recording which instance created it lets a+ // federated node pair attribute every worktree/branch to its origin instance+ // once CoS history federates. `ensureInstanceId()` creates the identity on the+ // cold path so the worktree is never tagged `unknown`.+ const instanceId = await ensureInstanceId();+// Fetch latest from origin so we base off up-to-date refsconst fetchSucceeded = await execGit(['fetch', 'origin'], sourceWorkspace).then(() => true)@@ -196,7 +205,7 @@ export async function createWorktree(agentId, sourceWorkspace, taskId, options =await execGit(['worktree', 'add', '-B', branchName, worktreePath, `origin/${branchName}`], sourceWorkspace);}console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} on existing branch ${branchName}`);- return { worktreePath, branchName, baseBranch: null, existingBranch: true };+ return { worktreePath, branchName, baseBranch: null, existingBranch: true, instanceId };}const branchName = options.planId@@ -226,7 +235,7 @@ export async function createWorktree(agentId, sourceWorkspace, taskId, options =console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} (branch: ${branchName}, base: ${baseRef})`);- return { worktreePath, branchName, baseBranch };+ return { worktreePath, branchName, baseBranch, instanceId };}/**