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-2618]): keep environmental failures out of task-learning success aggregates

[._.]/ Adam Eivy126e61714d62
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index 7c3de9633b..8f70886dba 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -17,6 +17,8 @@ import {
INVESTIGATION_CIRCUIT_MAX_CREATIONS,
__resetInvestigationCircuit
} from './agentErrorAnalysis.js';
+import { API_ACCESS_ERROR_CATEGORIES } from './agentErrorAnalysis.js';
+import { ENVIRONMENTAL_ERROR_CATEGORIES } from './taskLearning/metrics.js';
import { addTask, updateTask, getAllTasks } from './cos.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
@@ -565,3 +567,17 @@ describe('createInvestigationTask body', () => {
expect(body).not.toContain('/Users/alice');
});
});
+
+describe('API_ACCESS_ERROR_CATEGORIES ⊆ ENVIRONMENTAL_ERROR_CATEGORIES (issue #2618)', () => {
+ it('every investigation-skip category is also excluded from learning aggregates', () => {
+ // The two sets stay separate on purpose: API_ACCESS_ERROR_CATEGORIES gates
+ // investigation-task spawning here, while taskLearning's environmental set
+ // (a leaf constant — importing this module there would drag the cos.js task
+ // graph into every taskLearning consumer) gates the success-rate aggregates.
+ // But the subset relation must hold: a category whose failures can't even be
+ // investigated by an LLM is certainly not task/model signal.
+ for (const category of API_ACCESS_ERROR_CATEGORIES) {
+ expect(ENVIRONMENTAL_ERROR_CATEGORIES.has(category)).toBe(true);
+ }
+ });
+});
diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.js
index f0e134488f..0c9cf09b3a 100644
--- a/server/services/taskLearning.test.js
+++ b/server/services/taskLearning.test.js
@@ -509,6 +509,160 @@ describe('TaskLearning - recordTaskCompletion routing accuracy', () => {
});
});
+describe('TaskLearning - environmental failures (#2618)', () => {
+ let savedData;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ clearLearningCache();
+ savedData = null;
+ atomicWrite.mockImplementation(async (_path, data) => {
+ savedData = data;
+ });
+ });
+
+ const makeFailedAgent = (category, tier = 'heavy') => ({
+ metadata: { modelTier: tier, taskDescription: 'Fix UI' },
+ result: {
+ success: false,
+ duration: 30000,
+ errorAnalysis: { category, message: `provider says ${category}` }
+ }
+ });
+ const task = { description: 'Fix UI', taskType: 'user', metadata: {} };
+
+ it('keeps a rate-limit failure out of every success-rate aggregate and counts it separately', async () => {
+ const baseline = makeLearningData();
+ readFile.mockResolvedValue(JSON.stringify(baseline));
+
+ await recordTaskCompletion(makeFailedAgent('rate-limit'), task);
+
+ // byTaskType untouched — same counters/rate as the baseline, no recency sample.
+ expect(savedData.byTaskType['user-task']).toMatchObject({
+ completed: baseline.byTaskType['user-task'].completed,
+ succeeded: baseline.byTaskType['user-task'].succeeded,
+ failed: baseline.byTaskType['user-task'].failed,
+ successRate: baseline.byTaskType['user-task'].successRate
+ });
+ expect(savedData.byTaskType['user-task'].recentOutcomes).toBeUndefined();
+ // byModelTier untouched — the heavy tier bucket is not even initialized.
+ expect(savedData.byModelTier['heavy']).toBeUndefined();
+ // routingAccuracy untouched.
+ expect(savedData.routingAccuracy?.['user-task']).toBeUndefined();
+ // totals untouched — the overall rate is an aggregate too.
+ expect(savedData.totals).toMatchObject({
+ completed: baseline.totals.completed,
+ succeeded: baseline.totals.succeeded,
+ failed: baseline.totals.failed
+ });
+ // Correlation window untouched — an outage grades no routing prediction.
+ expect(savedData.correlationWindow ?? []).toEqual([]);
+
+ // ...but the event stays visible in the separate environmental record.
+ expect(savedData.environmentalFailures['rate-limit']).toMatchObject({
+ count: 1,
+ taskTypes: { 'user-task': 1 }
+ });
+ expect(savedData.environmentalFailures['rate-limit'].lastOccurred).toEqual(expect.any(String));
+ });
+
+ it('still records errorPatterns and failureSignatures for environmental categories (diagnostics)', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ await recordTaskCompletion(makeFailedAgent('billing-error'), task);
+
+ expect(savedData.errorPatterns['billing-error']).toMatchObject({
+ count: 1,
+ taskTypes: { 'user-task': 1 }
+ });
+ expect(savedData.failureSignatures['billing-error'].count).toBe(1);
+ expect(savedData.failureSignatures['billing-error'].recent[0]).toMatchObject({
+ taskType: 'user-task',
+ messageSnippet: 'provider says billing-error'
+ });
+ });
+
+ it('never creates a byTaskType bucket for a type whose only history is an outage', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ const freshTask = { description: '[auto-fix] investigate the crash', taskType: 'internal', metadata: {} };
+ await recordTaskCompletion(makeFailedAgent('startup-failure'), freshTask);
+
+ expect(savedData.byTaskType['auto-fix']).toBeUndefined();
+ expect(savedData.environmentalFailures['startup-failure'].taskTypes['auto-fix']).toBe(1);
+ });
+
+ it('accumulates environmental counts across completions', async () => {
+ let currentData = JSON.stringify(makeLearningData());
+ readFile.mockImplementation(async () => currentData);
+ atomicWrite.mockImplementation(async (_path, data) => {
+ currentData = JSON.stringify(data);
+ savedData = data;
+ });
+
+ await recordTaskCompletion(makeFailedAgent('rate-limit'), task);
+ await recordTaskCompletion(makeFailedAgent('rate-limit'), task);
+ await recordTaskCompletion(makeFailedAgent('auth'), task);
+
+ expect(savedData.environmentalFailures['rate-limit'].count).toBe(2);
+ expect(savedData.environmentalFailures['auth'].count).toBe(1);
+ expect(savedData.totals.failed).toBe(makeLearningData().totals.failed);
+ });
+
+ it('leaves a timeout failure counting against the aggregates exactly as today', async () => {
+ const baseline = makeLearningData();
+ readFile.mockResolvedValue(JSON.stringify(baseline));
+
+ await recordTaskCompletion(makeFailedAgent('timeout', 'light'), task);
+
+ // timeout is deliberately NOT environmental — it can be genuine task/model signal.
+ expect(savedData.byTaskType['user-task'].failed).toBe(baseline.byTaskType['user-task'].failed + 1);
+ expect(savedData.byModelTier['light'].failed).toBe(1);
+ expect(savedData.routingAccuracy['user-task']['light'].failed).toBe(1);
+ expect(savedData.totals.failed).toBe(baseline.totals.failed + 1);
+ expect(savedData.environmentalFailures).toBeUndefined();
+ });
+
+ it('loads a learning.json without the environmentalFailures key cleanly (back-compat)', async () => {
+ // makeLearningData has no environmentalFailures key — the additive key is
+ // initialized on first environmental recording, and a plain success write
+ // round-trips the file without fabricating one.
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ const agent = {
+ metadata: { modelTier: 'heavy', taskDescription: 'Fix UI' },
+ result: { success: true, duration: 30000 }
+ };
+ await recordTaskCompletion(agent, task);
+
+ expect(savedData.environmentalFailures).toBeUndefined();
+ expect(savedData.byTaskType['user-task'].succeeded)
+ .toBe(makeLearningData().byTaskType['user-task'].succeeded + 1);
+ });
+
+ it('surfaces environmentalFailures via getLearningInsights, sorted by count', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData({
+ environmentalFailures: {
+ 'auth': { count: 2, lastOccurred: '2026-07-01T00:00:00.000Z', taskTypes: { 'user-task': 2 } },
+ 'rate-limit': { count: 7, lastOccurred: '2026-07-02T00:00:00.000Z', taskTypes: { 'user-task': 4, 'auto-fix': 3 } }
+ }
+ })));
+
+ const insights = await getLearningInsights();
+
+ expect(insights.insights.environmentalFailures).toEqual([
+ { category: 'rate-limit', count: 7, lastOccurred: '2026-07-02T00:00:00.000Z', affectedTypes: ['user-task', 'auto-fix'] },
+ { category: 'auth', count: 2, lastOccurred: '2026-07-01T00:00:00.000Z', affectedTypes: ['user-task'] }
+ ]);
+ });
+
+ it('surfaces an empty environmentalFailures list for a learning.json that predates the key', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+ const insights = await getLearningInsights();
+ expect(insights.insights.environmentalFailures).toEqual([]);
+ });
+});
+
describe('TaskLearning - getRoutingAccuracy', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/server/services/taskLearning/index.js b/server/services/taskLearning/index.js
index 181310da7a..5a269d7fb2 100644
--- a/server/services/taskLearning/index.js
+++ b/server/services/taskLearning/index.js
@@ -47,6 +47,8 @@ export {
buildTaskTelemetryContext,
computeLatencySplit,
recordFailureSignature,
+ recordEnvironmentalFailure,
+ ENVIRONMENTAL_ERROR_CATEGORIES,
resetTaskTypeLearning,
recalculateModelTierMetrics,
recalculateDurationStats,
diff --git a/server/services/taskLearning/insights.js b/server/services/taskLearning/insights.js
index 1635ade176..90422be741 100644
--- a/server/services/taskLearning/insights.js
+++ b/server/services/taskLearning/insights.js
@@ -62,6 +62,19 @@ export async function getLearningInsights() {
// success-criteria miss counts the coarse errorPatterns aggregate can't carry.
const failureSignatures = summarizeFailureSignatures(data.failureSignatures);
+ // Environmental/infrastructure failures (issue #2618): rate-limit/auth/billing/
+ // startup-class events tracked apart from the task aggregates — surfaced here
+ // so the Learning UI can show an outage happened without it denting any rate.
+ // `|| {}` tolerates a learning.json that predates the additive key.
+ const environmentalFailures = Object.entries(data.environmentalFailures || {})
+ .map(([category, info]) => ({
+ category,
+ count: info.count,
+ lastOccurred: info.lastOccurred,
+ affectedTypes: Object.keys(info.taskTypes || {})
+ }))
+ .sort((a, b) => b.count - a.count);
+
// Model tier effectiveness
const modelEffectiveness = Object.entries(data.byModelTier)
.map(([tier, metrics]) => ({
@@ -111,6 +124,7 @@ export async function getLearningInsights() {
})),
commonErrors,
failureSignatures,
+ environmentalFailures,
modelEffectiveness,
recentUnknownErrors: data.recentUnknownErrors || []
},
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 2e82931007..4f09546dc2 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -34,6 +34,57 @@ import { recordCorrelationSample } from './correlationQuality.js';
// trends (provider/model/tier correlation) without a full agent-archive scan.
const MAX_SIGNATURE_SAMPLES = 10;
+// Environmental/infrastructure error categories (issue #2618): failures that say
+// nothing about the task or the model — a provider outage, an exhausted quota, a
+// revoked key, a dead network, an agent that never started. These are EXCLUDED
+// from the success-rate aggregates (`byTaskType` / `byModelTier` /
+// `routingAccuracy` / `totals` / the `recentOutcomes` windowed ring / the
+// correlation window) so an hour of provider 529s can't crater a task type's
+// rate, steer routing off a healthy tier, or trip the <30% skip gate. They are
+// instead counted in `data.environmentalFailures[category]` (count +
+// lastOccurred + affected task types) so the events stay visible, and they STILL
+// feed `errorPatterns` / `failureSignatures` — prompt recommendations and
+// diagnostics appropriately consume those.
+//
+// Deliberately EXCLUDES `timeout` and `unknown`: both can be genuine task/model
+// signal (a task too big for its tier times out; an uncategorized failure may be
+// anything). Superset of agentErrorAnalysis's `API_ACCESS_ERROR_CATEGORIES`
+// (auth-error / forbidden / usage-limit — asserted by a cross-check test in
+// agentErrorAnalysis.test.js) but defined here as its own leaf constant:
+// importing agentErrorAnalysis.js would drag the cos.js task-store graph into
+// every taskLearning consumer and suite.
+export const ENVIRONMENTAL_ERROR_CATEGORIES = new Set([
+ 'rate-limit',
+ 'usage-limit',
+ 'auth-error',
+ 'auth',
+ 'forbidden',
+ 'billing-error',
+ 'connection',
+ 'startup-failure',
+ 'model-not-available'
+]);
+
+/**
+ * Record an environmental failure into `data.environmentalFailures` (issue
+ * #2618). Pure — mutates and returns `data`. Mirrors the `errorPatterns` bucket
+ * shape (count + lastOccurred + per-task-type counts) so the UI can render both
+ * the same way. Additive + back-compat: tolerates a learning.json that predates
+ * the `environmentalFailures` key. No-op when the failure carries no category.
+ */
+export function recordEnvironmentalFailure(data, { category, taskType } = {}) {
+ if (!category) return data;
+ if (!data.environmentalFailures) data.environmentalFailures = {};
+ if (!data.environmentalFailures[category]) {
+ data.environmentalFailures[category] = { count: 0, lastOccurred: null, taskTypes: {} };
+ }
+ const bucket = data.environmentalFailures[category];
+ bucket.count++;
+ bucket.lastOccurred = new Date().toISOString();
+ bucket.taskTypes[taskType] = (bucket.taskTypes[taskType] || 0) + 1;
+ return data;
+}
+
/**
* Milliseconds between two ISO timestamps. Pure. Returns null (not 0) when
* either bound is missing/unparseable so an absent timestamp never masquerades
@@ -230,6 +281,14 @@ export async function recordTaskCompletion(agent, task) {
const duration = agent.result?.duration || 0;
const errorCategory = telemetry.failureSignature?.category || null;
+ // Environmental failure gate (issue #2618): a rate-limit/auth/billing/startup
+ // failure says nothing about the task type or the model tier, so it must not
+ // dent any success-rate aggregate or routing matrix — an outage would otherwise
+ // get a healthy task type skipped (<30% gate) or a healthy tier avoided. Such
+ // runs are diverted to `environmentalFailures` below; errorPatterns and
+ // failureSignatures still record them for diagnostics/prompt hints.
+ const isEnvironmentalFailure = !outcomeSuccess && ENVIRONMENTAL_ERROR_CATEGORIES.has(errorCategory);
+
// Correlation-quality prediction snapshot (issue #2344) — captured HERE, before
// ANY of this run's aggregates (byModelTier, routingAccuracy, failureSignatures)
// are folded in below, so the prediction reflects history strictly BEFORE this
@@ -245,82 +304,91 @@ export async function recordTaskCompletion(agent, task) {
? deriveFailureSignalAvoidance(data, taskType).avoidTiers.includes(modelTier)
: null;
- // Initialize task type bucket if needed
- if (!data.byTaskType[taskType]) {
- data.byTaskType[taskType] = {
- completed: 0,
- succeeded: 0,
- failed: 0,
- totalDurationMs: 0,
- avgDurationMs: 0,
- maxDurationMs: 0,
- p80DurationMs: 0,
- lastCompleted: null,
- successRate: 0,
- // Bounded recency ring (issue #2460) — feeds the windowed rate LI reads.
- recentOutcomes: []
- };
- }
+ if (isEnvironmentalFailure) {
+ // Divert to the separate environmental record (issue #2618): the event stays
+ // visible (count + lastOccurred + affected task types) without touching any
+ // bucket the routing/skip/approval decisions read. Deliberately skips even
+ // bucket *initialization* so a task type whose only history is an outage
+ // never grows an empty aggregate entry.
+ recordEnvironmentalFailure(data, { category: errorCategory, taskType });
+ } else {
+ // Initialize task type bucket if needed
+ if (!data.byTaskType[taskType]) {
+ data.byTaskType[taskType] = {
+ completed: 0,
+ succeeded: 0,
+ failed: 0,
+ totalDurationMs: 0,
+ avgDurationMs: 0,
+ maxDurationMs: 0,
+ p80DurationMs: 0,
+ lastCompleted: null,
+ successRate: 0,
+ // Bounded recency ring (issue #2460) — feeds the windowed rate LI reads.
+ recentOutcomes: []
+ };
+ }
- // Initialize model tier bucket if needed
- if (!data.byModelTier[modelTier]) {
- data.byModelTier[modelTier] = {
- completed: 0,
- succeeded: 0,
- failed: 0,
- totalDurationMs: 0,
- successDurationMs: 0,
- avgDurationMs: 0
- };
- }
+ // Initialize model tier bucket if needed
+ if (!data.byModelTier[modelTier]) {
+ data.byModelTier[modelTier] = {
+ completed: 0,
+ succeeded: 0,
+ failed: 0,
+ totalDurationMs: 0,
+ successDurationMs: 0,
+ avgDurationMs: 0
+ };
+ }
- // Update task type metrics
- const typeMetrics = data.byTaskType[taskType];
- typeMetrics.completed++;
- if (outcomeSuccess) {
- typeMetrics.succeeded++;
- // Only include successful durations in ETA calculations — failed agents often
- // run long in error loops and skew estimates
- typeMetrics.successDurationMs = (typeMetrics.successDurationMs || 0) + duration;
- typeMetrics.successMaxDurationMs = Math.max(typeMetrics.successMaxDurationMs || 0, duration);
- } else {
- typeMetrics.failed++;
- }
- typeMetrics.totalDurationMs += duration;
- 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 metrics
- const tierMetrics = data.byModelTier[modelTier];
- tierMetrics.completed++;
- if (outcomeSuccess) {
- tierMetrics.succeeded++;
- tierMetrics.successDurationMs = (tierMetrics.successDurationMs || 0) + duration;
- } else {
- tierMetrics.failed++;
- }
- tierMetrics.totalDurationMs += duration;
- tierMetrics.avgDurationMs = calculateDurationETA(tierMetrics).avgDurationMs;
-
- // Track routing accuracy: taskType × modelTier cross-reference
- if (!data.routingAccuracy) data.routingAccuracy = {};
- if (!data.routingAccuracy[taskType]) data.routingAccuracy[taskType] = {};
- if (!data.routingAccuracy[taskType][modelTier]) {
- data.routingAccuracy[taskType][modelTier] = { succeeded: 0, failed: 0, lastAttempt: null };
- }
- const routing = data.routingAccuracy[taskType][modelTier];
- if (outcomeSuccess) {
- routing.succeeded++;
- } else {
- routing.failed++;
+ // Update task type metrics
+ const typeMetrics = data.byTaskType[taskType];
+ typeMetrics.completed++;
+ if (outcomeSuccess) {
+ typeMetrics.succeeded++;
+ // Only include successful durations in ETA calculations — failed agents often
+ // run long in error loops and skew estimates
+ typeMetrics.successDurationMs = (typeMetrics.successDurationMs || 0) + duration;
+ typeMetrics.successMaxDurationMs = Math.max(typeMetrics.successMaxDurationMs || 0, duration);
+ } else {
+ typeMetrics.failed++;
+ }
+ typeMetrics.totalDurationMs += duration;
+ 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 metrics
+ const tierMetrics = data.byModelTier[modelTier];
+ tierMetrics.completed++;
+ if (outcomeSuccess) {
+ tierMetrics.succeeded++;
+ tierMetrics.successDurationMs = (tierMetrics.successDurationMs || 0) + duration;
+ } else {
+ tierMetrics.failed++;
+ }
+ tierMetrics.totalDurationMs += duration;
+ tierMetrics.avgDurationMs = calculateDurationETA(tierMetrics).avgDurationMs;
+
+ // Track routing accuracy: taskType × modelTier cross-reference
+ if (!data.routingAccuracy) data.routingAccuracy = {};
+ if (!data.routingAccuracy[taskType]) data.routingAccuracy[taskType] = {};
+ if (!data.routingAccuracy[taskType][modelTier]) {
+ data.routingAccuracy[taskType][modelTier] = { succeeded: 0, failed: 0, lastAttempt: null };
+ }
+ const routing = data.routingAccuracy[taskType][modelTier];
+ if (outcomeSuccess) {
+ routing.succeeded++;
+ } else {
+ routing.failed++;
+ }
+ routing.lastAttempt = new Date().toISOString();
}
- routing.lastAttempt = new Date().toISOString();
// Track error patterns — gated on the validation-authoritative outcome so a
// commit-found run isn't logged as an error and a criterion-miss is (#2344).
@@ -365,7 +433,10 @@ export async function recordTaskCompletion(agent, task) {
// with the actual outcome. Reuses the same validation-authoritative
// `outcomeSuccess` the aggregates above learn from, so the correlation `bad`
// label and the routing counts can never disagree about a single run.
- if (correlationPredictedRisk !== null) {
+ // Environmental failures are excluded (issue #2618): the window measures how
+ // well the routing signal predicts task/model outcomes, and an outage-shaped
+ // `bad` sample would grade the predictor on something it can't predict.
+ if (correlationPredictedRisk !== null && !isEnvironmentalFailure) {
recordCorrelationSample(data, { taskType, tier: modelTier, predictedRisk: correlationPredictedRisk, bad: !outcomeSuccess });
}
@@ -399,17 +470,20 @@ export async function recordTaskCompletion(agent, task) {
}
}
- // Update totals
- data.totals.completed++;
- if (outcomeSuccess) {
- data.totals.succeeded++;
- data.totals.successDurationMs = (data.totals.successDurationMs || 0) + duration;
- data.totals.successMaxDurationMs = Math.max(data.totals.successMaxDurationMs || 0, duration);
- } else {
- data.totals.failed++;
+ // Update totals — environmental failures stay out (issue #2618): the overall
+ // success rate is a rate aggregate too, and an outage must not dent it.
+ if (!isEnvironmentalFailure) {
+ data.totals.completed++;
+ if (outcomeSuccess) {
+ data.totals.succeeded++;
+ data.totals.successDurationMs = (data.totals.successDurationMs || 0) + duration;
+ data.totals.successMaxDurationMs = Math.max(data.totals.successMaxDurationMs || 0, duration);
+ } else {
+ data.totals.failed++;
+ }
+ data.totals.totalDurationMs += duration;
+ Object.assign(data.totals, calculateDurationETA(data.totals));
}
- data.totals.totalDurationMs += duration;
- Object.assign(data.totals, calculateDurationETA(data.totals));
await saveLearningData(data);
@@ -421,7 +495,7 @@ export async function recordTaskCompletion(agent, task) {
// rather than the misleading `success` the raw exit code would show (#2344).
const outcomeLabel = outcomeSuccess
? 'success'
- : `failed:${errorCategory || (success ? 'validation-miss' : 'uncategorized')}`;
+ : `failed:${errorCategory || (success ? 'validation-miss' : 'uncategorized')}${isEnvironmentalFailure ? ' environmental' : ''}`;
emitLog('debug', `Recorded task completion: ${taskType} (${outcomeLabel}) via ${provider || '?'}/${model || '?'}@${modelTier} [${component || '?'}] wall=${wallSecs}s`, {
taskType,
modelTier,
@@ -433,6 +507,7 @@ export async function recordTaskCompletion(agent, task) {
validationPassed: telemetry.validationPassed,
outcomeSuccess,
errorCategory,
+ environmental: isEnvironmentalFailure,
failurePosition: telemetry.failureSignature?.failurePosition ?? null,
wallMs,
queueMs,
diff --git a/server/services/taskLearning/metrics.test.js b/server/services/taskLearning/metrics.test.js
index c76587216a..3d683381b1 100644
--- a/server/services/taskLearning/metrics.test.js
+++ b/server/services/taskLearning/metrics.test.js
@@ -10,7 +10,7 @@ vi.mock('./store.js', async (importActual) => {
return { ...actual, loadLearningData: vi.fn() };
});
-import { buildTaskTelemetryContext, computeLatencySplit, recordFailureSignature, getWindowedStats } from './metrics.js';
+import { buildTaskTelemetryContext, computeLatencySplit, recordFailureSignature, getWindowedStats, recordEnvironmentalFailure, ENVIRONMENTAL_ERROR_CATEGORIES } from './metrics.js';
import { loadLearningData } from './store.js';
// buildTaskTelemetryContext + recordFailureSignature are the pure telemetry
@@ -398,3 +398,58 @@ describe('getWindowedStats (issue #2460)', () => {
expect(stats.windowedSuccessRate).toBe(100);
});
});
+
+describe('ENVIRONMENTAL_ERROR_CATEGORIES (issue #2618)', () => {
+ it('contains exactly the environmental/infrastructure categories', () => {
+ expect([...ENVIRONMENTAL_ERROR_CATEGORIES].sort()).toEqual([
+ 'auth',
+ 'auth-error',
+ 'billing-error',
+ 'connection',
+ 'forbidden',
+ 'model-not-available',
+ 'rate-limit',
+ 'startup-failure',
+ 'usage-limit'
+ ]);
+ });
+
+ it('deliberately excludes categories that can be genuine task/model signal', () => {
+ // timeout: a task too big for its tier legitimately times out; unknown: could
+ // be anything — excluding them from learning would blind routing to real signal.
+ expect(ENVIRONMENTAL_ERROR_CATEGORIES.has('timeout')).toBe(false);
+ expect(ENVIRONMENTAL_ERROR_CATEGORIES.has('unknown')).toBe(false);
+ expect(ENVIRONMENTAL_ERROR_CATEGORIES.has('test-failure')).toBe(false);
+ expect(ENVIRONMENTAL_ERROR_CATEGORIES.has(null)).toBe(false);
+ });
+});
+
+describe('recordEnvironmentalFailure (issue #2618)', () => {
+ it('initializes the additive key on data that predates it (back-compat)', () => {
+ const data = {}; // old learning.json shape — no environmentalFailures key
+ recordEnvironmentalFailure(data, { category: 'rate-limit', taskType: 'auto-fix' });
+
+ expect(data.environmentalFailures['rate-limit'].count).toBe(1);
+ expect(data.environmentalFailures['rate-limit'].lastOccurred).toEqual(expect.any(String));
+ expect(data.environmentalFailures['rate-limit'].taskTypes).toEqual({ 'auto-fix': 1 });
+ });
+
+ it('accumulates counts and affected task types per category', () => {
+ const data = {};
+ recordEnvironmentalFailure(data, { category: 'rate-limit', taskType: 'auto-fix' });
+ recordEnvironmentalFailure(data, { category: 'rate-limit', taskType: 'auto-fix' });
+ recordEnvironmentalFailure(data, { category: 'rate-limit', taskType: 'user-task' });
+ recordEnvironmentalFailure(data, { category: 'billing-error', taskType: 'user-task' });
+
+ expect(data.environmentalFailures['rate-limit'].count).toBe(3);
+ expect(data.environmentalFailures['rate-limit'].taskTypes).toEqual({ 'auto-fix': 2, 'user-task': 1 });
+ expect(data.environmentalFailures['billing-error'].count).toBe(1);
+ });
+
+ it('is a no-op when the failure carries no category', () => {
+ const data = {};
+ recordEnvironmentalFailure(data, { category: null, taskType: 'auto-fix' });
+ recordEnvironmentalFailure(data, {});
+ expect(data.environmentalFailures).toBeUndefined();
+ });
+});
diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.js
index 21b7779d30..9e4501f4ab 100644
--- a/server/services/taskLearning/store.js
+++ b/server/services/taskLearning/store.js
@@ -210,6 +210,14 @@ const DEFAULT_LEARNING_DATA = {
// Records which model tiers work/fail for each task type
routingAccuracy: {},
+ // Environmental/infrastructure failures (issue #2618): category →
+ // { count, lastOccurred, taskTypes } for rate-limit/auth/billing/startup-class
+ // failures, which are kept OUT of every success-rate aggregate above so an
+ // outage can't poison routing/skip decisions (see ENVIRONMENTAL_ERROR_CATEGORIES
+ // in metrics.js). Additive: older learning.json files predate this key and load
+ // fine — the recording path initializes it on first use.
+ environmentalFailures: {},
+
// Rolling correlation-quality window (issue #2344): prediction/outcome pairs
// measuring how well the enriched failure signals predict actual outcomes.
// Gates auto-adjustment aggressiveness (see correlationQuality.js). Additive: