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: reap resolved failure/investigation tasks + complete learning reset (#2619)

Adam Eivy8fa3e314effe
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d1370b7323..c466e2cc90 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,7 @@
- **[issue-2620] Layered Intelligence stops re-proposing finished work** — completed plan items stay recognized as done, and proposal outcomes now distinguish merged, rejected, and abandoned instead of counting every closed issue as merged.
- **[issue-2617] Task learning forgives fixed problems** — scheduling, model-routing, and self-diagnostics decisions now weigh recent runs instead of lifetime totals, so a task type recovers as soon as it starts succeeding again.
+- **[issue-2619] Self-heal cleanup after a fixed failure storm** — a health-tick reaper now auto-expires stale failure-blocked tasks (older than 14 days) and investigation tasks whose origin is gone/completed via a federation-safe status flip (never deletion); resetting a task type's learning now also purges its stale failure-signature samples and correlation-window rows; failure signatures are age-windowed (30 days) so an outage-era sample stops steering routing; and a poor-lifetime task type whose recent window is clean is now auto-rehabilitated even while it keeps running (not just when idle).
- **[issue-2615] One investigation per failure cause, not one per failure** — repeated agent failures now dedupe into a single investigation task, with an hourly cap and no investigations-of-investigations.
- **[issue-2621] Feature brainstorming remembers rejected ideas** — the feature-ideas task now checks REJECTED.md and previously closed-unmerged proposals before suggesting, so declined ideas stop coming back.
diff --git a/server/services/cos.js b/server/services/cos.js
index cc00daa965..16ef299250 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -54,8 +54,8 @@ export { runHealthCheck, getHealthStatus };
// backward compat with `import * as cos` and the cos route handlers. The store
// emits `tasks:changed`; init() below turns that into tryImmediateSpawn /
// 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, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck } from './cosTaskStore.js';
-export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck };
+import { firstLine, PRIORITY_VALUES, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';
+export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };
import { ensureInstanceId } from './instances.js';
import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';
@@ -278,8 +278,18 @@ export async function start() {
if (archived > 0) {
emitLog('info', `📦 Auto-archived ${archived} stale agent(s) from state`);
}
+ // Reap resolved failure artifacts (stale failure-blocked tasks +
+ // investigations whose origin is gone/completed) via federation-safe
+ // status flip — never deletion (#2619). Bounded per tick by the store.
+ const swept = await sweepResolvedFailureTasks().catch((err) => {
+ console.warn(`⚠️ sweepResolvedFailureTasks failed: ${err?.message || err}`);
+ return { reaped: 0 };
+ });
+ if (swept.reaped > 0) {
+ emitLog('info', `🧹 Auto-expired ${swept.reaped} resolved failure task(s) (${swept.staleBlocks} block(s), ${swept.investigations} investigation(s))`);
+ }
},
- metadata: { description: 'CoS health check + orphan cleanup + agent archival' }
+ metadata: { description: 'CoS health check + orphan cleanup + agent archival + failure-artifact reaper' }
});
// Performance summary (10 min)
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 8b61355ec0..37aa44e595 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -24,6 +24,7 @@ import { mergeTaskLists } from './cosTaskMerge.js';
import { canChallenge, getChallengeCount, buildChallengePatch, buildChallengeResolutionPatch, classifyRecheckOutcome, MAX_CHALLENGES_PER_TASK } from './cosChallenge.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { runLocalCodeReview, getCodeReviewDefaults } from './codeReview.js';
+import { isTruthyMeta } from './agentState.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
@@ -516,6 +517,143 @@ export async function deleteTask(taskId, taskType = 'user') {
});
}
+// ── Stale failure-artifact reaper (issue #2619) ──────────────────────────────
+//
+// After a failure storm is fixed, nothing retired what it left behind: tasks
+// parked in `blocked` by a failure category, and the `[Auto] Investigate agent
+// failure` tasks filed against them. They persisted indefinitely and stayed
+// input to every generator/learning read. The sweep below runs on the CoS
+// health tick and resolves them via STATUS FLIP (→ completed + a `resolution:
+// 'auto-expired'` marker), NEVER deletion: LWW federation sync does not
+// propagate deletions, so a delete just resurrects from any peer still holding
+// the row.
+
+// Default age a failure-blocked task must exceed before it is auto-expired.
+export const DEFAULT_FAILURE_TASK_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000; // 14 days
+
+// Max tasks the reaper flips in a single sweep — bounded so one tick can't fan
+// out an unbounded burst of writes/`tasks:changed` events after a large storm.
+export const DEFAULT_REAP_LIMIT = 50;
+
+// Blocked categories that encode USER INTENT or an OPEN user decision, not a
+// stale failure artifact — the reaper leaves these alone. Everything else with a
+// `blockedCategory` is a failure-path block and therefore reapable.
+const NON_REAPABLE_BLOCKED_CATEGORIES = new Set([
+ 'user-terminated', // user explicitly stopped the agent
+ 'agent-paused', // user paused; resumable on demand
+ 'challenge-escalation' // parked awaiting the user's arbitration
+]);
+
+// Durable marker + legacy-headline fallback for an investigation task. Kept
+// local (not imported from agentErrorAnalysis.js) to avoid a cosTaskStore ↔
+// cos.js ↔ agentErrorAnalysis import cycle; the headline prefix is the one
+// signal present on BOTH new and pre-#2615 investigation tasks.
+const INVESTIGATION_HEADLINE_PREFIX = '[Auto] Investigate agent failure';
+const isInvestigationTaskLocal = (task) =>
+ isTruthyMeta(task?.metadata?.isInvestigation) ||
+ (typeof task?.description === 'string' && task.description.trimStart().startsWith(INVESTIGATION_HEADLINE_PREFIX));
+
+/**
+ * Age (ms) of a failure-blocked task, read from the most specific timestamp it
+ * carries. Returns null when the task is not a reapable failure block, or when
+ * it has no parseable timestamp — an undated block is never reaped (we can't
+ * prove it is old, so leaving it is the safe default). Pure.
+ */
+export function blockedFailureAgeMs(task, now = Date.now()) {
+ if (task?.status !== 'blocked') return null;
+ const category = task.metadata?.blockedCategory;
+ if (!category || NON_REAPABLE_BLOCKED_CATEGORIES.has(category)) return null;
+ const stampedAt = task.metadata?.blockedAt
+ || task.metadata?.lastFailureAt
+ || task.metadata?.updatedAt;
+ const t = Date.parse(stampedAt);
+ if (!Number.isFinite(t)) return null;
+ return Math.max(0, now - t);
+}
+
+/** True when a failure-blocked task is old enough to auto-expire. Pure. */
+export function isReapableBlockedFailure(task, { now = Date.now(), maxAgeMs = DEFAULT_FAILURE_TASK_MAX_AGE_MS } = {}) {
+ const age = blockedFailureAgeMs(task, now);
+ return age !== null && age >= maxAgeMs;
+}
+
+/**
+ * True when an investigation task's originating task(s) are all resolved —
+ * absent (already reaped/deleted) or in a terminal `completed` status — so the
+ * investigation no longer tracks any live failure. Requires a known originating
+ * link (`metadata.affectedTasks`); a legacy investigation with no link is left
+ * alone (we can't prove its cause is resolved). Pure.
+ *
+ * @param {object} task the candidate investigation task
+ * @param {Map} tasksById id → task across BOTH queues
+ */
+export function isReapableInvestigation(task, tasksById) {
+ if (!isInvestigationTaskLocal(task)) return false;
+ if (task.status === 'completed') return false; // already terminal
+ const affected = Array.isArray(task.metadata?.affectedTasks) ? task.metadata.affectedTasks : [];
+ if (affected.length === 0) return false;
+ return affected.every((id) => {
+ const origin = tasksById?.get(id);
+ return !origin || origin.status === 'completed';
+ });
+}
+
+/**
+ * Sweep resolved failure artifacts and auto-expire them via status flip (#2619).
+ *
+ * Two categories, both resolved to `completed` with a `resolution: 'auto-expired'`
+ * marker (never deleted — federation-safe): (1) tasks parked in `blocked` by a
+ * failure `blockedCategory` older than `maxAgeMs`, and (2) `[Auto] Investigate
+ * agent failure` tasks whose originating task(s) are gone/completed. Bounded to
+ * `limit` flips per call and single-line-logged. Runs off the health tick.
+ *
+ * @param {{ now?:number, maxAgeMs?:number, limit?:number }} [opts]
+ * @returns {Promise<{ reaped:number, staleBlocks:number, investigations:number }>}
+ */
+export async function sweepResolvedFailureTasks({
+ now = Date.now(),
+ maxAgeMs = DEFAULT_FAILURE_TASK_MAX_AGE_MS,
+ limit = DEFAULT_REAP_LIMIT
+} = {}) {
+ const { user, cos } = await getAllTasks();
+ const userTasks = user?.tasks || [];
+ const cosTasks = cos?.tasks || [];
+ const tasksById = new Map([...userTasks, ...cosTasks].map((t) => [t.id, t]));
+
+ // Collect targets across both queues, tagging each with its file type so the
+ // flip writes back to the right markdown store. Bounded by `limit`.
+ const targets = [];
+ for (const [type, list] of [['user', userTasks], ['internal', cosTasks]]) {
+ for (const task of list) {
+ const reason = isReapableBlockedFailure(task, { now, maxAgeMs })
+ ? 'stale-failure-block'
+ : (isReapableInvestigation(task, tasksById) ? 'investigation-resolved' : null);
+ if (reason) targets.push({ task, type, reason });
+ if (targets.length >= limit) break;
+ }
+ if (targets.length >= limit) break;
+ }
+
+ if (targets.length === 0) return { reaped: 0, staleBlocks: 0, investigations: 0 };
+
+ let staleBlocks = 0;
+ let investigations = 0;
+ for (const { task, type, reason } of targets) {
+ const updated = await updateTask(task.id, {
+ status: 'completed',
+ metadata: { resolution: 'auto-expired', autoExpiredReason: reason, autoExpiredAt: new Date(now).toISOString() }
+ }, type, { now });
+ if (updated?.error) continue;
+ if (reason === 'stale-failure-block') staleBlocks++; else investigations++;
+ }
+
+ const reaped = staleBlocks + investigations;
+ if (reaped > 0) {
+ console.log(`🧹 Reaped ${reaped} resolved failure task(s): ${staleBlocks} stale block(s), ${investigations} investigation(s)`);
+ }
+ return { reaped, staleBlocks, investigations };
+}
+
/**
* Reorder user tasks based on an array of task IDs
*/
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 3153c30aea..2b3738d77f 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -73,7 +73,12 @@ import {
mergePeerTasks,
challengeTask,
resolveTaskChallenge,
- resolveTaskChallengeWithRecheck
+ resolveTaskChallengeWithRecheck,
+ blockedFailureAgeMs,
+ isReapableBlockedFailure,
+ isReapableInvestigation,
+ sweepResolvedFailureTasks,
+ DEFAULT_FAILURE_TASK_MAX_AGE_MS
} from './cosTaskStore.js';
import { MAX_TOTAL_SPAWNS } from '../lib/cosValidation.js';
@@ -622,6 +627,165 @@ describe('cosTaskStore.mergePeerTasks', () => {
});
});
+describe('cosTaskStore — stale failure-artifact reaper (#2619)', () => {
+ const NOW = Date.parse('2026-06-25T12:00:00.000Z');
+ const daysAgo = (n) => new Date(NOW - n * 24 * 60 * 60 * 1000).toISOString();
+
+ describe('blockedFailureAgeMs / isReapableBlockedFailure (pure)', () => {
+ const blocked = (category, blockedAt) => ({ status: 'blocked', metadata: { blockedCategory: category, blockedAt } });
+
+ it('returns null for a non-blocked task', () => {
+ expect(blockedFailureAgeMs({ status: 'pending', metadata: { blockedCategory: 'max-retries', blockedAt: daysAgo(30) } }, NOW)).toBeNull();
+ });
+
+ it('returns null when there is no blockedCategory', () => {
+ expect(blockedFailureAgeMs({ status: 'blocked', metadata: { blockedAt: daysAgo(30) } }, NOW)).toBeNull();
+ });
+
+ it('leaves user-intent / open-decision categories alone', () => {
+ for (const cat of ['user-terminated', 'agent-paused', 'challenge-escalation']) {
+ expect(blockedFailureAgeMs(blocked(cat, daysAgo(30)), NOW)).toBeNull();
+ expect(isReapableBlockedFailure(blocked(cat, daysAgo(30)), { now: NOW })).toBe(false);
+ }
+ });
+
+ it('computes age from blockedAt and reaps only past the threshold', () => {
+ expect(blockedFailureAgeMs(blocked('max-retries', daysAgo(20)), NOW)).toBe(20 * 24 * 60 * 60 * 1000);
+ expect(isReapableBlockedFailure(blocked('max-retries', daysAgo(20)), { now: NOW })).toBe(true);
+ expect(isReapableBlockedFailure(blocked('max-retries', daysAgo(10)), { now: NOW })).toBe(false);
+ });
+
+ it('falls back to lastFailureAt then updatedAt when blockedAt is absent', () => {
+ expect(blockedFailureAgeMs({ status: 'blocked', metadata: { blockedCategory: 'provider-config', lastFailureAt: daysAgo(20) } }, NOW)).toBe(20 * 24 * 60 * 60 * 1000);
+ expect(blockedFailureAgeMs({ status: 'blocked', metadata: { blockedCategory: 'provider-config', updatedAt: daysAgo(20) } }, NOW)).toBe(20 * 24 * 60 * 60 * 1000);
+ });
+
+ it('never reaps an undated block (cannot prove it is old)', () => {
+ expect(blockedFailureAgeMs({ status: 'blocked', metadata: { blockedCategory: 'max-retries' } }, NOW)).toBeNull();
+ expect(isReapableBlockedFailure({ status: 'blocked', metadata: { blockedCategory: 'max-retries', blockedAt: 'not-a-date' } }, { now: NOW })).toBe(false);
+ });
+ });
+
+ describe('isReapableInvestigation (pure)', () => {
+ const investigation = (overrides = {}) => ({
+ status: 'pending',
+ description: '[Auto] Investigate agent failure [fp]: boom',
+ metadata: { isInvestigation: true, affectedTasks: ['task-a'] },
+ ...overrides
+ });
+
+ it('reaps when every originating task is completed or gone', () => {
+ const byId = new Map([['task-a', { id: 'task-a', status: 'completed' }]]);
+ expect(isReapableInvestigation(investigation(), byId)).toBe(true);
+ // absent origin (already reaped/deleted) also counts as resolved
+ expect(isReapableInvestigation(investigation(), new Map())).toBe(true);
+ });
+
+ it('does not reap while any originating task is still live', () => {
+ const byId = new Map([['task-a', { id: 'task-a', status: 'blocked' }]]);
+ expect(isReapableInvestigation(investigation(), byId)).toBe(false);
+ });
+
+ it('detects investigations by the legacy headline when the marker is absent', () => {
+ const legacy = { status: 'pending', description: '[Auto] Investigate agent failure: legacy', metadata: { affectedTasks: ['task-a'] } };
+ expect(isReapableInvestigation(legacy, new Map())).toBe(true);
+ });
+
+ it('leaves a non-investigation task and an already-completed investigation alone', () => {
+ expect(isReapableInvestigation({ status: 'pending', description: 'ordinary', metadata: {} }, new Map())).toBe(false);
+ expect(isReapableInvestigation(investigation({ status: 'completed' }), new Map())).toBe(false);
+ });
+
+ it('leaves a linkless investigation alone (cannot prove its cause is resolved)', () => {
+ expect(isReapableInvestigation(investigation({ metadata: { isInvestigation: true } }), new Map())).toBe(false);
+ });
+ });
+
+ describe('sweepResolvedFailureTasks (orchestration)', () => {
+ it('flips a stale failure-blocked task to completed with an auto-expired marker, not deletion', async () => {
+ await addTask({ description: 'failed thing', id: 'task-old', priority: 'HIGH' }, 'user', { now: NOW });
+ await updateTask('task-old', { status: 'blocked', metadata: { blockedCategory: 'max-retries', blockedAt: daysAgo(20) } }, 'user', { now: NOW });
+ mock.events = [];
+ const res = await sweepResolvedFailureTasks({ now: NOW });
+ expect(res).toMatchObject({ reaped: 1, staleBlocks: 1, investigations: 0 });
+ const after = await getUserTasks();
+ const task = after.tasks.find(t => t.id === 'task-old');
+ expect(task).toBeTruthy(); // NOT deleted — federation-safe
+ expect(task.status).toBe('completed');
+ expect(task.metadata.resolution).toBe('auto-expired');
+ expect(task.metadata.autoExpiredReason).toBe('stale-failure-block');
+ // Leaving-blocked clears the failure metadata (existing updateTask behavior).
+ expect(task.metadata.blockedCategory).toBeUndefined();
+ });
+
+ it('leaves a fresh failure block and a user-terminated block untouched', async () => {
+ await addTask({ description: 'fresh', id: 'task-fresh', priority: 'LOW' }, 'user', { now: NOW });
+ await updateTask('task-fresh', { status: 'blocked', metadata: { blockedCategory: 'max-retries', blockedAt: daysAgo(3) } }, 'user', { now: NOW });
+ await addTask({ description: 'stopped', id: 'task-stop', priority: 'LOW' }, 'user', { now: NOW });
+ await updateTask('task-stop', { status: 'blocked', metadata: { blockedCategory: 'user-terminated', blockedAt: daysAgo(60) } }, 'user', { now: NOW });
+ const res = await sweepResolvedFailureTasks({ now: NOW });
+ expect(res.reaped).toBe(0);
+ const after = await getUserTasks();
+ expect(after.tasks.find(t => t.id === 'task-fresh').status).toBe('blocked');
+ expect(after.tasks.find(t => t.id === 'task-stop').status).toBe('blocked');
+ });
+
+ it('flips an investigation whose originating task has completed', async () => {
+ await addTask({ description: 'origin work', id: 'task-origin', priority: 'HIGH' }, 'user', { now: NOW });
+ await updateTask('task-origin', { status: 'completed' }, 'user', { now: NOW });
+ await addTask({
+ description: '[Auto] Investigate agent failure [fp]: boom',
+ id: 'sys-inv',
+ isInvestigation: true,
+ affectedTasks: ['task-origin']
+ }, 'internal', { now: NOW });
+ const res = await sweepResolvedFailureTasks({ now: NOW });
+ expect(res).toMatchObject({ reaped: 1, investigations: 1 });
+ const after = await getCosTasks();
+ const inv = after.tasks.find(t => t.id === 'sys-inv');
+ expect(inv.status).toBe('completed');
+ expect(inv.metadata.autoExpiredReason).toBe('investigation-resolved');
+ });
+
+ it('keeps an investigation whose originating task is still blocked', async () => {
+ await addTask({ description: 'origin still broken', id: 'task-origin2', priority: 'HIGH' }, 'user', { now: NOW });
+ await updateTask('task-origin2', { status: 'blocked', metadata: { blockedCategory: 'max-retries', blockedAt: daysAgo(1) } }, 'user', { now: NOW });
+ await addTask({
+ description: '[Auto] Investigate agent failure [fp]: boom',
+ id: 'sys-inv2',
+ isInvestigation: true,
+ affectedTasks: ['task-origin2']
+ }, 'internal', { now: NOW });
+ const res = await sweepResolvedFailureTasks({ now: NOW });
+ expect(res.reaped).toBe(0);
+ const after = await getCosTasks();
+ expect(after.tasks.find(t => t.id === 'sys-inv2').status).toBe('pending');
+ });
+
+ it('bounds the number of flips per sweep to the limit', async () => {
+ for (let i = 0; i < 4; i++) {
+ await addTask({ description: `old ${i}`, id: `task-b${i}`, priority: 'LOW' }, 'user', { now: NOW });
+ await updateTask(`task-b${i}`, { status: 'blocked', metadata: { blockedCategory: 'max-retries', blockedAt: daysAgo(20) } }, 'user', { now: NOW });
+ }
+ const res = await sweepResolvedFailureTasks({ now: NOW, limit: 2 });
+ expect(res.reaped).toBe(2);
+ const after = await getUserTasks();
+ expect(after.tasks.filter(t => t.status === 'completed')).toHaveLength(2);
+ expect(after.tasks.filter(t => t.status === 'blocked')).toHaveLength(2);
+ });
+
+ it('is a no-op returning zeroed counts when nothing is reapable', async () => {
+ await addTask({ description: 'plain pending', id: 'task-p', priority: 'LOW' }, 'user', { now: NOW });
+ const res = await sweepResolvedFailureTasks({ now: NOW });
+ expect(res).toEqual({ reaped: 0, staleBlocks: 0, investigations: 0 });
+ });
+
+ it('exposes a 14-day default threshold', () => {
+ expect(DEFAULT_FAILURE_TASK_MAX_AGE_MS).toBe(14 * 24 * 60 * 60 * 1000);
+ });
+ });
+});
+
describe('cosTaskStore.challengeTask / resolveTaskChallenge (#2441)', () => {
async function seedTask(desc = 'work under dispute') {
const created = await addTask({ description: desc, priority: 'HIGH' }, 'user');
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 2e82931007..f28678d855 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -536,6 +536,31 @@ export async function resetTaskTypeLearning(taskType) {
// Remove the task type entry
delete data.byTaskType[taskType];
+ // Purge the task type's samples from the enriched failure signatures (#2619).
+ // Each `recent[]` sample carries its `taskType` and drives
+ // deriveFailureSignalAvoidance, so a leftover sample would keep steering a
+ // just-reset type off a tier. Decrement each bucket's rolling count by the
+ // samples removed and drop a bucket left with nothing.
+ if (data.failureSignatures && typeof data.failureSignatures === 'object') {
+ for (const [category, bucket] of Object.entries(data.failureSignatures)) {
+ if (!Array.isArray(bucket?.recent)) continue;
+ const kept = bucket.recent.filter((s) => s?.taskType !== taskType);
+ const removed = bucket.recent.length - kept.length;
+ if (removed === 0) continue;
+ bucket.recent = kept;
+ bucket.count = Math.max(0, (Number(bucket.count) || 0) - removed);
+ if (bucket.recent.length === 0 && bucket.count <= 0) {
+ delete data.failureSignatures[category];
+ }
+ }
+ }
+
+ // Drop the task type's rows from the cross-type correlation window (#2619) so a
+ // rehabilitated type contributes no stale prediction/outcome pairs to the gauge.
+ if (Array.isArray(data.correlationWindow)) {
+ data.correlationWindow = data.correlationWindow.filter((row) => row?.taskType !== taskType);
+ }
+
await saveLearningData(data);
emitLog('info', `Reset learning data for ${taskType} (was ${metrics.successRate}% success after ${metrics.completed} attempts)`, {
diff --git a/server/services/taskLearning/metricsReset.test.js b/server/services/taskLearning/metricsReset.test.js
new file mode 100644
index 0000000000..e4d88e016f
--- /dev/null
+++ b/server/services/taskLearning/metricsReset.test.js
@@ -0,0 +1,113 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// resetTaskTypeLearning mutates + PERSISTS the learning store, so both the load
+// and the save are mocked here — the save capture lets us assert the purge
+// without ever touching the real learning.json (repo rule: file-backed tests
+// must never mutate real data). withLock/emitLog/calculateDurationETA stay real.
+const store = vi.hoisted(() => ({ saved: null }));
+
+vi.mock('./store.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ loadLearningData: vi.fn(),
+ saveLearningData: vi.fn(async (data) => { store.saved = data; })
+ };
+});
+
+import { resetTaskTypeLearning } from './metrics.js';
+import { loadLearningData } from './store.js';
+
+// A learning fixture whose failure signatures + correlation window carry samples
+// for TWO task types, so a reset of one must leave the other's samples intact.
+const fixture = () => ({
+ version: 2,
+ totals: { completed: 30, succeeded: 20, failed: 10, totalDurationMs: 300000, successMaxDurationMs: 60000 },
+ byTaskType: {
+ 'self-improve:x': { completed: 10, succeeded: 3, failed: 7, successRate: 30, totalDurationMs: 100000, avgDurationMs: 10000, successMaxDurationMs: 20000 },
+ 'self-improve:y': { completed: 20, succeeded: 17, failed: 3, successRate: 85, totalDurationMs: 200000, avgDurationMs: 10000, successMaxDurationMs: 60000 }
+ },
+ byModelTier: {},
+ routingAccuracy: {},
+ errorPatterns: {},
+ failureSignatures: {
+ 'timeout': {
+ count: 3,
+ lastOccurred: '2026-06-01T00:00:00.000Z',
+ recent: [
+ { taskType: 'self-improve:x', modelTier: 'heavy', recordedAt: '2026-05-30T00:00:00.000Z' },
+ { taskType: 'self-improve:x', modelTier: 'heavy', recordedAt: '2026-05-31T00:00:00.000Z' },
+ { taskType: 'self-improve:y', modelTier: 'light', recordedAt: '2026-06-01T00:00:00.000Z' }
+ ]
+ },
+ // A category populated ONLY by the reset type — must be dropped entirely.
+ 'oom': {
+ count: 2,
+ lastOccurred: '2026-06-02T00:00:00.000Z',
+ recent: [
+ { taskType: 'self-improve:x', modelTier: 'heavy', recordedAt: '2026-06-02T00:00:00.000Z' },
+ { taskType: 'self-improve:x', modelTier: 'heavy', recordedAt: '2026-06-02T00:00:00.000Z' }
+ ]
+ }
+ },
+ correlationWindow: [
+ { taskType: 'self-improve:x', tier: 'heavy', predictedRisk: true, bad: true, recordedAt: '2026-06-01T00:00:00.000Z' },
+ { taskType: 'self-improve:y', tier: 'light', predictedRisk: false, bad: false, recordedAt: '2026-06-01T00:00:00.000Z' }
+ ]
+});
+
+describe('resetTaskTypeLearning — failure-signature + correlation purge (#2619)', () => {
+ beforeEach(() => {
+ store.saved = null;
+ vi.mocked(loadLearningData).mockReset();
+ });
+
+ it('removes the reset type from every failureSignatures.recent[] and rebuilds counts', async () => {
+ vi.mocked(loadLearningData).mockResolvedValue(fixture());
+ const result = await resetTaskTypeLearning('self-improve:x');
+ expect(result.reset).toBe(true);
+
+ const sig = store.saved.failureSignatures;
+ // The shared 'timeout' bucket keeps only the y-sample; count decremented by 2.
+ expect(sig.timeout.recent).toHaveLength(1);
+ expect(sig.timeout.recent[0].taskType).toBe('self-improve:y');
+ expect(sig.timeout.count).toBe(1);
+ // The x-only 'oom' bucket is dropped entirely.
+ expect(sig.oom).toBeUndefined();
+ });
+
+ it('drops the reset type rows from correlationWindow, keeping others', async () => {
+ vi.mocked(loadLearningData).mockResolvedValue(fixture());
+ await resetTaskTypeLearning('self-improve:x');
+ expect(store.saved.correlationWindow).toHaveLength(1);
+ expect(store.saved.correlationWindow[0].taskType).toBe('self-improve:y');
+ });
+
+ it('never decrements a rebuilt count below zero (defensive against a corrupt count)', async () => {
+ const data = fixture();
+ data.failureSignatures.timeout.count = 0; // corrupt: fewer than recent[] implies
+ vi.mocked(loadLearningData).mockResolvedValue(data);
+ await resetTaskTypeLearning('self-improve:x');
+ // recent still trimmed to the y-sample; count floored at 0, bucket kept (has a sample).
+ expect(store.saved.failureSignatures.timeout.count).toBe(0);
+ expect(store.saved.failureSignatures.timeout.recent).toHaveLength(1);
+ });
+
+ it('is a no-op on the signature/window purge for an unknown task type', async () => {
+ vi.mocked(loadLearningData).mockResolvedValue(fixture());
+ const result = await resetTaskTypeLearning('never-seen');
+ expect(result.reset).toBe(false);
+ // Early return — nothing saved.
+ expect(store.saved).toBeNull();
+ });
+
+ it('tolerates a store that predates the failureSignatures / correlationWindow keys', async () => {
+ const data = fixture();
+ delete data.failureSignatures;
+ delete data.correlationWindow;
+ vi.mocked(loadLearningData).mockResolvedValue(data);
+ const result = await resetTaskTypeLearning('self-improve:x');
+ expect(result.reset).toBe(true);
+ expect(store.saved.byTaskType['self-improve:x']).toBeUndefined();
+ });
+});
diff --git a/server/services/taskLearning/routing.js b/server/services/taskLearning/routing.js
index 9476822d61..c1bf41a38e 100644
--- a/server/services/taskLearning/routing.js
+++ b/server/services/taskLearning/routing.js
@@ -9,7 +9,7 @@
* module.
*/
-import { loadLearningData, emitLog, isSandboxedTaskType, computeEffectiveSuccessRate, isSkipCandidate, DEFAULT_WINDOW_MAX_AGE_MS } from './store.js';
+import { loadLearningData, emitLog, isSandboxedTaskType, computeEffectiveSuccessRate, computeWindowedStats, isSkipCandidate, DEFAULT_WINDOW_MAX_AGE_MS } from './store.js';
import { resetTaskTypeLearning } from './metrics.js';
import { computeCorrelationQuality, isCorrelationProven } from './correlationQuality.js';
@@ -120,12 +120,24 @@ function topKey(counts) {
* stays at the aggressive `MIN_FAILURE_SAMPLES` for back-compat with direct
* callers/tests.
*
+ * `maxAgeMs` (issue #2619) windows the recent samples by age at read time,
+ * mirroring `computeWindowedStats`: a failure sample older than the window is
+ * ignored, so a fixed low-frequency type stops being steered off a tier by an
+ * outage-era sample that never gets pushed out of the count-capped ring. An
+ * undated sample (unparseable `recordedAt`) is kept — the count cap still bounds
+ * it. Defaults to the shared 30-day window.
+ *
* @returns {{ avoidTiers: string[], sampleCount: number,
* dominant: { tier, failures, provider, model }|null }}
*/
-export function deriveFailureSignalAvoidance(data, taskType, { minFailureSamples = MIN_FAILURE_SAMPLES } = {}) {
+export function deriveFailureSignalAvoidance(data, taskType, {
+ minFailureSamples = MIN_FAILURE_SAMPLES,
+ maxAgeMs = DEFAULT_WINDOW_MAX_AGE_MS,
+ now = Date.now()
+} = {}) {
const signatures = data?.failureSignatures || {};
const routing = data?.routingAccuracy?.[taskType] || {};
+ const ageCutoff = Number.isFinite(maxAgeMs) && maxAgeMs > 0 ? now - maxAgeMs : null;
// Gather recent failure samples scoped to this task type across all categories.
const byTier = {};
@@ -134,6 +146,12 @@ export function deriveFailureSignalAvoidance(data, taskType, { minFailureSamples
for (const sample of bucket?.recent || []) {
if (sample?.taskType !== taskType || !sample.modelTier) continue;
if (NON_ROUTABLE_LEARNED_TIERS.has(sample.modelTier)) continue;
+ // Age-window (#2619): drop a sample with a parseable timestamp older than
+ // the window; keep an undated one (the count cap still bounds it).
+ if (ageCutoff !== null) {
+ const ts = Date.parse(sample.recordedAt);
+ if (Number.isFinite(ts) && ts < ageCutoff) continue;
+ }
sampleCount++;
const tier = (byTier[sample.modelTier] ||= { failures: 0, pairs: {} });
tier.failures++;
@@ -639,6 +657,36 @@ function isLifetimeDrivenSkip(metrics) {
return Number.isFinite(metrics?.successRate) && metrics.successRate < 30;
}
+// Recovery-based rehabilitation bars (issue #2619). The idle path only ever
+// resets a type that has gone QUIET; a type that was fixed but still runs
+// regularly never goes idle, so its poisoned lifetime/duration/failure-signature
+// data would never be cleared. These bars catch that case: a poor-lifetime type
+// whose RECENT window is clean has demonstrably recovered.
+const RECOVERY_MIN_WINDOW_SAMPLES = 5;
+const RECOVERY_MIN_WINDOW_SUCCESS_RATE = HIGH_SUCCESS_THRESHOLD; // 80%
+// "Poor lifetime" bar — a lifetime rate at/above this would already earn
+// auto-approval on its own, so there is nothing stale to rehabilitate.
+const RECOVERY_MAX_LIFETIME_SUCCESS_RATE = 50;
+
+/**
+ * True when a task type has RECOVERED (issue #2619): its lifetime success rate
+ * is still poor (< RECOVERY_MAX_LIFETIME_SUCCESS_RATE — would deny auto-approval
+ * on lifetime alone) but its recency window is clean (≥ RECOVERY_MIN_WINDOW_SAMPLES
+ * outcomes at ≥ RECOVERY_MIN_WINDOW_SUCCESS_RATE% success). A recovery reset
+ * clears the stale lifetime/duration/failure-signature data so the type stops
+ * being penalized by history it has already outgrown — and, unlike the idle
+ * path, it fires even for a type that still runs regularly. Pure.
+ */
+function hasRecoveredWindow(metrics, { now = Date.now() } = {}) {
+ if (!Number.isFinite(metrics?.successRate) || metrics.successRate >= RECOVERY_MAX_LIFETIME_SUCCESS_RATE) {
+ return false;
+ }
+ const { windowedCompleted, windowedSuccessRate } = computeWindowedStats(metrics?.recentOutcomes, { now });
+ return windowedSuccessRate !== null
+ && windowedCompleted >= RECOVERY_MIN_WINDOW_SAMPLES
+ && windowedSuccessRate >= RECOVERY_MIN_WINDOW_SUCCESS_RATE;
+}
+
/**
* Get all task types that should be skipped due to poor performance
* Useful for filtering out problematic task types in evaluateTasks
@@ -700,41 +748,49 @@ export async function checkAndRehabilitateSkippedTasks(gracePeriodMs = 7 * 24 *
for (const [taskType, metrics] of Object.entries(data.byTaskType)) {
// Sandboxed fallback is never skipped, so never rehabilitated either (#2333).
if (isSandboxedTaskType(taskType)) continue;
- // Only consider task types that would be skipped (effective rate < 30% with
- // 5+ attempts, issue #2617) — a type that recovered in its recent window is
- // no longer skipped, so resetting its lifetime data would be pointless churn.
- // And only reset when the skip is LIFETIME-driven: a windowed-driven skip
- // (recent failure burst on a healthy lifetime record) self-heals as the
- // window rolls, so the destructive reset would wipe good learning data.
- if (!isSkipCandidate(metrics) || !isLifetimeDrivenSkip(metrics)) {
- continue;
- }
- // Check if enough time has passed since last attempt
const lastCompletedTime = metrics.lastCompleted
? new Date(metrics.lastCompleted).getTime()
: 0;
const timeSinceLastAttempt = now - lastCompletedTime;
+ const daysSinceLastAttempt = Math.round(timeSinceLastAttempt / (24 * 60 * 60 * 1000));
+
+ // IDLE path (existing): a LIFETIME-driven skip (effective rate < 30% with 5+
+ // attempts, issue #2617) that has sat untouched for the grace period gets a
+ // fresh start. Only a lifetime-driven skip qualifies — a windowed-driven skip
+ // (recent burst on a healthy lifetime record) self-heals as the window rolls,
+ // so the destructive reset would wipe good learning data.
+ const idleEligible = isSkipCandidate(metrics)
+ && isLifetimeDrivenSkip(metrics)
+ && timeSinceLastAttempt >= gracePeriodMs;
+
+ // RECOVERY path (issue #2619): a poor-lifetime type whose recent window is
+ // clean is rehabilitated regardless of idle time — a fixed type that still
+ // runs never goes idle, so the idle gate alone would never clear its stale
+ // lifetime data. Evaluated only when the idle path didn't already fire.
+ const recoveryEligible = !idleEligible && hasRecoveredWindow(metrics, { now });
+
+ if (!idleEligible && !recoveryEligible) continue;
+
+ const trigger = idleEligible ? 'idle' : 'recovery';
+ emitLog('info', `Auto-rehabilitating ${taskType} (${trigger}: was ${metrics.successRate}% lifetime success${idleEligible ? `, ${daysSinceLastAttempt} days since last attempt` : ', recent window recovered'})`, {
+ taskType,
+ trigger,
+ previousSuccessRate: metrics.successRate,
+ previousAttempts: metrics.completed,
+ daysSinceLastAttempt
+ }, '📚 TaskLearning');
- if (timeSinceLastAttempt >= gracePeriodMs) {
- // This task type is eligible for rehabilitation
- emitLog('info', `Auto-rehabilitating ${taskType} (was ${metrics.successRate}% success, ${Math.round(timeSinceLastAttempt / (24 * 60 * 60 * 1000))} days since last attempt)`, {
- taskType,
- previousSuccessRate: metrics.successRate,
- previousAttempts: metrics.completed,
- daysSinceLastAttempt: Math.round(timeSinceLastAttempt / (24 * 60 * 60 * 1000))
- }, '📚 TaskLearning');
-
- // Reset this task type's data
- await resetTaskTypeLearning(taskType);
+ // Reset this task type's data
+ await resetTaskTypeLearning(taskType);
- rehabilitated.push({
- taskType,
- previousSuccessRate: metrics.successRate,
- previousAttempts: metrics.completed,
- daysSinceLastAttempt: Math.round(timeSinceLastAttempt / (24 * 60 * 60 * 1000))
- });
- }
+ rehabilitated.push({
+ taskType,
+ trigger,
+ previousSuccessRate: metrics.successRate,
+ previousAttempts: metrics.completed,
+ daysSinceLastAttempt
+ });
}
if (rehabilitated.length > 0) {
diff --git a/server/services/taskLearning/routing.test.js b/server/services/taskLearning/routing.test.js
index a666abe174..1371f663b2 100644
--- a/server/services/taskLearning/routing.test.js
+++ b/server/services/taskLearning/routing.test.js
@@ -117,6 +117,67 @@ describe('deriveFailureSignalAvoidance (#2329)', () => {
const more = dataWith([sample(), sample(), sample(), sample(), sample()]);
expect(deriveFailureSignalAvoidance(more, 'user-task', { minFailureSamples: 5 }).avoidTiers).toContain('heavy');
});
+
+ describe('age windowing (issue #2619)', () => {
+ const NOW = Date.parse('2026-06-25T12:00:00.000Z');
+ const at = (days) => new Date(NOW - days * 24 * 60 * 60 * 1000).toISOString();
+
+ it('ignores failure samples older than the window (outage-era samples stop steering)', () => {
+ // Three heavy-tier failures, all >30 days old — a since-fixed outage.
+ const data = dataWith([
+ sample({ recordedAt: at(40) }),
+ sample({ recordedAt: at(45) }),
+ sample({ recordedAt: at(50) })
+ ]);
+ const out = deriveFailureSignalAvoidance(data, 'user-task', { now: NOW });
+ expect(out.sampleCount).toBe(0);
+ expect(out.avoidTiers).toEqual([]);
+ });
+
+ it('still steers off a tier whose recent failures are within the window', () => {
+ const data = dataWith([
+ sample({ recordedAt: at(1) }),
+ sample({ recordedAt: at(2) }),
+ sample({ recordedAt: at(3) })
+ ]);
+ const out = deriveFailureSignalAvoidance(data, 'user-task', { now: NOW });
+ expect(out.sampleCount).toBe(3);
+ expect(out.avoidTiers).toContain('heavy');
+ });
+
+ it('counts only in-window samples toward the failure-sample bar', () => {
+ // 2 fresh + 2 stale: below the aggressive bar (3) once the stale two drop.
+ const data = dataWith([
+ sample({ recordedAt: at(1) }),
+ sample({ recordedAt: at(2) }),
+ sample({ recordedAt: at(40) }),
+ sample({ recordedAt: at(45) })
+ ]);
+ const out = deriveFailureSignalAvoidance(data, 'user-task', { now: NOW });
+ expect(out.sampleCount).toBe(2);
+ expect(out.avoidTiers).toEqual([]);
+ });
+
+ it('keeps an undated sample (unparseable recordedAt), mirroring computeWindowedStats', () => {
+ const data = dataWith([
+ sample(), // no recordedAt
+ sample({ recordedAt: 'not-a-date' }),
+ sample({ recordedAt: at(1) })
+ ]);
+ const out = deriveFailureSignalAvoidance(data, 'user-task', { now: NOW });
+ expect(out.sampleCount).toBe(3);
+ expect(out.avoidTiers).toContain('heavy');
+ });
+
+ it('disables the age filter when maxAgeMs is null/0 (back-compat with direct callers)', () => {
+ const data = dataWith([
+ sample({ recordedAt: at(40) }),
+ sample({ recordedAt: at(45) }),
+ sample({ recordedAt: at(50) })
+ ]);
+ expect(deriveFailureSignalAvoidance(data, 'user-task', { now: NOW, maxAgeMs: 0 }).avoidTiers).toContain('heavy');
+ });
+ });
});
// ---------------------------------------------------------------------------
@@ -250,10 +311,22 @@ describe('windowed-rate decisions (issue #2617)', () => {
});
describe('checkAndRehabilitateSkippedTasks', () => {
- it('does not reset a recovered type — it is no longer skipped, so there is nothing to rehabilitate', async () => {
- const old = recoveredMetrics();
- old.lastCompleted = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();
- loadLearningData.mockResolvedValue(learningWith({ 'recovered': old }));
+ it('resets a recovered type via the recovery path even though it is not idle (issue #2619)', async () => {
+ // Poor lifetime (27%) but a clean recent window (100% over 15 samples) and
+ // still running (lastCompleted just now). Pre-#2619 the idle gate left its
+ // stale lifetime/duration/failure-signature data in place forever; now the
+ // recovery path clears it regardless of idle time.
+ loadLearningData.mockResolvedValue(learningWith({ 'recovered': recoveredMetrics() }));
+ const out = await checkAndRehabilitateSkippedTasks();
+ expect(out.count).toBe(1);
+ expect(out.rehabilitated[0]).toMatchObject({ taskType: 'recovered', trigger: 'recovery' });
+ expect(resetTaskTypeLearning).toHaveBeenCalledWith('recovered');
+ });
+
+ it('does not reset a poor-lifetime type whose recent window is still too thin to prove recovery (#2619)', async () => {
+ // Same 27% lifetime, but only 3 recent samples — below the 5-sample
+ // recovery bar — and not idle. Neither path should fire.
+ loadLearningData.mockResolvedValue(learningWith({ 'thin': thinWindowMetrics() }));
const out = await checkAndRehabilitateSkippedTasks();
expect(out.count).toBe(0);
expect(resetTaskTypeLearning).not.toHaveBeenCalled();