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(cos): add routing accuracy tracking for task-to-model routing (M40-P3)

Adam Eivyd5329cf512b5
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.md
index 4c1b10b7bc..d29d839ac8 100644
--- a/.changelog/v0.12.x.md
+++ b/.changelog/v0.12.x.md
@@ -444,7 +444,7 @@ This release adds branch management and automated release workflow capabilities
### M40: Agent Skill System — In Progress
- **Task-type-specific prompt templates** ✅: New `data/prompts/skills/` directory with 6 specialized agent briefings per task category (bug-fix, feature, security-audit, refactor, documentation, mobile-responsive) — each with routing descriptions, embedded examples, and task-specific guidelines. `buildAgentPrompt()` now detects skill type via keyword matching and injects the matched template into the agent briefing. Templates only load when matched to avoid token inflation.
- **Agent context compaction** ✅: Context-limit and output-limit error patterns now include compaction metadata (output size, retry hints) that propagates through task retry metadata. When an agent retries after a context-limit failure, the briefing prompt includes a "Context Compaction Required" section with mandatory output constraints. Agent briefing template updated with task-type-specific output format constraints for documentation, refactors, security audits, and bug fixes.
-- **Negative example routing**: Anti-pattern recording in task learning so failed model/task-type combinations are tracked and auto-avoided, with routing accuracy surfaced in the Learning tab
+- **Negative example routing** ✅: Anti-pattern recording in task learning — every task completion now records a `routingAccuracy` cross-reference (taskType × modelTier) with success/failure counts. `suggestModelTier()` enhanced to avoid tiers with <40% success and prefer proven-successful tiers. New "Routing Accuracy" section in Learning tab shows misroutes, tier overview cards, and a full task-type × tier matrix table. New `GET /api/cos/learning/routing` endpoint. Reset also cleans up routing data.
- **Deterministic workflow skills**: Recurring autonomous jobs (daily briefing, git maintenance, security audit, app improvement) converted from inline prompts to versioned, editable skill templates with defined steps, outputs, and success criteria
### CyberCity — Borough Layout Redesign
diff --git a/PLAN.md b/PLAN.md
index 637bec8d7e..732bc4a8f8 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -139,11 +139,12 @@ Long-running agents can hit context limits causing failures. Add proactive conte
- ✅ Add compaction metadata to agent error analysis so retries can include "compact context" instructions
- ✅ Update the agent briefing to include explicit output format constraints for verbose task types
-### P3: Negative Example Coverage for Task Routing
+### P3: Negative Example Coverage for Task Routing ✅
Improve task-to-model routing accuracy by adding negative examples to the model selection logic:
-- Document which task types should NOT use light models (already partially done, but formalize it)
-- Add "anti-patterns" to task learning: when a task type fails with a specific model, record the negative signal
-- Surface routing accuracy metrics in the Learning tab so the user can see misroutes
+- ✅ Document which task types should NOT use light models (already partially done, but formalize it)
+- ✅ Add "anti-patterns" to task learning: when a task type fails with a specific model, record the negative signal via `routingAccuracy` cross-reference (taskType × modelTier)
+- ✅ Surface routing accuracy metrics in the Learning tab so the user can see misroutes
+- ✅ Enhanced `suggestModelTier()` to use negative signal data for smarter tier avoidance
### P4: Deterministic Workflow Skills
For recurring autonomous jobs (daily briefing, git maintenance, security audit, app improvement), encode the full workflow as a deterministic skill:
diff --git a/client/src/components/cos/tabs/LearningTab.jsx b/client/src/components/cos/tabs/LearningTab.jsx
index e7b9cd0c04..e06a0854b8 100644
--- a/client/src/components/cos/tabs/LearningTab.jsx
+++ b/client/src/components/cos/tabs/LearningTab.jsx
@@ -16,7 +16,8 @@ import {
ChevronDown,
ChevronRight,
Database,
- RotateCcw
+ RotateCcw,
+ Crosshair
} from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../../services/api';
@@ -26,6 +27,7 @@ export default function LearningTab() {
const [performance, setPerformance] = useState(null);
const [skipped, setSkipped] = useState(null);
const [durations, setDurations] = useState(null);
+ const [routing, setRouting] = useState(null);
const [loading, setLoading] = useState(true);
const [backfilling, setBackfilling] = useState(false);
const [resettingType, setResettingType] = useState(null);
@@ -34,21 +36,24 @@ export default function LearningTab() {
skipped: true,
durations: false,
models: true,
+ routing: true,
errors: false
});
const loadData = useCallback(async () => {
setLoading(true);
- const [learningData, performanceData, skippedData, durationsData] = await Promise.all([
+ const [learningData, performanceData, skippedData, durationsData, routingData] = await Promise.all([
api.getCosLearning().catch(() => null),
api.getCosLearningPerformance().catch(() => null),
api.getCosLearningSkipped().catch(() => null),
- api.getCosLearningDurations().catch(() => null)
+ api.getCosLearningDurations().catch(() => null),
+ api.getCosLearningRouting().catch(() => null)
]);
setLearning(learningData);
setPerformance(performanceData);
setSkipped(skippedData);
setDurations(durationsData);
+ setRouting(routingData);
setLoading(false);
}, []);
@@ -481,6 +486,127 @@ export default function LearningTab() {
</div>
)}
+ {/* Routing Accuracy */}
+ {routing?.matrix?.length > 0 && (
+ <div>
+ <button
+ onClick={() => toggleSection('routing')}
+ className="flex items-center gap-2 w-full text-left mb-3"
+ >
+ {expandedSections.routing ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
+ <Crosshair size={16} className="text-orange-400" />
+ <span className="font-medium text-white">Routing Accuracy</span>
+ <span className="text-xs text-gray-500">
+ ({routing.matrix.length} task types)
+ </span>
+ {routing.totalMisroutes > 0 && (
+ <span className="text-xs text-port-error">
+ ({routing.totalMisroutes} misroute{routing.totalMisroutes !== 1 ? 's' : ''})
+ </span>
+ )}
+ </button>
+ {expandedSections.routing && (
+ <div className="space-y-4">
+ {/* Misroutes Alert */}
+ {routing.misroutes?.length > 0 && (
+ <div className="bg-port-error/10 border border-port-error/30 rounded-lg p-4">
+ <h4 className="text-sm font-medium text-port-error mb-2 flex items-center gap-2">
+ <XCircle size={14} />
+ Misroutes Detected
+ </h4>
+ <p className="text-xs text-gray-400 mb-3">
+ These task type + model tier combinations have &lt;40% success with 3+ attempts. The system will auto-adjust routing.
+ </p>
+ <div className="space-y-1">
+ {routing.misroutes.map((m, idx) => (
+ <div key={idx} className="flex items-center justify-between p-2 bg-port-bg rounded text-sm">
+ <div className="flex items-center gap-2">
+ <span className="text-white">{m.taskType}</span>
+ <span className="text-gray-500">on</span>
+ <span className="text-orange-400 font-medium">{m.tier}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="text-port-error font-mono">{m.successRate}%</span>
+ <span className="text-xs text-gray-500">({m.failed} failed / {m.total})</span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Tier Overview */}
+ {routing.tierOverview?.length > 0 && (
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
+ {routing.tierOverview.map((tier, idx) => {
+ const tierLabels = {
+ 'light': 'Haiku', 'medium': 'Sonnet', 'heavy': 'Opus',
+ 'default': 'Default', 'user-specified': 'User'
+ };
+ return (
+ <div key={idx} className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex items-center justify-between mb-1">
+ <span className="text-sm text-white">{tierLabels[tier.tier] || tier.tier}</span>
+ <span className={`text-sm font-mono ${getSuccessRateColor(tier.successRate)}`}>
+ {tier.successRate}%
+ </span>
+ </div>
+ <div className="w-full bg-port-border rounded-full h-1.5 mb-1">
+ <div
+ className={`h-1.5 rounded-full ${getSuccessRateBg(tier.successRate)}`}
+ style={{ width: `${tier.successRate}%` }}
+ />
+ </div>
+ <div className="flex justify-between text-xs text-gray-500">
+ <span>{tier.total} tasks across {tier.taskTypes} types</span>
+ {tier.misroutes > 0 && (
+ <span className="text-port-error">{tier.misroutes} misroute{tier.misroutes !== 1 ? 's' : ''}</span>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Full Matrix */}
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">
+ <table className="w-full text-sm">
+ <thead className="bg-port-bg">
+ <tr>
+ <th className="text-left p-3 text-gray-500 font-medium">Task Type</th>
+ <th className="text-left p-3 text-gray-500 font-medium">Tier</th>
+ <th className="text-right p-3 text-gray-500 font-medium">Success</th>
+ <th className="text-right p-3 text-gray-500 font-medium hidden sm:table-cell">Pass</th>
+ <th className="text-right p-3 text-gray-500 font-medium hidden sm:table-cell">Fail</th>
+ </tr>
+ </thead>
+ <tbody>
+ {routing.matrix.map((entry) =>
+ entry.tiers.map((tier, tIdx) => (
+ <tr key={`${entry.taskType}-${tier.tier}`} className="border-t border-port-border">
+ {tIdx === 0 ? (
+ <td className="p-3 text-gray-300 truncate max-w-[200px]" rowSpan={entry.tiers.length}>
+ {entry.taskType}
+ </td>
+ ) : null}
+ <td className="p-3 text-orange-400">{tier.tier}</td>
+ <td className={`p-3 text-right font-mono ${getSuccessRateColor(tier.successRate)}`}>
+ {tier.successRate}%
+ </td>
+ <td className="p-3 text-right text-port-success hidden sm:table-cell">{tier.succeeded}</td>
+ <td className="p-3 text-right text-port-error hidden sm:table-cell">{tier.failed}</td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
{/* Error Patterns */}
{learning.insights?.commonErrors?.length > 0 && (
<div>
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 21decd5d12..5f437b7be0 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -470,6 +470,7 @@ export const getCosLearning = () => request('/cos/learning');
export const getCosLearningDurations = () => request('/cos/learning/durations');
export const getCosLearningSkipped = () => request('/cos/learning/skipped');
export const getCosLearningPerformance = () => request('/cos/learning/performance');
+export const getCosLearningRouting = () => request('/cos/learning/routing');
export const getCosLearningSummary = () => request('/cos/learning/summary');
export const backfillCosLearning = () => request('/cos/learning/backfill', { method: 'POST' });
export const resetCosTaskTypeLearning = (taskType) => request(`/cos/learning/reset/${encodeURIComponent(taskType)}`, { method: 'POST' });
diff --git a/server/routes/cos.js b/server/routes/cos.js
index a66ba411be..ab35afd530 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -397,6 +397,12 @@ router.get('/learning/cooldown/:taskType', asyncHandler(async (req, res) => {
});
}));
+// GET /api/cos/learning/routing - Get routing accuracy metrics (task type × model tier)
+router.get('/learning/routing', asyncHandler(async (req, res) => {
+ const routing = await taskLearning.getRoutingAccuracy();
+ res.json(routing);
+}));
+
// GET /api/cos/learning/performance - Get performance summary
router.get('/learning/performance', asyncHandler(async (req, res) => {
const summary = await taskLearning.getPerformanceSummary();
diff --git a/server/services/taskLearning.js b/server/services/taskLearning.js
index 2aa96c2474..99355c7098 100644
--- a/server/services/taskLearning.js
+++ b/server/services/taskLearning.js
@@ -34,6 +34,10 @@ const DEFAULT_LEARNING_DATA = {
// Metrics by error category
errorPatterns: {},
+ // Routing accuracy: taskType → modelTier → { succeeded, failed }
+ // Records which model tiers work/fail for each task type
+ routingAccuracy: {},
+
// Overall stats
totals: {
completed: 0,
@@ -191,6 +195,20 @@ export async function recordTaskCompletion(agent, task) {
tierMetrics.totalDurationMs += duration;
tierMetrics.avgDurationMs = Math.round(tierMetrics.totalDurationMs / tierMetrics.completed);
+ // 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 (success) {
+ routing.succeeded++;
+ } else {
+ routing.failed++;
+ }
+ routing.lastAttempt = new Date().toISOString();
+
// Track error patterns
if (!success && errorCategory) {
if (!data.errorPatterns[errorCategory]) {
@@ -390,6 +408,8 @@ export async function getTaskTypePriorityMultiplier(taskType) {
/**
* Suggest model tier based on historical performance for a task type
+ * Enhanced with negative signal awareness: avoids tiers that consistently fail
+ * and prefers tiers with proven success for the task type
*/
export async function suggestModelTier(taskType) {
const data = await loadLearningData();
@@ -399,7 +419,41 @@ export async function suggestModelTier(taskType) {
return null; // Not enough data to suggest
}
- // If success rate is low, suggest heavier model
+ // Check routing accuracy for tier-specific signals
+ const routingData = data.routingAccuracy?.[taskType];
+ if (routingData) {
+ // Find tiers with enough data and their success rates
+ const tierResults = Object.entries(routingData)
+ .filter(([, r]) => (r.succeeded + r.failed) >= 3)
+ .map(([tier, r]) => {
+ const total = r.succeeded + r.failed;
+ return { tier, successRate: Math.round((r.succeeded / total) * 100), total };
+ })
+ .sort((a, b) => b.successRate - a.successRate);
+
+ // If a lighter tier has high success, no need to upgrade
+ const bestTier = tierResults[0];
+ if (bestTier && bestTier.successRate >= 80) {
+ return {
+ suggested: bestTier.tier,
+ reason: `${taskType} has ${bestTier.successRate}% success with ${bestTier.tier} tier`,
+ avoidTiers: tierResults.filter(t => t.successRate < 40).map(t => t.tier)
+ };
+ }
+
+ // If current default tier is failing, find a better one
+ const failingTiers = tierResults.filter(t => t.successRate < 40);
+ if (failingTiers.length > 0) {
+ const successfulTier = tierResults.find(t => t.successRate >= 60);
+ return {
+ suggested: successfulTier?.tier || 'heavy',
+ reason: `${taskType} fails with ${failingTiers.map(t => t.tier).join(', ')} (${failingTiers.map(t => `${t.successRate}%`).join(', ')})`,
+ avoidTiers: failingTiers.map(t => t.tier)
+ };
+ }
+ }
+
+ // Fallback: if overall success rate is low, suggest heavier model
if (metrics.successRate < 60) {
return {
suggested: 'heavy',
@@ -410,6 +464,85 @@ export async function suggestModelTier(taskType) {
return null; // Current selection is working fine
}
+/**
+ * Get routing accuracy metrics showing which model tiers succeed/fail for each task type
+ * Returns a matrix suitable for display in the Learning tab UI
+ */
+export async function getRoutingAccuracy() {
+ const data = await loadLearningData();
+ const routingData = data.routingAccuracy || {};
+
+ const matrix = [];
+ const tierSummary = {};
+
+ for (const [taskType, tiers] of Object.entries(routingData)) {
+ const taskEntry = { taskType, tiers: [] };
+
+ for (const [tier, counts] of Object.entries(tiers)) {
+ const total = counts.succeeded + counts.failed;
+ if (total === 0) continue;
+
+ const successRate = Math.round((counts.succeeded / total) * 100);
+ taskEntry.tiers.push({
+ tier,
+ succeeded: counts.succeeded,
+ failed: counts.failed,
+ total,
+ successRate,
+ lastAttempt: counts.lastAttempt
+ });
+
+ // Aggregate tier summary
+ if (!tierSummary[tier]) {
+ tierSummary[tier] = { succeeded: 0, failed: 0, taskTypes: 0, misroutes: 0 };
+ }
+ tierSummary[tier].succeeded += counts.succeeded;
+ tierSummary[tier].failed += counts.failed;
+ tierSummary[tier].taskTypes++;
+ if (successRate < 40 && total >= 3) {
+ tierSummary[tier].misroutes++;
+ }
+ }
+
+ // Sort tiers by success rate descending
+ taskEntry.tiers.sort((a, b) => b.successRate - a.successRate);
+ if (taskEntry.tiers.length > 0) {
+ matrix.push(taskEntry);
+ }
+ }
+
+ // Calculate tier-level success rates
+ const tierOverview = Object.entries(tierSummary).map(([tier, s]) => {
+ const total = s.succeeded + s.failed;
+ return {
+ tier,
+ successRate: total > 0 ? Math.round((s.succeeded / total) * 100) : 0,
+ total,
+ taskTypes: s.taskTypes,
+ misroutes: s.misroutes
+ };
+ }).sort((a, b) => b.successRate - a.successRate);
+
+ // Identify misroutes: task+tier combos with <40% success and 3+ attempts
+ const misroutes = [];
+ for (const entry of matrix) {
+ for (const tier of entry.tiers) {
+ if (tier.successRate < 40 && tier.total >= 3) {
+ misroutes.push({
+ taskType: entry.taskType,
+ tier: tier.tier,
+ successRate: tier.successRate,
+ failed: tier.failed,
+ total: tier.total
+ });
+ }
+ }
+ }
+ misroutes.sort((a, b) => a.successRate - b.successRate);
+
+ return { matrix, tierOverview, misroutes, totalMisroutes: misroutes.length };
+}
+
/**
* Get a performance summary for logging during task evaluation
* Provides insights about how different task types are performing
@@ -764,6 +897,11 @@ export async function resetTaskTypeLearning(taskType) {
}
}
+ // Clean up routing accuracy data for this task type
+ if (data.routingAccuracy) {
+ delete data.routingAccuracy[taskType];
+ }
+
// Remove the task type entry
delete data.byTaskType[taskType];
diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.js
index ae245b2e90..3d380862f9 100644
--- a/server/services/taskLearning.test.js
+++ b/server/services/taskLearning.test.js
@@ -32,7 +32,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {
});
import { readFile, writeFile } from 'fs/promises';
-import { resetTaskTypeLearning, getSkippedTaskTypes } from './taskLearning.js';
+import { resetTaskTypeLearning, getSkippedTaskTypes, recordTaskCompletion, getRoutingAccuracy, suggestModelTier } from './taskLearning.js';
const makeLearningData = (overrides = {}) => ({
version: 1,
@@ -237,4 +237,227 @@ describe('TaskLearning - getSkippedTaskTypes', () => {
expect(skipped).toHaveLength(0);
});
+
+ it('should clean up routingAccuracy data when resetting a task type', async () => {
+ let savedData;
+ writeFile.mockImplementation(async (_path, content) => {
+ savedData = JSON.parse(content);
+ });
+
+ const data = makeLearningData({
+ routingAccuracy: {
+ 'self-improve:ui': {
+ heavy: { succeeded: 2, failed: 8, lastAttempt: '2026-01-25T00:00:00.000Z' },
+ medium: { succeeded: 0, failed: 5, lastAttempt: '2026-01-24T00:00:00.000Z' }
+ },
+ 'user-task': {
+ heavy: { succeeded: 10, failed: 2, lastAttempt: '2026-01-26T00:00:00.000Z' }
+ }
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ await resetTaskTypeLearning('self-improve:ui');
+
+ expect(savedData.routingAccuracy['self-improve:ui']).toBeUndefined();
+ expect(savedData.routingAccuracy['user-task']).toBeDefined();
+ });
+});
+
+describe('TaskLearning - recordTaskCompletion routing accuracy', () => {
+ let savedData;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ savedData = null;
+ writeFile.mockImplementation(async (_path, content) => {
+ savedData = JSON.parse(content);
+ });
+ });
+
+ it('should record routing accuracy for successful task', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ const agent = {
+ metadata: { modelTier: 'heavy', taskDescription: 'Fix some UI bugs' },
+ result: { success: true, duration: 60000 }
+ };
+ const task = { description: 'Fix some UI bugs', taskType: 'user', metadata: {} };
+
+ await recordTaskCompletion(agent, task);
+
+ expect(savedData.routingAccuracy).toBeDefined();
+ expect(savedData.routingAccuracy['user-task']).toBeDefined();
+ expect(savedData.routingAccuracy['user-task']['heavy']).toBeDefined();
+ expect(savedData.routingAccuracy['user-task']['heavy'].succeeded).toBe(1);
+ expect(savedData.routingAccuracy['user-task']['heavy'].failed).toBe(0);
+ });
+
+ it('should record routing accuracy for failed task', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ const agent = {
+ metadata: { modelTier: 'light', taskDescription: 'Fix UI' },
+ result: { success: false, duration: 30000 }
+ };
+ const task = { description: 'Fix UI', taskType: 'user', metadata: {} };
+
+ await recordTaskCompletion(agent, task);
+
+ expect(savedData.routingAccuracy['user-task']['light'].succeeded).toBe(0);
+ expect(savedData.routingAccuracy['user-task']['light'].failed).toBe(1);
+ expect(savedData.routingAccuracy['user-task']['light'].lastAttempt).toBeDefined();
+ });
+
+ it('should accumulate routing accuracy across multiple completions', async () => {
+ let currentData = JSON.stringify(makeLearningData());
+ readFile.mockImplementation(async () => currentData);
+ writeFile.mockImplementation(async (_path, content) => {
+ currentData = content;
+ savedData = JSON.parse(content);
+ });
+
+ const makeAgent = (tier, success) => ({
+ metadata: { modelTier: tier, taskDescription: 'Test task' },
+ result: { success, duration: 30000 }
+ });
+ const task = { description: 'Test task', taskType: 'user', metadata: {} };
+
+ await recordTaskCompletion(makeAgent('medium', true), task);
+ await recordTaskCompletion(makeAgent('medium', true), task);
+ await recordTaskCompletion(makeAgent('medium', false), task);
+
+ expect(savedData.routingAccuracy['user-task']['medium'].succeeded).toBe(2);
+ expect(savedData.routingAccuracy['user-task']['medium'].failed).toBe(1);
+ });
+});
+
+describe('TaskLearning - getRoutingAccuracy', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should return routing accuracy matrix with misroutes', async () => {
+ const data = makeLearningData({
+ routingAccuracy: {
+ 'self-improve:ui': {
+ light: { succeeded: 1, failed: 9, lastAttempt: '2026-01-25T00:00:00.000Z' },
+ heavy: { succeeded: 8, failed: 2, lastAttempt: '2026-01-26T00:00:00.000Z' }
+ },
+ 'user-task': {
+ medium: { succeeded: 15, failed: 3, lastAttempt: '2026-01-26T00:00:00.000Z' }
+ }
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ const result = await getRoutingAccuracy();
+
+ expect(result.matrix).toHaveLength(2);
+ expect(result.totalMisroutes).toBe(1); // self-improve:ui on light (10% success, 10 attempts)
+
+ // Check misroutes
+ expect(result.misroutes).toHaveLength(1);
+ expect(result.misroutes[0].taskType).toBe('self-improve:ui');
+ expect(result.misroutes[0].tier).toBe('light');
+ expect(result.misroutes[0].successRate).toBe(10);
+
+ // Check tier overview
+ expect(result.tierOverview.length).toBeGreaterThan(0);
+ });
+
+ it('should return empty results when no routing data exists', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ const result = await getRoutingAccuracy();
+
+ expect(result.matrix).toHaveLength(0);
+ expect(result.misroutes).toHaveLength(0);
+ expect(result.totalMisroutes).toBe(0);
+ });
+
+ it('should sort matrix tiers by success rate descending', async () => {
+ const data = makeLearningData({
+ routingAccuracy: {
+ 'user-task': {
+ light: { succeeded: 1, failed: 4, lastAttempt: '2026-01-25T00:00:00.000Z' },
+ medium: { succeeded: 3, failed: 2, lastAttempt: '2026-01-25T00:00:00.000Z' },
+ heavy: { succeeded: 9, failed: 1, lastAttempt: '2026-01-26T00:00:00.000Z' }
+ }
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ const result = await getRoutingAccuracy();
+
+ const tiers = result.matrix[0].tiers;
+ expect(tiers[0].tier).toBe('heavy'); // 90%
+ expect(tiers[1].tier).toBe('medium'); // 60%
+ expect(tiers[2].tier).toBe('light'); // 20%
+ });
+});
+
+describe('TaskLearning - suggestModelTier with routing signals', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should suggest avoiding failing tiers', async () => {
+ const data = makeLearningData({
+ byTaskType: {
+ 'self-improve:ui': {
+ completed: 20, succeeded: 8, failed: 12,
+ totalDurationMs: 2000000, avgDurationMs: 100000,
+ successRate: 40
+ }
+ },
+ routingAccuracy: {
+ 'self-improve:ui': {
+ light: { succeeded: 1, failed: 9, lastAttempt: '2026-01-25T00:00:00.000Z' },
+ heavy: { succeeded: 7, failed: 3, lastAttempt: '2026-01-26T00:00:00.000Z' }
+ }
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ const result = await suggestModelTier('self-improve:ui');
+
+ expect(result).not.toBeNull();
+ expect(result.avoidTiers).toContain('light');
+ });
+
+ it('should suggest best performing tier when available', async () => {
+ const data = makeLearningData({
+ byTaskType: {
+ 'user-task': {
+ completed: 15, succeeded: 12, failed: 3,
+ totalDurationMs: 1500000, avgDurationMs: 100000,
+ successRate: 80
+ }
+ },
+ routingAccuracy: {
+ 'user-task': {
+ medium: { succeeded: 9, failed: 1, lastAttempt: '2026-01-26T00:00:00.000Z' },
+ heavy: { succeeded: 3, failed: 2, lastAttempt: '2026-01-25T00:00:00.000Z' }
+ }
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ const result = await suggestModelTier('user-task');
+
+ expect(result).not.toBeNull();
+ expect(result.suggested).toBe('medium'); // 90% success vs heavy at 60%
+ });
+
+ it('should return null when insufficient data', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData({
+ byTaskType: {
+ 'new-task': { completed: 2, succeeded: 1, failed: 1, successRate: 50 }
+ }
+ })));
+
+ const result = await suggestModelTier('new-task');
+ expect(result).toBeNull();
+ });
});