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([issue-2614]): treat failure-blocked tasks as duplicates in CoS queue dedup
[._.]/ Adam Eivyf88883bf66a8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 380b4358ae..8b16c8e9aa 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -69,3 +69,7 @@- **[issue-2541] Add a wall-clock timeout to the AI toolkit's API runner so a hung provider can't leak `activeRuns`.** `runner.js#executeApiRun` attached an `AbortController` but armed no timer, so an upstream that opened the SSE stream then stalled (or never responded) held its controller in `activeRuns` — and thus the run slot — indefinitely; the CLI path (`executeCliRun`) already had an internal timeout, and the Runs-router path invoked the API runner with no outer guard. `executeApiRun` now accepts an optional `timeout` (falling back to `provider.timeout` then a 300s default, mirroring `aiProvider`/`askService`) and arms it before the fetch. A single-settlement gate (`markSettled()`) guarantees exactly one of {timer, response paths} finalizes the run: on timeout the timer aborts the fetch/reader AND independently finalizes the run as an `ERROR_CATEGORIES.TIMEOUT` failure — so a stalled fetch/stream, a provider that never responds, and even a `ensureProviderReady` hook that never reaches the fetch are all bounded, and the failure is recorded as a timeout instead of the raw AbortError's `UNKNOWN`/HTTP 0. Both the Runs router and `promptRunner` now thread their `effectiveTimeout` into the API call (parity with the CLI/TUI branches), so a per-call override — e.g. the importer's long stage timeout — governs the ceiling instead of being cut short by the provider/default fallback; `promptRunner`'s own timer is demoted to a delayed backstop so the runner's timeout wins classification. The non-2xx error-body read now runs with the abort timer still armed (a provider that sends error headers then stalls the body is cancelled, not hung), and the success-path finalization-failure fallback rebuilds metadata from the stored record so run identity survives a write error. New unit tests prove both a hung stream and a hung readiness hook flip `isRunActive` back to false and complete with `errorCategory: 'timeout'`.- **[issue-2553] Size four viewport-height surfaces with `100dvh` (vh fallback) so iOS Safari chrome no longer clips them.** MediaLightbox's fullscreen image (`max-h-[100vh]`), the CollectionPicker popover (`min(360px, calc(100vh - 16px))`), the Layout sidebar flyout (`calc(100vh - 16px)`), and the ChiefOfStaff avatar panel/canvas caps (`min(460px|620px, calc(100vh - 1rem))`) all measured against `100vh`, which iOS Safari inflates by the retractable browser-chrome height — so each spilled under the chrome. New parametrized `max-h-dvh-cap`/`min-h-dvh-cap`/`h-dvh-cap` `@utility` classes in `index.css` size to `100dvh` (the visible dynamic viewport) with a `100vh` fallback gated behind `@supports (height: 1dvh)` — the two-declaration idiom `.h-dvh-screen` uses does not work once the value is wrapped in `var()`/`min()`/`calc()` (both declarations become valid-at-parse-time, so the `dvh` one wins the cascade then computes to invalid rather than restoring the `vh` line), so the `vh` value is the unconditional base and the `dvh` value overrides only where supported. A `--dvh-cap` upper bound and `--dvh-inset` subtracted margin (set per-surface, and per-breakpoint via arbitrary-property utilities for the responsive CoS caps) let one utility serve the plain, capped, and inset variants; the CoS panel keeps its fixed `min-h-[180px]`/`190px` at base/sm/md and only switches to the dvh cap at `lg:`/`xl:`, where the original used a viewport unit. Behavior is byte-identical on engines that predate `dvh`; on iOS Safari the surfaces now stay within the visible viewport.- **[issue-2548] Replace the vacuous agentLifecycle spawn/completion replica tests with imports of real guard helpers.** `agentLifecycle.test.js` re-implemented production logic — local `unfixedSpawn`/`fixedSpawn` copies of the `spawningTasks` dedup flow and a `runCompletion`/`makeCompletionHarness` copy of the completion try/finally — and never imported `spawnAgentForTask`/`handleAgentCompletion`, so they stayed green when production regressed. The two concurrency contracts those replicas modelled are now extracted into `server/services/agentGuards.js`: `withSpawnDedupGuard(spawningTasks, taskId, fn)` (acquire-before-first-await, hold across the whole spawn body incl. the runner-enqueue handoff, release in `finally`, `SPAWN_DEDUP_SKIP` on a concurrent duplicate) and `withMapEntryCleanup(map, key, fn)` (delete the `runnerAgents` entry in `finally` even when a completion step throws). `spawnAgentForTask` now wraps `runAgentSpawn` in the former (dropping six inline `spawningTasks.delete` sites), and `handleAgentCompletion` wraps its body in the latter — so the tests drive the exact code production runs. The late-delete race that spawned a second agent for the same task id is now a behavioral test against the real guard, not a hand-copied one; the remaining source-scan tests were trimmed to non-negotiable orderings (the handedOff pre-spawn/post-handoff split, the #1563 claim/register ordering, the #989 marker release, the #2243 runner env merge) plus two wiring guards that pin the delegation. `cos.test.js` already drove the real `createDequeueCapacity`/`isMissionTierEligible`/`isIdleTierEligible` exports after #2530, so it was left as-is. New `agentGuards.test.js` unit-tests both helpers in isolation.++## CoS self-learning reliability++- **[issue-2614] Failing scheduled tasks no longer pile up duplicates** — a task blocked by repeated failures now counts as "already queued," so the same improvement task isn't re-created every cycle.diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 15c64cde85..6553728821 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -1160,48 +1160,85 @@ export async function generateIdleReviewTask(state) {}/**- * Queue eligible self-improvement and app improvement tasks as system tasks- * Called during every evaluation to ensure system tasks are queued even when user tasks exist- * Tasks are queued to COS-TASKS.md and will be picked up in Priority 2+ * Build the dedup sets `queueEligibleImprovementTasks` uses to decide whether+ * an improvement slot is already occupied.+ *+ * Active (pending/in_progress) tasks occupy both their per-type slot and the+ * per-app "one improvement at a time" cap. Blocked tasks ALSO occupy their+ * per-type slot regardless of blockedCategory (#2614): before this, only+ * `user-terminated` blocked tasks counted, so a task blocked by repeated+ * failures (max-retries, max-spawns, provider-config, unknown, …) was+ * invisible to dedup and the generator minted an identical duplicate every+ * cadence tick — nothing reaps blocked tasks, so the pile grew unbounded.+ * Failure-blocked tasks (blocked with any category except `user-terminated`)+ * also count toward the per-app cap — the retry path is unblocking the+ * existing task, not creating a new one. `user-terminated` keeps its original+ * scope (per-type slot only) so an intentional kill of one type doesn't+ * freeze the whole app's improvement rotation.+ *+ * `blockedTaskTypes` / `appsWithBlockedImprovement` mirror which entries came+ * from blocked tasks so the caller can log a visible skip reason instead of+ * silently suppressing generation.+ *+ * `ignoreTaskId` excludes one task from every set — used by the perpetual+ * drain-on-completion refill, where the just-completed task is still+ * `in_progress` on disk (agent:completed fires before updateTask finalizes+ * it). Without it the completing task would make its own app look busy and+ * block the next perpetual run.*/-export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId = null } = {}) {- const { getNextTaskType, recordExecution } = await import('./taskSchedule.js');-- if (!isImprovementEnabled(state)) return;-- // Get existing pending/in_progress system tasks to avoid duplicates- // Also skip task types where a user-terminated blocked task exists (user intentionally killed it)- // `ignoreTaskId` excludes one task from both the per-app "already busy" cap and- // the per-type dedup set — used by the perpetual drain-on-completion refill,- // where the just-completed task is still `in_progress` on disk (agent:completed- // fires before updateTask finalizes it). Without it the completing task would- // make its own app look busy and block the next perpetual run. The same id is- // forwarded to addTask below so its disk-level duplicate scan ignores it too.- const existingTasks = cosTaskData.tasks || [];+export function buildImprovementDedupSets(existingTasks, { ignoreTaskId = null } = {}) {const existingTaskTypes = new Set();- // Apps that already have *any* pending/in_progress improvement task. We cap each- // app at one queued improvement at a time to avoid a fan-out where multiple- // improvement types pile up faster than the per-app cooldown can drain them.+ // Apps that already have *any* pending/in_progress/failure-blocked improvement+ // task. We cap each app at one queued improvement at a time to avoid a fan-out+ // where multiple improvement types pile up faster than the per-app cooldown+ // can drain them.const appsWithPendingImprovement = new Set();+ const blockedTaskTypes = new Set();+ const appsWithBlockedImprovement = new Set();for (const task of existingTasks) {if (task.id === ignoreTaskId) continue;const isActive = task.status === 'pending' || task.status === 'in_progress';- const isUserTerminated = task.status === 'blocked' && task.metadata?.blockedCategory === 'user-terminated';- if (isActive || isUserTerminated) {+ const isBlocked = task.status === 'blocked';+ const isFailureBlocked = isBlocked && task.metadata?.blockedCategory !== 'user-terminated';+ if (isActive || isBlocked) {const analysisType = task.metadata?.analysisType ||task.metadata?.selfImprovementType ||task.description?.match(/\[(?:self-improvement|improvement)\]\s*(\w[\w-]*)/i)?.[1];const appId = task.metadata?.app;if (analysisType) {- existingTaskTypes.add(appId ? `app:${appId}:${analysisType}` : analysisType);+ const taskKey = appId ? `app:${appId}:${analysisType}` : analysisType;+ existingTaskTypes.add(taskKey);+ if (isBlocked) blockedTaskTypes.add(taskKey);}}- if (isActive && task.metadata?.app && !isRecoveryTask(task)) {+ if ((isActive || isFailureBlocked) && task.metadata?.app && !isRecoveryTask(task)) {appsWithPendingImprovement.add(task.metadata.app);+ if (isFailureBlocked) appsWithBlockedImprovement.add(task.metadata.app);}}+ return { existingTaskTypes, appsWithPendingImprovement, blockedTaskTypes, appsWithBlockedImprovement };+}++/**+ * Queue eligible self-improvement and app improvement tasks as system tasks+ * Called during every evaluation to ensure system tasks are queued even when user tasks exist+ * Tasks are queued to COS-TASKS.md and will be picked up in Priority 2+ */+export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId = null } = {}) {+ const { getNextTaskType, recordExecution } = await import('./taskSchedule.js');++ if (!isImprovementEnabled(state)) return;++ // Existing active AND blocked system tasks feed the dedup sets — see+ // buildImprovementDedupSets for the occupancy semantics (#2614). The same+ // `ignoreTaskId` is forwarded to addTask below so its disk-level duplicate+ // scan ignores it too.+ const existingTasks = cosTaskData.tasks || [];+ const { existingTaskTypes, appsWithPendingImprovement, blockedTaskTypes, appsWithBlockedImprovement } =+ buildImprovementDedupSets(existingTasks, { ignoreTaskId });+let queued = 0;// Load the activity snapshot ONCE before the per-app loop. Both the@@ -1223,7 +1260,11 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore// until the current task drains, otherwise they queue faster than they// can run (per-project concurrency limit + cooldown after each completion).if (appsWithPendingImprovement.has(app.id)) {- emitLog('debug', `App ${app.name} already has a pending improvement task — skipping queue`);+ if (appsWithBlockedImprovement.has(app.id)) {+ emitLog('info', `⛔ Skipping improvement queue for ${app.name}: a failure-blocked improvement task occupies the app slot — resolve or delete it to resume`, { appId: app.id });+ } else {+ emitLog('debug', `App ${app.name} already has a pending improvement task — skipping queue`);+ }continue;}@@ -1268,7 +1309,11 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoreconst taskKey = `app:${app.id}:${nextType}`;if (existingTaskTypes.has(taskKey)) {- emitLog('debug', `Improvement task ${nextType} for ${app.name} already queued`);+ if (blockedTaskTypes.has(taskKey)) {+ emitLog('info', `⛔ Skipping ${nextType} for ${app.name}: a blocked task of this type already exists — resolve or delete it to resume`, { appId: app.id });+ } else {+ emitLog('debug', `Improvement task ${nextType} for ${app.name} already queued`);+ }continue;}diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex c345353b20..70a0141d50 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -28,7 +28,7 @@ vi.mock('./codeReview.js', async (importActual) => ({getCodeReviewDefaults: vi.fn(async () => ({ reviewers: ['copilot'], usernames: ['alice'], optionalReviewers: [] })),}));-import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitOnDemandEmpty, buildJiraTicketTask } from './cosTaskGenerator.js';+import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitOnDemandEmpty, buildJiraTicketTask, buildImprovementDedupSets } from './cosTaskGenerator.js';import { cosEvents } from './cosEvents.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';@@ -560,3 +560,92 @@ describe('emitOnDemandEmpty', () => {expect(body).toMatch(/layeredIntelligence\?\.lastRunReason/);});});++describe('buildImprovementDedupSets (#2614 — failure-blocked tasks occupy their slot)', () => {+ const liTask = (over = {}, meta = {}) => ({+ id: 'sys-t1',+ status: 'pending',+ description: '[Improvement: App One] Layered Intelligence',+ metadata: { app: 'app-1', analysisType: 'layered-intelligence', ...meta },+ ...over+ });++ it('an active (pending) task occupies its type slot and the per-app cap, unflagged as blocked', () => {+ const sets = buildImprovementDedupSets([liTask()]);+ expect(sets.existingTaskTypes.has('app:app-1:layered-intelligence')).toBe(true);+ expect(sets.appsWithPendingImprovement.has('app-1')).toBe(true);+ expect(sets.blockedTaskTypes.size).toBe(0);+ expect(sets.appsWithBlockedImprovement.size).toBe(0);+ });++ it('a failure-blocked task occupies its type slot AND the per-app cap, flagged for logging', () => {+ // Pre-fix, a task blocked with a failure category counted toward NEITHER+ // set, so the generator minted an identical duplicate every cadence tick.+ const sets = buildImprovementDedupSets([+ liTask({ status: 'blocked' }, { blockedCategory: 'max-retries' })+ ]);+ expect(sets.existingTaskTypes.has('app:app-1:layered-intelligence')).toBe(true);+ expect(sets.appsWithPendingImprovement.has('app-1')).toBe(true);+ expect(sets.blockedTaskTypes.has('app:app-1:layered-intelligence')).toBe(true);+ expect(sets.appsWithBlockedImprovement.has('app-1')).toBe(true);+ });++ it('a blocked task with NO blockedCategory counts as failure-blocked', () => {+ const sets = buildImprovementDedupSets([liTask({ status: 'blocked' })]);+ expect(sets.existingTaskTypes.has('app:app-1:layered-intelligence')).toBe(true);+ expect(sets.appsWithPendingImprovement.has('app-1')).toBe(true);+ });++ it('a user-terminated blocked task occupies ONLY its type slot (semantics unchanged)', () => {+ // An intentional kill of one type must not freeze the whole app's rotation.+ const sets = buildImprovementDedupSets([+ liTask({ status: 'blocked' }, { blockedCategory: 'user-terminated' })+ ]);+ expect(sets.existingTaskTypes.has('app:app-1:layered-intelligence')).toBe(true);+ expect(sets.blockedTaskTypes.has('app:app-1:layered-intelligence')).toBe(true);+ expect(sets.appsWithPendingImprovement.size).toBe(0);+ expect(sets.appsWithBlockedImprovement.size).toBe(0);+ });++ it('a resolved (completed) task re-opens the slot — occupies nothing', () => {+ const sets = buildImprovementDedupSets([liTask({ status: 'completed' })]);+ expect(sets.existingTaskTypes.size).toBe(0);+ expect(sets.appsWithPendingImprovement.size).toBe(0);+ expect(sets.blockedTaskTypes.size).toBe(0);+ expect(sets.appsWithBlockedImprovement.size).toBe(0);+ });++ it('ignoreTaskId excludes that task from every set', () => {+ const sets = buildImprovementDedupSets(+ [liTask({ status: 'blocked' }, { blockedCategory: 'max-retries' })],+ { ignoreTaskId: 'sys-t1' }+ );+ expect(sets.existingTaskTypes.size).toBe(0);+ expect(sets.appsWithPendingImprovement.size).toBe(0);+ });++ it('recovery tasks never count toward the per-app cap, blocked or not', () => {+ const sets = buildImprovementDedupSets([+ liTask({ status: 'blocked' }, { blockedCategory: 'max-retries', isRecovery: true })+ ]);+ expect(sets.appsWithPendingImprovement.size).toBe(0);+ // ...but the type slot is still held so the same recovery type doesn't dupe.+ expect(sets.existingTaskTypes.has('app:app-1:layered-intelligence')).toBe(true);+ });++ it('falls back to the description [improvement] tag when metadata has no analysis type', () => {+ const sets = buildImprovementDedupSets([{+ id: 'sys-t2',+ status: 'blocked',+ description: '[improvement] performance for the app',+ metadata: { app: 'app-2', blockedCategory: 'unknown' }+ }]);+ expect(sets.existingTaskTypes.has('app:app-2:performance')).toBe(true);+ });++ it('queueEligibleImprovementTasks derives its dedup sets from the shared helper', () => {+ // Source-pinned: the queue path must consume buildImprovementDedupSets so+ // its occupancy semantics can't silently drift from the tested helper.+ expect(GEN_SRC).toMatch(/buildImprovementDedupSets\(existingTasks/);+ });+});diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex dd35b79ee6..f246c45969 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -187,7 +187,7 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore}// Reject duplicate: same first-line description AND same target app already- // pending or in_progress. The `metadata.app` scope matters — the same+ // pending, in_progress, or blocked. The `metadata.app` scope matters — the same// description against two different apps is two different pieces of work// (e.g. "fix the failing test" in PortOS vs in BookLoom), and collapsing// them silently drops the second dispatch.@@ -212,14 +212,20 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore// improvement-check timer firing close together) each add an identical// `[Improvement: PortOS] …` task, producing the overlapping duplicate runs.const targetApp = taskData.app ?? taskData.metadata?.app ?? null;+ // Blocked tasks count as duplicates too (#2614): a task blocked by repeated+ // failures (max-retries, max-spawns, provider-config, …) still occupies its+ // slot — the retry path is unblocking the existing task, not minting a new+ // identical one. Before this, a persistently-failing scheduled type piled up+ // one blocked duplicate per cadence tick, forever (nothing reaps blocked+ // tasks automatically).const duplicate = tasks.find(t =>t.id !== ignoreTaskId &&- (t.status === 'pending' || t.status === 'in_progress') &&+ (t.status === 'pending' || t.status === 'in_progress' || t.status === 'blocked') &&firstLine(t.description).toLowerCase() === normalizedDesc &&(t.metadata?.app || null) === targetApp);if (duplicate) {- console.log(`⚠️ Duplicate task rejected: "${normalizedDesc.substring(0, 60)}" matches ${duplicate.id}`);+ console.log(`⚠️ Duplicate task rejected: "${normalizedDesc.substring(0, 60)}" matches ${duplicate.id}${duplicate.status === 'blocked' ? ` (blocked: ${duplicate.metadata?.blockedCategory || 'unknown'})` : ''}`);return { ...duplicate, duplicate: true };}diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 77733f4c1b..ac721e1848 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -256,6 +256,37 @@ describe('cosTaskStore.addTask', () => {expect(tasks.filter(t => firstLine(t.description) === 'shared raw')).toHaveLength(2);});+ it('rejects a duplicate of a failure-blocked task (#2614)', async () => {+ // A task blocked by repeated failures still occupies its slot — without+ // this, a persistently-failing scheduled type minted one identical blocked+ // duplicate per cadence tick, forever.+ const first = await addTask({ description: 'keeps failing', app: 'portos', id: 'sys-fail' }, 'internal');+ await updateTask(first.id, { status: 'blocked', metadata: { blockedCategory: 'max-retries' } }, 'internal');+ const second = await addTask({ description: 'keeps failing', app: 'portos' }, 'internal');+ expect(second.duplicate).toBe(true);+ expect(second.id).toBe(first.id);+ const { tasks } = await getCosTasks();+ expect(tasks.filter(t => firstLine(t.description) === 'keeps failing')).toHaveLength(1);+ });++ it('rejects a duplicate of a user-terminated blocked task (#2614)', async () => {+ const first = await addTask({ description: 'killed on purpose', app: 'portos', id: 'sys-killed' }, 'internal');+ await updateTask(first.id, { status: 'blocked', metadata: { blockedCategory: 'user-terminated' } }, 'internal');+ const second = await addTask({ description: 'killed on purpose', app: 'portos' }, 'internal');+ expect(second.duplicate).toBe(true);+ });++ it('resolving a blocked task re-opens the slot for an identical task (#2614)', async () => {+ const first = await addTask({ description: 'retry me', app: 'portos', id: 'sys-retry' }, 'internal');+ await updateTask(first.id, { status: 'blocked', metadata: { blockedCategory: 'max-retries' } }, 'internal');+ // Completed no longer occupies the slot...+ await updateTask(first.id, { status: 'completed' }, 'internal');+ const second = await addTask({ description: 'retry me', app: 'portos', id: 'sys-retry-2' }, 'internal');+ expect(second.duplicate).toBeUndefined();+ const { tasks } = await getCosTasks();+ expect(tasks.filter(t => firstLine(t.description) === 'retry me')).toHaveLength(2);+ });+it('ignoreTaskId excludes one in-flight task from the dedup scan (perpetual drain-on-completion)', async () => {// The just-completed perpetual task is still in_progress on disk when the// refill re-queues an identical first-line for the same app. Passing its id