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: unwind every poisoned LI aggregate via a shared helper, and keep real outages (#2700)

[._.]/ Adam Eivyde567131354a
diff --git a/scripts/migrations/197-purge-poisoned-li-learning-bucket.js b/scripts/migrations/197-purge-poisoned-li-learning-bucket.js
index 6336a2b4cf..2ef34144b9 100644
--- a/scripts/migrations/197-purge-poisoned-li-learning-bucket.js
+++ b/scripts/migrations/197-purge-poisoned-li-learning-bucket.js
@@ -33,12 +33,24 @@
* execution-health signal from its confidence math). Inventing a success rate to
* replace it would be the same sin in the opposite direction.
*
+ * Reuses `removeTaskTypeFromLearningData` rather than hand-rolling the removal.
+ * The bucket is not the only place the fabricated failures landed — they were also
+ * folded into `totals`, `byModelTier`, `routingAccuracy`, `errorPatterns`,
+ * `failureSignatures`, and `correlationWindow`. Deleting only `byTaskType` would
+ * leave the global success rate (the CoS Learning card) and routing still skewed
+ * while reporting success, and a second hand-written unwind here would drift from
+ * the runtime's as aggregates are added.
+ *
+ * Environmental failures are deliberately PRESERVED. `shouldDivertToEnvironmental`
+ * routes rate-limit/auth/network events to their own ledger and never into
+ * `byTaskType`, so they are recorded from real errors and are true regardless of
+ * this bug — unlike `resetTaskTypeLearning`, which purges them because a
+ * user-initiated reset means "forget this type entirely". This migration repairs
+ * mis-recorded data; it must not destroy a genuine outage history.
+ *
* Scoped to `self-improve:layered-intelligence` — the ONLY registered
- * programmatic-I/O task type (taskTypeHooks.js `HOOK_MODULES`), so no other
- * bucket was affected by the bug and none are touched here. Environmental-failure
- * entries keyed to the type are purged alongside it via the existing
- * `purgeEnvironmentalFailuresForType` helper, so the ledger can't keep pointing at
- * failures whose bucket is gone.
+ * programmatic-I/O task type (taskTypeHooks.js `HOOK_MODULES`), so no other bucket
+ * was affected by the bug and none are touched here.
*
* No-op by construction on installs that never ran LI (the common case) — the
* file is only rewritten when the bucket is actually present.
@@ -47,7 +59,7 @@
import { readFile, writeFile } from 'fs/promises';
import { join } from 'path';
-import { purgeEnvironmentalFailuresForType } from '../../server/services/taskLearning/metrics.js';
+import { removeTaskTypeFromLearningData } from '../../server/services/taskLearning/metrics.js';
const LEARNING_REL = 'data/cos/learning.json';
@@ -91,14 +103,14 @@ export default {
return { purged: 0 };
}
- const completed = byTaskType[LI_BUCKET]?.completed || 0;
- delete byTaskType[LI_BUCKET];
- // Keep the environmental-failure ledger consistent with the bucket we just
- // dropped — reuses the runtime helper rather than re-encoding its shape here.
- purgeEnvironmentalFailuresForType(data, LI_BUCKET);
+ // Unwinds the bucket AND its contribution to every other aggregate (totals,
+ // byModelTier, routingAccuracy, errorPatterns, failureSignatures,
+ // correlationWindow). The environmental ledger is intentionally left alone.
+ const previous = removeTaskTypeFromLearningData(data, LI_BUCKET);
+ const purged = previous?.completed || 0;
await writeFile(path, JSON.stringify(data, null, 2) + '\n');
- console.log(`🧹 LI learning: purged ${completed} mis-recorded layered-intelligence run(s) (#2700)`);
- return { purged: completed };
+ console.log(`🧹 LI learning: purged ${purged} mis-recorded layered-intelligence run(s) (#2700)`);
+ return { purged };
},
};
diff --git a/scripts/migrations/197-purge-poisoned-li-learning-bucket.test.js b/scripts/migrations/197-purge-poisoned-li-learning-bucket.test.js
index 3b76cdaa04..4a378e83d7 100644
--- a/scripts/migrations/197-purge-poisoned-li-learning-bucket.test.js
+++ b/scripts/migrations/197-purge-poisoned-li-learning-bucket.test.js
@@ -40,21 +40,63 @@ describe('197-purge-poisoned-li-learning-bucket (#2700)', () => {
expect(data.byTaskType['self-improve:ui'].successRate).toBe(80);
});
- it('purges the environmental-failure ledger entries for the dropped bucket', async () => {
+ it('unwinds the LI contribution from totals as well as the bucket', async () => {
+ // Deleting only byTaskType would leave the global success rate (the CoS
+ // Learning card) still reporting the fabricated failures.
await seed({
- byTaskType: { [LI_BUCKET]: { completed: 2, succeeded: 0, failed: 2, successRate: 0 } },
+ byTaskType: {
+ [LI_BUCKET]: { completed: 10, succeeded: 0, failed: 10, successRate: 0, totalDurationMs: 5000, successDurationMs: 0, successMaxDurationMs: 0 },
+ 'idle-review': { completed: 4, succeeded: 4, failed: 0, successRate: 100, totalDurationMs: 2000, successDurationMs: 2000, successMaxDurationMs: 700 }
+ },
+ totals: { completed: 14, succeeded: 4, failed: 10, totalDurationMs: 7000, successDurationMs: 2000, successMaxDurationMs: 700 }
+ });
+ await migration.up({ rootDir });
+ const { totals } = await readLearning();
+ // Only the surviving idle-review runs remain — a true 4/4, not 4/14.
+ expect(totals.completed).toBe(4);
+ expect(totals.succeeded).toBe(4);
+ expect(totals.failed).toBe(0);
+ expect(totals.totalDurationMs).toBe(2000);
+ });
+
+ it('unwinds routingAccuracy and its byModelTier contribution', async () => {
+ await seed({
+ byTaskType: {
+ [LI_BUCKET]: { completed: 4, succeeded: 0, failed: 4, successRate: 0, totalDurationMs: 4000, avgDurationMs: 1000 },
+ 'idle-review': { completed: 2, succeeded: 2, failed: 0, successRate: 100, totalDurationMs: 1000, avgDurationMs: 500 }
+ },
+ totals: { completed: 6, succeeded: 2, failed: 4, totalDurationMs: 5000 },
+ routingAccuracy: {
+ [LI_BUCKET]: { light: { succeeded: 0, failed: 4 } },
+ 'idle-review': { light: { succeeded: 2, failed: 0 } }
+ },
+ byModelTier: { light: { completed: 6, succeeded: 2, failed: 4, totalDurationMs: 5000, avgDurationMs: 833 } }
+ });
+ await migration.up({ rootDir });
+ const data = await readLearning();
+ expect(data.routingAccuracy[LI_BUCKET]).toBeUndefined();
+ expect(data.routingAccuracy['idle-review']).toBeDefined();
+ // The tier keeps only the non-LI runs, so routing stops seeing a poisoned tier.
+ expect(data.byModelTier.light.completed).toBe(2);
+ expect(data.byModelTier.light.failed).toBe(0);
+ });
+
+ it('PRESERVES genuine environmental failures — they were never poisoned by the bug', async () => {
+ // Rate-limit/auth/network events are diverted to their own ledger and never
+ // reach byTaskType, so they are real outages regardless of the commit bug.
+ // (resetTaskTypeLearning purges them; this repair migration must not.)
+ await seed({
+ byTaskType: { [LI_BUCKET]: { completed: 2, succeeded: 0, failed: 2, successRate: 0, totalDurationMs: 0 } },
+ totals: { completed: 2, succeeded: 0, failed: 2, totalDurationMs: 0 },
environmentalFailures: {
- 'network': { count: 3, lastOccurred: '2026-07-01T00:00:00Z', taskTypes: { [LI_BUCKET]: 2, 'idle-review': 1 } },
- 'disk': { count: 1, lastOccurred: '2026-07-01T00:00:00Z', taskTypes: { [LI_BUCKET]: 1 } }
+ 'network': { count: 3, lastOccurred: '2026-07-01T00:00:00Z', taskTypes: { [LI_BUCKET]: 2, 'idle-review': 1 } }
}
});
await migration.up({ rootDir });
const data = await readLearning();
- // The LI share is removed; the unrelated task type's entry survives.
- expect(data.environmentalFailures.network.taskTypes).toEqual({ 'idle-review': 1 });
- expect(data.environmentalFailures.network.count).toBe(1);
- // A category that only ever held LI failures goes away entirely.
- expect(data.environmentalFailures.disk).toBeUndefined();
+ expect(data.byTaskType[LI_BUCKET]).toBeUndefined();
+ expect(data.environmentalFailures.network.taskTypes[LI_BUCKET]).toBe(2);
+ expect(data.environmentalFailures.network.count).toBe(3);
});
it('is a no-op on an install that never ran LI', async () => {
@@ -66,6 +108,15 @@ describe('197-purge-poisoned-li-learning-bucket (#2700)', () => {
expect(await readFile(join(rootDir, LEARNING_REL), 'utf-8')).toBe(before);
});
+ it('tolerates a raw store missing the aggregates the runtime always layers on', async () => {
+ // Offline, there is no loadLearningData to apply defaults — a throw here would
+ // block boot instead of repairing anything.
+ await seed({ byTaskType: { [LI_BUCKET]: { completed: 3, succeeded: 0, failed: 3, successRate: 0 } } });
+ const out = await migration.up({ rootDir });
+ expect(out.purged).toBe(3);
+ expect((await readLearning()).byTaskType[LI_BUCKET]).toBeUndefined();
+ });
+
it('no-ops when the learning store does not exist yet', async () => {
const out = await migration.up({ rootDir });
expect(out).toEqual({ purged: 0, reason: 'no-file' });
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 615fc1a8aa..3e3487929b 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -592,6 +592,12 @@ export async function resetTaskTypeLearning(taskType) {
// Purge this type from the environmental buckets FIRST (#2618): an
// outage-only type has no byTaskType bucket, so the purge must not sit
// behind the task-type-not-found early return below.
+ //
+ // Deliberately part of the RESET path, not of removeTaskTypeFromLearningData:
+ // this function is "the user says this type is fixed — forget all of it", so
+ // dropping its outage history is intended. A caller repairing mis-recorded
+ // BUCKET data (e.g. migration 197) must not purge outages, which are recorded
+ // from real errors and are true regardless of any bucket-level bug.
const environmentalRemoved = purgeEnvironmentalFailuresForType(data, taskType);
const metrics = data.byTaskType[taskType];
@@ -604,22 +610,64 @@ export async function resetTaskTypeLearning(taskType) {
return { reset: false, reason: 'task-type-not-found', taskType };
}
- // Subtract this task type's contribution from totals
- data.totals.completed -= metrics.completed;
- data.totals.succeeded -= metrics.succeeded;
- data.totals.failed -= metrics.failed;
- data.totals.totalDurationMs -= metrics.totalDurationMs;
- if (data.totals.successDurationMs) {
- data.totals.successDurationMs = Math.max(0, data.totals.successDurationMs - (metrics.successDurationMs || 0));
+ const previousMetrics = removeTaskTypeFromLearningData(data, taskType);
+
+ await saveLearningData(data);
+
+ emitLog('info', `Reset learning data for ${taskType} (was ${metrics.successRate}% success after ${metrics.completed} attempts)`, {
+ taskType,
+ previousSuccessRate: metrics.successRate,
+ previousAttempts: metrics.completed
+ }, '📚 TaskLearning');
+
+ return { reset: true, taskType, previousMetrics };
+ });
+}
+
+/**
+ * Remove one task type's contribution from every learning aggregate, in place.
+ * Pure (mutates `data`, no I/O) so both the runtime reset and offline repairs
+ * (migrations) can share ONE definition of "what a task type contributes to" —
+ * a second, hand-rolled version would silently drift as aggregates are added.
+ *
+ * Unwinds: `totals` (+ recomputed max/ETA), `errorPatterns`, `byModelTier` (via
+ * `routingAccuracy`, which must be read BEFORE it is deleted), `routingAccuracy`,
+ * `byTaskType`, `failureSignatures` (#2619), and `correlationWindow` (#2619).
+ *
+ * Does NOT touch `environmentalFailures` — that is a separate ledger fed only by
+ * real outages, so removing it is a policy decision belonging to the caller (see
+ * `resetTaskTypeLearning`, which purges it; migration 197, which must not).
+ *
+ * @param {Object} data - the loaded learning store, mutated in place
+ * @param {string} taskType - e.g. 'self-improve:layered-intelligence'
+ * @returns {{ completed:number, succeeded:number, failed:number, successRate:number }|null}
+ * the removed bucket's headline metrics, or null when the type had no bucket.
+ */
+export function removeTaskTypeFromLearningData(data, taskType) {
+ const metrics = data?.byTaskType?.[taskType];
+ if (!metrics) return null;
+
+ // Subtract this task type's contribution from totals. Guarded because this helper
+ // also runs OFFLINE against a raw on-disk store (migrations), where the defaults
+ // loadLearningData applies at runtime haven't been layered on — and an aggregate
+ // this function throws on would block boot rather than repair anything.
+ if (data.totals && typeof data.totals === 'object') {
+ data.totals.completed -= metrics.completed;
+ data.totals.succeeded -= metrics.succeeded;
+ data.totals.failed -= metrics.failed;
+ data.totals.totalDurationMs -= metrics.totalDurationMs;
+ if (data.totals.successDurationMs) {
+ data.totals.successDurationMs = Math.max(0, data.totals.successDurationMs - (metrics.successDurationMs || 0));
+ }
+ // Recalculate max from remaining task types (we can't subtract a max)
+ const remainingTypes = Object.entries(data.byTaskType).filter(([t]) => t !== taskType);
+ data.totals.successMaxDurationMs = remainingTypes.reduce((max, [, m]) => Math.max(max, m.successMaxDurationMs || 0), 0);
+ Object.assign(data.totals, calculateDurationETA(data.totals));
}
- // Recalculate max from remaining task types (we can't subtract a max)
- const remainingTypes = Object.entries(data.byTaskType).filter(([t]) => t !== taskType);
- data.totals.successMaxDurationMs = remainingTypes.reduce((max, [, m]) => Math.max(max, m.successMaxDurationMs || 0), 0);
- Object.assign(data.totals, calculateDurationETA(data.totals));
// Clean up error patterns referencing this task type
- for (const [category, pattern] of Object.entries(data.errorPatterns)) {
- const taskTypeCount = pattern.taskTypes[taskType] || 0;
+ for (const [category, pattern] of Object.entries(data.errorPatterns || {})) {
+ const taskTypeCount = pattern?.taskTypes?.[taskType] || 0;
if (taskTypeCount > 0) {
pattern.count -= taskTypeCount;
delete pattern.taskTypes[taskType];
@@ -685,25 +733,12 @@ export async function resetTaskTypeLearning(taskType) {
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)`, {
- taskType,
- previousSuccessRate: metrics.successRate,
- previousAttempts: metrics.completed
- }, '📚 TaskLearning');
-
return {
- reset: true,
- taskType,
- previousMetrics: {
- completed: metrics.completed,
- succeeded: metrics.succeeded,
- failed: metrics.failed,
- successRate: metrics.successRate
- }
+ completed: metrics.completed,
+ succeeded: metrics.succeeded,
+ failed: metrics.failed,
+ successRate: metrics.successRate
};
- });
}
/**