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

feat: mirror spawn-time routing key + consume failureSignatures (#2333)

Adam Eivy842d61119ca5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index bf468eb85e..531c666963 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -16,6 +16,7 @@
- **[issue-2328] Auto-fix outcomes are now aggregated into dashboard telemetry with a success-rate trend.** The structured `metadata.diagnostics` persisted on every error-driven task (tier / category / failure reason) were queryable but never surfaced. A new pure aggregator (`server/services/autoFixMetrics.js`) reads them off task records and rolls them up by fallback tier, failure category, and task status — plus a time-to-recovery summary (count / avg / median / min / max) and a daily success-rate trend — exposed via `GET /api/autofix/metrics` and rendered by a new **Auto-Fix Telemetry** dashboard widget (overall recovery rate, trend sparkline, per-tier breakdown, median recovery time). To measure time-to-recovery, each diagnostics record now carries an `observedAt` failure timestamp; recovery is derived from the task's completion edit. Sentinel discipline throughout — a rate with no denominator and a duration with no completed-with-timing samples return `null`, never a fabricated `0`, so "no data yet" can't read as "0% success". (Further #2328 slice remains: full 4-tier fallback *execution* wiring — the classifier still annotates the investigation task rather than attempting each tier's fix in sequence.)
- **[issue-2333] Untyped task executions are now auto-classified instead of piling up as `unknown`.** Task-learning's `extractTaskType` used to dump every execution it couldn't pattern-match into a single blind `unknown` bucket — those tasks bypassed routing logic, skipped outcome learning, and leaked unstructured failures. It now runs an execution-entry classification hook (`classifyUntypedTask`, pure/idempotent/<50ms) that, before giving up, infers a concrete domain from additional signals — a `selfImprovementType` metadata hint, an explicit `task.taskType` the primary extractor didn't special-case (e.g. `scheduled` → `scheduled-task`), and broader whole-word description keyword signatures (`fix`/`investigate`/`crash` → `auto-fix`, `refactor`/`optimize` → `self-improve:general`, `review`/`audit` → `idle-review`, `unit test`/`coverage` → `test-task`) — and only falls back to a new sandboxed `external/untyped` type when nothing matches. Newly-classified and fallback executions flow through the existing #2329 failure-signature harvesting so their failures are captured in the normalized telemetry schema. The `external/untyped` bucket is explicitly walled off from routing (it never drives a model-tier suggestion and is never globally skipped) so a heterogeneous grab-bag can't create a routing blind spot or loop. (Partial delivery of #2333; the spawn-time key mirror in `agentModelSelection.extractTaskTypeKey` and deeper self-improvement-loop consumption of the harvested `failureSignatures` remain.)
+- **[issue-2333] The spawn-time routing lookup key now mirrors the recorded domain, and the self-improvement loop reads the enriched failure signatures (the #2333 remainder).** Two follow-ons close out #2333. First, `agentModelSelection.extractTaskTypeKey` — the key used at spawn time to look up historical routing performance — no longer falls back to a blind `'unknown'`; it now delegates the fallback to the same `classifyUntypedTask` the completion path records under, so an untyped task's routing lookup keys off the exact bucket its outcome will be recorded in (a concrete inferred domain, or the sandboxed `external/untyped`) instead of a bucket that never matches. Second, a new pure `summarizeFailureSignatures` reader turns the per-completion `failureSignatures` map (provider/model-attributed, success-criteria-aware) into a ranked, display-ready summary that the self-improvement loop now consumes: `getPromptImprovementRecommendations` emits a provider-attributed "route this task type away from X" suggestion (escalated to high priority when recent runs missed a declared success criterion) and exposes the structured signatures, and the Learning insights view surfaces the summary plus a provider/model-named recommendation once a provider crosses three recent failures — attribution the coarse `errorPatterns` count could never express. This closes #2333.
- **[issue-2344] Task-learning now stamps a success-criteria validation verdict on every completion and gates routing aggressiveness on a correlation-quality window (the #2329 remainder).** Each completion now carries an explicit `validationPassed` boolean — "did the run meet its DECLARED success criteria?" — distinct from the runner's exit-code `success`, so a task-referencing-commit task that exits clean but committed nothing is honestly recorded as a miss. Computed once at the shared completion chokepoint (`finalizeAgent`) via the existing `[task-<id>]` commit check and threaded through `buildTaskTelemetryContext`, the persisted agent result, and the harvested failure-signature samples; a null sentinel means "no machine-checkable criterion was declared" (interactive/user tasks, user-terminated runs) so "not declared" never collapses into "declared and failed". Separately, a new rolling correlation-quality window (`server/services/taskLearning/correlationQuality.js`) pairs each run's failure-signal *prediction* (did the enriched signal flag this run's tier, from history before the run) with its actual outcome and scores their correlation via the Matthews/phi coefficient — with a null sentinel (not `0`) for a degenerate window where a class is absent. `suggestModelTier` gates auto-adjustment aggressiveness on that score: until it clears >0.8 with enough samples, tier-avoidance requires a higher failure-sample bar (5 vs 3) so the system doesn't over-correct on an unproven signal. The gauge is surfaced on the Learning insights payload. This closes out the two deferred #2329 slices.
- **[issue-2329] Model routing now consumes the enriched failure signatures, and the latency split derives a queue/compute breakdown when a source timestamp is missing.** The `failureSignatures` telemetry recorded per completion (provider/model/tier-attributed, recency-bounded) is now read by `suggestModelTier`: a new pure `deriveFailureSignalAvoidance` cross-references those recent failures against `routingAccuracy` and steers selection off a tier that is BOTH accumulating recent failures for a task type AND unproven (success rate < 80%, or no success data) — catching a freshly-degrading tier before its all-time rate crosses the hard misroute line, while a proven tier keeps its slot despite absolute failures (signatures record failures only, so counts alone can't condemn a tier). The dominant failing provider/model is surfaced as a `failureSignal` on the suggestion and named in the model-selection log, so the routing decision is legible rather than "avoid tier X". Separately, the queue/compute latency split now falls back to `wall − compute` (or `wall − queue`) when a run carries no `createdAt` or no runner duration, with a per-leg `source` marker (`measured`/`derived`/`null`) so a derived value is never confused with a measured one and a legitimate `0ms` is never confused with an absent leg. (Further #2329 work remains: success-criteria validation booleans on every completion path and the >0.8 correlation-quality measurement window.)
- **[issue-2329] Task-learning now records a structured telemetry context for every completed agent.** On each completion the learning system builds a `TaskTelemetryContext` — a failure signature (`{ category, messageSnippet, failurePosition }`, reusing the category `agentErrorAnalysis` already classified), execution context (`provider`, `model`, `modelTier`, `taskType`, `component`, input-size, and the routing decision rationale), and a latency breakdown (`wallMs` spawn→completion vs. `queueMs` wait vs. `executionMs` measured) — using explicit null sentinels for anything not cheaply derivable rather than fabricating values. Failure signatures are aggregated per error category into a new additive `failureSignatures` block in `learning.json` (older files without the key load unchanged), and the enriched context is surfaced on the single-line completion log. (Partial delivery of #2329; routing auto-adjustment that consumes these signals, success-criteria validation flags, the queue/compute split where spawn timestamps are missing, and correlation-quality measurement remain.)
diff --git a/server/services/agentModelSelection.js b/server/services/agentModelSelection.js
index 36e3845559..1754802d50 100644
--- a/server/services/agentModelSelection.js
+++ b/server/services/agentModelSelection.js
@@ -7,10 +7,19 @@
import { resolveThinkingLevel, getModelForLevel, isLocalPreferred } from './thinkingLevels.js';
import { suggestModelTier } from './taskLearning.js';
+// Imported from the store submodule (not the mocked barrel) so the spawn-time key
+// mirrors the exact same classification the completion records under.
+import { classifyUntypedTask } from './taskLearning/store.js';
/**
* Extract task type key for learning lookup.
- * Matches the format used in taskLearning.js for consistency.
+ *
+ * Mirrors the domain `extractTaskType`/`classifyUntypedTask` record in the
+ * learning store so the spawn-time routing lookup keys off the SAME bucket the
+ * completion will later be recorded under (issue #2333). The fallback delegates
+ * to `classifyUntypedTask` — inferring a concrete domain (or the sandboxed
+ * `external/untyped` bucket) instead of the old blind `'unknown'`, which would
+ * miss the recorded domain and defeat the learning lookup on every untyped task.
*/
export function extractTaskTypeKey(task) {
if (task?.metadata?.analysisType) {
@@ -25,7 +34,7 @@ export function extractTaskTypeKey(task) {
if (typeMatch) return `self-improve:${typeMatch[1]}`;
}
if (task?.taskType === 'user') return 'user-task';
- return 'unknown';
+ return classifyUntypedTask(task);
}
/**
diff --git a/server/services/agentModelSelection.test.js b/server/services/agentModelSelection.test.js
index 1da89c95af..ef5e54e098 100644
--- a/server/services/agentModelSelection.test.js
+++ b/server/services/agentModelSelection.test.js
@@ -6,8 +6,9 @@ vi.mock('./taskLearning.js', () => ({
suggestModelTier: vi.fn()
}));
-import { selectModelForTask } from './agentModelSelection.js';
+import { selectModelForTask, extractTaskTypeKey } from './agentModelSelection.js';
import { suggestModelTier } from './taskLearning.js';
+import { EXTERNAL_UNTYPED_TASK_TYPE } from './taskLearning/store.js';
const PROVIDER = {
defaultModel: 'default-model',
@@ -59,3 +60,22 @@ describe('selectModelForTask — learning-suggested tier resolution', () => {
expect(result.reason).toBe('standard-task');
});
});
+
+describe('extractTaskTypeKey — spawn-time key mirror (issue #2333)', () => {
+ it('keeps the existing explicit-branch keys', () => {
+ expect(extractTaskTypeKey({ metadata: { analysisType: 'ui-bugs' } })).toBe('self-improve:ui-bugs');
+ expect(extractTaskTypeKey({ metadata: { reviewType: 'idle' } })).toBe('idle-review');
+ expect(extractTaskTypeKey({ description: '[self-improvement] security audit' })).toBe('self-improve:security');
+ expect(extractTaskTypeKey({ taskType: 'user' })).toBe('user-task');
+ });
+
+ it('delegates the fallback to classifyUntypedTask instead of the old blind "unknown"', () => {
+ // A description with no explicit branch match but a classifier keyword →
+ // the concrete recorded domain, not 'unknown'.
+ expect(extractTaskTypeKey({ description: 'fix the crashing login flow' })).toBe('auto-fix');
+ // Nothing classifiable → the sandboxed fallback bucket the store records.
+ expect(extractTaskTypeKey({ description: 'organize the weekly digest' })).toBe(EXTERNAL_UNTYPED_TASK_TYPE);
+ // Never the legacy 'unknown' sink.
+ expect(extractTaskTypeKey({})).not.toBe('unknown');
+ });
+});
diff --git a/server/services/taskLearning/index.js b/server/services/taskLearning/index.js
index a9203ed17a..f5ad37ca72 100644
--- a/server/services/taskLearning/index.js
+++ b/server/services/taskLearning/index.js
@@ -24,6 +24,7 @@ export {
extractTaskType,
classifyUntypedTask,
isSandboxedTaskType,
+ summarizeFailureSignatures,
EXTERNAL_UNTYPED_TASK_TYPE
} from './store.js';
diff --git a/server/services/taskLearning/insights.js b/server/services/taskLearning/insights.js
index 4f9371fd75..277f1c52b2 100644
--- a/server/services/taskLearning/insights.js
+++ b/server/services/taskLearning/insights.js
@@ -11,7 +11,8 @@ import {
loadLearningData,
saveLearningData,
loadDismissedRecommendations,
- saveDismissedRecommendations
+ saveDismissedRecommendations,
+ summarizeFailureSignatures
} from './store.js';
import { computeCorrelationQuality, isCorrelationProven, CORRELATION_QUALITY_THRESHOLD } from './correlationQuality.js';
@@ -50,6 +51,10 @@ export async function getLearningInsights() {
.sort((a, b) => b.count - a.count)
.slice(0, 5);
+ // Enriched failure signatures (issue #2333): provider/model attribution and
+ // success-criteria miss counts the coarse errorPatterns aggregate can't carry.
+ const failureSignatures = summarizeFailureSignatures(data.failureSignatures);
+
// Model tier effectiveness
const modelEffectiveness = Object.entries(data.byModelTier)
.map(([tier, metrics]) => ({
@@ -94,10 +99,11 @@ export async function getLearningInsights() {
completed: t.completed
})),
commonErrors,
+ failureSignatures,
modelEffectiveness,
recentUnknownErrors: data.recentUnknownErrors || []
},
- recommendations: generateRecommendations(data, bestPerforming, worstPerforming, commonErrors, dismissed)
+ recommendations: generateRecommendations(data, bestPerforming, worstPerforming, commonErrors, dismissed, failureSignatures)
};
}
@@ -131,7 +137,7 @@ function pushIfActive(recommendations, dismissed, rec) {
/**
* Generate actionable recommendations based on learning data
*/
-function generateRecommendations(data, bestPerforming, worstPerforming, commonErrors, dismissed = {}) {
+function generateRecommendations(data, bestPerforming, worstPerforming, commonErrors, dismissed = {}, failureSignatures = []) {
const recommendations = [];
// Recommend focusing on high-success task types
@@ -164,6 +170,20 @@ function generateRecommendations(data, bestPerforming, worstPerforming, commonEr
});
}
+ // Provider/model-attributed failure recommendation (issue #2333): the enriched
+ // failureSignatures map can name a specific provider/model behind a recurring
+ // failure category — more actionable than the raw errorPatterns count above.
+ const attributedSignature = failureSignatures.find(sig => sig.providers[0] && sig.providers[0].count >= 3);
+ if (attributedSignature) {
+ const topProvider = attributedSignature.providers[0];
+ pushIfActive(recommendations, dismissed, {
+ id: `failure-signature:${attributedSignature.category}`,
+ type: 'action',
+ message: `${topProvider.count} recent "${attributedSignature.category}" failures via ${topProvider.key}${attributedSignature.validationMissed > 0 ? ` (${attributedSignature.validationMissed} missed success criteria)` : ''} - investigate or route away`,
+ snapshot: { kind: 'count', value: topProvider.count }
+ });
+ }
+
// Check model tier usage
const heavyTier = data.byModelTier['heavy'];
const lightTier = data.byModelTier['light'];
diff --git a/server/services/taskLearning/insights.test.js b/server/services/taskLearning/insights.test.js
new file mode 100644
index 0000000000..4ea2daa2aa
--- /dev/null
+++ b/server/services/taskLearning/insights.test.js
@@ -0,0 +1,80 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./store.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ loadLearningData: vi.fn(),
+ loadDismissedRecommendations: vi.fn()
+ };
+});
+
+import { loadLearningData, loadDismissedRecommendations } from './store.js';
+import { getLearningInsights } from './insights.js';
+
+const learningData = (overrides = {}) => ({
+ lastUpdated: '2026-07-09T00:00:00Z',
+ totals: { completed: 10, succeeded: 6, avgDurationMs: 60000 },
+ byTaskType: {},
+ errorPatterns: {},
+ byModelTier: {},
+ correlationWindow: [],
+ failureSignatures: {},
+ recentUnknownErrors: [],
+ ...overrides
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ loadDismissedRecommendations.mockResolvedValue({});
+});
+
+describe('insights.getLearningInsights — failureSignatures consumption (issue #2333)', () => {
+ it('surfaces the enriched failureSignatures summary in the insights view', async () => {
+ loadLearningData.mockResolvedValue(learningData({
+ failureSignatures: {
+ 'tool-error': {
+ count: 4, lastOccurred: '2026-07-09T01:00:00Z',
+ recent: [
+ { provider: 'claude', model: 'opus', taskType: 'auto-fix', validationPassed: false, messageSnippet: 'a' },
+ { provider: 'claude', model: 'opus', taskType: 'auto-fix', validationPassed: true, messageSnippet: 'b' }
+ ]
+ }
+ }
+ }));
+ const view = await getLearningInsights();
+ expect(view.insights.failureSignatures).toHaveLength(1);
+ expect(view.insights.failureSignatures[0]).toMatchObject({
+ category: 'tool-error',
+ providers: [{ key: 'claude/opus', count: 2 }],
+ validationMissed: 1
+ });
+ });
+
+ it('emits a provider-attributed recommendation once a provider has >= 3 recent failures', async () => {
+ const recent = Array.from({ length: 3 }, (_, i) => ({
+ provider: 'codex', model: 'gpt', taskType: 'auto-fix', validationPassed: i === 0 ? false : null, messageSnippet: 'x'
+ }));
+ loadLearningData.mockResolvedValue(learningData({
+ failureSignatures: { 'startup-failure': { count: 3, recent } }
+ }));
+ const view = await getLearningInsights();
+ const rec = view.recommendations.find(r => r.id === 'failure-signature:startup-failure');
+ expect(rec).toBeTruthy();
+ expect(rec.message).toContain('codex/gpt');
+ expect(rec.snapshot).toEqual({ kind: 'count', value: 3 });
+ });
+
+ it('does not emit a failure-signature recommendation below the 3-failure threshold', async () => {
+ loadLearningData.mockResolvedValue(learningData({
+ failureSignatures: {
+ 'tool-error': { count: 2, recent: [
+ { provider: 'codex', model: 'gpt', taskType: 'auto-fix', validationPassed: null },
+ { provider: 'codex', model: 'gpt', taskType: 'auto-fix', validationPassed: null }
+ ] }
+ }
+ }));
+ const view = await getLearningInsights();
+ expect(view.recommendations.some(r => r.id?.startsWith('failure-signature:'))).toBe(false);
+ });
+});
diff --git a/server/services/taskLearning/promptRecommendations.js b/server/services/taskLearning/promptRecommendations.js
index efd618ec4f..534df4e1e6 100644
--- a/server/services/taskLearning/promptRecommendations.js
+++ b/server/services/taskLearning/promptRecommendations.js
@@ -6,7 +6,7 @@
* store.
*/
-import { loadLearningData } from './store.js';
+import { loadLearningData, summarizeFailureSignatures } from './store.js';
/**
* Generate prompt improvement recommendations for a specific task type
@@ -29,7 +29,8 @@ export async function getPromptImprovementRecommendations(taskType) {
completed: metrics?.completed || 0,
suggestions: [],
errorInsights: [],
- promptHints: []
+ promptHints: [],
+ failureSignatures: []
};
// Not enough data to make recommendations
@@ -112,6 +113,26 @@ export async function getPromptImprovementRecommendations(taskType) {
});
}
+ // Deeper failure-signature consumption (issue #2333): the enriched
+ // failureSignatures map names WHICH provider/model recently failed for this
+ // task type and how many missed a declared success criterion — attribution the
+ // coarse errorPatterns count above can't express. Surface the structured data
+ // plus an actionable "route away" suggestion the self-improvement loop can act on.
+ const failureSignatures = summarizeFailureSignatures(data.failureSignatures, { taskType });
+ recommendations.failureSignatures = failureSignatures;
+ for (const sig of failureSignatures) {
+ const topProvider = sig.providers[0];
+ if (!topProvider || topProvider.count < 2) continue;
+ recommendations.suggestions.push({
+ priority: sig.validationMissed > 0 ? 'high' : 'medium',
+ type: 'failure-signature',
+ message: `${topProvider.count} recent "${sig.category}" failures for this task type via ${topProvider.key}${sig.validationMissed > 0 ? ` (${sig.validationMissed} missed declared success criteria)` : ''}`,
+ action: sig.validationMissed > 0
+ ? `Tighten acceptance criteria or route this task type away from ${topProvider.key}`
+ : `Consider routing this task type away from ${topProvider.key} or adding guidance for the "${sig.category}" failure mode`
+ });
+ }
+
// Add general best practices based on task type category
const generalHints = getGeneralPromptHints(taskType);
recommendations.promptHints.push(...generalHints);
@@ -269,7 +290,8 @@ export async function getAllPromptRecommendations() {
completed: recommendations.completed,
topSuggestion: recommendations.suggestions[0] || null,
errorCount: recommendations.errorInsights.length,
- hintCount: recommendations.promptHints.length
+ hintCount: recommendations.promptHints.length,
+ failureSignatureCount: recommendations.failureSignatures.length
});
}
}
diff --git a/server/services/taskLearning/promptRecommendations.test.js b/server/services/taskLearning/promptRecommendations.test.js
index 2be5ebb692..e5ad0eed6e 100644
--- a/server/services/taskLearning/promptRecommendations.test.js
+++ b/server/services/taskLearning/promptRecommendations.test.js
@@ -84,6 +84,42 @@ describe('promptRecommendations.getPromptImprovementRecommendations', () => {
const rec = await getPromptImprovementRecommendations('self-improve:security-audit');
expect(rec.promptHints.some(h => h.hint === 'Add severity classification')).toBe(true);
});
+
+ it('consumes the enriched failureSignatures map for provider-attributed suggestions (issue #2333)', async () => {
+ loadLearningData.mockResolvedValue(data({
+ byTaskType: { t: { completed: 10, failed: 6, successRate: 40, avgDurationMs: 60000 } },
+ failureSignatures: {
+ 'tool-error': {
+ count: 4, lastOccurred: '2026-07-09T00:00:00Z',
+ recent: [
+ { taskType: 't', provider: 'claude', model: 'opus', validationPassed: false, messageSnippet: 'x' },
+ { taskType: 't', provider: 'claude', model: 'opus', validationPassed: true, messageSnippet: 'y' },
+ { taskType: 'other', provider: 'codex', model: 'gpt', validationPassed: false, messageSnippet: 'z' }
+ ]
+ }
+ },
+ }));
+ const rec = await getPromptImprovementRecommendations('t');
+ // Only the two 't' samples inform this task type's summary.
+ expect(rec.failureSignatures).toHaveLength(1);
+ expect(rec.failureSignatures[0].providers[0]).toEqual({ key: 'claude/opus', count: 2 });
+ const sig = rec.suggestions.find(s => s.type === 'failure-signature');
+ expect(sig).toBeTruthy();
+ expect(sig.priority).toBe('high'); // a validation miss present → high
+ expect(sig.message).toContain('claude/opus');
+ });
+
+ it('omits a failure-signature suggestion when a provider has fewer than 2 recent failures', async () => {
+ loadLearningData.mockResolvedValue(data({
+ byTaskType: { t: { completed: 10, failed: 6, successRate: 40, avgDurationMs: 60000 } },
+ failureSignatures: {
+ 'tool-error': { count: 1, recent: [{ taskType: 't', provider: 'claude', model: 'opus', validationPassed: null }] }
+ },
+ }));
+ const rec = await getPromptImprovementRecommendations('t');
+ expect(rec.failureSignatures).toHaveLength(1);
+ expect(rec.suggestions.some(s => s.type === 'failure-signature')).toBe(false);
+ });
});
describe('promptRecommendations.getAllPromptRecommendations', () => {
diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.js
index ac674d70c3..b8b1ca90e9 100644
--- a/server/services/taskLearning/store.js
+++ b/server/services/taskLearning/store.js
@@ -144,9 +144,10 @@ export async function saveLearningData(data) {
export const EXTERNAL_UNTYPED_TASK_TYPE = 'external/untyped';
// The new sandboxed fallback plus the legacy `'unknown'` sink it replaces. Older
-// installs (and the not-yet-migrated spawn-time key in agentModelSelection.js)
-// still produce `'unknown'` buckets, so it gets the same wall: stale/heterogeneous
-// uncategorized data must never drive a tier suggestion or globally skip work.
+// installs still hold `'unknown'` buckets from before the classifier (and the
+// spawn-time key in agentModelSelection.js) migrated onto the sandboxed bucket, so
+// it keeps the same wall: stale/heterogeneous uncategorized data must never drive a
+// tier suggestion or globally skip work.
const SANDBOXED_TASK_TYPES = new Set([EXTERNAL_UNTYPED_TASK_TYPE, 'unknown']);
/**
@@ -156,6 +157,66 @@ const SANDBOXED_TASK_TYPES = new Set([EXTERNAL_UNTYPED_TASK_TYPE, 'unknown']);
*/
export const isSandboxedTaskType = (taskType) => SANDBOXED_TASK_TYPES.has(taskType);
+/**
+ * Summarize the enriched `failureSignatures` map (issues #2329/#2333) into a
+ * ranked, display-ready list. Reads each category's `recent[]` samples to add
+ * provider/model attribution and success-criteria (validation) miss counts that
+ * the coarser `errorPatterns` aggregate can't express — so the self-improvement
+ * loop (insights + prompt recommendations) can say WHICH provider/model recently
+ * failed for a task type, not just how often a category occurred.
+ *
+ * Pure / read-only. When `taskType` is given, only samples recorded for that
+ * task type count (and categories with no matching sample are dropped) so a
+ * per-type recommendation never inherits another type's failures.
+ *
+ * @param {Object} failureSignatures - `data.failureSignatures`: `{ [category]: { count, lastOccurred, recent: [] } }`
+ * @param {Object} [opts]
+ * @param {string|null} [opts.taskType] - restrict samples to this task type
+ * @param {number} [opts.limit] - max categories returned (ranked by count desc)
+ * @returns {Array<{category, count, samples, lastOccurred, providers, validationMissed, sampleSnippet}>}
+ */
+export function summarizeFailureSignatures(failureSignatures, { taskType = null, limit = 5 } = {}) {
+ const map = failureSignatures && typeof failureSignatures === 'object' ? failureSignatures : {};
+ const summaries = [];
+
+ for (const [category, bucket] of Object.entries(map)) {
+ const recent = Array.isArray(bucket?.recent) ? bucket.recent : [];
+ const matched = taskType ? recent.filter((s) => s?.taskType === taskType) : recent;
+ // Task-type-scoped view drops categories with no sample for that type.
+ if (taskType && matched.length === 0) continue;
+
+ const attribution = new Map();
+ let validationMissed = 0;
+ for (const s of matched) {
+ const key = s?.provider
+ ? `${s.provider}${s.model ? `/${s.model}` : ''}`
+ : (s?.modelTier || 'unknown');
+ attribution.set(key, (attribution.get(key) || 0) + 1);
+ // Explicit === false so an absent/undefined criterion (null) isn't a miss.
+ if (s?.validationPassed === false) validationMissed++;
+ }
+
+ const providers = [...attribution.entries()]
+ .map(([key, count]) => ({ key, count }))
+ .sort((a, b) => b.count - a.count);
+ const latest = matched.length ? matched[matched.length - 1] : null;
+
+ summaries.push({
+ category,
+ // Per-type count reflects the matched samples; the global view prefers the
+ // lifetime `count` (recent[] is capped) and falls back to the sample size.
+ count: taskType ? matched.length : (Number(bucket?.count) || matched.length),
+ samples: matched.length,
+ lastOccurred: bucket?.lastOccurred || latest?.recordedAt || null,
+ providers,
+ validationMissed,
+ sampleSnippet: latest?.messageSnippet || null
+ });
+ }
+
+ return summaries.sort((a, b) => b.count - a.count).slice(0, Math.max(0, limit));
+}
+
/**
* Ordered description-keyword → concrete-type rules, tried only as a last resort
* before the sandboxed fallback. First match wins. Patterns are whole-word/stem
diff --git a/server/services/taskLearning/store.test.js b/server/services/taskLearning/store.test.js
index 6c8af34087..df73288600 100644
--- a/server/services/taskLearning/store.test.js
+++ b/server/services/taskLearning/store.test.js
@@ -4,6 +4,7 @@ import {
calculateDurationETA,
classifyUntypedTask,
isSandboxedTaskType,
+ summarizeFailureSignatures,
EXTERNAL_UNTYPED_TASK_TYPE
} from './store.js';
@@ -193,3 +194,72 @@ describe('store.calculateDurationETA', () => {
expect(out.p80DurationMs).toBe(300000);
});
});
+
+describe('store.summarizeFailureSignatures (issue #2333)', () => {
+ const sample = (over = {}) => ({
+ messageSnippet: 'boom', failurePosition: 'mid', provider: 'claude', model: 'opus',
+ modelTier: 'heavy', taskType: 'auto-fix', validationPassed: null, recordedAt: '2026-07-09T00:00:00Z',
+ ...over
+ });
+
+ it('returns [] for a missing / non-object map', () => {
+ expect(summarizeFailureSignatures(undefined)).toEqual([]);
+ expect(summarizeFailureSignatures(null)).toEqual([]);
+ expect(summarizeFailureSignatures('nope')).toEqual([]);
+ });
+
+ it('attributes provider/model and counts validation misses across recent samples', () => {
+ const out = summarizeFailureSignatures({
+ 'tool-error': {
+ count: 5, lastOccurred: '2026-07-09T01:00:00Z',
+ recent: [
+ sample({ provider: 'claude', model: 'opus', validationPassed: false }),
+ sample({ provider: 'claude', model: 'opus', validationPassed: true }),
+ sample({ provider: 'codex', model: 'gpt', validationPassed: false, messageSnippet: 'latest' })
+ ]
+ }
+ });
+ expect(out).toHaveLength(1);
+ const sig = out[0];
+ expect(sig.category).toBe('tool-error');
+ expect(sig.count).toBe(5); // lifetime count preferred in the global view
+ expect(sig.samples).toBe(3);
+ expect(sig.validationMissed).toBe(2);
+ // claude/opus is the dominant attribution (2 of 3)
+ expect(sig.providers[0]).toEqual({ key: 'claude/opus', count: 2 });
+ expect(sig.sampleSnippet).toBe('latest'); // most-recent sample wins
+ });
+
+ it('filters to a task type and drops categories with no matching sample', () => {
+ const out = summarizeFailureSignatures({
+ 'tool-error': {
+ count: 9,
+ recent: [sample({ taskType: 'auto-fix' }), sample({ taskType: 'idle-review' })]
+ },
+ 'rate-limit': {
+ count: 4,
+ recent: [sample({ taskType: 'idle-review' })]
+ }
+ }, { taskType: 'auto-fix' });
+ expect(out).toHaveLength(1);
+ expect(out[0].category).toBe('tool-error');
+ expect(out[0].count).toBe(1); // per-type view counts only matched samples
+ expect(out[0].samples).toBe(1);
+ });
+
+ it('falls back to modelTier attribution when provider is absent, and ranks by count desc', () => {
+ const out = summarizeFailureSignatures({
+ a: { count: 1, recent: [sample({ provider: null, model: null, modelTier: 'light' })] },
+ b: { count: 3, recent: [sample(), sample(), sample()] }
+ });
+ expect(out.map(s => s.category)).toEqual(['b', 'a']); // b (3) before a (1)
+ expect(out[1].providers[0]).toEqual({ key: 'light', count: 1 });
+ });
+
+ it('respects the limit', () => {
+ const map = Object.fromEntries(
+ Array.from({ length: 8 }, (_, i) => [`c${i}`, { count: i + 1, recent: [sample()] }])
+ );
+ expect(summarizeFailureSignatures(map, { limit: 3 })).toHaveLength(3);
+ });
+});