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: skip peer-claimed tasks during dequeue candidate selection (#1650)

[._.]/ Adam Eivy5bdabe7a8599
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 44715b19cc..96dac82964 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -14,6 +14,7 @@
## Chief of Staff
- **[issue-1683] CoS daily action-budget can no longer overshoot by one at the boundary.** `completeAgent()` emitted `agent:completed` — whose handler schedules `dequeueNextTask()` and its daily action-budget gate — *before* recording the just-finished action via `recordDomainUsage('cos', …)`. At the exact `maxActionsPerDay` boundary the dequeue read stale usage that didn't yet include the completing action (which was already `status: 'completed'`, so it wasn't counted as in-flight either), admitting one autonomous spawn past the cap. The usage ledger is now written before the `agent:completed` emit so the gate always counts the completing action. (`server/services/cosAgents.js`)
+- **[issue-1650] A task a federated peer is already working can no longer starve this machine's queue.** Now that peer claims/leases are visible via task-list federation (#1712), both spawn engines skip a task whose live lease belongs to *another* instance **during candidate selection** — before they emit `task:ready` and consume a spawn slot. Previously such a task (often the highest-priority pick) was selected each cycle, the lifecycle spawn guard then refused it (spawning nothing), and that wasted slot starved the next unclaimed task. The skip now runs in `dequeueNextTask` (cos.js) and `evaluateTasks` (cosTaskGenerator.js), across their user-task and auto-approved tiers and their dry-run plan, using the shared `isHeldByOther(task.metadata, instanceId)` predicate. This closes the last open acceptance criterion of #1650 (the dequeue-time peer-claim skip from the #1563 review). (`server/services/cos.js`, `server/services/cosTaskGenerator.js`)
## Federation
diff --git a/server/services/cos.js b/server/services/cos.js
index 6dae0e13bf..88783d534c 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -699,6 +699,11 @@ async function dequeueNextTask() {
if (availableSlots <= 0) return;
+ // This instance's federation id, resolved once per cycle so the priority
+ // tiers below can skip tasks a peer holds a live lease on (#1650). Warm path
+ // is the cheap cached read; only the cold boot creates the identity.
+ const instanceId = await ensureInstanceId();
+
const perProjectLimit = state.config.maxConcurrentAgentsPerProject || state.config.maxConcurrentAgents;
const agentsByProject = countRunningAgentsByProject(state.agents);
const spawnProjectCounts = { ...agentsByProject };
@@ -802,6 +807,14 @@ async function dequeueNextTask() {
for (const task of pendingUserTasks) {
if (spawned >= availableSlots) break;
+ // A federated peer holds a live lease on this task (#1650) — it's being
+ // worked on the other machine. Skip it during candidate selection so it
+ // doesn't consume this cycle's spawn slot (the spawn guard would return
+ // null anyway) and starve later unclaimed tasks.
+ if (isHeldByOther(task.metadata, instanceId)) {
+ emitLog('debug', `Skipping user task ${task.id} — live lease held by peer instance ${getClaimOwner(task.metadata)}`, { taskId: task.id });
+ continue;
+ }
if (await blockIfExceedsMaxSpawns(task, 'user')) continue;
const userTask = { ...task, taskType: 'user' };
if (!canSpawn(userTask)) continue;
@@ -862,7 +875,8 @@ async function dequeueNextTask() {
spawnProjectCounts,
isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),
cooldownExempt: isCooldownExemptTask,
- extraSkip: isDisabledAnalysisType
+ extraSkip: isDisabledAnalysisType,
+ heldByOther: (task) => isHeldByOther(task.metadata, instanceId)
});
for (const task of wouldSpawn) {
emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });
@@ -871,6 +885,13 @@ async function dequeueNextTask() {
} else {
for (const task of autoApproved) {
if (spawned >= autonomousSpawnCeiling) break;
+ // A federated peer holds a live lease on this task (#1650) — skip it
+ // during candidate selection so it doesn't consume an autonomous slot
+ // the spawn guard would just reject.
+ if (isHeldByOther(task.metadata, instanceId)) {
+ emitLog('debug', `Skipping system task ${task.id} — live lease held by peer instance ${getClaimOwner(task.metadata)}`, { taskId: task.id });
+ continue;
+ }
if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;
// Skip improvement tasks whose type was disabled after queuing
if (isDisabledAnalysisType(task)) {
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index e6b213dcf5..cea79561b3 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -37,6 +37,8 @@ import { getTaskTypeConfidence } from './taskLearning.js';
import { generateProactiveTasks as generateMissionTasks } from './missions.js';
import { isRecoveryTask } from './recoveryTasks.js';
import { getCodeReviewDefaults } from './codeReview.js';
+import { isHeldByOther, getClaimOwner } from './cosTaskClaim.js';
+import { ensureInstanceId } from './instances.js';
/**
* Block a task that has exceeded the max spawn limit. Returns true if blocked.
@@ -116,6 +118,7 @@ export function isCooldownExemptTask(task) {
* @param {(appId: string) => Promise<boolean>} ctx.isOnCooldown - async cooldown probe
* @param {(task: object) => boolean} [ctx.cooldownExempt] - true ⇒ skip the cooldown gate for this task
* @param {(task: object) => boolean} [ctx.extraSkip] - true ⇒ task ineligible (engine-specific gate)
+ * @param {(task: object) => boolean} [ctx.heldByOther] - true ⇒ a federated peer holds a live lease on this task (#1650); the execute path skips it before spawning, so the dry-run plan must too
* @returns {Promise<object[]>} the tasks execute mode would spawn, in order
*/
export async function selectDryRunAutoApproved(autoApproved, ctx) {
@@ -126,7 +129,8 @@ export async function selectDryRunAutoApproved(autoApproved, ctx) {
spawnProjectCounts = {},
isOnCooldown,
cooldownExempt = () => false,
- extraSkip = () => false
+ extraSkip = () => false,
+ heldByOther = () => false
} = ctx;
const counts = { ...spawnProjectCounts };
@@ -135,6 +139,7 @@ export async function selectDryRunAutoApproved(autoApproved, ctx) {
for (const task of autoApproved) {
if (spawned >= availableSlots) break;
+ if (heldByOther(task)) continue;
if (exceedsMaxSpawns(task)) continue;
if (extraSkip(task)) continue;
const appId = task.metadata?.app;
@@ -546,9 +551,17 @@ async function spawnPriority0OnDemand(ctx) {
* autonomous action budget.
*/
async function spawnPriority1UserTasks(ctx) {
- const { pendingUserTasks, availableSlots, perProjectLimit, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;
+ const { pendingUserTasks, availableSlots, perProjectLimit, tasksToSpawn, canSpawnTask, trackSpawn, instanceId } = ctx;
for (const task of pendingUserTasks) {
if (tasksToSpawn.length >= availableSlots) break;
+ // A federated peer holds a live lease on this task (#1650) — it's being
+ // worked on the other machine. Skip it during candidate selection so it
+ // doesn't consume this cycle's spawn slot (the spawn guard would return
+ // null anyway) and starve later unclaimed tasks.
+ if (isHeldByOther(task.metadata, instanceId)) {
+ emitLog('debug', `Skipping user task ${task.id} — live lease held by peer instance ${getClaimOwner(task.metadata)}`, { taskId: task.id });
+ continue;
+ }
if (await blockIfExceedsMaxSpawns(task, 'user')) continue;
const userTask = { ...task, taskType: 'user' };
if (!canSpawnTask(userTask)) {
@@ -573,20 +586,21 @@ async function spawnPriority1UserTasks(ctx) {
* by `autonomousSlotCeiling` (the CoS action budget, #711).
*/
async function spawnPriority2AutoApproved(ctx) {
- const { state, cosTaskData, cosAutonomyMode, autonomousSlotCeiling, perProjectLimit, spawnProjectCounts, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;
+ const { state, cosTaskData, cosAutonomyMode, autonomousSlotCeiling, perProjectLimit, spawnProjectCounts, tasksToSpawn, canSpawnTask, trackSpawn, instanceId } = ctx;
if (tasksToSpawn.length < autonomousSlotCeiling && cosTaskData.exists && cosAutonomyMode !== 'execute') {
if (cosAutonomyMode === 'dry-run') {
// Log only the tasks execute mode would ACTUALLY spawn — applying the same
- // max-spawns / cooldown / per-project gates against virtual capacity —
- // rather than every auto-approved task regardless of eligibility.
+ // peer-lease / max-spawns / cooldown / per-project gates against virtual
+ // capacity — rather than every auto-approved task regardless of eligibility.
const wouldSpawn = await selectDryRunAutoApproved(cosTaskData.autoApproved || [], {
availableSlots: autonomousSlotCeiling,
alreadySpawned: tasksToSpawn.length,
perProjectLimit,
spawnProjectCounts,
isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),
- cooldownExempt: isCooldownExemptTask
+ cooldownExempt: isCooldownExemptTask,
+ heldByOther: (task) => isHeldByOther(task.metadata, instanceId)
});
for (const task of wouldSpawn) {
emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });
@@ -597,6 +611,14 @@ async function spawnPriority2AutoApproved(ctx) {
for (const task of autoApproved) {
if (tasksToSpawn.length >= autonomousSlotCeiling) break;
+ // A federated peer holds a live lease on this task (#1650) — skip it
+ // during candidate selection so it doesn't consume an autonomous slot
+ // the spawn guard would just reject.
+ if (isHeldByOther(task.metadata, instanceId)) {
+ emitLog('debug', `Skipping system task ${task.id} — live lease held by peer instance ${getClaimOwner(task.metadata)}`, { taskId: task.id });
+ continue;
+ }
+
if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;
// Check if task's app is on cooldown (pipeline continuations AND perpetual
@@ -780,6 +802,11 @@ export async function evaluateTasks(options) {
return s;
});
+ // Resolve this instance's federation id once per cycle so the priority tiers
+ // can skip tasks a peer holds a live lease on (#1650). Warm path is the cheap
+ // cached read; only the cold boot creates the identity.
+ const instanceId = await ensureInstanceId();
+
// Get both user and CoS tasks
const { user: userTaskData, cos: cosTaskData } = await getAllTasks();
@@ -839,6 +866,7 @@ export async function evaluateTasks(options) {
const ctx = {
state,
cosTaskData,
+ instanceId,
availableSlots,
perProjectLimit,
tasksToSpawn,
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 04d071d01b..e0866153f9 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -66,6 +66,41 @@ describe('dry-run hook wiring matches each engine execute path', () => {
});
});
+// #1650: once a peer's claim/lease is visible via task-record federation, a
+// task whose live lease belongs to ANOTHER instance must be skipped during
+// candidate selection — BEFORE the engine emits `task:ready` + trackSpawn.
+// Otherwise that peer-claimed task (often the highest-priority pick) consumes
+// this instance's spawn slot every cycle (the spawn guard then returns null,
+// spawning nothing) and starves later unclaimed tasks. Both spawn engines
+// (dequeueNextTask in cos.js, evaluateTasks here) must apply it, in both their
+// execute loops AND their dry-run plan.
+describe('peer-claim skip during candidate selection (#1650)', () => {
+ it('both engines import isHeldByOther from the shared claim module', () => {
+ expect(COS_SRC).toContain("from './cosTaskClaim.js'");
+ expect(COS_SRC).toMatch(/import\s*\{[^}]*isHeldByOther[^}]*\}\s*from\s*'\.\/cosTaskClaim\.js'/);
+ expect(GEN_SRC).toMatch(/import\s*\{[^}]*isHeldByOther[^}]*\}\s*from\s*'\.\/cosTaskClaim\.js'/);
+ });
+
+ it('both engines resolve this instance id once per cycle via ensureInstanceId', () => {
+ expect(COS_SRC).toContain('const instanceId = await ensureInstanceId();');
+ expect(GEN_SRC).toContain('const instanceId = await ensureInstanceId();');
+ });
+
+ it('both engines skip peer-held tasks in their EXECUTE candidate loops', () => {
+ // Each engine must have the live-lease skip in BOTH the user-task and the
+ // auto-approved tiers — at least two execute-path skip sites per engine.
+ const cosSkips = COS_SRC.match(/if\s*\(isHeldByOther\(task\.metadata,\s*instanceId\)\)/g) || [];
+ const genSkips = GEN_SRC.match(/if\s*\(isHeldByOther\(task\.metadata,\s*instanceId\)\)/g) || [];
+ expect(cosSkips.length).toBeGreaterThanOrEqual(2);
+ expect(genSkips.length).toBeGreaterThanOrEqual(2);
+ });
+
+ it('both engines pass heldByOther into their dry-run plan so it matches execute', () => {
+ expect(COS_SRC).toContain('heldByOther: (task) => isHeldByOther(task.metadata, instanceId)');
+ expect(GEN_SRC).toContain('heldByOther: (task) => isHeldByOther(task.metadata, instanceId)');
+ });
+});
+
// isCooldownExemptTask is the single source of truth for "this task bypasses the
// per-app review cooldown." The perpetual-string case is the subtle one: a
// perpetual task is queued with `metadata.perpetual === true`, but that bare
@@ -299,6 +334,27 @@ describe('selectDryRunAutoApproved', () => {
expect(out.map(t => t.id)).toEqual(['2']);
});
+ it('skips tasks a federated peer holds a live lease on (#1650)', async () => {
+ const tasks = [task('1', { claimedBy: 'peer' }), task('2'), task('3', { claimedBy: 'peer' })];
+ const out = await selectDryRunAutoApproved(tasks, {
+ ...baseCtx,
+ heldByOther: (t) => t.metadata?.claimedBy === 'peer'
+ });
+ expect(out.map(t => t.id)).toEqual(['2']);
+ });
+
+ it('a peer-held task does not consume virtual project capacity (#1650 skip-before-increment)', async () => {
+ // Both tasks on appX, per-project limit 1. Task 1 is peer-held → it must not
+ // burn appX's only slot, so task 2 (claimable here) still fits.
+ const tasks = [task('1', { app: 'appX', claimedBy: 'peer' }), task('2', { app: 'appX' })];
+ const out = await selectDryRunAutoApproved(tasks, {
+ ...baseCtx,
+ perProjectLimit: 1,
+ heldByOther: (t) => t.metadata?.claimedBy === 'peer'
+ });
+ expect(out.map(t => t.id)).toEqual(['2']);
+ });
+
it('does not mutate the passed-in spawnProjectCounts', async () => {
const counts = { appA: 1 };
await selectDryRunAutoApproved([task('1', { app: 'appA' })], { ...baseCtx, spawnProjectCounts: counts });