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([issue-978]): defer active-agent bind until idle-review task exists

Adam Eivyb8bb79f8b35e
diff --git a/server/services/appActivity.js b/server/services/appActivity.js
index 2c07586a1e..618b92255b 100644
--- a/server/services/appActivity.js
+++ b/server/services/appActivity.js
@@ -92,7 +92,39 @@ export async function startAppCooldown(appId, cooldownMs) {
}
/**
- * Mark an app review as started
+ * Advance an app's review cooldown WITHOUT binding an active agent.
+ *
+ * Stamps `lastReviewedAt` (which `isAppActivityOnCooldown` reads) so the app
+ * isn't re-picked on the very next idle tick — the re-pick-storm guard. This is
+ * the half of the old `markAppReviewStarted` that must run *before* the per-app
+ * task generator, since a no-op poll (task generator returns `null`) still has
+ * to advance the cooldown. Crucially it does NOT touch `activeAgentId`, so a
+ * null result can't leave a phantom "in review" marker. See `bindAppReviewAgent`
+ * for the agent-binding half, called only once a task actually exists.
+ */
+export async function markAppReviewCooldown(appId) {
+ return updateAppActivity(appId, {
+ lastReviewedAt: new Date().toISOString()
+ });
+}
+
+/**
+ * Bind an active agent to an app whose review cooldown was already advanced by
+ * `markAppReviewCooldown`. Call this only after the per-app task generator has
+ * produced a task — binding before generation is what stranded `activeAgentId`
+ * on no-op polls (the app read as "in review" until stale-agent cleanup).
+ */
+export async function bindAppReviewAgent(appId, agentId) {
+ return updateAppActivity(appId, {
+ activeAgentId: agentId
+ });
+}
+
+/**
+ * Mark an app review as started — advances the cooldown AND binds the active
+ * agent in one step. Use only when a task is guaranteed to follow (the agent
+ * id is known up front). When the task may be `null`, prefer the split pair:
+ * `markAppReviewCooldown` eagerly + `bindAppReviewAgent` once the task exists.
*/
export async function markAppReviewStarted(appId, agentId) {
return updateAppActivity(appId, {
diff --git a/server/services/appActivity.test.js b/server/services/appActivity.test.js
new file mode 100644
index 0000000000..c8f7df04a4
--- /dev/null
+++ b/server/services/appActivity.test.js
@@ -0,0 +1,79 @@
+/**
+ * Tests for the split review-marker functions in appActivity.js (issue #978).
+ *
+ * The phantom-active-agent bug: `markAppReviewStarted` advanced the cooldown
+ * AND bound `activeAgentId` in one step, called *before* the per-app task
+ * generator ran. When the generator returned null (no claimable PLAN item,
+ * watcher no-op, precondition skip), the bind was left stranded and the app
+ * read as "in review" until stale-agent cleanup or a restart.
+ *
+ * The fix splits the marker into `markAppReviewCooldown` (advance the re-pick
+ * guard, no bind) + `bindAppReviewAgent` (bind only once a task exists). These
+ * tests pin that split's semantics directly.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'app-activity-test-'));
+
+// appActivity.js reads PATHS.cos (data/cos), which is computed independently of
+// PATHS.data — so redirecting `data` alone leaves writes landing in the real
+// data/cos dir. Redirect `cos` too via extraOverrides.
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), {
+ dataRoot: TEST_DATA_ROOT,
+ extraOverrides: (root) => ({ cos: join(root, 'cos') }),
+ }));
+
+const appActivity = await import('./appActivity.js');
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe('appActivity review markers (issue #978)', () => {
+ beforeEach(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(TEST_DATA_ROOT, { recursive: true });
+ });
+
+ it('markAppReviewCooldown advances the cooldown without binding an agent', async () => {
+ await appActivity.markAppReviewCooldown('app-1');
+ const rec = await appActivity.getAppActivityById('app-1');
+ expect(rec.lastReviewedAt, 'cooldown stamp must be set').toBeTruthy();
+ expect(rec.activeAgentId, 'no agent must be bound by the cooldown stamp alone').toBeNull();
+ });
+
+ it('cooldown stamp alone puts the app on cooldown (re-pick-storm guard)', async () => {
+ await appActivity.markAppReviewCooldown('app-1');
+ // A wide window means lastReviewedAt is recent enough to be on cooldown.
+ expect(await appActivity.isAppOnCooldown('app-1', 60_000)).toBe(true);
+ });
+
+ it('a null-task idle poll (cooldown only, no bind) does NOT leave a phantom active agent', async () => {
+ // Simulate the idle-review path when the task generator returns null:
+ // cooldown is advanced, bind is skipped.
+ await appActivity.markAppReviewCooldown('app-1');
+ const rec = await appActivity.getAppActivityById('app-1');
+ expect(rec.activeAgentId, 'app must not read as in-review after a no-op poll').toBeNull();
+ });
+
+ it('bindAppReviewAgent binds the active agent after a task exists', async () => {
+ await appActivity.markAppReviewCooldown('app-1');
+ await appActivity.bindAppReviewAgent('app-1', 'idle-review-123');
+ const rec = await appActivity.getAppActivityById('app-1');
+ expect(rec.activeAgentId).toBe('idle-review-123');
+ expect(rec.lastReviewedAt, 'cooldown stamp survives the bind').toBeTruthy();
+ });
+
+ it('bindAppReviewAgent preserves the cooldown stamp set earlier in the cycle', async () => {
+ await appActivity.markAppReviewCooldown('app-1');
+ const afterStamp = (await appActivity.getAppActivityById('app-1')).lastReviewedAt;
+ await appActivity.bindAppReviewAgent('app-1', 'on-demand-456');
+ const afterBind = await appActivity.getAppActivityById('app-1');
+ expect(afterBind.lastReviewedAt).toBe(afterStamp);
+ expect(afterBind.activeAgentId).toBe('on-demand-456');
+ });
+});
diff --git a/server/services/cos.js b/server/services/cos.js
index be9fef9d2a..7573f0a5ba 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -18,7 +18,7 @@ import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { getActiveProvider } from './providers.js';
import { isInternalTaskId } from '../lib/taskParser.js';
-import { isAppOnCooldown, markAppReviewStarted, clearStaleActiveAgents } from './appActivity.js';
+import { isAppOnCooldown, markAppReviewCooldown, bindAppReviewAgent, clearStaleActiveAgents } from './appActivity.js';
import { getActiveApps } from './apps.js';
import { getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights } from './taskLearning.js';
import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats } from './eventScheduler.js';
@@ -718,12 +718,18 @@ async function dequeueNextTask() {
if (targetApp) {
emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });
+ // Advance the cooldown eagerly (deduped per app per cycle), but defer
+ // binding the active agent until a task is produced — a null result
+ // here must not strand `activeAgentId` (issue #978).
if (!reviewStartedApps.has(targetApp.id)) {
- await markAppReviewStarted(targetApp.id, `on-demand-${Date.now()}`);
+ await markAppReviewCooldown(targetApp.id);
reviewStartedApps.add(targetApp.id);
}
await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);
task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, { skipPreconditions: true });
+ if (task) {
+ await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
+ }
} else {
emitLog('info', `Processing on-demand improvement: ${request.taskType}`, { requestId: request.id });
await taskScheduleMod.recordExecution(`task:${request.taskType}`);
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 523991dcc9..47627d3318 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -694,14 +694,13 @@ describe('cos.js source — priority + capacity invariants', () => {
.toMatch(/idleReviewEnabled\s*&&\s*getDomainMode\(\s*state\.config\s*,\s*['"]cos['"]\s*\)\s*===\s*['"]execute['"]/);
});
- it('both on-demand loops dedupe markAppReviewStarted per app via reviewStartedApps set', () => {
- // Multiple on-demand requests targeting the same app should mark its
- // activity record review-started only once per cycle — without the guard,
- // each request rewrites the same record. BOTH on-demand loops carry the
- // duplication: the startup/manual `evaluateTasks` loop AND the
- // event-driven `dequeueNextTask` loop (the common "Run Now" path). Pin
- // (a) the set is declared and (b) markAppReviewStarted is gated on it in
- // each.
+ it('both on-demand loops dedupe the cooldown stamp per app via reviewStartedApps set', () => {
+ // Multiple on-demand requests targeting the same app should advance its
+ // cooldown only once per cycle — without the guard, each request rewrites
+ // the same record. BOTH on-demand loops carry the duplication: the
+ // startup/manual `evaluateTasks` loop AND the event-driven `dequeueNextTask`
+ // loop (the common "Run Now" path). Pin (a) the set is declared and (b) the
+ // cooldown stamp is gated on it in each.
// evaluateTasks now lives in cosTaskGenerator.js; dequeueNextTask stays in cos.js.
for (const { fnName, src } of [
{ fnName: 'export async function evaluateTasks', src: GEN_SRC },
@@ -714,11 +713,37 @@ describe('cos.js source — priority + capacity invariants', () => {
).toMatch(/const\s+reviewStartedApps\s*=\s*new\s+Set\(/);
expect(
fnBody,
- `${fnName} must gate markAppReviewStarted on !reviewStartedApps.has(targetApp.id)`
+ `${fnName} must gate markAppReviewCooldown on !reviewStartedApps.has(targetApp.id)`
).toMatch(/if\s*\(\s*!\s*reviewStartedApps\.has\(\s*targetApp\.id\s*\)\s*\)/);
}
});
+ it('on-demand loops defer bindAppReviewAgent until a task is produced (issue #978)', () => {
+ // The phantom-active-agent bug: binding activeAgentId before the per-app
+ // task generator runs strands the marker when the generator returns null.
+ // Pin that both on-demand loops (a) advance the cooldown with
+ // markAppReviewCooldown, NOT markAppReviewStarted, and (b) only bind the
+ // active agent inside an `if (task)` guard after generation.
+ for (const { fnName, src } of [
+ { fnName: 'export async function evaluateTasks', src: GEN_SRC },
+ { fnName: 'async function dequeueNextTask', src: COS_SRC },
+ ]) {
+ const fnBody = extractFnBody(src, src.indexOf(fnName));
+ expect(
+ fnBody,
+ `${fnName} must advance cooldown via markAppReviewCooldown (not the conflated markAppReviewStarted)`
+ ).toMatch(/markAppReviewCooldown\(\s*targetApp\.id\s*\)/);
+ expect(
+ fnBody,
+ `${fnName} must NOT call markAppReviewStarted (conflates cooldown + bind, the #978 bug)`
+ ).not.toMatch(/markAppReviewStarted\(/);
+ expect(
+ fnBody,
+ `${fnName} must bind the active agent only after a task exists`
+ ).toMatch(/if\s*\(\s*task\s*\)\s*\{\s*await\s+bindAppReviewAgent\(\s*targetApp\.id/);
+ }
+ });
+
it('queueEligibleImprovementTasks routes through generateManagedAppImprovementTaskForType', () => {
// Regression guard: a 2026-05-21 incident saw two `plan-task` agents both
// open PRs for the same PLAN.md slug because the queue path was writing
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index e17c0748fb..622e2ff2dc 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -31,7 +31,7 @@ import { getDomainBudgetStatus } from './domainUsage.js';
import { cosEvents, emitLog } from './cosEvents.js';
import { addTask, updateTask, getAllTasks, getCosTasks, firstLine, PRIORITY_VALUES } from './cosTaskStore.js';
import { recordDecision, DECISION_TYPES } from './decisionLog.js';
-import { isAppOnCooldown, markAppReviewStarted, markIdleReviewStarted, getNextAppForReview, loadAppActivity, isAppActivityOnCooldown } from './appActivity.js';
+import { isAppOnCooldown, markAppReviewCooldown, bindAppReviewAgent, markIdleReviewStarted, getNextAppForReview, loadAppActivity, isAppActivityOnCooldown } from './appActivity.js';
import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';
import { getTaskTypeConfidence } from './taskLearning.js';
import { generateProactiveTasks as generateMissionTasks } from './missions.js';
@@ -403,12 +403,18 @@ export async function evaluateTasks(options) {
if (targetApp) {
emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });
+ // Advance the cooldown eagerly (deduped per app per cycle), but defer
+ // binding the active agent until a task is produced — a null result
+ // here must not strand `activeAgentId` (issue #978).
if (!reviewStartedApps.has(targetApp.id)) {
- await markAppReviewStarted(targetApp.id, `on-demand-${Date.now()}`);
+ await markAppReviewCooldown(targetApp.id);
reviewStartedApps.add(targetApp.id);
}
await taskSchedule.recordExecution(`task:${request.taskType}`, targetApp.id);
task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, { skipPreconditions: true });
+ if (task) {
+ await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
+ }
} else {
emitLog('info', `Processing on-demand improvement: ${request.taskType}`, { requestId: request.id });
await taskSchedule.recordExecution(`task:${request.taskType}`);
@@ -678,9 +684,14 @@ export async function generateIdleReviewTask(state) {
const nextApp = await getNextAppForReview(apps, state.config.appReviewCooldownMs);
if (nextApp) {
- // Mark that we're starting an idle review
+ // Mark that we're starting an idle review. Advance the per-app cooldown
+ // eagerly (so this app isn't re-picked on the next idle tick) but do NOT
+ // bind an active agent yet — the task generator below may return null
+ // (no claimable PLAN item, watcher no-op, precondition skip), in which
+ // case binding here would strand `activeAgentId` and leave the app stuck
+ // reading "in review" until stale-agent cleanup (issue #978).
await markIdleReviewStarted();
- await markAppReviewStarted(nextApp.id, `idle-review-${Date.now()}`);
+ await markAppReviewCooldown(nextApp.id);
// Update lastIdleReview timestamp
await withStateLock(async () => {
@@ -690,7 +701,12 @@ export async function generateIdleReviewTask(state) {
});
emitLog('info', `Generating improvement task for ${nextApp.name}`, { appId: nextApp.id });
- return await generateManagedAppImprovementTask(nextApp, state);
+ const idleTask = await generateManagedAppImprovementTask(nextApp, state);
+ // Only bind the active marker once a real task exists.
+ if (idleTask) {
+ await bindAppReviewAgent(nextApp.id, `idle-review-${Date.now()}`);
+ }
+ return idleTask;
}
}