Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: decay CoS task-learning success rates via a recency window (#2460)
Adam Eivyadc64b77e969
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0e8d54be52..8c78846383 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changes+- **CoS task-learning success rates now decay via a recency window, so a since-resolved failure burst stops signaling Layered Intelligence that work is needed (#2460).** The `byTaskType` counters in `data/cos/learning.json` are lifetime-cumulative and never age out — a provider misconfig or PTY-capture artifacts recorded as failures on a now-retired task type permanently depressed the success rate the LI reasoner reads via its `cosMetrics` source (default-on for PortOS), long after the root cause was fixed. Each task-type bucket now also carries a bounded `recentOutcomes` ring (`{ t, s }`, cap 50, mirroring the `failureSignatures.recent` precedent) that `recordTaskCompletion` appends to; a new pure `computeWindowedStats` derives a `recentSuccessRate` windowed by BOTH count and age (defaults: last 30 runs / 30 days, configurable), exposed via `getWindowedStats(taskType, { maxCount, maxAgeMs })`. The LI `cosMetrics` source now surfaces lifetime and windowed rates labeled distinctly, so a resolved failure burst self-heals without a manual `resetTaskTypeLearning`, while the lifetime counters stay intact for the dashboard/telemetry views. `recentSuccessRate` uses a `null` sentinel (never a fabricated `0%`) when the window has no samples, so the reasoner falls back to the lifetime rate. Store version bumped 1→2 with an idempotent migration (188) that initializes an EMPTY ring per task type — deliberately not backfilled from failure-only history, which would fabricate an all-failure window.+- **The inline-claim task prompts now name `grok` as a local-CLI reviewer (#2453).** After Grok became a selectable Review Loop reviewer, the four inline-claim prompt defaults (`plan-task`, `claim-issue`, `claim-issue-gitlab`, `claim-issue-jira`) still enumerated only `` `claude` / `codex` / `antigravity` `` in their per-kind reviewer-handling bullets, leaving grok un-categorized as a CLI reviewer when a user set it as their default. All seven bullet sites now list `` `grok` `` alongside the other coding-agent CLIs. Following the cross-install prompt-upgrade contract, each of the four task types gets a `PROMPT_VERSIONS` bump with the entire prior default preserved in `PREVIOUS_DEFAULT_PROMPTS`, so non-customized installs auto-upgrade; the integrity snapshot is regenerated. Text-only change.- **Media-gen marker parsers converged onto `createLineReader` too (#2463, follow-up to #2392).** The two remaining hand-copied per-chunk splitters — `imageGen/local.js` (stderr + stdout) and `videoGen/local.js` (stderr, plus a stdout `'\n'`-carry that never flushed the last line and decoded each chunk independently) — parsed `STAGE:`/`STATUS:`/`DOWNLOAD:` protocol markers with no carry buffer, so a marker or multibyte char split across a pipe chunk boundary could tear a progress event. Both services now route line parsing through `server/lib/streamLines.js#createLineReader` (StringDecoder-backed, carry across chunks, `flush()` on `close`), while the render-critical machinery is left exactly as-is: idle-stall + completion watchdogs still fire on the same signals (`resetIdleStallTimer` stays in the per-chunk `data` handler; the videoGen flush runs *before* the watchdog clears so a final result-JSON line can't re-arm a stray SIGKILL), the imageGen `stderrBuffer` error tail keeps accumulating raw chunk text, and the stdout JSON `video_path`/result capture is unchanged. Behavior-preserving; adds a chunk-boundary test proving a marker split across two chunks parses as one event.diff --git a/scripts/migrations/188-cos-learning-recent-outcomes-ring.js b/scripts/migrations/188-cos-learning-recent-outcomes-ring.jsnew file mode 100644index 0000000000..7dd741ce05--- /dev/null+++ b/scripts/migrations/188-cos-learning-recent-outcomes-ring.js@@ -0,0 +1,72 @@+/**+ * Initialize the per-task-type recent-outcomes ring on data/cos/learning.json+ * and bump the store version to 2 (issue #2460).+ *+ * Background: the CoS task-learning counters (`byTaskType[type].completed/+ * succeeded/failed/successRate`) are lifetime-cumulative and never decay, so a+ * burst of since-resolved failures permanently depresses the success rate the+ * Layered Intelligence reasoner reads via its `cosMetrics` source. `metrics.js`+ * now appends every completion to a bounded `recentOutcomes` ring, and LI reads a+ * recency-windowed rate derived from it (`computeWindowedStats`). Existing+ * installs' learning.json predate the ring; this migration adds an empty ring to+ * each task-type bucket so the store shape matches v2.+ *+ * Deliberately EMPTY, not backfilled: `failureSignatures.recent` holds only+ * FAILURE samples, so seeding the ring from it would fabricate an all-failure+ * recent window — the exact false signal this issue removes. The ring fills from+ * real outcomes going forward; until it holds samples, LI's windowed rate is null+ * and the reasoner falls back to the intact lifetime rate.+ *+ * Idempotent: a second run finds every bucket already has a `recentOutcomes`+ * array and the version already at 2, so it writes nothing.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';++const readJson = async (path, fallback) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return fallback;+ try { return JSON.parse(raw); } catch { return fallback; }+};++const writeJson = (path, value) =>+ writeFile(path, JSON.stringify(value, null, 2) + '\n');++export async function up({ rootDir }) {+ const learningPath = join(rootDir, 'data', 'cos', 'learning.json');+ const data = await readJson(learningPath, null);++ // No learning.json yet — a fresh install seeds v2 with empty rings on first+ // completion (DEFAULT_LEARNING_DATA + bucket init in metrics.js). Nothing to do.+ if (!data || typeof data !== 'object') {+ console.log('📚 cos-learning ring: no learning.json — nothing to migrate (fresh install seeds v2)');+ return { migrated: false, initialized: 0 };+ }++ const byTaskType = data.byTaskType && typeof data.byTaskType === 'object' ? data.byTaskType : {};+ let initialized = 0;+ for (const metrics of Object.values(byTaskType)) {+ if (metrics && typeof metrics === 'object' && !Array.isArray(metrics.recentOutcomes)) {+ metrics.recentOutcomes = [];+ initialized++;+ }+ }++ const bumpedVersion = data.version !== 2;+ if (bumpedVersion) data.version = 2;++ if (initialized > 0 || bumpedVersion) {+ await writeJson(learningPath, data);+ console.log(`📚 cos-learning ring: initialized recentOutcomes on ${initialized} task type(s), version → 2`);+ return { migrated: true, initialized };+ }++ console.log('✅ cos-learning ring: already initialized — no changes');+ return { migrated: false, initialized: 0 };+}++export default { up };diff --git a/scripts/migrations/188-cos-learning-recent-outcomes-ring.test.js b/scripts/migrations/188-cos-learning-recent-outcomes-ring.test.jsnew file mode 100644index 0000000000..7e275d5688--- /dev/null+++ b/scripts/migrations/188-cos-learning-recent-outcomes-ring.test.js@@ -0,0 +1,83 @@+/**+ * Tests for migration 188 — initialize the per-task-type recent-outcomes ring on+ * data/cos/learning.json and bump the store version to 2 (issue #2460).+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './188-cos-learning-recent-outcomes-ring.js';++describe('migration 188 — cos-learning recent-outcomes ring', () => {+ let rootDir;+ let learningPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'mig188-'));+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });+ learningPath = join(rootDir, 'data', 'cos', 'learning.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ const write = (obj) => writeFileSync(learningPath, JSON.stringify(obj, null, 2));+ const read = () => JSON.parse(readFileSync(learningPath, 'utf-8'));++ it('initializes an empty ring on each task type and bumps version to 2', async () => {+ write({+ version: 1,+ byTaskType: {+ 'self-improve:ui': { completed: 3, succeeded: 1, failed: 2, successRate: 33 },+ 'idle-review': { completed: 5, succeeded: 5, failed: 0, successRate: 100 }+ }+ });++ const result = await migration.up({ rootDir });+ expect(result).toEqual({ migrated: true, initialized: 2 });++ const data = read();+ expect(data.version).toBe(2);+ expect(data.byTaskType['self-improve:ui'].recentOutcomes).toEqual([]);+ expect(data.byTaskType['idle-review'].recentOutcomes).toEqual([]);+ // Lifetime counters left untouched.+ expect(data.byTaskType['self-improve:ui'].completed).toBe(3);+ });++ it('does NOT backfill the ring from failure history (would fabricate an all-failure window)', async () => {+ write({+ version: 1,+ byTaskType: { 'auto-fix': { completed: 4, succeeded: 0, failed: 4, successRate: 0 } },+ failureSignatures: { timeout: { count: 4, recent: [{ taskType: 'auto-fix' }] } }+ });++ await migration.up({ rootDir });+ expect(read().byTaskType['auto-fix'].recentOutcomes).toEqual([]);+ });++ it('is idempotent — a second run writes nothing new', async () => {+ write({+ version: 1,+ byTaskType: { 'auto-fix': { completed: 1, succeeded: 1, failed: 0, successRate: 100 } }+ });++ await migration.up({ rootDir });+ // Simulate real activity landing in the ring between runs.+ const afterFirst = read();+ afterFirst.byTaskType['auto-fix'].recentOutcomes.push({ t: '2026-07-11T00:00:00.000Z', s: true });+ writeFileSync(learningPath, JSON.stringify(afterFirst, null, 2));++ const result = await migration.up({ rootDir });+ expect(result).toEqual({ migrated: false, initialized: 0 });+ // The real sample recorded between runs is preserved (not clobbered/reset).+ expect(read().byTaskType['auto-fix'].recentOutcomes).toEqual([{ t: '2026-07-11T00:00:00.000Z', s: true }]);+ });++ it('no-ops when learning.json does not exist yet (fresh install)', async () => {+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ migrated: false, initialized: 0 });+ expect(existsSync(learningPath)).toBe(false);+ });+});diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex 5fb95a7e08..8974496715 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -26,6 +26,7 @@ import { existsSync } from 'fs';import { DAY, tryReadFile, readJSONFile, safeJSONParse, PATHS } from '../lib/fileUtils.js';import { bufferedSpawn } from '../lib/bufferedSpawn.js';import { createTicket, searchIssues, addLabels, escapeJql } from './jira.js';+import { computeWindowedStats } from './taskLearning/store.js';// Tracker labels + slug marker. The slug is the stable dedup key the reasoner// chooses; it is embedded in each filed issue body so a later run (or the@@ -611,7 +612,24 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos } = {}) {// rationale (default-off for managed apps).const learning = await readJSONFile(join(cosPath, 'learning.json'), null);if (learning?.byTaskType) {- out.cosMetrics = JSON.stringify(learning.byTaskType).slice(0, 4000);+ // Surface BOTH the lifetime rate (the cumulative dashboard/telemetry truth)+ // AND a recency-windowed rate (issue #2460) per task type, labeled distinctly+ // so the reasoner doesn't conflate them. The windowed rate lets a+ // since-resolved failure burst age out of the "is work needed" signal instead+ // of permanently depressing it; `recentSuccessRate` is null when there are no+ // in-window runs, in which case the reasoner leans on the lifetime rate.+ const summary = {};+ for (const [type, m] of Object.entries(learning.byTaskType)) {+ const windowed = computeWindowedStats(m?.recentOutcomes);+ summary[type] = {+ lifetimeSuccessRate: typeof m?.successRate === 'number' ? m.successRate : null,+ lifetimeCompleted: m?.completed || 0,+ recentSuccessRate: windowed.windowedSuccessRate,+ recentCompleted: windowed.windowedCompleted,+ avgDurationMs: m?.avgDurationMs || 0+ };+ }+ out.cosMetrics = JSON.stringify(summary).slice(0, 4000);}}for (const custom of src.custom || []) {diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex 6aacf02bea..a944084fc8 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -1148,3 +1148,64 @@ describe('listForgeIssues url surfacing (issue #2293)', () => {expect(issues[0].url).toBeNull();});});++describe('gatherSources cosMetrics windowed rate (issue #2460)', () => {+ let dir;+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'lil-cosmetrics-')); });+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });++ const writeLearning = (learning) => writeFile(join(dir, 'learning.json'), JSON.stringify(learning));++ it('surfaces a recency-windowed rate distinct from the lifetime rate', async () => {+ const now = Date.now();+ const DAY = 24 * 60 * 60 * 1000;+ // Lifetime rate is dragged down by an old failure burst; the recent ring is+ // all successes → windowed rate should read high while lifetime reads low.+ await writeLearning({+ byTaskType: {+ 'self-improve:ui': {+ completed: 12, succeeded: 2, failed: 10, successRate: 17, avgDurationMs: 1000,+ recentOutcomes: [+ { t: new Date(now - 40 * DAY).toISOString(), s: false }, // aged out of the 30d window+ { t: new Date(now - 2 * DAY).toISOString(), s: true },+ { t: new Date(now - 1 * DAY).toISOString(), s: true }+ ]+ }+ }+ });+ const out = await gatherSources({ repoPath: dir }, { sources: { cosMetrics: true } }, { cosPath: dir });+ const parsed = JSON.parse(out.cosMetrics);+ expect(parsed['self-improve:ui'].lifetimeSuccessRate).toBe(17);+ expect(parsed['self-improve:ui'].lifetimeCompleted).toBe(12);+ expect(parsed['self-improve:ui'].recentSuccessRate).toBe(100);+ expect(parsed['self-improve:ui'].recentCompleted).toBe(2);+ });++ it('reports a null recentSuccessRate (not 0) when the ring is empty so LI leans on lifetime', async () => {+ await writeLearning({+ byTaskType: {+ 'idle-review': { completed: 5, succeeded: 5, failed: 0, successRate: 100, recentOutcomes: [] }+ }+ });+ const out = await gatherSources({ repoPath: dir }, { sources: { cosMetrics: true } }, { cosPath: dir });+ const parsed = JSON.parse(out.cosMetrics);+ expect(parsed['idle-review'].recentSuccessRate).toBeNull();+ expect(parsed['idle-review'].lifetimeSuccessRate).toBe(100);+ });++ it('tolerates a pre-migration bucket with no recentOutcomes key', async () => {+ await writeLearning({+ byTaskType: { 'auto-fix': { completed: 3, succeeded: 1, failed: 2, successRate: 33 } }+ });+ const out = await gatherSources({ repoPath: dir }, { sources: { cosMetrics: true } }, { cosPath: dir });+ const parsed = JSON.parse(out.cosMetrics);+ expect(parsed['auto-fix'].recentSuccessRate).toBeNull();+ expect(parsed['auto-fix'].lifetimeSuccessRate).toBe(33);+ });++ it('does not read learning.json when cosMetrics is off', async () => {+ await writeLearning({ byTaskType: { x: { successRate: 50, recentOutcomes: [] } } });+ const out = await gatherSources({ repoPath: dir }, { sources: { cosMetrics: false } }, { cosPath: dir });+ expect(out.cosMetrics).toBeUndefined();+ });+});diff --git a/server/services/taskLearning/index.js b/server/services/taskLearning/index.jsindex e58e22d7fb..c25589baff 100644--- a/server/services/taskLearning/index.js+++ b/server/services/taskLearning/index.js@@ -31,7 +31,12 @@ export {recurrenceMilestoneReached,INSIGHT_CAP,RECURRENCE_INSIGHT_MILESTONES,- EXTERNAL_UNTYPED_TASK_TYPE+ EXTERNAL_UNTYPED_TASK_TYPE,+ appendRecentOutcome,+ computeWindowedStats,+ RECENT_OUTCOMES_CAP,+ DEFAULT_WINDOW_MAX_COUNT,+ DEFAULT_WINDOW_MAX_AGE_MS} from './store.js';export {@@ -41,7 +46,8 @@ export {recordFailureSignature,resetTaskTypeLearning,recalculateModelTierMetrics,- recalculateDurationStats+ recalculateDurationStats,+ getWindowedStats} from './metrics.js';export {diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.jsindex 58c30eb588..2e82931007 100644--- a/server/services/taskLearning/metrics.js+++ b/server/services/taskLearning/metrics.js@@ -20,7 +20,11 @@ import {saveLearningData,appendInsight,buildRecurrenceInsight,- recurrenceMilestoneReached+ recurrenceMilestoneReached,+ appendRecentOutcome,+ computeWindowedStats,+ DEFAULT_WINDOW_MAX_COUNT,+ DEFAULT_WINDOW_MAX_AGE_MS} from './store.js';import { deriveFailureSignalAvoidance, isNonRoutableLearnedTier } from './routing.js';import { recordCorrelationSample } from './correlationQuality.js';@@ -252,7 +256,9 @@ export async function recordTaskCompletion(agent, task) {maxDurationMs: 0,p80DurationMs: 0,lastCompleted: null,- successRate: 0+ successRate: 0,+ // Bounded recency ring (issue #2460) — feeds the windowed rate LI reads.+ recentOutcomes: []};}@@ -284,6 +290,11 @@ export async function recordTaskCompletion(agent, task) {Object.assign(typeMetrics, calculateDurationETA(typeMetrics));typeMetrics.lastCompleted = new Date().toISOString();typeMetrics.successRate = Math.round((typeMetrics.succeeded / typeMetrics.completed) * 100);+ // Append this run to the bounded recency ring (issue #2460). The lifetime+ // counters above never decay; the ring lets LI read a recency-windowed rate so+ // a since-resolved failure burst ages out of the "is work needed" signal+ // instead of depressing it forever. Stamped with the same `lastCompleted` time.+ appendRecentOutcome(typeMetrics, { success: outcomeSuccess, at: typeMetrics.lastCompleted });// Update model tier metricsconst tierMetrics = data.byModelTier[modelTier];@@ -433,6 +444,26 @@ export async function recordTaskCompletion(agent, task) {});}+/**+ * Recency-windowed success stats for a task type (issue #2460). Loads the+ * learning store, reads the task type's `recentOutcomes` ring, and windows it by+ * count and/or age via the pure `computeWindowedStats`. Read-only. Returns the+ * `null`-successRate sentinel when the task type is absent or has no in-window+ * samples, so callers (Layered Intelligence) can fall back to the lifetime rate+ * rather than treat "no recent runs" as a fabricated 0%.+ *+ * @param {string} taskType+ * @param {{ maxCount?:number, maxAgeMs?:number }} [opts]+ */+export async function getWindowedStats(taskType, {+ maxCount = DEFAULT_WINDOW_MAX_COUNT,+ maxAgeMs = DEFAULT_WINDOW_MAX_AGE_MS+} = {}) {+ const data = await loadLearningData();+ const metrics = data.byTaskType?.[taskType];+ return computeWindowedStats(metrics?.recentOutcomes, { maxCount, maxAgeMs });+}+/*** Reset learning data for a specific task type* Used when a previously-failing task type has been fixed and should be retrieddiff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.jsindex eab3387612..03179831df 100644--- a/server/services/taskLearning/store.js+++ b/server/services/taskLearning/store.js@@ -39,11 +39,103 @@ export function calculateDurationETA(metrics) {return { avgDurationMs: avg, maxDurationMs: max, p80DurationMs: p80 };}+// ---------------------------------------------------------------------------+// Recent-outcomes ring (issue #2460)+//+// Lifetime `byTaskType` counters (completed/succeeded/failed/successRate) are+// cumulative and never decay, so a burst of since-resolved failures (a provider+// misconfig, PTY-capture artifacts on a now-retired task type) permanently+// depresses the success rate the Layered Intelligence reasoner reads via its+// `cosMetrics` source and keeps signaling "work needed" long after the root cause+// is fixed. To let that signal self-heal WITHOUT destroying the lifetime stats the+// dashboards display, each task-type bucket also carries a bounded ring of recent+// outcomes (`{ t: ISO timestamp, s: success bool }`). `computeWindowedStats`+// derives a recency-windowed success rate from it (bounded by BOTH count and age)+// that LI consumes instead of the lifetime rate. Mirrors the existing+// `failureSignatures.recent` / `recentUnknownErrors` rolling-buffer precedent.+// ---------------------------------------------------------------------------++// Cap on retained recent-outcome samples per task type (oldest pruned first).+export const RECENT_OUTCOMES_CAP = 50;++// Default recency window applied when reading the ring: at most this many+// most-recent runs AND no older than this age. Either bound alone can shrink the+// window; both are overridable per call.+export const DEFAULT_WINDOW_MAX_COUNT = 30;+export const DEFAULT_WINDOW_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days++/**+ * Append a recent outcome to a task-type metrics bucket's bounded ring (issue+ * #2460). Pure — mutates and returns `metrics`. Stores the compact `{ t, s }`+ * shape (ISO timestamp + success bool). Tolerates a bucket that predates the ring+ * (older learning.json before migration 188) by initializing it. Enforces+ * `RECENT_OUTCOMES_CAP`, dropping the oldest sample first.+ */+export function appendRecentOutcome(metrics, { success, at } = {}) {+ if (!metrics || typeof metrics !== 'object') return metrics;+ if (!Array.isArray(metrics.recentOutcomes)) metrics.recentOutcomes = [];+ metrics.recentOutcomes.push({ t: at || new Date().toISOString(), s: !!success });+ if (metrics.recentOutcomes.length > RECENT_OUTCOMES_CAP) {+ metrics.recentOutcomes = metrics.recentOutcomes.slice(-RECENT_OUTCOMES_CAP);+ }+ return metrics;+}++/**+ * Compute recency-windowed success stats from a task-type recent-outcomes ring+ * (issue #2460). Pure / no I/O. Windows the ring by BOTH a max sample count and a+ * max age, then computes the success rate over just that window.+ *+ * Sentinel discipline (repo "absent vs empty" rule): `windowedSuccessRate` is+ * `null` when the window contains NO samples — never 0 — so a task type with no+ * recent runs is distinguishable from one that recently failed everything. LI+ * falls back to the lifetime rate on null rather than reading a fabricated 0%.+ *+ * @param {Array<{t:string,s:boolean}>} recentOutcomes - the bucket's ring+ * @param {{ maxCount?:number, maxAgeMs?:number, now?:number }} [opts]+ * @returns {{ windowedCompleted:number, windowedSucceeded:number,+ * windowedFailed:number, windowedSuccessRate:number|null }}+ */+export function computeWindowedStats(recentOutcomes, {+ maxCount = DEFAULT_WINDOW_MAX_COUNT,+ maxAgeMs = DEFAULT_WINDOW_MAX_AGE_MS,+ now = Date.now()+} = {}) {+ const ring = Array.isArray(recentOutcomes) ? recentOutcomes : [];+ const ageCutoff = Number.isFinite(maxAgeMs) && maxAgeMs > 0 ? now - maxAgeMs : null;++ // Age-filter first (drop stale outcomes), then keep only the most-recent+ // `maxCount`. An undated sample (unparseable `t`) is kept — the count bound+ // still applies, so a hand-edited ring can't grow the window unbounded.+ const withinAge = ageCutoff === null+ ? ring+ : ring.filter((o) => {+ const t = Date.parse(o?.t);+ return Number.isFinite(t) ? t >= ageCutoff : true;+ });+ const windowed = Number.isFinite(maxCount) && maxCount > 0+ ? withinAge.slice(-maxCount)+ : withinAge;++ const windowedCompleted = windowed.length;+ const windowedSucceeded = windowed.reduce((n, o) => n + (o?.s ? 1 : 0), 0);+ const windowedFailed = windowedCompleted - windowedSucceeded;+ const windowedSuccessRate = windowedCompleted > 0+ ? Math.round((windowedSucceeded / windowedCompleted) * 100)+ : null;++ return { windowedCompleted, windowedSucceeded, windowedFailed, windowedSuccessRate };+}+/*** Default learning data structure*/const DEFAULT_LEARNING_DATA = {- version: 1,+ // v2 (issue #2460): each byTaskType bucket carries a bounded `recentOutcomes`+ // ring so the signal LI reads can be recency-windowed (see appendRecentOutcome+ // / computeWindowedStats below). Migration 188 initializes the ring on existing+ // installs; fresh installs seed at v2.+ version: 2,lastUpdated: null,// Metrics by self-improvement task typediff --git a/server/services/taskLearning/store.test.js b/server/services/taskLearning/store.test.jsindex 068a73e924..749397932e 100644--- a/server/services/taskLearning/store.test.js+++ b/server/services/taskLearning/store.test.js@@ -10,7 +10,11 @@ import {recurrenceMilestoneReached,RECURRENCE_INSIGHT_MILESTONES,INSIGHT_CAP,- EXTERNAL_UNTYPED_TASK_TYPE+ EXTERNAL_UNTYPED_TASK_TYPE,+ appendRecentOutcome,+ computeWindowedStats,+ RECENT_OUTCOMES_CAP,+ DEFAULT_WINDOW_MAX_COUNT} from './store.js';// These two helpers are the pure foundation every other taskLearning submodule@@ -379,3 +383,100 @@ describe('store.buildRecurrenceInsight', () => {expect(insight.message).not.toContain('via');});});++// ---------------------------------------------------------------------------+// Recent-outcomes ring (issue #2460) — pure ring append/cap + windowed-rate math.+// No I/O, so exercised directly without touching the real learning.json.+// ---------------------------------------------------------------------------++describe('store.appendRecentOutcome', () => {+ it('initializes the ring and stores the compact { t, s } shape', () => {+ const metrics = {};+ appendRecentOutcome(metrics, { success: true, at: '2026-07-10T00:00:00.000Z' });+ expect(metrics.recentOutcomes).toEqual([{ t: '2026-07-10T00:00:00.000Z', s: true }]);+ });++ it('coerces success to a boolean and defaults the timestamp when absent', () => {+ const metrics = { recentOutcomes: [] };+ appendRecentOutcome(metrics, { success: 0 });+ expect(metrics.recentOutcomes[0].s).toBe(false);+ expect(typeof metrics.recentOutcomes[0].t).toBe('string');+ });++ it('caps the ring at RECENT_OUTCOMES_CAP, dropping the oldest first', () => {+ const metrics = {};+ for (let i = 0; i < RECENT_OUTCOMES_CAP + 10; i++) {+ appendRecentOutcome(metrics, { success: true, at: `run-${i}` });+ }+ expect(metrics.recentOutcomes).toHaveLength(RECENT_OUTCOMES_CAP);+ // Oldest 10 dropped — first retained is run-10, last is the newest.+ expect(metrics.recentOutcomes[0].t).toBe('run-10');+ expect(metrics.recentOutcomes.at(-1).t).toBe(`run-${RECENT_OUTCOMES_CAP + 9}`);+ });++ it('is a no-op on a non-object metrics bucket', () => {+ expect(appendRecentOutcome(null, { success: true })).toBeNull();+ });+});++describe('store.computeWindowedStats', () => {+ const iso = (msAgo, now) => new Date(now - msAgo).toISOString();++ it('returns a null successRate sentinel (not 0) when the window is empty', () => {+ const stats = computeWindowedStats([]);+ expect(stats).toEqual({+ windowedCompleted: 0,+ windowedSucceeded: 0,+ windowedFailed: 0,+ windowedSuccessRate: null+ });+ // A missing/undefined ring behaves the same.+ expect(computeWindowedStats(undefined).windowedSuccessRate).toBeNull();+ });++ it('computes the success rate over all in-window samples', () => {+ const ring = [+ { t: '2026-07-10T00:00:00.000Z', s: true },+ { t: '2026-07-10T00:01:00.000Z', s: false },+ { t: '2026-07-10T00:02:00.000Z', s: true },+ { t: '2026-07-10T00:03:00.000Z', s: true }+ ];+ const stats = computeWindowedStats(ring, { maxAgeMs: Infinity });+ expect(stats.windowedCompleted).toBe(4);+ expect(stats.windowedSucceeded).toBe(3);+ expect(stats.windowedFailed).toBe(1);+ expect(stats.windowedSuccessRate).toBe(75);+ });++ it('keeps only the most-recent maxCount samples', () => {+ // 10 failures (older) followed by 5 successes (newer); window last 5 → 100%.+ const ring = [];+ for (let i = 0; i < 10; i++) ring.push({ t: `old-${i}`, s: false });+ for (let i = 0; i < 5; i++) ring.push({ t: `new-${i}`, s: true });+ const stats = computeWindowedStats(ring, { maxCount: 5, maxAgeMs: Infinity });+ expect(stats.windowedCompleted).toBe(5);+ expect(stats.windowedSuccessRate).toBe(100);+ });++ it('ages out samples older than maxAgeMs — a resolved failure burst self-heals', () => {+ const now = Date.parse('2026-07-12T00:00:00.000Z');+ const DAY = 24 * 60 * 60 * 1000;+ const ring = [+ // Old failure burst (40 days ago) — should age out of a 30-day window.+ { t: iso(40 * DAY, now), s: false },+ { t: iso(40 * DAY, now), s: false },+ // Recent successes (within 30 days).+ { t: iso(2 * DAY, now), s: true },+ { t: iso(1 * DAY, now), s: true }+ ];+ const stats = computeWindowedStats(ring, { maxAgeMs: 30 * DAY, now });+ expect(stats.windowedCompleted).toBe(2);+ expect(stats.windowedSuccessRate).toBe(100);+ });++ it('defaults to the exported count window when maxCount is unspecified', () => {+ const ring = Array.from({ length: DEFAULT_WINDOW_MAX_COUNT + 20 }, (_, i) => ({ t: `r-${i}`, s: true }));+ const stats = computeWindowedStats(ring, { maxAgeMs: Infinity });+ expect(stats.windowedCompleted).toBe(DEFAULT_WINDOW_MAX_COUNT);+ });+});