Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix([issue-2617]): base learning decisions and self-diagnostics on windowed success rates, not lifetime totals

[._.]/ Adam Eivy04e8778219d0
diff --git a/server/services/autonomousJobs/selfDiagnostics.js b/server/services/autonomousJobs/selfDiagnostics.js
index 0e5129ae3f..f2a5e5def5 100644
--- a/server/services/autonomousJobs/selfDiagnostics.js
+++ b/server/services/autonomousJobs/selfDiagnostics.js
@@ -6,13 +6,18 @@
* automated pulse on system health. On each run it:
* 1. Reads the task-learning per-category metrics (`byTaskType`) — the same
* completion data the Learning tab renders.
- * 2. For every category with `failed > 0`, records a structured single-line log
- * entry (slug, total/failed counts, lastCompleted, avg/max duration).
+ * 2. For every category with failures in the RECENT WINDOW (issue #2617: the
+ * `recentOutcomes` ring windowed by `computeWindowedStats`, NOT the
+ * never-decaying lifetime `failed` counter), records a structured
+ * single-line log entry (slug, windowed total/failed counts, lastCompleted,
+ * avg/max duration). A category that failed historically but has a clean
+ * recent window drops off as the window rolls.
* 3. Aggregates the failing categories, ordered by impact, into ONE persistent
* GitHub summary issue — reusing an existing issue marked `monitoring` so the
* loop never files a fresh duplicate each cycle.
- * 4. Applies a `needs attention` label while failures exist (and removes it once
- * the categories recover) so the same summary isn't re-reported as stale.
+ * 4. Applies a `needs attention` label while recent failures exist (and removes
+ * it once the windowed failing set is empty) so the same summary isn't
+ * re-reported as stale.
*
* NO LLM calls — this is a pure metrics-read + `gh` issue write, safe to run on a
* schedule under the cold-bootstrap AI policy. The pure helpers (compute/sort,
@@ -22,7 +27,7 @@
import { spawn } from 'child_process'
import { PATHS, safeJSONParse } from '../../lib/fileUtils.js'
-import { loadLearningData } from '../taskLearning/store.js'
+import { loadLearningData, computeWindowedStats } from '../taskLearning/store.js'
// The label that marks the ONE persistent summary issue to reuse across runs, and
// the attention label the loop toggles so a still-open summary isn't re-filed.
@@ -38,33 +43,43 @@ const SLUG_MARKER = `<!-- lil-slug: ${DIAGNOSTICS_SLUG} -->`
const STABLE_TITLE = 'CoS self-diagnostics: self-healing failures'
/**
- * Reduce the learning `byTaskType` map to the categories that have at least one
- * failure, projected onto the fields the summary + logs need, ordered by impact.
- * Pure. Impact order: most failures first, then lowest success rate, then most
- * total runs (a big-sample low-rate category outranks a one-off flake).
+ * Reduce the learning `byTaskType` map to the categories with at least one
+ * failure in the RECENT WINDOW (issue #2617), projected onto the fields the
+ * summary + logs need, ordered by impact. Pure. Counts come from
+ * `computeWindowedStats` over each bucket's `recentOutcomes` ring (bounded by
+ * both sample count and age) — NOT the lifetime `failed` counter, which never
+ * decays and would keep a long-fixed category on the monitoring issue forever.
+ * A category with a clean (or empty) recent window is excluded, so stale rows
+ * drop off as the window rolls and the `needs attention` label can clear.
+ * Impact order: most recent failures first, then lowest windowed success rate,
+ * then most windowed runs (a big-sample low-rate category outranks a one-off
+ * flake).
*
* @param {Record<string, object>} byTaskType
- * @param {{ minCompleted?: number }} [opts] - ignore thin categories below this
- * completion count (default 1 — any category with a recorded failure qualifies).
+ * @param {{ minCompleted?: number, now?: number }} [opts] - `minCompleted`
+ * ignores thin categories below this windowed run count (default 1 — any
+ * category with a recent failure qualifies); `now` is the clock seam
+ * forwarded to the windowing (epoch ms).
* @returns {Array<{ slug, total, failed, succeeded, successRate, lastCompleted, avgDurationMs, maxDurationMs }>}
*/
-export function computeFailingCategories(byTaskType, { minCompleted = 1 } = {}) {
+export function computeFailingCategories(byTaskType, { minCompleted = 1, now = Date.now() } = {}) {
if (!byTaskType || typeof byTaskType !== 'object') return []
return Object.entries(byTaskType)
- .map(([slug, m]) => ({
- slug,
- total: m?.completed ?? 0,
- failed: m?.failed ?? 0,
- succeeded: m?.succeeded ?? 0,
- // Prefer the stored rate; fall back to a derived one so an older record
- // without `successRate` still sorts/renders correctly.
- successRate: Number.isFinite(m?.successRate)
- ? m.successRate
- : (m?.completed > 0 ? Math.round(((m.succeeded ?? 0) / m.completed) * 100) : 0),
- lastCompleted: m?.lastCompleted ?? null,
- avgDurationMs: m?.avgDurationMs ?? null,
- maxDurationMs: m?.maxDurationMs ?? null
- }))
+ .map(([slug, m]) => {
+ const w = computeWindowedStats(m?.recentOutcomes, { now })
+ return {
+ slug,
+ total: w.windowedCompleted,
+ failed: w.windowedFailed,
+ succeeded: w.windowedSucceeded,
+ // Post-filter rows always have windowed samples, so the null sentinel
+ // (empty window) only shows up in rows the filter drops.
+ successRate: w.windowedSuccessRate ?? 0,
+ lastCompleted: m?.lastCompleted ?? null,
+ avgDurationMs: m?.avgDurationMs ?? null,
+ maxDurationMs: m?.maxDurationMs ?? null
+ }
+ })
.filter(c => c.failed > 0 && c.total >= minCompleted)
.sort((a, b) =>
b.failed - a.failed ||
@@ -94,7 +109,7 @@ export function formatDurationShort(ms) {
* emits it via console so logs stay single-line + emoji-prefixed (CLAUDE.md).
*/
export function formatCategoryLogLine(c) {
- return `🩺 ${c.slug}: ${c.failed}/${c.total} failed (${c.successRate}% success) · ` +
+ return `🩺 ${c.slug}: ${c.failed}/${c.total} recent failed (${c.successRate}% success) · ` +
`last ${c.lastCompleted || 'n/a'} · avg ${formatDurationShort(c.avgDurationMs)} · max ${formatDurationShort(c.maxDurationMs)}`
}
@@ -113,11 +128,11 @@ export function buildDiagnosticsIssueBody(failing, { generatedAt = new Date().to
lines.push('_Automated CoS self-diagnostics — regenerated each run. Do not hand-edit; edits are overwritten._')
lines.push('')
if (!failing || failing.length === 0) {
- lines.push('✅ **All self-healing categories are passing** — no categories with recorded failures.')
+ lines.push('✅ **All self-healing categories are passing** — no categories with failures in the recent window.')
} else {
- lines.push(`Found **${failing.length}** self-healing categor${failing.length === 1 ? 'y' : 'ies'} with recorded failures, ordered by impact:`)
+ lines.push(`Found **${failing.length}** self-healing categor${failing.length === 1 ? 'y' : 'ies'} with recent failures (recency-windowed — long-fixed categories drop off as the window rolls), ordered by impact:`)
lines.push('')
- lines.push('| Category | Failed / Total | Success rate | Last completed | Avg duration | Max duration |')
+ lines.push('| Category | Failed / Total (recent) | Success rate (recent) | Last completed | Avg duration | Max duration |')
lines.push('| --- | --- | --- | --- | --- | --- |')
for (const c of failing) {
lines.push(`| \`${c.slug}\` | ${c.failed} / ${c.total} | ${c.successRate}% | ${c.lastCompleted || '—'} | ${formatDurationShort(c.avgDurationMs)} | ${formatDurationShort(c.maxDurationMs)} |`)
@@ -215,10 +230,11 @@ export async function runSelfDiagnostics({
now = () => new Date().toISOString()
} = {}) {
const data = await loadLearning()
- const failing = computeFailingCategories(data?.byTaskType)
+ // Window against the injected clock so tests are deterministic (issue #2617).
+ const failing = computeFailingCategories(data?.byTaskType, { now: new Date(now()).getTime() })
if (failing.length === 0) {
- console.log('🩺 Self-diagnostics: no self-healing categories with recorded failures — all clear')
+ console.log('🩺 Self-diagnostics: no self-healing categories with recent failures — all clear')
} else {
console.log(`🩺 Self-diagnostics: ${failing.length} failing categor${failing.length === 1 ? 'y' : 'ies'} (top: ${failing[0].slug} ${failing[0].failed}/${failing[0].total})`)
for (const c of failing) console.log(formatCategoryLogLine(c))
diff --git a/server/services/autonomousJobs/selfDiagnostics.test.js b/server/services/autonomousJobs/selfDiagnostics.test.js
index e7595d92f5..ee29556edc 100644
--- a/server/services/autonomousJobs/selfDiagnostics.test.js
+++ b/server/services/autonomousJobs/selfDiagnostics.test.js
@@ -12,48 +12,105 @@ import {
DIAGNOSTICS_SLUG
} from './selfDiagnostics.js'
-// A sample byTaskType map mirroring the learning.json shape.
+// Deterministic clock shared by the windowed fixtures and the tests (#2617).
+const NOW = Date.parse('2026-07-12T00:00:00.000Z')
+const DAY = 24 * 60 * 60 * 1000
+
+// A recent-outcomes ring ending at `endAt`, oldest first.
+const ring = (results, { endAt = NOW, stepMs = 60000 } = {}) =>
+ results.map((s, i) => ({ t: new Date(endAt - (results.length - i) * stepMs).toISOString(), s }))
+
+// A sample byTaskType map mirroring the learning.json shape. Since #2617 the
+// failing set comes from the recency-windowed `recentOutcomes` ring, NOT the
+// lifetime counters — so each bucket carries both, and `self-improve:update`
+// is the acceptance case: heavy lifetime failures but a clean recent window.
const sampleMetrics = {
- 'self-improve:claim-issue': { completed: 192, succeeded: 137, failed: 55, successRate: 71, lastCompleted: '2026-07-01T00:00:00.000Z', avgDurationMs: 160000, maxDurationMs: 900000 },
- 'self-improve:console': { completed: 3, succeeded: 1, failed: 2, successRate: 33, lastCompleted: '2026-06-01T00:00:00.000Z', avgDurationMs: 40000, maxDurationMs: 60000 },
- 'user-task': { completed: 1177, succeeded: 1002, failed: 175, successRate: 85, lastCompleted: '2026-07-02T00:00:00.000Z', avgDurationMs: 120000, maxDurationMs: 500000 },
- 'self-improve:update': { completed: 7, succeeded: 7, failed: 0, successRate: 100, lastCompleted: '2026-02-04T00:00:00.000Z', avgDurationMs: 160000, maxDurationMs: 200000 }
+ // Windowed: 4 failed / 12 (67%)
+ 'self-improve:claim-issue': {
+ completed: 192, succeeded: 137, failed: 55, successRate: 71, lastCompleted: '2026-07-01T00:00:00.000Z', avgDurationMs: 160000, maxDurationMs: 900000,
+ recentOutcomes: ring([true, false, true, true, false, true, true, false, true, true, false, true])
+ },
+ // Windowed: 2 failed / 3 (33%)
+ 'self-improve:console': {
+ completed: 3, succeeded: 1, failed: 2, successRate: 33, lastCompleted: '2026-06-01T00:00:00.000Z', avgDurationMs: 40000, maxDurationMs: 60000,
+ recentOutcomes: ring([false, true, false])
+ },
+ // Windowed: 6 failed / 20 (70%)
+ 'user-task': {
+ completed: 1177, succeeded: 1002, failed: 175, successRate: 85, lastCompleted: '2026-07-02T00:00:00.000Z', avgDurationMs: 120000, maxDurationMs: 500000,
+ recentOutcomes: ring([...Array(6).fill(false), ...Array(14).fill(true)])
+ },
+ // Lifetime-failed (55 failures during a since-fixed bug) but CLEAN recent
+ // window → must drop off the monitoring issue (#2617 acceptance criterion).
+ 'self-improve:update': {
+ completed: 100, succeeded: 45, failed: 55, successRate: 45, lastCompleted: '2026-07-10T00:00:00.000Z', avgDurationMs: 160000, maxDurationMs: 200000,
+ recentOutcomes: ring(Array(6).fill(true))
+ }
}
describe('computeFailingCategories', () => {
- it('returns only categories with failures, ordered by impact (failed desc, then successRate asc)', () => {
- const out = computeFailingCategories(sampleMetrics)
+ it('returns only categories with RECENT failures, ordered by impact (windowed failed desc, then windowed successRate asc)', () => {
+ const out = computeFailingCategories(sampleMetrics, { now: NOW })
expect(out.map(c => c.slug)).toEqual([
- 'user-task', // 175 failures — most
- 'self-improve:claim-issue', // 55 failures
- 'self-improve:console' // 2 failures
+ 'user-task', // 6 recent failures — most
+ 'self-improve:claim-issue', // 4 recent failures
+ 'self-improve:console' // 2 recent failures
])
- // The passing category is excluded entirely.
+ // Historically-failed but window-clean category is excluded entirely (#2617).
expect(out.find(c => c.slug === 'self-improve:update')).toBeUndefined()
})
- it('projects the required fields (slug, total, failed, successRate, lastCompleted, avg/max duration)', () => {
- const [top] = computeFailingCategories(sampleMetrics)
+ it('projects the required fields with WINDOWED counts (slug, total, failed, successRate) plus lifetime metadata', () => {
+ const [top] = computeFailingCategories(sampleMetrics, { now: NOW })
expect(top).toMatchObject({
slug: 'user-task',
- total: 1177,
- failed: 175,
- succeeded: 1002,
- successRate: 85,
+ total: 20,
+ failed: 6,
+ succeeded: 14,
+ successRate: 70,
lastCompleted: '2026-07-02T00:00:00.000Z',
avgDurationMs: 120000,
maxDurationMs: 500000
})
})
- it('derives successRate when the stored value is missing', () => {
- const [c] = computeFailingCategories({ x: { completed: 4, succeeded: 1, failed: 3 } })
+ it('excludes a category whose lifetime counter has failures but whose ring is empty (stale row drops off)', () => {
+ // Pre-#2460 bucket shape (no ring) or a type with no runs in the window:
+ // lifetime failed > 0 must no longer keep it on the monitoring issue.
+ const out = computeFailingCategories({
+ x: { completed: 40, succeeded: 10, failed: 30, successRate: 25 }
+ }, { now: NOW })
+ expect(out).toEqual([])
+ })
+
+ it('ages old ring failures out of the window', () => {
+ const out = computeFailingCategories({
+ x: {
+ completed: 10, succeeded: 4, failed: 6, successRate: 40,
+ // The failure burst is 40 days old — outside the 30-day window; the
+ // only in-window samples are successes.
+ recentOutcomes: [
+ ...ring(Array(6).fill(false), { endAt: NOW - 40 * DAY }),
+ ...ring(Array(4).fill(true))
+ ]
+ }
+ }, { now: NOW })
+ expect(out).toEqual([])
+ })
+
+ it('derives the windowed successRate from the ring', () => {
+ const [c] = computeFailingCategories({
+ x: { recentOutcomes: ring([false, false, false, true]) }
+ }, { now: NOW })
expect(c.successRate).toBe(25)
+ expect(c.failed).toBe(3)
+ expect(c.total).toBe(4)
})
- it('honors minCompleted to drop thin categories', () => {
- const out = computeFailingCategories(sampleMetrics, { minCompleted: 10 })
- expect(out.map(c => c.slug)).not.toContain('self-improve:console') // only 3 completions
+ it('honors minCompleted (against the windowed run count) to drop thin categories', () => {
+ const out = computeFailingCategories(sampleMetrics, { minCompleted: 10, now: NOW })
+ expect(out.map(c => c.slug)).not.toContain('self-improve:console') // only 3 windowed runs
+ expect(out.map(c => c.slug)).toContain('user-task') // 20 windowed runs
})
it('is null-safe', () => {
@@ -77,20 +134,20 @@ describe('formatDurationShort', () => {
})
describe('formatCategoryLogLine', () => {
- it('is a single line with the required fields', () => {
- const line = formatCategoryLogLine(computeFailingCategories(sampleMetrics)[1])
+ it('is a single line with the required fields (windowed counts)', () => {
+ const line = formatCategoryLogLine(computeFailingCategories(sampleMetrics, { now: NOW })[1])
expect(line).not.toContain('\n')
expect(line).toContain('self-improve:claim-issue')
- expect(line).toContain('55/192 failed')
- expect(line).toContain('71% success')
+ expect(line).toContain('4/12 recent failed')
+ expect(line).toContain('67% success')
})
})
describe('buildDiagnosticsIssueBody', () => {
it('lists failing categories as a table and embeds the dedup slug marker', () => {
- const body = buildDiagnosticsIssueBody(computeFailingCategories(sampleMetrics), { generatedAt: '2026-07-12T00:00:00.000Z' })
+ const body = buildDiagnosticsIssueBody(computeFailingCategories(sampleMetrics, { now: NOW }), { generatedAt: '2026-07-12T00:00:00.000Z' })
expect(body).toContain(`lil-slug: ${DIAGNOSTICS_SLUG}`)
- expect(body).toContain('| `user-task` | 175 / 1177 |')
+ expect(body).toContain('| `user-task` | 6 / 20 |')
expect(body).toContain('Last run: 2026-07-12T00:00:00.000Z')
// Table order matches impact order.
expect(body.indexOf('user-task')).toBeLessThan(body.indexOf('self-improve:claim-issue'))
@@ -215,6 +272,8 @@ describe('runSelfDiagnostics', () => {
})
it('does not create a new issue when everything is passing and none exists', async () => {
+ // Note the bucket has 55 LIFETIME failures — only the clean recent window
+ // counts (#2617), so this is "passing" despite the lifetime counter.
const allGood = async () => ({ byTaskType: { 'self-improve:update': sampleMetrics['self-improve:update'] } })
const exec = makeExec([{ match: argsHave('issue', 'list'), result: { code: 0, stdout: '[]' } }])
const res = await runSelfDiagnostics({ loadLearning: allGood, exec, now: () => '2026-07-12T00:00:00.000Z' })
@@ -223,7 +282,9 @@ describe('runSelfDiagnostics', () => {
expect(exec.mock.calls.find(c => c[1].includes('create') && c[1].includes('issue'))).toBeUndefined()
})
- it('clears the needs-attention label when a previously-failing summary recovers', async () => {
+ it('clears the needs-attention label when the windowed failing set empties — even with lifetime failures on record (#2617)', async () => {
+ // The category failed 55 times historically (lifetime `failed` can never
+ // reach 0 organically) but its recent window is clean, so the label clears.
const allGood = async () => ({ byTaskType: { 'self-improve:update': sampleMetrics['self-improve:update'] } })
const exec = makeExec([
{ match: argsHave('issue', 'list'), result: { code: 0, stdout: JSON.stringify([
diff --git a/server/services/taskLearning/index.js b/server/services/taskLearning/index.js
index c25589baff..28af8f2f68 100644
--- a/server/services/taskLearning/index.js
+++ b/server/services/taskLearning/index.js
@@ -34,6 +34,8 @@ export {
EXTERNAL_UNTYPED_TASK_TYPE,
appendRecentOutcome,
computeWindowedStats,
+ computeEffectiveSuccessRate,
+ EFFECTIVE_RATE_MIN_WINDOW_SAMPLES,
RECENT_OUTCOMES_CAP,
DEFAULT_WINDOW_MAX_COUNT,
DEFAULT_WINDOW_MAX_AGE_MS
diff --git a/server/services/taskLearning/routing.js b/server/services/taskLearning/routing.js
index 0c46494221..5734b9cb2f 100644
--- a/server/services/taskLearning/routing.js
+++ b/server/services/taskLearning/routing.js
@@ -9,7 +9,7 @@
* module.
*/
-import { loadLearningData, emitLog, isSandboxedTaskType } from './store.js';
+import { loadLearningData, emitLog, isSandboxedTaskType, computeEffectiveSuccessRate } from './store.js';
import { resetTaskTypeLearning } from './metrics.js';
import { computeCorrelationQuality, isCorrelationProven } from './correlationQuality.js';
@@ -175,6 +175,10 @@ function mergeAvoidTiers(...lists) {
/**
* Get suggested priority boost for a task type based on historical success
* Returns a multiplier: >1 for boost, <1 for demotion
+ *
+ * Reads the EFFECTIVE success rate (issue #2617): the recency-windowed rate
+ * when the outcome ring has enough samples, else the lifetime rate — so a type
+ * that recovered from a since-fixed failure burst stops being demoted.
*/
export async function getTaskTypePriorityMultiplier(taskType) {
const data = await loadLearningData();
@@ -184,12 +188,14 @@ export async function getTaskTypePriorityMultiplier(taskType) {
return 1.0; // Not enough data, use default priority
}
+ const { successRate } = computeEffectiveSuccessRate(metrics);
+
// High success rate = boost priority
- if (metrics.successRate >= 90) return 1.2;
- if (metrics.successRate >= 75) return 1.1;
+ if (successRate >= 90) return 1.2;
+ if (successRate >= 75) return 1.1;
// Low success rate = demote priority slightly (but not too much, as we want to retry)
- if (metrics.successRate < 50) return 0.9;
+ if (successRate !== null && successRate < 50) return 0.9;
return 1.0;
}
@@ -482,7 +488,11 @@ export async function getAdaptiveCooldownMultiplier(taskType) {
};
}
- const successRate = metrics.successRate;
+ // Effective rate (issue #2617): windowed when the outcome ring has enough
+ // samples, else lifetime — so a since-fixed failure burst stops inflating the
+ // cooldown (or holding `skip: true`) once the type succeeds again. All the
+ // completed-count thresholds below stay on the LIFETIME counter, unchanged.
+ const { successRate, source: rateSource } = computeEffectiveSuccessRate(metrics);
// Very high success (90%+): Reduce cooldown by 30% - this task type works well
if (successRate >= 90) {
@@ -491,6 +501,7 @@ export async function getAdaptiveCooldownMultiplier(taskType) {
reason: 'high-success',
skip: false,
successRate,
+ rateSource,
completed: metrics.completed,
recommendation: `Task type has ${successRate}% success rate - reduced cooldown`
};
@@ -503,6 +514,7 @@ export async function getAdaptiveCooldownMultiplier(taskType) {
reason: 'good-success',
skip: false,
successRate,
+ rateSource,
completed: metrics.completed
};
}
@@ -514,6 +526,7 @@ export async function getAdaptiveCooldownMultiplier(taskType) {
reason: 'moderate-success',
skip: false,
successRate,
+ rateSource,
completed: metrics.completed
};
}
@@ -525,6 +538,7 @@ export async function getAdaptiveCooldownMultiplier(taskType) {
reason: 'low-success',
skip: false,
successRate,
+ rateSource,
completed: metrics.completed,
recommendation: `Task type has only ${successRate}% success rate - increased cooldown`
};
@@ -537,6 +551,7 @@ export async function getAdaptiveCooldownMultiplier(taskType) {
reason: 'skip-failing',
skip: true,
successRate,
+ rateSource,
completed: metrics.completed,
recommendation: `Task type has ${successRate}% success rate after ${metrics.completed} attempts - skipping until reviewed`
};
@@ -548,11 +563,27 @@ export async function getAdaptiveCooldownMultiplier(taskType) {
reason: 'very-low-success',
skip: false,
successRate,
+ rateSource,
completed: metrics.completed,
recommendation: `Task type has ${successRate}% success rate - doubled cooldown for retry`
};
}
+/**
+ * Shared skip predicate (issue #2617): a task type is a skip candidate when it
+ * has ≥5 lifetime completions AND its EFFECTIVE success rate is <30%. Using the
+ * effective rate (windowed when the ring has enough samples, else lifetime)
+ * keeps this decision, `getAdaptiveCooldownMultiplier`'s skip branch, and the
+ * rehabilitation/status views agreeing — a type that recovered in its recent
+ * window is no longer skipped, so it must not be listed as skipped or have its
+ * lifetime data auto-reset either.
+ */
+function isSkipCandidate(metrics) {
+ if (!metrics || (metrics.completed ?? 0) < 5) return false;
+ const { successRate } = computeEffectiveSuccessRate(metrics);
+ return successRate !== null && successRate < 30;
+}
+
/**
* Get all task types that should be skipped due to poor performance
* Useful for filtering out problematic task types in evaluateTasks
@@ -564,11 +595,11 @@ export async function getSkippedTaskTypes() {
for (const [taskType, metrics] of Object.entries(data.byTaskType)) {
// Sandboxed fallback is never globally skipped (issue #2333).
if (isSandboxedTaskType(taskType)) continue;
- // Skip if: completed >= 5 AND success rate < 30%
- if (metrics.completed >= 5 && metrics.successRate < 30) {
+ // Skip if: completed >= 5 AND effective success rate < 30%
+ if (isSkipCandidate(metrics)) {
skipped.push({
taskType,
- successRate: metrics.successRate,
+ successRate: computeEffectiveSuccessRate(metrics).successRate,
completed: metrics.completed,
lastCompleted: metrics.lastCompleted
});
@@ -609,8 +640,10 @@ 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 (< 30% success with 5+ attempts)
- if (metrics.completed < 5 || metrics.successRate >= 30) {
+ // 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.
+ if (!isSkipCandidate(metrics)) {
continue;
}
@@ -664,8 +697,8 @@ export async function getSkippedTaskTypesWithStatus(gracePeriodMs = 7 * 24 * 60
for (const [taskType, metrics] of Object.entries(data.byTaskType)) {
// Sandboxed fallback is never skipped (#2333) — exclude from the skip status list.
if (isSandboxedTaskType(taskType)) continue;
- // Only include task types that would be skipped
- if (metrics.completed < 5 || metrics.successRate >= 30) {
+ // Only include task types that would be skipped (effective rate, issue #2617)
+ if (!isSkipCandidate(metrics)) {
continue;
}
@@ -680,7 +713,7 @@ export async function getSkippedTaskTypesWithStatus(gracePeriodMs = 7 * 24 * 60
skipped.push({
taskType,
- successRate: metrics.successRate,
+ successRate: computeEffectiveSuccessRate(metrics).successRate,
completed: metrics.completed,
lastCompleted: metrics.lastCompleted,
daysSinceLastAttempt: Math.round(timeSinceLastAttempt / (24 * 60 * 60 * 1000)),
@@ -693,17 +726,23 @@ export async function getSkippedTaskTypesWithStatus(gracePeriodMs = 7 * 24 * 60
}
/**
- * Pure classifier — returns { tier, autoApprove } for a given metrics object.
- * Shared by getTaskTypeConfidence() and getConfidenceLevels().
+ * Pure classifier — returns { tier, autoApprove, successRate, rateSource } for
+ * a given metrics object. Shared by getTaskTypeConfidence() and
+ * getConfidenceLevels() so the auto-approve gate and the Learning tab display
+ * always agree. Classifies on the EFFECTIVE success rate (issue #2617):
+ * windowed when the outcome ring has enough samples, else lifetime — so a type
+ * with a poor lifetime rate but a healthy recent window regains auto-approval.
+ * The returned `successRate` is the rate the tier was classified on.
*/
function classifyConfidenceTier(metrics, { highThreshold = 80, lowThreshold = 50, minSamples = 5 } = {}) {
const completed = metrics?.completed ?? 0;
- const successRate = metrics?.successRate ?? 0;
+ const effective = computeEffectiveSuccessRate(metrics);
+ const successRate = effective.successRate ?? 0;
- if (completed < minSamples) return { tier: 'new', autoApprove: true };
- if (successRate >= highThreshold) return { tier: 'high', autoApprove: true };
- if (successRate >= lowThreshold) return { tier: 'medium', autoApprove: true };
- return { tier: 'low', autoApprove: false };
+ if (completed < minSamples) return { tier: 'new', autoApprove: true, successRate, rateSource: effective.source };
+ if (successRate >= highThreshold) return { tier: 'high', autoApprove: true, successRate, rateSource: effective.source };
+ if (successRate >= lowThreshold) return { tier: 'medium', autoApprove: true, successRate, rateSource: effective.source };
+ return { tier: 'low', autoApprove: false, successRate, rateSource: effective.source };
}
/**
@@ -716,20 +755,25 @@ function classifyConfidenceTier(metrics, { highThreshold = 80, lowThreshold = 50
export async function getTaskTypeConfidence(taskType, thresholds = {}) {
const data = await loadLearningData();
const metrics = data.byTaskType[taskType];
- const { tier, autoApprove } = classifyConfidenceTier(metrics, thresholds);
+ const { tier, autoApprove, successRate, rateSource } = classifyConfidenceTier(metrics, thresholds);
+ // Reasons quote the EFFECTIVE rate the tier was classified on (issue #2617),
+ // annotated when it came from the recency window so "82% success" next to a
+ // depressed lifetime rate is explainable.
+ const rateLabel = rateSource === 'windowed' ? `${successRate}% recent success` : `${successRate}% success`;
const reasons = {
new: `Fewer than ${thresholds.minSamples ?? 5} completions — auto-approve by default`,
- high: `${metrics?.successRate}% success across ${metrics?.completed} runs — high confidence`,
- medium: `${metrics?.successRate}% success — acceptable confidence`,
- low: `${metrics?.successRate}% success after ${metrics?.completed} attempts — requires approval`
+ high: `${rateLabel} across ${metrics?.completed} runs — high confidence`,
+ medium: `${rateLabel} — acceptable confidence`,
+ low: `${rateLabel} after ${metrics?.completed} attempts — requires approval`
};
return {
taskType,
tier,
autoApprove,
- successRate: metrics?.successRate ?? null,
+ successRate: metrics ? successRate : null,
+ rateSource,
completed: metrics?.completed ?? 0,
reason: reasons[tier]
};
@@ -747,10 +791,10 @@ export async function getConfidenceLevels(thresholds = {}) {
const levels = { high: [], medium: [], low: [], new: [] };
for (const [taskType, metrics] of Object.entries(data.byTaskType)) {
- const { tier, autoApprove } = classifyConfidenceTier(metrics, thresholds);
+ const { tier, autoApprove, successRate } = classifyConfidenceTier(metrics, thresholds);
levels[tier].push({
taskType,
- successRate: metrics.successRate ?? 0,
+ successRate,
completed: metrics.completed || 0,
autoApprove,
lastCompleted: metrics.lastCompleted
diff --git a/server/services/taskLearning/routing.test.js b/server/services/taskLearning/routing.test.js
index 9f0529158a..6b0a5b63ae 100644
--- a/server/services/taskLearning/routing.test.js
+++ b/server/services/taskLearning/routing.test.js
@@ -1,5 +1,23 @@
-import { describe, it, expect } from 'vitest';
-import { deriveFailureSignalAvoidance } from './routing.js';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import {
+ deriveFailureSignalAvoidance,
+ getAdaptiveCooldownMultiplier,
+ getSkippedTaskTypes,
+ getTaskTypeConfidence,
+ getTaskTypePriorityMultiplier,
+ checkAndRehabilitateSkippedTasks
+} from './routing.js';
+import { loadLearningData } from './store.js';
+import { resetTaskTypeLearning } from './metrics.js';
+
+// Stub ONLY the persistence + log surface of the store; every pure helper
+// (computeEffectiveSuccessRate, computeWindowedStats, isSandboxedTaskType, …)
+// stays real so the decision tests exercise the actual windowed-rate math.
+vi.mock('./store.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, loadLearningData: vi.fn(), emitLog: vi.fn() };
+});
+vi.mock('./metrics.js', () => ({ resetTaskTypeLearning: vi.fn() }));
// deriveFailureSignalAvoidance is the pure "routing consumes the enriched
// failure signatures" core added for issue #2329. It takes learning data + a
@@ -97,3 +115,158 @@ describe('deriveFailureSignalAvoidance (#2329)', () => {
expect(deriveFailureSignalAvoidance(more, 'user-task', { minFailureSamples: 5 }).avoidTiers).toContain('heavy');
});
});
+
+// ---------------------------------------------------------------------------
+// Effective (windowed) success rate in decisions — issue #2617.
+//
+// The issue's failure scenario: a task type accrues 40 failures during a
+// since-fixed bug, then succeeds 15 straight. Lifetime rate ≈ 27%, windowed
+// rate = 100%. Every decision below must read the windowed rate once the ring
+// has ≥5 windowed samples, and fall back to lifetime behavior when it doesn't.
+// ---------------------------------------------------------------------------
+
+// A recent outcome ring ending now, oldest first.
+const ring = (results, now = Date.now()) =>
+ results.map((s, i) => ({ t: new Date(now - (results.length - i) * 60000).toISOString(), s }));
+
+// Lifetime-poor / recently-recovered bucket (the issue's scenario).
+const recoveredMetrics = () => ({
+ completed: 55, succeeded: 15, failed: 40, successRate: 27,
+ lastCompleted: new Date().toISOString(),
+ avgDurationMs: 60000,
+ recentOutcomes: ring(Array(15).fill(true))
+});
+
+// Lifetime-poor bucket with a window too thin to trust (<5 samples) — must
+// behave exactly as the lifetime rate dictates (acceptance criterion 2).
+const thinWindowMetrics = () => ({
+ completed: 55, succeeded: 15, failed: 40, successRate: 27,
+ lastCompleted: new Date().toISOString(),
+ recentOutcomes: ring([true, true, true])
+});
+
+// Still-broken bucket: poor lifetime AND poor recent window.
+const stillFailingMetrics = () => ({
+ completed: 20, succeeded: 2, failed: 18, successRate: 10,
+ lastCompleted: new Date().toISOString(),
+ recentOutcomes: ring(Array(8).fill(false))
+});
+
+const learningWith = (byTaskType) => ({
+ byTaskType,
+ routingAccuracy: {},
+ failureSignatures: {},
+ correlationWindow: [],
+ totals: { completed: 0, succeeded: 0, failed: 0, totalDurationMs: 0, avgDurationMs: 0 }
+});
+
+describe('windowed-rate decisions (issue #2617)', () => {
+ beforeEach(() => {
+ vi.mocked(loadLearningData).mockReset();
+ vi.mocked(resetTaskTypeLearning).mockReset();
+ });
+
+ describe('getAdaptiveCooldownMultiplier', () => {
+ it('no longer skips a recovered task type (windowed 100% beats lifetime 27%)', async () => {
+ loadLearningData.mockResolvedValue(learningWith({ 'self-improve:x': recoveredMetrics() }));
+ const out = await getAdaptiveCooldownMultiplier('self-improve:x');
+ expect(out.skip).toBe(false);
+ expect(out.multiplier).toBe(0.7); // windowed 100% → high-success branch
+ expect(out.successRate).toBe(100);
+ expect(out.rateSource).toBe('windowed');
+ });
+
+ it('keeps skipping when the window is too thin (lifetime fallback, acceptance criterion 2)', async () => {
+ loadLearningData.mockResolvedValue(learningWith({ 'self-improve:x': thinWindowMetrics() }));
+ const out = await getAdaptiveCooldownMultiplier('self-improve:x');
+ expect(out.skip).toBe(true); // lifetime 27% < 30 with ≥5 completions
+ expect(out.successRate).toBe(27);
+ expect(out.rateSource).toBe('lifetime');
+ });
+
+ it('still skips a type whose recent window is also failing', async () => {
+ loadLearningData.mockResolvedValue(learningWith({ 'self-improve:x': stillFailingMetrics() }));
+ const out = await getAdaptiveCooldownMultiplier('self-improve:x');
+ expect(out.skip).toBe(true);
+ expect(out.rateSource).toBe('windowed');
+ });
+ });
+
+ describe('getSkippedTaskTypes', () => {
+ it('drops a recovered type from the skip list but keeps a still-failing one', async () => {
+ loadLearningData.mockResolvedValue(learningWith({
+ 'recovered': recoveredMetrics(),
+ 'still-broken': stillFailingMetrics(),
+ 'thin-window': thinWindowMetrics()
+ }));
+ const skipped = await getSkippedTaskTypes();
+ const types = skipped.map(s => s.taskType);
+ expect(types).not.toContain('recovered');
+ expect(types).toContain('still-broken');
+ expect(types).toContain('thin-window'); // lifetime fallback still applies
+ });
+ });
+
+ describe('getTaskTypeConfidence', () => {
+ it('restores auto-approval for a recovered type (windowed rate gates the tier)', async () => {
+ loadLearningData.mockResolvedValue(learningWith({ 'self-improve:x': recoveredMetrics() }));
+ const out = await getTaskTypeConfidence('self-improve:x');
+ expect(out.tier).toBe('high');
+ expect(out.autoApprove).toBe(true);
+ expect(out.successRate).toBe(100);
+ expect(out.rateSource).toBe('windowed');
+ expect(out.reason).toContain('recent success');
+ });
+
+ it('still requires approval when the window is too thin (lifetime fallback)', async () => {
+ loadLearningData.mockResolvedValue(learningWith({ 'self-improve:x': thinWindowMetrics() }));
+ const out = await getTaskTypeConfidence('self-improve:x');
+ expect(out.tier).toBe('low');
+ expect(out.autoApprove).toBe(false);
+ expect(out.rateSource).toBe('lifetime');
+ });
+
+ it('keeps the null successRate sentinel for an unknown task type', async () => {
+ loadLearningData.mockResolvedValue(learningWith({}));
+ const out = await getTaskTypeConfidence('never-seen');
+ expect(out.tier).toBe('new');
+ expect(out.successRate).toBeNull();
+ });
+ });
+
+ describe('getTaskTypePriorityMultiplier', () => {
+ it('boosts a recovered type instead of demoting it', async () => {
+ loadLearningData.mockResolvedValue(learningWith({ 'self-improve:x': recoveredMetrics() }));
+ expect(await getTaskTypePriorityMultiplier('self-improve:x')).toBe(1.2);
+ });
+
+ it('demotes on the lifetime rate when the window is too thin', async () => {
+ loadLearningData.mockResolvedValue(learningWith({ 'self-improve:x': thinWindowMetrics() }));
+ expect(await getTaskTypePriorityMultiplier('self-improve:x')).toBe(0.9);
+ });
+ });
+
+ 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 }));
+ const out = await checkAndRehabilitateSkippedTasks();
+ expect(out.count).toBe(0);
+ expect(resetTaskTypeLearning).not.toHaveBeenCalled();
+ });
+
+ it('still rehabilitates a genuinely skipped type past the grace period', async () => {
+ const broken = stillFailingMetrics();
+ // Push BOTH the ring and lastCompleted outside any recency concern for the
+ // grace period; the ring stays in-window (30 days > 8 samples aged 10 days).
+ const tenDaysAgo = Date.now() - 10 * 24 * 60 * 60 * 1000;
+ broken.lastCompleted = new Date(tenDaysAgo).toISOString();
+ broken.recentOutcomes = ring(Array(8).fill(false), tenDaysAgo);
+ loadLearningData.mockResolvedValue(learningWith({ 'still-broken': broken }));
+ const out = await checkAndRehabilitateSkippedTasks(7 * 24 * 60 * 60 * 1000);
+ expect(out.count).toBe(1);
+ expect(resetTaskTypeLearning).toHaveBeenCalledWith('still-broken');
+ });
+ });
+});
diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.js
index 54664449a9..7d89c3edfc 100644
--- a/server/services/taskLearning/store.js
+++ b/server/services/taskLearning/store.js
@@ -127,6 +127,41 @@ export function computeWindowedStats(recentOutcomes, {
return { windowedCompleted, windowedSucceeded, windowedFailed, windowedSuccessRate };
}
+// Minimum windowed outcomes before the windowed rate is trusted over the
+// lifetime rate (issue #2617). Below this bar the window is too thin to read a
+// trend from, so decisions keep today's lifetime behavior (cold-start parity).
+export const EFFECTIVE_RATE_MIN_WINDOW_SAMPLES = 5;
+
+/**
+ * Effective success rate for DECISION paths (issue #2617). Pure / no I/O.
+ *
+ * Lifetime `successRate` never decays, so a burst of since-fixed failures
+ * permanently depresses it — cooldown/skip/approval decisions built on it keep
+ * punishing a task type long after it recovered. This returns the recency-
+ * windowed rate (`computeWindowedStats` over the bucket's `recentOutcomes`
+ * ring) whenever the window holds at least `minWindowSamples` outcomes, and
+ * falls back to the lifetime rate otherwise — so a type with a thin/empty
+ * window behaves exactly as before, while a type with a healthy recent record
+ * recovers as soon as it starts succeeding again.
+ *
+ * Sentinel discipline: `successRate` is `null` (never a fabricated 0) when the
+ * fallback lifetime rate is itself absent. `source` names which rate was used
+ * (`'windowed'` | `'lifetime'`) so decisions can surface it in reasons/logs.
+ *
+ * @param {Object|null|undefined} metrics - a `byTaskType` bucket
+ * @param {{ minWindowSamples?:number, maxCount?:number, maxAgeMs?:number, now?:number }} [opts]
+ * - extra keys are forwarded to `computeWindowedStats` (window bounds/clock seam)
+ * @returns {{ successRate:number|null, source:'windowed'|'lifetime', windowedCompleted:number }}
+ */
+export function computeEffectiveSuccessRate(metrics, opts = {}) {
+ const { minWindowSamples = EFFECTIVE_RATE_MIN_WINDOW_SAMPLES } = opts;
+ const { windowedCompleted, windowedSuccessRate } = computeWindowedStats(metrics?.recentOutcomes, opts);
+ if (windowedSuccessRate !== null && windowedCompleted >= minWindowSamples) {
+ return { successRate: windowedSuccessRate, source: 'windowed', windowedCompleted };
+ }
+ return { successRate: metrics?.successRate ?? null, source: 'lifetime', windowedCompleted };
+}
+
/**
* Default learning data structure
*/
diff --git a/server/services/taskLearning/store.test.js b/server/services/taskLearning/store.test.js
index 749397932e..853d5b1411 100644
--- a/server/services/taskLearning/store.test.js
+++ b/server/services/taskLearning/store.test.js
@@ -13,6 +13,8 @@ import {
EXTERNAL_UNTYPED_TASK_TYPE,
appendRecentOutcome,
computeWindowedStats,
+ computeEffectiveSuccessRate,
+ EFFECTIVE_RATE_MIN_WINDOW_SAMPLES,
RECENT_OUTCOMES_CAP,
DEFAULT_WINDOW_MAX_COUNT
} from './store.js';
@@ -480,3 +482,74 @@ describe('store.computeWindowedStats', () => {
expect(stats.windowedCompleted).toBe(DEFAULT_WINDOW_MAX_COUNT);
});
});
+
+describe('store.computeEffectiveSuccessRate (issue #2617)', () => {
+ // A recent ring of `n` outcomes ending now, oldest first.
+ const ring = (results, now = Date.now()) =>
+ results.map((s, i) => ({ t: new Date(now - (results.length - i) * 60000).toISOString(), s }));
+
+ it('returns the windowed rate when the window has enough samples (the issue\'s failure scenario)', () => {
+ // 40 failures during a since-fixed bug, then 15 straight successes:
+ // lifetime ≈ 27%, windowed = 100%. Decisions must read the windowed rate.
+ const metrics = {
+ completed: 55, succeeded: 15, failed: 40, successRate: 27,
+ recentOutcomes: ring(Array(15).fill(true))
+ };
+ expect(computeEffectiveSuccessRate(metrics)).toEqual({
+ successRate: 100, source: 'windowed', windowedCompleted: 15
+ });
+ });
+
+ it('falls back to the lifetime rate when the window has fewer than the minimum samples', () => {
+ const metrics = {
+ completed: 20, succeeded: 4, failed: 16, successRate: 20,
+ recentOutcomes: ring([true, true, true, true]) // 4 < EFFECTIVE_RATE_MIN_WINDOW_SAMPLES(5)
+ };
+ expect(computeEffectiveSuccessRate(metrics)).toEqual({
+ successRate: 20, source: 'lifetime', windowedCompleted: 4
+ });
+ });
+
+ it('falls back to lifetime on an empty or missing ring (pre-migration bucket)', () => {
+ expect(computeEffectiveSuccessRate({ completed: 10, successRate: 40 })).toMatchObject({
+ successRate: 40, source: 'lifetime', windowedCompleted: 0
+ });
+ expect(computeEffectiveSuccessRate({ completed: 10, successRate: 40, recentOutcomes: [] }).successRate).toBe(40);
+ });
+
+ it('returns the null sentinel (never a fabricated 0) when no rate exists at all', () => {
+ expect(computeEffectiveSuccessRate(undefined)).toEqual({
+ successRate: null, source: 'lifetime', windowedCompleted: 0
+ });
+ expect(computeEffectiveSuccessRate({ completed: 0 }).successRate).toBeNull();
+ });
+
+ it('ages stale samples out of the window before deciding — an old burst cannot keep the window "full"', () => {
+ const now = Date.parse('2026-07-12T00:00:00.000Z');
+ const DAY = 24 * 60 * 60 * 1000;
+ const stale = Array.from({ length: 10 }, () => ({ t: new Date(now - 40 * DAY).toISOString(), s: false }));
+ const metrics = { completed: 10, succeeded: 0, failed: 10, successRate: 0, recentOutcomes: stale };
+ // All 10 samples are older than the 30-day default window → lifetime fallback.
+ expect(computeEffectiveSuccessRate(metrics, { now })).toEqual({
+ successRate: 0, source: 'lifetime', windowedCompleted: 0
+ });
+ });
+
+ it('respects a caller-supplied minWindowSamples bar', () => {
+ const metrics = { successRate: 10, recentOutcomes: ring([true, true, true]) };
+ expect(computeEffectiveSuccessRate(metrics).source).toBe('lifetime'); // 3 < default 5
+ expect(computeEffectiveSuccessRate(metrics, { minWindowSamples: 3 })).toMatchObject({
+ successRate: 100, source: 'windowed'
+ });
+ expect(EFFECTIVE_RATE_MIN_WINDOW_SAMPLES).toBe(5);
+ });
+
+ it('trusts a BAD recent window too — recency cuts both ways', () => {
+ // Good lifetime rate but 6 recent failures → windowed 0% wins.
+ const metrics = {
+ completed: 100, succeeded: 90, failed: 10, successRate: 90,
+ recentOutcomes: ring(Array(6).fill(false))
+ };
+ expect(computeEffectiveSuccessRate(metrics)).toMatchObject({ successRate: 0, source: 'windowed' });
+ });
+});