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

feat: type-level consecutive-failure backoff with auto-park + unparseable-as-failure (#2616)

Adam Eivy8059c81acf12
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d3ff52d053..bd9f26fb89 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -85,3 +85,4 @@
- **[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.
- **[issue-2554] Align CoS chrome and scrollbar colors with port design tokens.** The Chief of Staff panel chrome hardcoded `bg-slate-900/60`, `hover:bg-slate-800/80`, the `from-slate-900/80 to-slate-900/40` gradients, and `text-slate-400` — a `slate` surface that ignored the active theme. Those now map to `bg-port-card`/`hover:bg-port-border`/`text-port-text-muted` (the collapse button's `text-gray-500 hover:text-white` also became `text-port-text-muted hover:text-port-text` so its icon stays legible in light themes), so the panel restyles with the selected theme. The global `::-webkit-scrollbar-thumb` (and its `:hover`) dropped their hardcoded `#3a3a3a`/`#4a4a4a` for the opaque, theme-derived `rgb(var(--port-text-muted))` and `rgb(var(--port-text))` — colors that stay high-contrast against the already-tokenized `rgb(var(--port-card))` track in both dark and light themes (an alpha-over-track blend would wash out on light cards, so the opaque muted-text token is used). The unread-count badges in `Layout.jsx` (four sites) and `NotificationDropdown.jsx` swapped `bg-yellow-500 text-black` for `bg-port-warning text-port-on-warning`; the Dashboard server-health glow's `shadow-[0_0_8px_#22c55e]`/`#ef4444` now reference `rgb(var(--port-success))`/`rgb(var(--port-error))`. The Ambient full-screen idle display is intentionally left on its fixed deep-black `bg-[#050505]` (with `text-white` content) — it is a theme-independent ambient/OLED surface, and making the backdrop theme-following would strand its non-tokenized white clock and translucent panels invisibly on light themes. Visual-only token swaps — no logic or layout change; the retokenized surfaces now follow the active theme instead of a fixed palette.
+- **[issue-2616] Add type-level consecutive-failure backoff with auto-park + notification; count unparseable agent output as failure.** The agent engine had no failure memory at the task-*type* level, so a permanently-broken scheduled type (or one whose instances all fail) re-queued on schedule forever — burning provider quota with no backoff, auto-disable, or notification (`failureCount` lived only in per-instance metadata; ROTATION types had no cadence gate at all, returning `shouldRun: true` unconditionally). A new per-type failure ledger now lives on the schedule execution record (`consecutiveFailures`/`lastFailureAt`/`lastErrorCategory`, per app + global) — persisted alongside `lastRun`, so it survives restarts as per-install runtime state (additive, backward-compatible, never synced). `shouldRunTask` applies an escalating failure cooldown (`2^n × base`, capped at a day) to *all* cadence types including ROTATION, so a failing type slows down instead of re-queuing every tick; after 5 consecutive failures the type auto-parks (indefinitely, for every cadence type) and fires a user-facing `AGENT_WARNING` notification naming the type, app, and last error category. A success resets the counter and lifts the park; a manual "Run now" or a config change (`updateTaskInterval`) clears the ledger to unpark. Separately, an LLM run that exits 0 but whose `.agent-done` output is unparseable — previously recorded as a benign completed success, invisible to any failure accounting — now feeds a failure signal into the ledger via the pure `resolveTypeFailureSignal` (an `unparseable-response` hook reason, or a thrown output hook, counts as a failure regardless of exit code; benign hook reasons like `no-proposal`/`duplicate` defer to the exit code). The existing per-instance retry ladder (`MAX_TASK_RETRIES`/`MAX_TOTAL_SPAWNS`) is unchanged. New unit tests cover the backoff math, ledger increment/reset/auto-park/notify/unpark, the ROTATION cooldown/park gates, and the unparseable-as-failure decision.
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index 8fcdb6c7c9..3dbe28126a 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -817,6 +817,46 @@ export function resolveFailedTaskDecision(task, errorAnalysis) {
};
}
+/**
+ * Pure decision for the type-LEVEL failure ledger (#2616), distinct from the
+ * per-instance retry decision above. Given a finished run's exit-code success,
+ * whether the user terminated it, and the programmatic-I/O hook result (if any),
+ * decide what signal to feed the per-type consecutive-failure ledger:
+ *
+ * - `'skip'` — don't touch the ledger (user-terminated run).
+ * - `'success'` — reset the type's failure counter.
+ * - `'failure'` — increment it (with `category`).
+ *
+ * The key case this exists for: a layered-intelligence run that exits 0 but whose
+ * `.agent-done` output was unparseable (`hookResult.outcome.reason ===
+ * 'unparseable-response'`) — or whose hook threw (`hookResult.threw`) — produced
+ * nothing usable, so it's a FAILURE even though the exit code says success. Other
+ * benign hook reasons (no-proposal, duplicate, scope-suppressed) leave the
+ * exit-code verdict intact. Extracted pure so the branching is unit-tested here.
+ *
+ * @returns {{ record: 'skip'|'success'|'failure', category: string|null }}
+ */
+export function resolveTypeFailureSignal({ success, terminatedByUser = false, hookResult = null, errorCategory = null } = {}) {
+ if (terminatedByUser) return { record: 'skip', category: null };
+
+ let failure = !success;
+ let category = errorCategory || 'unknown';
+
+ if (hookResult?.ran) {
+ if (hookResult.threw) {
+ failure = true;
+ category = 'hook-error';
+ } else if (hookResult.outcome?.reason === 'unparseable-response') {
+ failure = true;
+ category = 'unparseable-response';
+ }
+ }
+
+ return failure
+ ? { record: 'failure', category }
+ : { record: 'success', category: null };
+}
+
/**
* Handle task status update after agent failure.
* Tracks retry count and blocks the task after MAX_TASK_RETRIES,
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index 7c3de9633b..9da7b03375 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -8,6 +8,7 @@ vi.mock('./cos.js', () => ({ addTask: vi.fn(), updateTask: vi.fn(), getAllTasks:
import {
analyzeAgentFailure,
resolveFailedTaskDecision,
+ resolveTypeFailureSignal,
maybeCreateInvestigationTask,
createInvestigationTask,
buildInvestigationFingerprint,
@@ -222,6 +223,48 @@ describe('resolveFailedTaskDecision', () => {
});
});
+describe('resolveTypeFailureSignal (#2616)', () => {
+ it('a user-terminated run is skipped (never touches the ledger)', () => {
+ expect(resolveTypeFailureSignal({ success: false, terminatedByUser: true }))
+ .toEqual({ record: 'skip', category: null });
+ // ...even when the exit code says success.
+ expect(resolveTypeFailureSignal({ success: true, terminatedByUser: true }).record).toBe('skip');
+ });
+
+ it('a clean exit with no hook is a success signal', () => {
+ expect(resolveTypeFailureSignal({ success: true })).toEqual({ record: 'success', category: null });
+ });
+
+ it('a failed exit with no hook is a failure signal carrying the error category', () => {
+ expect(resolveTypeFailureSignal({ success: false, errorCategory: 'rate-limit' }))
+ .toEqual({ record: 'failure', category: 'rate-limit' });
+ // No category → 'unknown'.
+ expect(resolveTypeFailureSignal({ success: false }).category).toBe('unknown');
+ });
+
+ it('an exit-0 run whose hook reports unparseable-response counts as a failure', () => {
+ const signal = resolveTypeFailureSignal({
+ success: true,
+ hookResult: { ran: true, outcome: { action: 'no-op', reason: 'unparseable-response' } }
+ });
+ expect(signal).toEqual({ record: 'failure', category: 'unparseable-response' });
+ });
+
+ it('a thrown hook counts as a failure (hook-error) even on a clean exit', () => {
+ const signal = resolveTypeFailureSignal({ success: true, hookResult: { ran: true, threw: true } });
+ expect(signal).toEqual({ record: 'failure', category: 'hook-error' });
+ });
+
+ it('benign hook reasons (no-proposal/duplicate) leave the exit-code verdict intact', () => {
+ for (const reason of ['no-proposal', 'duplicate', 'scope-suppressed', null]) {
+ expect(resolveTypeFailureSignal({ success: true, hookResult: { ran: true, outcome: { reason } } }).record)
+ .toBe('success');
+ }
+ // A hook that didn't run at all (no-op path) also defers to the exit code.
+ expect(resolveTypeFailureSignal({ success: true, hookResult: { ran: false } }).record).toBe('success');
+ });
+});
+
// The actual "create an investigation task or skip it" decision lives in
// maybeCreateInvestigationTask (the sole owner of the API_ACCESS gate). Assert
// the real branch by spying on the store write it ultimately performs.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 7123474f40..84f1be84d3 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -19,7 +19,7 @@ import { isInternalTaskId } from '../lib/taskParser.js';
import { ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';
import { createToolExecution, startExecution, completeExecution, errorExecution } from './toolStateMachine.js';
import { determineLane, acquire, release } from './executionLanes.js';
-import { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalysis.js';
+import { analyzeAgentFailure, resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';
import { createAgentRun, completeAgentRun, checkForTaskCommit } from './agentRunTracking.js';
import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';
import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';
@@ -917,10 +917,37 @@ export async function finalizeAgent({
// isolated from the agent's discarded worktree — the payload is the only
// durable channel out. Errors are caught: a hook failure must not strand the
// rest of finalize. See taskTypeHooks.js + the design plan.
- await dispatchTaskOutputHook({ agentId, task, success, workspacePath }).catch(err => {
+ const hookResult = await dispatchTaskOutputHook({ agentId, task, success, workspacePath }).catch(err => {
emitLog('error', `processTaskOutput hook threw for ${agentId} (${task?.taskType}): ${err.message}`, { agentId, error: err.message });
+ // A thrown hook is a non-success signal for the type ledger (#2616).
+ return { ran: true, threw: true };
});
+ // Type-level consecutive-failure ledger (#2616): feed the per-type
+ // backoff/auto-park in taskSchedule. Only SCHEDULED task types carry
+ // `metadata.analysisType`; user/ad-hoc tasks don't participate. The pure
+ // resolveTypeFailureSignal decides success vs failure vs skip — including the
+ // exit-0-but-unparseable-output case that must count as a failure.
+ const scheduledType = task?.metadata?.analysisType || null;
+ if (scheduledType) {
+ const signal = resolveTypeFailureSignal({
+ success,
+ terminatedByUser,
+ hookResult,
+ errorCategory: errorAnalysis?.category
+ });
+ if (signal.record !== 'skip') {
+ const ledgerAppId = task?.metadata?.app || null;
+ const { recordTaskTypeFailure, recordTaskTypeSuccess } = await import('./taskSchedule.js');
+ const ledgerUpdate = signal.record === 'failure'
+ ? recordTaskTypeFailure(scheduledType, ledgerAppId, { errorCategory: signal.category })
+ : recordTaskTypeSuccess(scheduledType, ledgerAppId);
+ await ledgerUpdate.catch(err => {
+ emitLog('warn', `⚠️ Task-type ledger update failed for ${scheduledType}: ${err.message}`, { taskType: scheduledType, agentId });
+ });
+ }
+ }
+
await processAgentCompletion(agentId, task, success, outputBuffer);
}
@@ -935,10 +962,10 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath })
// task.taskType is the CoS queue category, e.g. 'internal'). A programmatic-I/O
// hook is keyed on the scheduled type.
const taskType = task?.metadata?.analysisType || task?.taskType;
- if (!taskType) return;
+ if (!taskType) return { ran: false };
const { getTaskOutputHook } = await import('./taskTypeHooks.js');
const hook = await getTaskOutputHook(taskType);
- if (!hook) return;
+ if (!hook) return { ran: false };
const cwd = workspacePath || task?.metadata?.repoPath || null;
let payload = null;
@@ -961,7 +988,7 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath })
}
}
- await hook({
+ const outcome = await hook({
appId: task?.metadata?.app || null,
success,
payload,
@@ -969,6 +996,10 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath })
agentId,
task,
});
+ // The outcome's `reason` is what lets finalizeAgent count a "completed" run
+ // that produced nothing usable (`unparseable-response`) as a type-level
+ // failure (#2616) — an exit-0 run whose structured output couldn't be parsed.
+ return { ran: true, outcome };
}
/**
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 15c64cde85..62e96f48a1 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -651,6 +651,10 @@ async function spawnPriority0OnDemand(ctx) {
// reconcile convergence signature so the detector below runs fresh (see
// cos.dequeueNextTask for the full rationale).
await taskSchedule.resetPerpetualForManualRun(request.taskType, targetApp.id);
+ // A manual "Run" also unparks a failure-parked type (#2616): the user
+ // explicitly re-running is an "I've addressed it" signal, so clear the
+ // per-type consecutive-failure ledger for this app.
+ await taskSchedule.clearTaskTypeFailurePark(request.taskType, 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).
@@ -666,6 +670,8 @@ async function spawnPriority0OnDemand(ctx) {
} else {
emitLog('info', `Processing on-demand improvement: ${request.taskType}`, { requestId: request.id });
await taskSchedule.resetPerpetualForManualRun(request.taskType);
+ // Manual re-run unparks a failure-parked type (global scope) — #2616.
+ await taskSchedule.clearTaskTypeFailurePark(request.taskType);
await taskSchedule.recordExecution(`task:${request.taskType}`);
await withStateLock(async () => {
const s = await loadState();
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index c4283902ce..30f789839a 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -76,6 +76,38 @@ const WEEK = 7 * DAY;
// work-detector, when neither `recheckCron` nor `recheckIntervalMs` is set.
const DEFAULT_PERPETUAL_RECHECK_MS = DAY;
+// ── Type-level consecutive-failure backoff (#2616) ────────────────────────────
+// Distinct from the per-INSTANCE retry ladder (MAX_TASK_RETRIES /
+// MAX_TOTAL_SPAWNS in agentErrorAnalysis.js), which blocks a SINGLE task after
+// too many failures. This ledger tracks a task TYPE (per app + global) so a
+// permanently-broken scheduled type slows down and eventually auto-parks instead
+// of burning provider quota on schedule forever. The ledger lives on the
+// execution record alongside `lastRun` (survives restarts; per-install runtime
+// state, never synced).
+export const FAILURE_BACKOFF_BASE_MS = HOUR; // scaled by 2^n (n = consecutiveFailures)
+export const FAILURE_BACKOFF_CAP_MS = DAY; // cap the escalation
+export const FAILURE_PARK_THRESHOLD = 5; // auto-park after N consecutive failures
+
+// The full set of ledger fields, kept as one list so the record/reset/clear
+// paths can't drift from what recordTaskTypeFailure writes.
+const FAILURE_LEDGER_FIELDS = [
+ 'consecutiveFailures',
+ 'lastFailureAt',
+ 'lastErrorCategory',
+ 'failureParkedAt',
+ 'failureParkReason'
+];
+
+/**
+ * Escalating failure cooldown: 2^n × base, capped. n=0 → 0 (no cooldown).
+ * Pure — exported for direct unit testing.
+ */
+export function computeFailureBackoffMs(consecutiveFailures, baseMs = FAILURE_BACKOFF_BASE_MS, capMs = FAILURE_BACKOFF_CAP_MS) {
+ const n = Number(consecutiveFailures) || 0;
+ if (n <= 0) return 0;
+ return Math.min(baseMs * Math.pow(2, n), capMs);
+}
+
/**
* Get learning-adjusted interval for a task type
*/
@@ -659,6 +691,16 @@ export async function updateTaskInterval(taskType, settings) {
// gets the locked value back in its response.
enforceManagedAgentOptions(taskType, schedule.tasks[taskType]);
+ // Config change unparks a failure-parked type (#2616): editing a type's
+ // settings is an explicit "I've addressed the cause" signal, so clear the
+ // consecutive-failure ledger + auto-park (global + every per-app record) so
+ // the type gets a fresh start on its next tick.
+ const topExec = schedule.executions[`task:${taskType}`];
+ if (topExec) {
+ clearFailureLedgerFields(topExec);
+ for (const rec of Object.values(topExec.perApp || {})) clearFailureLedgerFields(rec);
+ }
+
// Globally disabling pr-watcher also drops its execution cooldown so a later
// re-enable baselines on the very next tick rather than waiting out the prior
// 30-min interval — otherwise PRs opened in that delayed window slip past the
@@ -918,6 +960,139 @@ export async function resetPerpetualForManualRun(taskType, appId = null) {
return changed;
}
+// ============================================================
+// Type-level consecutive-failure ledger (#2616)
+// ============================================================
+
+/** Delete every failure-ledger field from a record. Returns true if any changed. */
+function clearFailureLedgerFields(record) {
+ if (!record) return false;
+ let changed = false;
+ for (const field of FAILURE_LEDGER_FIELDS) {
+ if (record[field] !== undefined) { delete record[field]; changed = true; }
+ }
+ return changed;
+}
+
+/**
+ * Surface a user-facing notification when a task type auto-parks. Lazy-imports
+ * the notifications service so taskSchedule has no static dependency on it (and
+ * so the failure path stays free of that I/O until a park actually fires).
+ * Deduped per type+app so a re-park after a manual retry doesn't spam the bell.
+ */
+async function notifyTaskTypeFailurePark(taskType, appId, record) {
+ const { addNotification, exists, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');
+ const dedupeKey = appId ? `${taskType}:${appId}` : taskType;
+ if (await exists(NOTIFICATION_TYPES.AGENT_WARNING, 'failureParkKey', dedupeKey)) return;
+ const scope = appId ? `app ${appId}` : 'global';
+ const category = record.failureParkReason || record.lastErrorCategory || 'unknown';
+ await addNotification({
+ type: NOTIFICATION_TYPES.AGENT_WARNING,
+ title: `Scheduled task "${taskType}" auto-parked after ${record.consecutiveFailures} failures`,
+ description: `The "${taskType}" scheduled task (${scope}) failed ${record.consecutiveFailures} times in a row (last error: ${category}). It is parked and will not re-queue until you retry it or change its config.`,
+ priority: PRIORITY_LEVELS.HIGH,
+ link: '/cos/schedule',
+ metadata: {
+ taskType,
+ appId: appId || null,
+ failureParkKey: dedupeKey,
+ consecutiveFailures: record.consecutiveFailures,
+ lastErrorCategory: category
+ }
+ });
+}
+
+/**
+ * Record a task-type FAILURE into the per-type ledger (per app + global).
+ * Increments `consecutiveFailures`, stamps `lastFailureAt`/`lastErrorCategory`,
+ * and auto-parks (+notifies) once the threshold is crossed. The auto-park is
+ * indefinite — cleared only by a success, a manual retry, or a config change.
+ */
+export async function recordTaskTypeFailure(taskType, appId = null, { errorCategory = null } = {}) {
+ const schedule = await loadSchedule();
+ const record = ensureExecutionRecord(schedule, taskType, appId);
+ record.consecutiveFailures = (Number(record.consecutiveFailures) || 0) + 1;
+ record.lastFailureAt = new Date().toISOString();
+ if (errorCategory) record.lastErrorCategory = errorCategory;
+
+ let justParked = false;
+ if (record.consecutiveFailures >= FAILURE_PARK_THRESHOLD && !record.failureParkedAt) {
+ record.failureParkedAt = new Date().toISOString();
+ record.failureParkReason = errorCategory || record.lastErrorCategory || 'unknown';
+ justParked = true;
+ }
+
+ await saveSchedule(schedule);
+ emitLog(
+ justParked ? 'warn' : 'info',
+ `Task type ${taskType}${appId ? ` (app ${appId})` : ''} failure #${record.consecutiveFailures}${justParked ? ' — AUTO-PARKED' : ''} (${errorCategory || 'unknown'})`,
+ { taskType, appId, consecutiveFailures: record.consecutiveFailures, parked: justParked },
+ '📅 TaskSchedule'
+ );
+
+ if (justParked) {
+ cosEvents.emit('schedule:failure-parked', { taskType, appId, consecutiveFailures: record.consecutiveFailures, reason: record.failureParkReason });
+ await notifyTaskTypeFailurePark(taskType, appId, record).catch((err) => {
+ emitLog('warn', `Failure-park notification failed for ${taskType}: ${err.message}`, { taskType, appId }, '📅 TaskSchedule');
+ });
+ }
+ return record;
+}
+
+/**
+ * Record a task-type SUCCESS: reset the consecutive-failure ledger (and any
+ * auto-park) for this type. No-op (no write) when the ledger is already clean.
+ */
+export async function recordTaskTypeSuccess(taskType, appId = null) {
+ const schedule = await loadSchedule();
+ const record = resolveExecutionRecord(schedule, taskType, appId);
+ if (!clearFailureLedgerFields(record)) return false;
+ await saveSchedule(schedule);
+ emitLog('info', `Task type ${taskType}${appId ? ` (app ${appId})` : ''} succeeded — failure ledger reset`, { taskType, appId }, '📅 TaskSchedule');
+ return true;
+}
+
+/**
+ * Read the failure-park state for a task type (or null when not parked). Mirrors
+ * getPerpetualParkInfo for the failure ledger.
+ */
+export async function getTaskTypeFailureInfo(taskType, appId = null) {
+ const schedule = await loadSchedule();
+ const record = resolveExecutionRecord(schedule, taskType, appId);
+ if (!record) return null;
+ return {
+ consecutiveFailures: Number(record.consecutiveFailures) || 0,
+ lastFailureAt: record.lastFailureAt ?? null,
+ lastErrorCategory: record.lastErrorCategory ?? null,
+ failureParkedAt: record.failureParkedAt ?? null,
+ failureParkReason: record.failureParkReason ?? null
+ };
+}
+
+/**
+ * Clear a task type's failure ledger + auto-park for a manual retry or config
+ * change (unpark). Clears the global record AND every per-app record for the
+ * type when `appId` is null, so a config change resets the whole type; targets a
+ * single app when `appId` is set (a manual per-app "Run now"). Returns true if
+ * anything was cleared.
+ */
+export async function clearTaskTypeFailurePark(taskType, appId = null) {
+ const schedule = await loadSchedule();
+ const top = schedule.executions[executionKey(taskType)];
+ if (!top) return false;
+ let changed = false;
+ if (appId) {
+ changed = clearFailureLedgerFields(top.perApp?.[appId]);
+ } else {
+ changed = clearFailureLedgerFields(top);
+ for (const rec of Object.values(top.perApp || {})) {
+ if (clearFailureLedgerFields(rec)) changed = true;
+ }
+ }
+ if (changed) await saveSchedule(schedule);
+ return changed;
+}
+
/**
* Check if all runAfter dependencies have completed since this task's last run.
* Returns { satisfied, pending } where pending lists unfinished dependency task types.
@@ -1003,6 +1178,20 @@ export async function shouldRunTask(taskType, appId = null) {
? (execution.perApp[appId] || { lastRun: null, count: 0 })
: execution;
+ // Type-level failure auto-park (#2616): a type whose instances failed
+ // FAILURE_PARK_THRESHOLD times in a row is parked for ALL cadence types
+ // (including ROTATION) until a manual retry or config change clears the
+ // ledger. Checked before the cadence switch so it short-circuits every type.
+ if (appExecution.failureParkedAt) {
+ return {
+ shouldRun: false,
+ reason: 'failure-parked',
+ failureParkedAt: appExecution.failureParkedAt,
+ failureParkReason: appExecution.failureParkReason || null,
+ consecutiveFailures: Number(appExecution.consecutiveFailures) || 0
+ };
+ }
+
const now = Date.now();
const lastRun = appExecution.lastRun ? new Date(appExecution.lastRun).getTime() : 0;
const timeSinceLastRun = now - lastRun;
@@ -1173,6 +1362,32 @@ export async function shouldRunTask(taskType, appId = null) {
result = { shouldRun: true, reason: 'unknown-default-rotation' };
}
+ // Escalating failure backoff (#2616): a type with recent consecutive failures
+ // (still below the park threshold) slows down — 2^n × base, capped — instead
+ // of re-queuing every tick. Applies to ALL cadence types, including ROTATION
+ // (which is otherwise `shouldRun: true` unconditionally). Gated on
+ // `lastFailureAt` so a never-failed type is unaffected; a success resets the
+ // ledger via recordTaskTypeSuccess so the backoff lifts immediately.
+ if (result.shouldRun) {
+ const consecutiveFailures = Number(appExecution.consecutiveFailures) || 0;
+ const lastFailure = appExecution.lastFailureAt ? new Date(appExecution.lastFailureAt).getTime() : 0;
+ if (consecutiveFailures > 0 && lastFailure) {
+ const backoffMs = computeFailureBackoffMs(consecutiveFailures);
+ const sinceFailure = now - lastFailure;
+ if (sinceFailure < backoffMs) {
+ result = {
+ shouldRun: false,
+ reason: 'failure-cooldown',
+ consecutiveFailures,
+ failureBackoffMs: backoffMs,
+ nextRunIn: backoffMs - sinceFailure,
+ nextRunAt: new Date(lastFailure + backoffMs).toISOString(),
+ lastErrorCategory: appExecution.lastErrorCategory || null
+ };
+ }
+ }
+ }
+
// If the task would run, check runAfter dependencies — blocked until all enabled deps have run since our last run.
// Disabled deps (globally or for this app) are skipped, since they'll never run.
if (result.shouldRun && interval.runAfter?.length > 0) {
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 81acf751f6..6c379e834e 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -73,6 +73,16 @@ vi.mock('./eventScheduler.js', () => ({
parseCronToPrevRun: vi.fn()
}))
+// Failure-park auto-notification (#2616): recordTaskTypeFailure lazy-imports
+// notifications.js and fires an AGENT_WARNING when a type auto-parks. Mock it so
+// the ledger tests can assert the notification without touching the real store.
+vi.mock('./notifications.js', () => ({
+ addNotification: vi.fn().mockResolvedValue({}),
+ exists: vi.fn().mockResolvedValue(false),
+ NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },
+ PRIORITY_LEVELS: { HIGH: 'high' }
+}))
+
// Use the real isImprovementEnabled implementation; only stub loadState.
// Mocking the helper would let regressions in production logic slip through.
vi.mock('./cosState.js', async () => {
@@ -107,6 +117,14 @@ import {
getPerpetualParkInfo,
getPerpetualSignature,
setPerpetualSignature,
+ recordTaskTypeFailure,
+ recordTaskTypeSuccess,
+ getTaskTypeFailureInfo,
+ clearTaskTypeFailurePark,
+ computeFailureBackoffMs,
+ FAILURE_BACKOFF_BASE_MS,
+ FAILURE_BACKOFF_CAP_MS,
+ FAILURE_PARK_THRESHOLD,
PROMPT_VERSIONS,
DEFAULT_TASK_INTERVALS,
MANAGED_AGENT_OPTIONS,
@@ -131,6 +149,7 @@ import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, clearAllPrWatcherState
import { getLocalParts } from '../lib/timezone.js'
import { getAdaptiveCooldownMultiplier } from './taskLearning.js'
import { parseCronToNextRun, parseCronToPrevRun } from './eventScheduler.js'
+import { addNotification, exists as notificationExists } from './notifications.js'
const mockSchedule = ({ tasks = {}, executions = {}, templates = [] } = {}) => {
readJSONFile.mockResolvedValue({ version: 2, tasks, executions, templates })
@@ -1440,6 +1459,166 @@ describe('taskSchedule', () => {
})
})
+ describe('type-level failure ledger (#2616)', () => {
+ it('computeFailureBackoffMs scales 2^n × base, capped, and 0 for n<=0', () => {
+ expect(computeFailureBackoffMs(0)).toBe(0)
+ expect(computeFailureBackoffMs(-3)).toBe(0)
+ expect(computeFailureBackoffMs(1)).toBe(FAILURE_BACKOFF_BASE_MS * 2)
+ expect(computeFailureBackoffMs(2)).toBe(FAILURE_BACKOFF_BASE_MS * 4)
+ expect(computeFailureBackoffMs(3)).toBe(FAILURE_BACKOFF_BASE_MS * 8)
+ // Large n saturates at the cap.
+ expect(computeFailureBackoffMs(50)).toBe(FAILURE_BACKOFF_CAP_MS)
+ })
+
+ it('recordTaskTypeFailure increments consecutiveFailures + stamps category', async () => {
+ mockSchedule({ tasks: { security: { type: 'rotation', enabled: true } } })
+ const rec = await recordTaskTypeFailure('security', 'app-1', { errorCategory: 'timeout' })
+ expect(rec.consecutiveFailures).toBe(1)
+ expect(rec.lastErrorCategory).toBe('timeout')
+ expect(rec.lastFailureAt).toBeTruthy()
+ expect(rec.failureParkedAt).toBeUndefined()
+ const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
+ expect(saved.executions['task:security'].perApp['app-1'].consecutiveFailures).toBe(1)
+ })
+
+ it('auto-parks + notifies after FAILURE_PARK_THRESHOLD consecutive failures', async () => {
+ mockSchedule({
+ tasks: { security: { type: 'rotation', enabled: true } },
+ executions: { 'task:security': { lastRun: null, count: 0, perApp: {
+ 'app-1': { lastRun: null, count: 0, consecutiveFailures: FAILURE_PARK_THRESHOLD - 1, lastFailureAt: new Date().toISOString() }
+ } } }
+ })
+ const rec = await recordTaskTypeFailure('security', 'app-1', { errorCategory: 'auth-error' })
+ expect(rec.consecutiveFailures).toBe(FAILURE_PARK_THRESHOLD)
+ expect(rec.failureParkedAt).toBeTruthy()
+ expect(rec.failureParkReason).toBe('auth-error')
+ expect(addNotification).toHaveBeenCalledTimes(1)
+ expect(addNotification.mock.calls[0][0]).toMatchObject({
+ type: 'agent_warning',
+ metadata: { taskType: 'security', appId: 'app-1', failureParkKey: 'security:app-1' }
+ })
+ })
+
+ it('does not re-notify (deduped) when a park already exists', async () => {
+ notificationExists.mockResolvedValueOnce(true)
+ mockSchedule({
+ tasks: { security: { type: 'rotation', enabled: true } },
+ executions: { 'task:security': { lastRun: null, count: 0, perApp: {
+ 'app-1': { lastRun: null, count: 0, consecutiveFailures: FAILURE_PARK_THRESHOLD - 1, lastFailureAt: new Date().toISOString() }
+ } } }
+ })
+ await recordTaskTypeFailure('security', 'app-1', { errorCategory: 'auth-error' })
+ expect(addNotification).not.toHaveBeenCalled()
+ })
+
+ it('recordTaskTypeSuccess resets the ledger and returns false when already clean', async () => {
+ mockSchedule({
+ tasks: { security: { type: 'rotation', enabled: true } },
+ executions: { 'task:security': { lastRun: null, count: 0, perApp: {
+ 'app-1': { lastRun: null, count: 0, consecutiveFailures: 3, lastFailureAt: new Date().toISOString(), failureParkedAt: new Date().toISOString(), failureParkReason: 'x' }
+ } } }
+ })
+ expect(await recordTaskTypeSuccess('security', 'app-1')).toBe(true)
+ const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
+ const rec = saved.executions['task:security'].perApp['app-1']
+ expect(rec.consecutiveFailures).toBeUndefined()
+ expect(rec.failureParkedAt).toBeUndefined()
+ // Second call: nothing left to clear.
+ mockSchedule({ tasks: { security: { type: 'rotation', enabled: true } }, executions: { 'task:security': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } } })
+ expect(await recordTaskTypeSuccess('security', 'app-1')).toBe(false)
+ })
+
+ it('getTaskTypeFailureInfo reads back the ledger (0 defaults when absent)', async () => {
+ mockSchedule({
+ tasks: { security: { type: 'rotation', enabled: true } },
+ executions: { 'task:security': { lastRun: null, count: 0, perApp: {
+ 'app-1': { lastRun: null, count: 0, consecutiveFailures: 2, lastErrorCategory: 'timeout' }
+ } } }
+ })
+ expect(await getTaskTypeFailureInfo('security', 'app-1')).toMatchObject({ consecutiveFailures: 2, lastErrorCategory: 'timeout' })
+ expect(await getTaskTypeFailureInfo('security', 'app-2')).toBeNull()
+ })
+
+ it('clearTaskTypeFailurePark(appId=null) clears global + every per-app record', async () => {
+ mockSchedule({
+ tasks: { security: { type: 'rotation', enabled: true } },
+ executions: { 'task:security': {
+ lastRun: null, count: 0, consecutiveFailures: 4, failureParkedAt: new Date().toISOString(),
+ perApp: {
+ 'app-1': { lastRun: null, count: 0, consecutiveFailures: 5, failureParkedAt: new Date().toISOString() },
+ 'app-2': { lastRun: null, count: 0, consecutiveFailures: 1 }
+ }
+ } }
+ })
+ expect(await clearTaskTypeFailurePark('security')).toBe(true)
+ const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
+ const top = saved.executions['task:security']
+ expect(top.consecutiveFailures).toBeUndefined()
+ expect(top.failureParkedAt).toBeUndefined()
+ expect(top.perApp['app-1'].consecutiveFailures).toBeUndefined()
+ expect(top.perApp['app-1'].failureParkedAt).toBeUndefined()
+ expect(top.perApp['app-2'].consecutiveFailures).toBeUndefined()
+ })
+
+ it('shouldRunTask returns failure-parked for a parked ROTATION type', async () => {
+ mockSchedule({
+ tasks: { security: { type: 'rotation', enabled: true } },
+ executions: { 'task:security': { lastRun: null, count: 0, perApp: {
+ 'app-1': { lastRun: null, count: 0, consecutiveFailures: FAILURE_PARK_THRESHOLD, failureParkedAt: new Date().toISOString(), failureParkReason: 'auth-error' }
+ } } }
+ })
+ const res = await shouldRunTask('security', 'app-1')
+ expect(res.shouldRun).toBe(false)
+ expect(res.reason).toBe('failure-parked')
+ expect(res.failureParkReason).toBe('auth-error')
+ })
+
+ it('shouldRunTask applies escalating failure-cooldown to ROTATION (otherwise always-run)', async () => {
+ // 2 consecutive failures → backoff = base*4; last failure just now → in cooldown.
+ mockSchedule({
+ tasks: { security: { type: 'rotation', enabled: true } },
+ executions: { 'task:security': { lastRun: null, count: 0, perApp: {
+ 'app-1': { lastRun: null, count: 0, consecutiveFailures: 2, lastFailureAt: new Date().toISOString(), lastErrorCategory: 'timeout' }
+ } } }
+ })
+ const res = await shouldRunTask('security', 'app-1')
+ expect(res.shouldRun).toBe(false)
+ expect(res.reason).toBe('failure-cooldown')
+ expect(res.consecutiveFailures).toBe(2)
+ expect(res.failureBackoffMs).toBe(FAILURE_BACKOFF_BASE_MS * 4)
+ })
+
+ it('shouldRunTask lets ROTATION run once the failure-cooldown has elapsed', async () => {
+ // 1 failure → backoff = base*2; last failure long ago → cooldown elapsed.
+ const longAgo = new Date(Date.now() - (FAILURE_BACKOFF_CAP_MS + 60_000)).toISOString()
+ mockSchedule({
+ tasks: { security: { type: 'rotation', enabled: true } },
+ executions: { 'task:security': { lastRun: null, count: 0, perApp: {
+ 'app-1': { lastRun: null, count: 0, consecutiveFailures: 1, lastFailureAt: longAgo }
+ } } }
+ })
+ const res = await shouldRunTask('security', 'app-1')
+ expect(res.shouldRun).toBe(true)
+ expect(res.reason).toBe('rotation')
+ })
+
+ it('updateTaskInterval clears the failure ledger (config-change unpark)', async () => {
+ mockSchedule({
+ tasks: { security: { type: 'rotation', enabled: true } },
+ executions: { 'task:security': {
+ lastRun: null, count: 0, consecutiveFailures: 5, failureParkedAt: new Date().toISOString(),
+ perApp: { 'app-1': { lastRun: null, count: 0, consecutiveFailures: 5, failureParkedAt: new Date().toISOString() } }
+ } }
+ })
+ await updateTaskInterval('security', { enabled: true })
+ const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
+ const top = saved.executions['task:security']
+ expect(top.consecutiveFailures).toBeUndefined()
+ expect(top.failureParkedAt).toBeUndefined()
+ expect(top.perApp['app-1'].failureParkedAt).toBeUndefined()
+ })
+ })
+
describe('updateTaskInterval recompute-on-cadence-change', () => {
it('re-derives an existing park when the recheck cadence changes', async () => {
const farFuture = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()