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 learning data reset for auto-paused task types

Adam Eivyffa80f0301d3
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.md
index 6c305048b5..ed886b7c4f 100644
--- a/.changelog/v0.10.x.md
+++ b/.changelog/v0.10.x.md
@@ -124,6 +124,13 @@ This release introduces a structured changelog documentation system for creating
- **Socket.IO Events**: Real-time `provider:status:changed` events notify UI of provider status changes
- **API Endpoints**: New `/api/providers/status`, `/api/providers/:id/status`, and `/api/providers/:id/status/recover` endpoints for status management
+### CoS Learning Data Reset
+- **Reset Skipped Task Types**: Added ability to reset learning data for auto-paused task types that have been stuck due to historical failures (e.g., task types with 5% success after 200+ attempts from a now-fixed bug)
+- **Clean Metric Subtraction**: Resetting a task type correctly subtracts its metrics from totals and cleans up associated error patterns, giving it a fresh start
+- **UI Reset Button**: Each skipped task type in the Learning tab now shows a "Reset" button with toast notification feedback
+- **API Endpoint**: New `POST /api/cos/learning/reset/:taskType` endpoint for programmatic access
+- **Test Coverage**: 9 new unit tests covering reset logic, metric subtraction, error pattern cleanup, and edge cases
+
## 🔧 Improvements
### Release Process
diff --git a/client/src/components/cos/tabs/LearningTab.jsx b/client/src/components/cos/tabs/LearningTab.jsx
index de85b17359..3b7cdfdffb 100644
--- a/client/src/components/cos/tabs/LearningTab.jsx
+++ b/client/src/components/cos/tabs/LearningTab.jsx
@@ -15,8 +15,10 @@ import {
Target,
ChevronDown,
ChevronRight,
- Database
+ Database,
+ RotateCcw
} from 'lucide-react';
+import toast from 'react-hot-toast';
import * as api from '../../../services/api';
export default function LearningTab() {
@@ -26,6 +28,7 @@ export default function LearningTab() {
const [durations, setDurations] = useState(null);
const [loading, setLoading] = useState(true);
const [backfilling, setBackfilling] = useState(false);
+ const [resettingType, setResettingType] = useState(null);
const [expandedSections, setExpandedSections] = useState({
taskTypes: true,
skipped: true,
@@ -62,6 +65,16 @@ export default function LearningTab() {
setBackfilling(false);
}, [loadData]);
+ const handleResetTaskType = useCallback(async (taskType) => {
+ setResettingType(taskType);
+ const result = await api.resetCosTaskTypeLearning(taskType).catch(() => null);
+ if (result?.reset) {
+ toast.success(`Reset learning data for ${taskType}`);
+ await loadData();
+ }
+ setResettingType(null);
+ }, [loadData]);
+
const toggleSection = useCallback((section) => {
setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
}, []);
@@ -343,12 +356,23 @@ export default function LearningTab() {
({item.completed} attempts)
</span>
</div>
- <span className="text-sm text-port-error font-mono">{item.successRate}%</span>
+ <div className="flex items-center gap-3">
+ <span className="text-sm text-port-error font-mono">{item.successRate}%</span>
+ <button
+ onClick={() => handleResetTaskType(item.taskType)}
+ disabled={resettingType === item.taskType}
+ className="flex items-center gap-1 px-2 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded transition-colors disabled:opacity-50 min-h-[40px]"
+ title="Reset learning data to re-enable this task type"
+ >
+ <RotateCcw size={12} className={resettingType === item.taskType ? 'animate-spin' : ''} />
+ Reset
+ </button>
+ </div>
</div>
))}
</div>
<p className="text-xs text-gray-500 mt-3">
- Fix underlying issues to re-enable these task types
+ Reset clears historical metrics so the task type can be retried with a fresh start
</p>
</div>
)}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index e0455c994a..18471b7e84 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -272,6 +272,7 @@ export const getCosLearningDurations = () => request('/cos/learning/durations');
export const getCosLearningSkipped = () => request('/cos/learning/skipped');
export const getCosLearningPerformance = () => request('/cos/learning/performance');
export const backfillCosLearning = () => request('/cos/learning/backfill', { method: 'POST' });
+export const resetCosTaskTypeLearning = (taskType) => request(`/cos/learning/reset/${encodeURIComponent(taskType)}`, { method: 'POST' });
// CoS Scripts
export const getCosScripts = () => request('/cos/scripts');
diff --git a/server/routes/cos.js b/server/routes/cos.js
index cac6504324..33a1714693 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -329,6 +329,19 @@ router.get('/learning/skipped', asyncHandler(async (req, res) => {
});
}));
+// POST /api/cos/learning/reset/:taskType - Reset learning data for a specific task type
+router.post('/learning/reset/:taskType', asyncHandler(async (req, res) => {
+ const { taskType } = req.params;
+ if (!taskType) {
+ throw new ServerError('Task type is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const result = await taskLearning.resetTaskTypeLearning(taskType);
+ if (!result.reset) {
+ throw new ServerError(`Task type "${taskType}" not found in learning data`, { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(result);
+}));
+
// GET /api/cos/learning/cooldown/:taskType - Get adaptive cooldown for specific task type
router.get('/learning/cooldown/:taskType', asyncHandler(async (req, res) => {
const { taskType } = req.params;
diff --git a/server/services/taskLearning.js b/server/services/taskLearning.js
index cef33dbc3a..e54b3e32d1 100644
--- a/server/services/taskLearning.js
+++ b/server/services/taskLearning.js
@@ -589,6 +589,66 @@ export async function shouldSkipTaskType(taskType) {
return result.skip;
}
+/**
+ * Reset learning data for a specific task type
+ * Used when a previously-failing task type has been fixed and should be retried
+ * Subtracts the task type's metrics from totals and removes the task type entry
+ * @param {string} taskType - The task type to reset (e.g., 'self-improve:ui')
+ * @returns {Object} Summary of what was reset
+ */
+export async function resetTaskTypeLearning(taskType) {
+ const data = await loadLearningData();
+
+ const metrics = data.byTaskType[taskType];
+ if (!metrics) {
+ 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;
+ data.totals.avgDurationMs = data.totals.completed > 0
+ ? Math.round(data.totals.totalDurationMs / data.totals.completed)
+ : 0;
+
+ // Clean up error patterns referencing this task type
+ 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];
+ }
+ // Remove empty error categories
+ if (pattern.count <= 0) {
+ delete data.errorPatterns[category];
+ }
+ }
+
+ // Remove the task type entry
+ delete data.byTaskType[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
+ }
+ };
+}
+
/**
* Get estimated duration for a task based on historical averages
* @param {string} taskDescription - The task description to analyze
diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.js
new file mode 100644
index 0000000000..b550e92408
--- /dev/null
+++ b/server/services/taskLearning.test.js
@@ -0,0 +1,226 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock fs/promises and fs before importing the module
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(),
+ writeFile: vi.fn(),
+ mkdir: vi.fn()
+}));
+
+vi.mock('fs', () => ({
+ existsSync: vi.fn(() => true)
+}));
+
+// Mock cos.js to avoid circular dependency
+vi.mock('./cos.js', () => ({
+ cosEvents: { on: vi.fn(), emit: vi.fn() },
+ emitLog: vi.fn()
+}));
+
+import { readFile, writeFile } from 'fs/promises';
+import { resetTaskTypeLearning, getSkippedTaskTypes } from './taskLearning.js';
+
+const makeLearningData = (overrides = {}) => ({
+ version: 1,
+ lastUpdated: '2026-01-26T00:00:00.000Z',
+ byTaskType: {
+ 'self-improve:ui': {
+ completed: 200,
+ succeeded: 10,
+ failed: 190,
+ totalDurationMs: 2000000,
+ avgDurationMs: 10000,
+ lastCompleted: '2026-01-25T00:00:00.000Z',
+ successRate: 5
+ },
+ 'user-task': {
+ completed: 40,
+ succeeded: 30,
+ failed: 10,
+ totalDurationMs: 4000000,
+ avgDurationMs: 100000,
+ lastCompleted: '2026-01-26T00:00:00.000Z',
+ successRate: 75
+ }
+ },
+ byModelTier: {
+ 'user-specified': {
+ completed: 240,
+ succeeded: 40,
+ failed: 200,
+ totalDurationMs: 6000000,
+ avgDurationMs: 25000
+ }
+ },
+ errorPatterns: {
+ 'server-error': {
+ count: 190,
+ taskTypes: { 'self-improve:ui': 185, 'user-task': 5 },
+ lastOccurred: '2026-01-25T00:00:00.000Z'
+ },
+ 'unknown': {
+ count: 10,
+ taskTypes: { 'self-improve:ui': 10 },
+ lastOccurred: '2026-01-24T00:00:00.000Z'
+ }
+ },
+ totals: {
+ completed: 240,
+ succeeded: 40,
+ failed: 200,
+ totalDurationMs: 6000000,
+ avgDurationMs: 25000
+ },
+ ...overrides
+});
+
+describe('TaskLearning - resetTaskTypeLearning', () => {
+ let savedData;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ savedData = null;
+ writeFile.mockImplementation(async (_path, content) => {
+ savedData = JSON.parse(content);
+ });
+ });
+
+ it('should return not-found when task type does not exist', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ const result = await resetTaskTypeLearning('nonexistent-type');
+
+ expect(result.reset).toBe(false);
+ expect(result.reason).toBe('task-type-not-found');
+ });
+
+ it('should remove the task type from byTaskType', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ const result = await resetTaskTypeLearning('self-improve:ui');
+
+ expect(result.reset).toBe(true);
+ expect(result.taskType).toBe('self-improve:ui');
+ expect(savedData.byTaskType['self-improve:ui']).toBeUndefined();
+ expect(savedData.byTaskType['user-task']).toBeDefined();
+ });
+
+ it('should subtract task type metrics from totals', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ await resetTaskTypeLearning('self-improve:ui');
+
+ // Original totals: completed=240, succeeded=40, failed=200, totalDurationMs=6000000
+ // self-improve:ui: completed=200, succeeded=10, failed=190, totalDurationMs=2000000
+ // After reset: completed=40, succeeded=30, failed=10, totalDurationMs=4000000
+ expect(savedData.totals.completed).toBe(40);
+ expect(savedData.totals.succeeded).toBe(30);
+ expect(savedData.totals.failed).toBe(10);
+ expect(savedData.totals.totalDurationMs).toBe(4000000);
+ expect(savedData.totals.avgDurationMs).toBe(100000); // 4000000 / 40
+ });
+
+ it('should clean up error patterns referencing the task type', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ await resetTaskTypeLearning('self-improve:ui');
+
+ // server-error had 190 total (185 from ui, 5 from user-task) → should now have 5
+ expect(savedData.errorPatterns['server-error'].count).toBe(5);
+ expect(savedData.errorPatterns['server-error'].taskTypes['self-improve:ui']).toBeUndefined();
+ expect(savedData.errorPatterns['server-error'].taskTypes['user-task']).toBe(5);
+
+ // unknown had 10 total, all from ui → should be removed entirely
+ expect(savedData.errorPatterns['unknown']).toBeUndefined();
+ });
+
+ it('should return previous metrics in result', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ const result = await resetTaskTypeLearning('self-improve:ui');
+
+ expect(result.previousMetrics).toEqual({
+ completed: 200,
+ succeeded: 10,
+ failed: 190,
+ successRate: 5
+ });
+ });
+
+ it('should handle totals going to zero gracefully', async () => {
+ const data = makeLearningData({
+ byTaskType: {
+ 'self-improve:ui': {
+ completed: 100, succeeded: 5, failed: 95,
+ totalDurationMs: 500000, avgDurationMs: 5000,
+ lastCompleted: '2026-01-25T00:00:00.000Z', successRate: 5
+ }
+ },
+ errorPatterns: {},
+ totals: {
+ completed: 100, succeeded: 5, failed: 95,
+ totalDurationMs: 500000, avgDurationMs: 5000
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ await resetTaskTypeLearning('self-improve:ui');
+
+ expect(savedData.totals.completed).toBe(0);
+ expect(savedData.totals.avgDurationMs).toBe(0);
+ });
+});
+
+describe('TaskLearning - getSkippedTaskTypes', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should return task types with <30% success and 5+ attempts', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ const skipped = await getSkippedTaskTypes();
+
+ expect(skipped).toHaveLength(1);
+ expect(skipped[0].taskType).toBe('self-improve:ui');
+ expect(skipped[0].successRate).toBe(5);
+ });
+
+ it('should not include task types with >= 30% success', async () => {
+ readFile.mockResolvedValue(JSON.stringify(makeLearningData()));
+
+ const skipped = await getSkippedTaskTypes();
+
+ const userTask = skipped.find(s => s.taskType === 'user-task');
+ expect(userTask).toBeUndefined();
+ });
+
+ it('should return empty after resetting a skipped type', async () => {
+ const data = makeLearningData({
+ byTaskType: {
+ 'self-improve:ui': {
+ completed: 100, succeeded: 5, failed: 95,
+ totalDurationMs: 500000, avgDurationMs: 5000,
+ lastCompleted: '2026-01-25T00:00:00.000Z', successRate: 5
+ }
+ },
+ errorPatterns: {},
+ totals: {
+ completed: 100, succeeded: 5, failed: 95,
+ totalDurationMs: 500000, avgDurationMs: 5000
+ }
+ });
+
+ // Track what was written so subsequent reads return updated data
+ let currentData = JSON.stringify(data);
+ readFile.mockImplementation(async () => currentData);
+ writeFile.mockImplementation(async (_path, content) => {
+ currentData = content;
+ });
+
+ await resetTaskTypeLearning('self-improve:ui');
+ const skipped = await getSkippedTaskTypes();
+
+ expect(skipped).toHaveLength(0);
+ });
+});