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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(cos): add comprehensive route test coverage for CoS API endpoints
Adam Eivy916ab4b26dbf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4dac0fac0b..62862119a2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,7 @@- Submodules management page under Dev Tools — view status, check for updates, and update individual or all git submodules from the dashboard- Update scripts (`update.sh`, `update.ps1`) now auto-update submodules (including slash-do) during PortOS updates+- CoS route test coverage — 170 new tests across 6 test files covering templates, learning, schedule, jobs, insights, and missing gaps in task/agent/report routes (83-100% route coverage, up from ~12%)- Slash-do agent operations panel on app detail Overview tab — buttons for `/do:push`, `/do:review`, `/do:release`, `/do:better`, and `/do:better-swift` that queue CoS agent tasks with the full command instructions- Multi-line task context now renders as a dedicated `### Task Context` section in agent prompts instead of inline- Enter key submits the task add form (Shift+Enter for newline)diff --git a/PLAN.md b/PLAN.mdindex bdb690df7e..56dfcc6052 100644--- a/PLAN.md+++ b/PLAN.md@@ -10,7 +10,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]## Backlog-- [ ] **Test coverage** — cosRunnerClient.js ✅ (37 tests), agentActionExecutor.js ✅ (27 tests). Remaining gap: cos.js (~29% service, ~12% route coverage)+- [x] **Test coverage** — cosRunnerClient.js ✅ (37 tests), agentActionExecutor.js ✅ (27 tests), CoS routes ✅ (170 tests across 6 test files, 83-100% route coverage). Remaining gap: cos.js service (~4% coverage)- [ ] **M50 P9**: CoS Automation & Rules — Automated email classification, rule-based pre-filtering, email-to-task pipeline- [ ] **M50 P10**: Auto-Send with AI Review Gate — Per-account trust level, second LLM reviews drafts. See [Messages Security](./docs/features/messages-security.md)- [ ] **M34 P5-P7**: Digital Twin — Multi-modal capture, advanced testing, personasdiff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsindex e5ef41132a..931d9dd330 100644--- a/server/routes/cos.test.js+++ b/server/routes/cos.test.js@@ -33,13 +33,21 @@ vi.mock('../services/cos.js', () => ({getAgentProcessStats: vi.fn(),deleteAgent: vi.fn(),clearCompletedAgents: vi.fn(),+ submitAgentFeedback: vi.fn(),+ sendBtwToAgent: vi.fn(),+ getFeedbackStats: vi.fn(),listReports: vi.fn(),getTodayReport: vi.fn(),getReport: vi.fn(),generateReport: vi.fn(),+ listBriefings: vi.fn(),+ getLatestBriefing: vi.fn(),+ getBriefing: vi.fn(),listScripts: vi.fn(),getScript: vi.fn(),- forceSpawnTask: vi.fn()+ forceSpawnTask: vi.fn(),+ getTodayActivity: vi.fn(),+ getRecentTasks: vi.fn()}));// Mock the taskWatcher service@@ -57,10 +65,29 @@ vi.mock('../services/appActivity.js', () => ({clearAppCooldown: vi.fn()}));+// Mock the claudeChangelog service+vi.mock('../services/claudeChangelog.js', () => ({+ checkChangelog: vi.fn(),+ getCachedChangelog: vi.fn()+}));++// Mock the taskEnhancer service+vi.mock('../services/taskEnhancer.js', () => ({+ enhanceTaskPrompt: vi.fn()+}));++// Mock the subAgentSpawner service+vi.mock('../services/subAgentSpawner.js', () => ({+ loadSlashdoCommand: vi.fn()+}));+// Import mocked modulesimport * as cos from '../services/cos.js';import * as taskWatcher from '../services/taskWatcher.js';import * as appActivity from '../services/appActivity.js';+import * as claudeChangelog from '../services/claudeChangelog.js';+import { enhanceTaskPrompt } from '../services/taskEnhancer.js';+import { loadSlashdoCommand } from '../services/subAgentSpawner.js';describe('CoS Routes', () => {let app;@@ -682,4 +709,339 @@ describe('CoS Routes', () => {expect(response.body.code).toBe('NO_CAPACITY');});});++ // ============================================================+ // Task Routes — additional coverage+ // ============================================================++ describe('GET /api/cos/tasks/user', () => {+ it('should return user tasks', async () => {+ cos.getUserTasks.mockResolvedValue({ tasks: [{ id: 't1' }], grouped: {} });++ const response = await request(app).get('/api/cos/tasks/user');++ expect(response.status).toBe(200);+ expect(response.body.tasks).toHaveLength(1);+ });+ });++ describe('GET /api/cos/tasks/internal', () => {+ it('should return internal tasks', async () => {+ cos.getCosTasks.mockResolvedValue({ tasks: [], grouped: {} });++ const response = await request(app).get('/api/cos/tasks/internal');++ expect(response.status).toBe(200);+ expect(response.body).toHaveProperty('tasks');+ });+ });++ describe('POST /api/cos/tasks/refresh', () => {+ it('should force refresh tasks', async () => {+ taskWatcher.refreshTasks.mockResolvedValue({ user: [], cos: [] });++ const response = await request(app).post('/api/cos/tasks/refresh');++ expect(response.status).toBe(200);+ expect(taskWatcher.refreshTasks).toHaveBeenCalled();+ });+ });++ describe('POST /api/cos/tasks/enhance', () => {+ it('should enhance a task prompt', async () => {+ enhanceTaskPrompt.mockResolvedValue({ enhanced: 'Better description' });++ const response = await request(app)+ .post('/api/cos/tasks/enhance')+ .send({ description: 'Fix bug', context: 'app-001' });++ expect(response.status).toBe(200);+ expect(enhanceTaskPrompt).toHaveBeenCalledWith('Fix bug', 'app-001');+ });++ it('should return 400 if description is missing', async () => {+ const response = await request(app)+ .post('/api/cos/tasks/enhance')+ .send({});++ expect(response.status).toBe(400);+ });+ });++ describe('POST /api/cos/tasks/slashdo', () => {+ it('should create a task from a slashdo command', async () => {+ loadSlashdoCommand.mockResolvedValue('command content');+ cos.addTask.mockResolvedValue({ id: 'task-sd1', status: 'pending' });++ const response = await request(app)+ .post('/api/cos/tasks/slashdo')+ .send({ command: 'push', app: 'my-app' });++ expect(response.status).toBe(200);+ expect(response.body.id).toBe('task-sd1');+ expect(loadSlashdoCommand).toHaveBeenCalledWith('push');+ });++ it('should return 400 for invalid command', async () => {+ const response = await request(app)+ .post('/api/cos/tasks/slashdo')+ .send({ command: 'invalid', app: 'my-app' });++ expect(response.status).toBe(400);+ });++ it('should return 400 if app is missing', async () => {+ const response = await request(app)+ .post('/api/cos/tasks/slashdo')+ .send({ command: 'push' });++ expect(response.status).toBe(400);+ });++ it('should return 409 for duplicate task', async () => {+ loadSlashdoCommand.mockResolvedValue('command content');+ cos.addTask.mockResolvedValue({ duplicate: true, status: 'pending' });++ const response = await request(app)+ .post('/api/cos/tasks/slashdo')+ .send({ command: 'push', app: 'my-app' });++ expect(response.status).toBe(409);+ });+ });++ describe('POST /api/cos/tasks (duplicate)', () => {+ it('should return 409 for duplicate task', async () => {+ cos.addTask.mockResolvedValue({ duplicate: true, status: 'running' });++ const response = await request(app)+ .post('/api/cos/tasks')+ .send({ description: 'Duplicate task' });++ expect(response.status).toBe(409);+ });+ });++ // ============================================================+ // Agent Routes — additional coverage+ // ============================================================++ describe('DELETE /api/cos/agents/completed', () => {+ it('should clear completed agents', async () => {+ cos.clearCompletedAgents.mockResolvedValue({ cleared: 3 });++ const response = await request(app).delete('/api/cos/agents/completed');++ expect(response.status).toBe(200);+ expect(response.body.cleared).toBe(3);+ });+ });++ describe('POST /api/cos/agents/:id/feedback', () => {+ it('should submit positive feedback', async () => {+ cos.submitAgentFeedback.mockResolvedValue({ success: true });++ const response = await request(app)+ .post('/api/cos/agents/agent-001/feedback')+ .send({ rating: 'positive', comment: 'Great work' });++ expect(response.status).toBe(200);+ expect(cos.submitAgentFeedback).toHaveBeenCalledWith('agent-001', { rating: 'positive', comment: 'Great work' });+ });++ it('should return 400 for invalid rating', async () => {+ const response = await request(app)+ .post('/api/cos/agents/agent-001/feedback')+ .send({ rating: 'invalid' });++ expect(response.status).toBe(400);+ });++ it('should return 404 if agent not found', async () => {+ cos.submitAgentFeedback.mockResolvedValue({ error: 'Agent not found' });++ const response = await request(app)+ .post('/api/cos/agents/agent-999/feedback')+ .send({ rating: 'negative' });++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/cos/agents/:id/btw', () => {+ it('should send btw message to agent', async () => {+ cos.sendBtwToAgent.mockResolvedValue({ success: true });++ const response = await request(app)+ .post('/api/cos/agents/agent-001/btw')+ .send({ message: 'Additional context here' });++ expect(response.status).toBe(200);+ expect(cos.sendBtwToAgent).toHaveBeenCalledWith('agent-001', 'Additional context here');+ });++ it('should return 400 for empty message', async () => {+ const response = await request(app)+ .post('/api/cos/agents/agent-001/btw')+ .send({ message: '' });++ expect(response.status).toBe(400);+ });++ it('should return 400 for missing message', async () => {+ const response = await request(app)+ .post('/api/cos/agents/agent-001/btw')+ .send({});++ expect(response.status).toBe(400);+ });++ it('should return 400 for message over 5000 chars', async () => {+ const response = await request(app)+ .post('/api/cos/agents/agent-001/btw')+ .send({ message: 'x'.repeat(5001) });++ expect(response.status).toBe(400);+ });++ it('should return 404 if agent not found', async () => {+ cos.sendBtwToAgent.mockResolvedValue({ error: 'Agent not found' });++ const response = await request(app)+ .post('/api/cos/agents/agent-999/btw')+ .send({ message: 'hello' });++ expect(response.status).toBe(404);+ });+ });++ describe('GET /api/cos/feedback/stats', () => {+ it('should return feedback statistics', async () => {+ cos.getFeedbackStats.mockResolvedValue({ total: 10, positive: 7, negative: 2, neutral: 1 });++ const response = await request(app).get('/api/cos/feedback/stats');++ expect(response.status).toBe(200);+ expect(response.body.total).toBe(10);+ });+ });++ // ============================================================+ // Report Routes — additional coverage+ // ============================================================++ describe('POST /api/cos/reports/generate', () => {+ it('should generate a report', async () => {+ cos.generateReport.mockResolvedValue({ date: '2026-02-25', summary: {} });++ const response = await request(app)+ .post('/api/cos/reports/generate')+ .send({ date: '2026-02-25' });++ expect(response.status).toBe(200);+ expect(cos.generateReport).toHaveBeenCalledWith('2026-02-25');+ });+ });++ describe('GET /api/cos/briefings', () => {+ it('should list all briefings', async () => {+ cos.listBriefings.mockResolvedValue(['2026-02-25', '2026-02-24']);++ const response = await request(app).get('/api/cos/briefings');++ expect(response.status).toBe(200);+ expect(response.body.briefings).toHaveLength(2);+ });+ });++ describe('GET /api/cos/briefings/latest', () => {+ it('should return latest briefing', async () => {+ cos.getLatestBriefing.mockResolvedValue({ date: '2026-02-25', content: 'Latest' });++ const response = await request(app).get('/api/cos/briefings/latest');++ expect(response.status).toBe(200);+ expect(response.body.date).toBe('2026-02-25');+ });+ });++ describe('GET /api/cos/briefings/:date', () => {+ it('should return briefing by date', async () => {+ cos.getBriefing.mockResolvedValue({ date: '2026-02-24', content: 'Briefing' });++ const response = await request(app).get('/api/cos/briefings/2026-02-24');++ expect(response.status).toBe(200);+ });++ it('should return 404 if briefing not found', async () => {+ cos.getBriefing.mockResolvedValue(null);++ const response = await request(app).get('/api/cos/briefings/1999-01-01');++ expect(response.status).toBe(404);+ });+ });++ describe('GET /api/cos/claude-changelog', () => {+ it('should return changelog', async () => {+ claudeChangelog.checkChangelog.mockResolvedValue({ entries: [], lastChecked: Date.now() });++ const response = await request(app).get('/api/cos/claude-changelog');++ expect(response.status).toBe(200);+ expect(response.body).toHaveProperty('entries');+ });+ });++ describe('GET /api/cos/claude-changelog/cached', () => {+ it('should return cached changelog', async () => {+ claudeChangelog.getCachedChangelog.mockResolvedValue({ entries: [], cached: true });++ const response = await request(app).get('/api/cos/claude-changelog/cached');++ expect(response.status).toBe(200);+ });+ });++ describe('GET /api/cos/scripts', () => {+ it('should list scripts', async () => {+ cos.listScripts.mockResolvedValue([{ name: 'backup.sh' }]);++ const response = await request(app).get('/api/cos/scripts');++ expect(response.status).toBe(200);+ expect(response.body).toHaveLength(1);+ });+ });++ describe('GET /api/cos/scripts/:name', () => {+ it('should return script content', async () => {+ cos.getScript.mockResolvedValue({ name: 'backup.sh', content: '#!/bin/bash' });++ const response = await request(app).get('/api/cos/scripts/backup.sh');++ expect(response.status).toBe(200);+ expect(response.body.name).toBe('backup.sh');+ });++ it('should return 404 if script not found', async () => {+ cos.getScript.mockResolvedValue(null);++ const response = await request(app).get('/api/cos/scripts/missing.sh');++ expect(response.status).toBe(404);+ });+ });++ describe('GET /api/cos/activity/today', () => {+ it('should return today activity summary', async () => {+ cos.getTodayActivity.mockResolvedValue({ stats: { completed: 5 } });++ const response = await request(app).get('/api/cos/activity/today');++ expect(response.status).toBe(200);+ expect(response.body.stats.completed).toBe(5);+ });+ });});diff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.jsnew file mode 100644index 0000000000..483591a010--- /dev/null+++ b/server/routes/cosInsightRoutes.test.js@@ -0,0 +1,280 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import insightRoutes from './cosInsightRoutes.js';++vi.mock('../services/cos.js', () => ({+ getAllTasks: vi.fn(),+ runHealthCheck: vi.fn(),+ getTodayActivity: vi.fn(),+ getRecentTasks: vi.fn()+}));++vi.mock('../services/taskLearning.js', () => ({+ getLearningInsights: vi.fn(),+ estimateQueueCompletion: vi.fn()+}));++vi.mock('../services/autonomousJobs.js', () => ({+ getJobStats: vi.fn()+}));++vi.mock('../services/productivity.js', () => ({+ getProductivityInsights: vi.fn(),+ getProductivitySummary: vi.fn(),+ recalculateProductivity: vi.fn(),+ getDailyTrends: vi.fn(),+ getActivityCalendar: vi.fn(),+ getOptimalTimeInfo: vi.fn(),+ getVelocityMetrics: vi.fn(),+ getWeekComparison: vi.fn()+}));++vi.mock('../services/goalProgress.js', () => ({+ getGoalProgress: vi.fn(),+ getGoalProgressSummary: vi.fn()+}));++vi.mock('../services/decisionLog.js', () => ({+ getRecentDecisions: vi.fn(),+ getDecisionSummary: vi.fn(),+ getDecisionPatterns: vi.fn()+}));++vi.mock('../services/notifications.js', () => ({+ getNotifications: vi.fn().mockResolvedValue([])+}));++import * as cos from '../services/cos.js';+import * as taskLearning from '../services/taskLearning.js';+import * as autonomousJobs from '../services/autonomousJobs.js';+import * as productivity from '../services/productivity.js';+import * as goalProgress from '../services/goalProgress.js';+import * as decisionLog from '../services/decisionLog.js';++describe('CoS Insight Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/cos', insightRoutes);+ vi.clearAllMocks();+ });++ describe('GET /api/cos/productivity', () => {+ it('should return productivity insights', async () => {+ productivity.getProductivityInsights.mockResolvedValue({ streaks: {}, efficiency: 0.8 });++ const response = await request(app).get('/api/cos/productivity');++ expect(response.status).toBe(200);+ expect(response.body).toHaveProperty('efficiency');+ });+ });++ describe('GET /api/cos/productivity/summary', () => {+ it('should return productivity summary', async () => {+ productivity.getProductivitySummary.mockResolvedValue({ currentStreak: 5 });++ const response = await request(app).get('/api/cos/productivity/summary');++ expect(response.status).toBe(200);+ expect(response.body.currentStreak).toBe(5);+ });+ });++ describe('POST /api/cos/productivity/recalculate', () => {+ it('should recalculate productivity', async () => {+ productivity.recalculateProductivity.mockResolvedValue({ recalculated: true });++ const response = await request(app).post('/api/cos/productivity/recalculate');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });+ });++ describe('GET /api/cos/productivity/trends', () => {+ it('should return daily trends with default days', async () => {+ productivity.getDailyTrends.mockResolvedValue([{ date: '2026-04-01', completed: 3 }]);++ const response = await request(app).get('/api/cos/productivity/trends');++ expect(response.status).toBe(200);+ expect(productivity.getDailyTrends).toHaveBeenCalledWith(30);+ });++ it('should respect custom days', async () => {+ productivity.getDailyTrends.mockResolvedValue([]);++ const response = await request(app).get('/api/cos/productivity/trends?days=7');++ expect(response.status).toBe(200);+ expect(productivity.getDailyTrends).toHaveBeenCalledWith(7);+ });+ });++ describe('GET /api/cos/productivity/calendar', () => {+ it('should return activity calendar with default weeks', async () => {+ productivity.getActivityCalendar.mockResolvedValue({ weeks: [] });++ const response = await request(app).get('/api/cos/productivity/calendar');++ expect(response.status).toBe(200);+ expect(productivity.getActivityCalendar).toHaveBeenCalledWith(12);+ });+ });++ describe('GET /api/cos/actionable-insights', () => {+ it('should return actionable insights sorted by priority', async () => {+ cos.getAllTasks.mockResolvedValue({+ user: { grouped: { pending: [{ id: 't1', description: 'Task' }], blocked: [] } },+ cos: { awaitingApproval: [{ id: 'a1', description: 'Approve me' }], grouped: { pending: [], blocked: [] } }+ });+ taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });+ cos.runHealthCheck.mockResolvedValue({ issues: [] });+ productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });++ const response = await request(app).get('/api/cos/actionable-insights');++ expect(response.status).toBe(200);+ expect(response.body.hasActionableItems).toBe(true);+ expect(response.body.insights.length).toBeGreaterThan(0);+ expect(response.body.insights[0].type).toBe('approval');+ });++ it('should handle errors gracefully in parallel calls', async () => {+ cos.getAllTasks.mockRejectedValue(new Error('fail'));+ taskLearning.getLearningInsights.mockRejectedValue(new Error('fail'));+ cos.runHealthCheck.mockRejectedValue(new Error('fail'));+ productivity.getOptimalTimeInfo.mockRejectedValue(new Error('fail'));++ const response = await request(app).get('/api/cos/actionable-insights');++ expect(response.status).toBe(200);+ expect(response.body.insights).toEqual([]);+ });+ });++ describe('GET /api/cos/recent-tasks', () => {+ it('should return recent tasks with default limit', async () => {+ cos.getRecentTasks.mockResolvedValue([{ id: 't1' }]);++ const response = await request(app).get('/api/cos/recent-tasks');++ expect(response.status).toBe(200);+ expect(cos.getRecentTasks).toHaveBeenCalledWith(10);+ });++ it('should respect custom limit', async () => {+ cos.getRecentTasks.mockResolvedValue([]);++ const response = await request(app).get('/api/cos/recent-tasks?limit=5');++ expect(response.status).toBe(200);+ expect(cos.getRecentTasks).toHaveBeenCalledWith(5);+ });+ });++ describe('GET /api/cos/quick-summary', () => {+ it('should return combined dashboard summary', async () => {+ cos.getTodayActivity.mockResolvedValue({+ stats: { completed: 3, succeeded: 2, failed: 1, running: 0, successRate: 67 },+ time: { combined: '2h 30m' },+ isRunning: true,+ isPaused: false,+ lastEvaluation: Date.now(),+ accomplishments: ['Fixed bug']+ });+ productivity.getProductivitySummary.mockResolvedValue({+ currentStreak: 5, longestStreak: 10, weeklyStreak: 3, lastActive: Date.now()+ });+ cos.getAllTasks.mockResolvedValue({+ user: { grouped: { pending: [] } },+ cos: { awaitingApproval: [], grouped: { pending: [] } }+ });+ autonomousJobs.getJobStats.mockResolvedValue({ nextDue: null });+ productivity.getVelocityMetrics.mockResolvedValue({+ velocity: 120, velocityLabel: 'Above average', avgPerDay: 3, historicalDays: 30+ });+ productivity.getWeekComparison.mockResolvedValue({ delta: 2 });+ productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });+ taskLearning.estimateQueueCompletion.mockResolvedValue({ eta: null });++ const response = await request(app).get('/api/cos/quick-summary');++ expect(response.status).toBe(200);+ expect(response.body.today.completed).toBe(3);+ expect(response.body.streak.current).toBe(5);+ expect(response.body.velocity.percentage).toBe(120);+ });+ });++ describe('GET /api/cos/goal-progress', () => {+ it('should return goal progress', async () => {+ goalProgress.getGoalProgress.mockResolvedValue({ goals: [], overall: 0.5 });++ const response = await request(app).get('/api/cos/goal-progress');++ expect(response.status).toBe(200);+ expect(response.body).toHaveProperty('overall');+ });+ });++ describe('GET /api/cos/goal-progress/summary', () => {+ it('should return goal progress summary', async () => {+ goalProgress.getGoalProgressSummary.mockResolvedValue({ topGoals: [] });++ const response = await request(app).get('/api/cos/goal-progress/summary');++ expect(response.status).toBe(200);+ });+ });++ // ============================================================+ // Decision Log Routes+ // ============================================================++ describe('GET /api/cos/decisions', () => {+ it('should return recent decisions with default limit', async () => {+ decisionLog.getRecentDecisions.mockResolvedValue([{ id: 'd1', type: 'approval' }]);++ const response = await request(app).get('/api/cos/decisions');++ expect(response.status).toBe(200);+ expect(response.body.decisions).toHaveLength(1);+ expect(decisionLog.getRecentDecisions).toHaveBeenCalledWith(20, null);+ });++ it('should respect custom limit and type', async () => {+ decisionLog.getRecentDecisions.mockResolvedValue([]);++ const response = await request(app).get('/api/cos/decisions?limit=5&type=routing');++ expect(response.status).toBe(200);+ expect(decisionLog.getRecentDecisions).toHaveBeenCalledWith(5, 'routing');+ });+ });++ describe('GET /api/cos/decisions/summary', () => {+ it('should return decision summary', async () => {+ decisionLog.getDecisionSummary.mockResolvedValue({ total: 50, byType: {} });++ const response = await request(app).get('/api/cos/decisions/summary');++ expect(response.status).toBe(200);+ expect(response.body.total).toBe(50);+ });+ });++ describe('GET /api/cos/decisions/patterns', () => {+ it('should return decision patterns', async () => {+ decisionLog.getDecisionPatterns.mockResolvedValue({ patterns: [] });++ const response = await request(app).get('/api/cos/decisions/patterns');++ expect(response.status).toBe(200);+ });+ });+});diff --git a/server/routes/cosJobRoutes.test.js b/server/routes/cosJobRoutes.test.jsnew file mode 100644index 0000000000..6824293d19--- /dev/null+++ b/server/routes/cosJobRoutes.test.js@@ -0,0 +1,329 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import jobRoutes from './cosJobRoutes.js';++vi.mock('../services/cos.js', () => ({+ addTask: vi.fn()+}));++vi.mock('../services/autonomousJobs.js', () => ({+ getAllJobs: vi.fn(),+ getJobStats: vi.fn(),+ getDueJobs: vi.fn(),+ INTERVAL_OPTIONS: ['hourly', 'daily', 'weekly'],+ getAllowedCommands: vi.fn(),+ getJob: vi.fn(),+ createJob: vi.fn(),+ updateJob: vi.fn(),+ toggleJob: vi.fn(),+ deleteJob: vi.fn(),+ isShellJob: vi.fn(),+ isScriptJob: vi.fn(),+ executeShellJob: vi.fn(),+ executeScriptJob: vi.fn(),+ generateTaskFromJob: vi.fn()+}));++vi.mock('../services/jobGates.js', () => ({+ checkJobGate: vi.fn(),+ hasGate: vi.fn(),+ getRegisteredGates: vi.fn()+}));++vi.mock('../services/eventScheduler.js', () => ({+ parseCronToNextRun: vi.fn()+}));++import * as cos from '../services/cos.js';+import * as autonomousJobs from '../services/autonomousJobs.js';+import { checkJobGate, hasGate, getRegisteredGates } from '../services/jobGates.js';+import { parseCronToNextRun } from '../services/eventScheduler.js';++describe('CoS Job Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/cos', jobRoutes);+ vi.clearAllMocks();+ });++ describe('GET /api/cos/jobs', () => {+ it('should return all jobs with gates and stats', async () => {+ autonomousJobs.getAllJobs.mockResolvedValue([{ id: 'j1', name: 'Review' }]);+ autonomousJobs.getJobStats.mockResolvedValue({ total: 1 });+ hasGate.mockReturnValue(false);+ getRegisteredGates.mockReturnValue([]);++ const response = await request(app).get('/api/cos/jobs');++ expect(response.status).toBe(200);+ expect(response.body.jobs).toHaveLength(1);+ expect(response.body.jobs[0].hasGate).toBe(false);+ expect(response.body.stats).toHaveProperty('total');+ });+ });++ describe('GET /api/cos/jobs/due', () => {+ it('should return due jobs', async () => {+ autonomousJobs.getDueJobs.mockResolvedValue([{ id: 'j1' }]);++ const response = await request(app).get('/api/cos/jobs/due');++ expect(response.status).toBe(200);+ expect(response.body.due).toHaveLength(1);+ });+ });++ describe('GET /api/cos/jobs/intervals', () => {+ it('should return available intervals', async () => {+ const response = await request(app).get('/api/cos/jobs/intervals');++ expect(response.status).toBe(200);+ expect(response.body.intervals).toContain('daily');+ });+ });++ describe('GET /api/cos/jobs/allowed-commands', () => {+ it('should return allowed commands', async () => {+ autonomousJobs.getAllowedCommands.mockReturnValue(['git', 'npm']);++ const response = await request(app).get('/api/cos/jobs/allowed-commands');++ expect(response.status).toBe(200);+ expect(response.body.commands).toEqual(['git', 'npm']);+ });+ });++ describe('GET /api/cos/jobs/gates', () => {+ it('should return all gate results', async () => {+ getRegisteredGates.mockReturnValue(['j1']);+ checkJobGate.mockResolvedValue({ shouldRun: true, reason: 'approved' });++ const response = await request(app).get('/api/cos/jobs/gates');++ expect(response.status).toBe(200);+ expect(response.body.gates).toHaveLength(1);+ expect(response.body.gates[0].shouldRun).toBe(true);+ });+ });++ describe('POST /api/cos/jobs/:id/gate-check', () => {+ it('should check job gate', async () => {+ checkJobGate.mockResolvedValue({ shouldRun: false, reason: 'not today' });+ hasGate.mockReturnValue(true);++ const response = await request(app).post('/api/cos/jobs/j1/gate-check');++ expect(response.status).toBe(200);+ expect(response.body.hasGate).toBe(true);+ expect(response.body.shouldRun).toBe(false);+ });+ });++ describe('GET /api/cos/jobs/:id', () => {+ it('should return a single job', async () => {+ autonomousJobs.getJob.mockResolvedValue({ id: 'j1', name: 'Review' });++ const response = await request(app).get('/api/cos/jobs/j1');++ expect(response.status).toBe(200);+ expect(response.body.name).toBe('Review');+ });++ it('should return 404 if job not found', async () => {+ autonomousJobs.getJob.mockResolvedValue(null);++ const response = await request(app).get('/api/cos/jobs/j999');++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/cos/jobs', () => {+ it('should create an agent job', async () => {+ autonomousJobs.createJob.mockResolvedValue({ id: 'j1', name: 'Review' });++ const response = await request(app)+ .post('/api/cos/jobs')+ .send({ name: 'Review', type: 'agent', promptTemplate: 'Review code' });++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 400 if name is missing', async () => {+ const response = await request(app)+ .post('/api/cos/jobs')+ .send({ type: 'agent', promptTemplate: 'test' });++ expect(response.status).toBe(400);+ });++ it('should return 400 for invalid job type', async () => {+ const response = await request(app)+ .post('/api/cos/jobs')+ .send({ name: 'Test', type: 'invalid' });++ expect(response.status).toBe(400);+ });++ it('should return 400 if shell job missing command', async () => {+ const response = await request(app)+ .post('/api/cos/jobs')+ .send({ name: 'Shell Job', type: 'shell' });++ expect(response.status).toBe(400);+ });++ it('should return 400 if agent job missing promptTemplate', async () => {+ const response = await request(app)+ .post('/api/cos/jobs')+ .send({ name: 'Agent Job', type: 'agent' });++ expect(response.status).toBe(400);+ });++ it('should validate cron expression', async () => {+ parseCronToNextRun.mockReturnValue(new Date());+ autonomousJobs.createJob.mockResolvedValue({ id: 'j1' });++ const response = await request(app)+ .post('/api/cos/jobs')+ .send({ name: 'Cron Job', promptTemplate: 'test', cronExpression: '0 9 * * 1' });++ expect(response.status).toBe(200);+ });++ it('should return 400 for invalid cron expression format', async () => {+ const response = await request(app)+ .post('/api/cos/jobs')+ .send({ name: 'Bad Cron', promptTemplate: 'test', cronExpression: 'invalid' });++ expect(response.status).toBe(400);+ });+ });++ describe('PUT /api/cos/jobs/:id', () => {+ it('should update a job', async () => {+ autonomousJobs.updateJob.mockResolvedValue({ id: 'j1', name: 'Updated' });++ const response = await request(app)+ .put('/api/cos/jobs/j1')+ .send({ name: 'Updated' });++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 404 if job not found', async () => {+ autonomousJobs.updateJob.mockResolvedValue(null);++ const response = await request(app)+ .put('/api/cos/jobs/j999')+ .send({ name: 'Fail' });++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/cos/jobs/:id/toggle', () => {+ it('should toggle job enabled state', async () => {+ autonomousJobs.toggleJob.mockResolvedValue({ id: 'j1', enabled: false });++ const response = await request(app).post('/api/cos/jobs/j1/toggle');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 404 if job not found', async () => {+ autonomousJobs.toggleJob.mockResolvedValue(null);++ const response = await request(app).post('/api/cos/jobs/j999/toggle');++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/cos/jobs/:id/trigger', () => {+ it('should trigger a shell job', async () => {+ autonomousJobs.getJob.mockResolvedValue({ id: 'j1', type: 'shell' });+ autonomousJobs.isShellJob.mockReturnValue(true);+ autonomousJobs.executeShellJob.mockResolvedValue({ success: true, output: 'ok' });++ const response = await request(app).post('/api/cos/jobs/j1/trigger');++ expect(response.status).toBe(200);+ expect(response.body.type).toBe('shell');+ });++ it('should trigger a script job', async () => {+ autonomousJobs.getJob.mockResolvedValue({ id: 'j1', type: 'script' });+ autonomousJobs.isShellJob.mockReturnValue(false);+ autonomousJobs.isScriptJob.mockReturnValue(true);+ autonomousJobs.executeScriptJob.mockResolvedValue({ success: true });++ const response = await request(app).post('/api/cos/jobs/j1/trigger');++ expect(response.status).toBe(200);+ expect(response.body.type).toBe('script');+ });++ it('should trigger an agent job', async () => {+ autonomousJobs.getJob.mockResolvedValue({ id: 'j1', type: 'agent', name: 'Review' });+ autonomousJobs.isShellJob.mockReturnValue(false);+ autonomousJobs.isScriptJob.mockReturnValue(false);+ autonomousJobs.generateTaskFromJob.mockResolvedValue({ description: 'Review', priority: 'MEDIUM' });+ cos.addTask.mockResolvedValue({ id: 'task-1' });++ const response = await request(app).post('/api/cos/jobs/j1/trigger');++ expect(response.status).toBe(200);+ expect(response.body.type).toBe('agent');+ expect(response.body.taskId).toBe('task-1');+ });++ it('should return 404 if job not found', async () => {+ autonomousJobs.getJob.mockResolvedValue(null);++ const response = await request(app).post('/api/cos/jobs/j999/trigger');++ expect(response.status).toBe(404);+ });++ it('should handle failed agent task queuing', async () => {+ autonomousJobs.getJob.mockResolvedValue({ id: 'j1', type: 'agent', name: 'Review' });+ autonomousJobs.isShellJob.mockReturnValue(false);+ autonomousJobs.isScriptJob.mockReturnValue(false);+ autonomousJobs.generateTaskFromJob.mockResolvedValue({ description: 'Review', priority: 'MEDIUM' });+ cos.addTask.mockResolvedValue(null);++ const response = await request(app).post('/api/cos/jobs/j1/trigger');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(false);+ });+ });++ describe('DELETE /api/cos/jobs/:id', () => {+ it('should delete a job', async () => {+ autonomousJobs.deleteJob.mockResolvedValue(true);++ const response = await request(app).delete('/api/cos/jobs/j1');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 404 if job not found', async () => {+ autonomousJobs.deleteJob.mockResolvedValue(false);++ const response = await request(app).delete('/api/cos/jobs/j999');++ expect(response.status).toBe(404);+ });+ });+});diff --git a/server/routes/cosLearningRoutes.test.js b/server/routes/cosLearningRoutes.test.jsnew file mode 100644index 0000000000..f834907558--- /dev/null+++ b/server/routes/cosLearningRoutes.test.js@@ -0,0 +1,374 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import learningRoutes from './cosLearningRoutes.js';++vi.mock('../services/taskLearning.js', () => ({+ getLearningInsights: vi.fn(),+ getAllTaskDurations: vi.fn(),+ backfillFromHistory: vi.fn(),+ getSkippedTaskTypes: vi.fn(),+ resetTaskTypeLearning: vi.fn(),+ getAdaptiveCooldownMultiplier: vi.fn(),+ getRoutingAccuracy: vi.fn(),+ getPerformanceSummary: vi.fn(),+ getLearningSummary: vi.fn(),+ getRecentInsights: vi.fn(),+ recordLearningInsight: vi.fn(),+ getAllPromptRecommendations: vi.fn(),+ getPromptImprovementRecommendations: vi.fn(),+ recalculateModelTierMetrics: vi.fn(),+ recalculateDurationStats: vi.fn(),+ getConfidenceLevels: vi.fn(),+ getTaskTypeConfidence: vi.fn()+}));++vi.mock('../services/weeklyDigest.js', () => ({+ getWeeklyDigest: vi.fn(),+ listWeeklyDigests: vi.fn(),+ getCurrentWeekProgress: vi.fn(),+ generateTextSummary: vi.fn(),+ generateWeeklyDigest: vi.fn(),+ compareWeeks: vi.fn()+}));++vi.mock('../services/cosState.js', () => ({+ loadState: vi.fn().mockResolvedValue({ config: { confidenceAutoApproval: {} } })+}));++import * as taskLearning from '../services/taskLearning.js';+import * as weeklyDigest from '../services/weeklyDigest.js';++describe('CoS Learning Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/cos', learningRoutes);+ vi.clearAllMocks();+ });++ describe('GET /api/cos/learning', () => {+ it('should return learning insights', async () => {+ taskLearning.getLearningInsights.mockResolvedValue({ taskTypes: {}, skippedTypes: [] });++ const response = await request(app).get('/api/cos/learning');++ expect(response.status).toBe(200);+ expect(response.body).toHaveProperty('taskTypes');+ });+ });++ describe('GET /api/cos/learning/durations', () => {+ it('should return task durations', async () => {+ taskLearning.getAllTaskDurations.mockResolvedValue({ 'app-improve': { avg: 300 } });++ const response = await request(app).get('/api/cos/learning/durations');++ expect(response.status).toBe(200);+ });+ });++ describe('POST /api/cos/learning/backfill', () => {+ it('should backfill learning data', async () => {+ taskLearning.backfillFromHistory.mockResolvedValue(15);++ const response = await request(app).post('/api/cos/learning/backfill');++ expect(response.status).toBe(200);+ expect(response.body.backfilledCount).toBe(15);+ });+ });++ describe('GET /api/cos/learning/skipped', () => {+ it('should return skipped task types', async () => {+ taskLearning.getSkippedTaskTypes.mockResolvedValue([{ type: 'deploy', rate: 0.2 }]);++ const response = await request(app).get('/api/cos/learning/skipped');++ expect(response.status).toBe(200);+ expect(response.body.skippedCount).toBe(1);+ });++ it('should return message when no types skipped', async () => {+ taskLearning.getSkippedTaskTypes.mockResolvedValue([]);++ const response = await request(app).get('/api/cos/learning/skipped');++ expect(response.status).toBe(200);+ expect(response.body.skippedCount).toBe(0);+ expect(response.body.message).toContain('No task types');+ });+ });++ describe('POST /api/cos/learning/reset/:taskType', () => {+ it('should reset learning data for task type', async () => {+ taskLearning.resetTaskTypeLearning.mockResolvedValue({ reset: true });++ const response = await request(app).post('/api/cos/learning/reset/deploy');++ expect(response.status).toBe(200);+ expect(response.body.reset).toBe(true);+ });++ it('should return 404 if task type not found', async () => {+ taskLearning.resetTaskTypeLearning.mockResolvedValue({ reset: false });++ const response = await request(app).post('/api/cos/learning/reset/unknown');++ expect(response.status).toBe(404);+ });+ });++ describe('GET /api/cos/learning/cooldown/:taskType', () => {+ it('should return cooldown info', async () => {+ taskLearning.getAdaptiveCooldownMultiplier.mockResolvedValue({ multiplier: 1.5, reason: 'low success' });++ const response = await request(app).get('/api/cos/learning/cooldown/deploy');++ expect(response.status).toBe(200);+ expect(response.body.taskType).toBe('deploy');+ expect(response.body.multiplier).toBe(1.5);+ });+ });++ describe('GET /api/cos/learning/routing', () => {+ it('should return routing accuracy', async () => {+ taskLearning.getRoutingAccuracy.mockResolvedValue({ accuracy: 0.85 });++ const response = await request(app).get('/api/cos/learning/routing');++ expect(response.status).toBe(200);+ });+ });++ describe('GET /api/cos/learning/performance', () => {+ it('should return performance summary', async () => {+ taskLearning.getPerformanceSummary.mockResolvedValue({ overall: 0.75 });++ const response = await request(app).get('/api/cos/learning/performance');++ expect(response.status).toBe(200);+ });+ });++ describe('GET /api/cos/learning/summary', () => {+ it('should return learning health summary', async () => {+ taskLearning.getLearningSummary.mockResolvedValue({ healthy: true });++ const response = await request(app).get('/api/cos/learning/summary');++ expect(response.status).toBe(200);+ });+ });++ describe('GET /api/cos/learning/insights', () => {+ it('should return recent insights with default limit', async () => {+ taskLearning.getRecentInsights.mockResolvedValue([{ message: 'insight 1' }]);++ const response = await request(app).get('/api/cos/learning/insights');++ expect(response.status).toBe(200);+ expect(response.body.count).toBe(1);+ expect(taskLearning.getRecentInsights).toHaveBeenCalledWith(10);+ });++ it('should respect custom limit', async () => {+ taskLearning.getRecentInsights.mockResolvedValue([]);++ const response = await request(app).get('/api/cos/learning/insights?limit=5');++ expect(response.status).toBe(200);+ expect(taskLearning.getRecentInsights).toHaveBeenCalledWith(5);+ });+ });++ describe('POST /api/cos/learning/insights', () => {+ it('should record a learning insight', async () => {+ taskLearning.recordLearningInsight.mockResolvedValue({ id: 'i1', message: 'test' });++ const response = await request(app)+ .post('/api/cos/learning/insights')+ .send({ message: 'test insight', type: 'discovery' });++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 400 if message is missing', async () => {+ const response = await request(app)+ .post('/api/cos/learning/insights')+ .send({ type: 'observation' });++ expect(response.status).toBe(400);+ });+ });++ describe('GET /api/cos/learning/recommendations', () => {+ it('should return prompt recommendations with summary', async () => {+ taskLearning.getAllPromptRecommendations.mockResolvedValue([+ { status: 'critical', taskType: 'deploy' },+ { status: 'good', taskType: 'review' }+ ]);++ const response = await request(app).get('/api/cos/learning/recommendations');++ expect(response.status).toBe(200);+ expect(response.body.count).toBe(2);+ expect(response.body.summary.critical).toBe(1);+ expect(response.body.summary.good).toBe(1);+ });+ });++ describe('GET /api/cos/learning/recommendations/:taskType', () => {+ it('should return recommendations for specific task type', async () => {+ taskLearning.getPromptImprovementRecommendations.mockResolvedValue({ suggestions: [] });++ const response = await request(app).get('/api/cos/learning/recommendations/deploy');++ expect(response.status).toBe(200);+ expect(taskLearning.getPromptImprovementRecommendations).toHaveBeenCalledWith('deploy');+ });+ });++ describe('POST /api/cos/learning/recalculate-model-tiers', () => {+ it('should recalculate model tier metrics', async () => {+ taskLearning.recalculateModelTierMetrics.mockResolvedValue({ recalculated: 5 });++ const response = await request(app).post('/api/cos/learning/recalculate-model-tiers');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });+ });++ describe('POST /api/cos/learning/recalculate-durations', () => {+ it('should recalculate duration stats', async () => {+ taskLearning.recalculateDurationStats.mockResolvedValue({ recalculated: 3 });++ const response = await request(app).post('/api/cos/learning/recalculate-durations');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });+ });++ describe('GET /api/cos/learning/confidence', () => {+ it('should return confidence levels', async () => {+ taskLearning.getConfidenceLevels.mockResolvedValue({ levels: {} });++ const response = await request(app).get('/api/cos/learning/confidence');++ expect(response.status).toBe(200);+ });+ });++ describe('GET /api/cos/learning/confidence/:taskType', () => {+ it('should return confidence for specific task type', async () => {+ taskLearning.getTaskTypeConfidence.mockResolvedValue({ level: 'high', score: 0.9 });++ const response = await request(app).get('/api/cos/learning/confidence/review');++ expect(response.status).toBe(200);+ });+ });++ // ============================================================+ // Weekly Digest Routes+ // ============================================================++ describe('GET /api/cos/digest', () => {+ it('should return current week digest', async () => {+ weeklyDigest.getWeeklyDigest.mockResolvedValue({ weekId: '2026-W14', stats: {} });++ const response = await request(app).get('/api/cos/digest');++ expect(response.status).toBe(200);+ expect(response.body.weekId).toBe('2026-W14');+ });+ });++ describe('GET /api/cos/digest/list', () => {+ it('should list weekly digests', async () => {+ weeklyDigest.listWeeklyDigests.mockResolvedValue(['2026-W14', '2026-W13']);++ const response = await request(app).get('/api/cos/digest/list');++ expect(response.status).toBe(200);+ expect(response.body.digests).toHaveLength(2);+ });+ });++ describe('GET /api/cos/digest/progress', () => {+ it('should return current week progress', async () => {+ weeklyDigest.getCurrentWeekProgress.mockResolvedValue({ completed: 5, total: 10 });++ const response = await request(app).get('/api/cos/digest/progress');++ expect(response.status).toBe(200);+ });+ });++ describe('GET /api/cos/digest/text', () => {+ it('should return text summary', async () => {+ weeklyDigest.generateTextSummary.mockResolvedValue('Weekly summary text');++ const response = await request(app).get('/api/cos/digest/text');++ expect(response.status).toBe(200);+ expect(response.text).toContain('Weekly summary text');+ });+ });++ describe('GET /api/cos/digest/:weekId', () => {+ it('should return digest for specific week', async () => {+ weeklyDigest.getWeeklyDigest.mockResolvedValue({ weekId: '2026-W13', stats: {} });++ const response = await request(app).get('/api/cos/digest/2026-W13');++ expect(response.status).toBe(200);+ });++ it('should return 400 for invalid weekId format', async () => {+ const response = await request(app).get('/api/cos/digest/bad-format');++ expect(response.status).toBe(400);+ });++ it('should return 404 if digest not found', async () => {+ weeklyDigest.getWeeklyDigest.mockResolvedValue(null);++ const response = await request(app).get('/api/cos/digest/2020-W01');++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/cos/digest/generate', () => {+ it('should force generate digest', async () => {+ weeklyDigest.generateWeeklyDigest.mockResolvedValue({ weekId: '2026-W14' });++ const response = await request(app)+ .post('/api/cos/digest/generate')+ .send({ weekId: '2026-W14' });++ expect(response.status).toBe(200);+ });++ it('should generate for current week if weekId not provided', async () => {+ weeklyDigest.generateWeeklyDigest.mockResolvedValue({ weekId: '2026-W14' });++ const response = await request(app)+ .post('/api/cos/digest/generate')+ .send({});++ expect(response.status).toBe(200);+ expect(weeklyDigest.generateWeeklyDigest).toHaveBeenCalledWith(null);+ });+ });++ // Note: GET /api/cos/digest/compare is unreachable because /digest/:weekId+ // is defined before it in the route file. "compare" matches :weekId and fails+ // the YYYY-WXX validation, returning 400. This is a known route ordering issue.+});diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.jsnew file mode 100644index 0000000000..d8909a62da--- /dev/null+++ b/server/routes/cosScheduleRoutes.test.js@@ -0,0 +1,321 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import scheduleRoutes from './cosScheduleRoutes.js';++vi.mock('../services/taskSchedule.js', () => ({+ getScheduleStatus: vi.fn(),+ getUpcomingTasks: vi.fn(),+ getTaskInterval: vi.fn(),+ shouldRunTask: vi.fn(),+ updateTaskInterval: vi.fn(),+ getDueTasks: vi.fn(),+ triggerOnDemandTask: vi.fn(),+ getOnDemandRequests: vi.fn(),+ clearOnDemandRequest: vi.fn(),+ resetExecutionHistory: vi.fn(),+ getTemplateTasks: vi.fn(),+ addTemplateTask: vi.fn(),+ deleteTemplateTask: vi.fn(),+ INTERVAL_TYPES: ['rotation', 'daily', 'weekly', 'once', 'on-demand', 'custom', 'cron']+}));++vi.mock('../lib/validation.js', () => ({+ sanitizeTaskMetadata: vi.fn((meta) => meta)+}));++import * as taskSchedule from '../services/taskSchedule.js';++describe('CoS Schedule Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/cos', scheduleRoutes);+ vi.clearAllMocks();+ });++ describe('GET /api/cos/schedule', () => {+ it('should return schedule status', async () => {+ taskSchedule.getScheduleStatus.mockResolvedValue({ tasks: [], enabled: true });++ const response = await request(app).get('/api/cos/schedule');++ expect(response.status).toBe(200);+ });+ });++ describe('GET /api/cos/upcoming', () => {+ it('should return upcoming tasks with default limit', async () => {+ taskSchedule.getUpcomingTasks.mockResolvedValue([{ taskType: 'review', dueIn: 300 }]);++ const response = await request(app).get('/api/cos/upcoming');++ expect(response.status).toBe(200);+ expect(taskSchedule.getUpcomingTasks).toHaveBeenCalledWith(10);+ });++ it('should respect custom limit', async () => {+ taskSchedule.getUpcomingTasks.mockResolvedValue([]);++ const response = await request(app).get('/api/cos/upcoming?limit=3');++ expect(response.status).toBe(200);+ expect(taskSchedule.getUpcomingTasks).toHaveBeenCalledWith(3);+ });+ });++ describe('GET /api/cos/schedule/task/:taskType', () => {+ it('should return interval and shouldRun for task type', async () => {+ taskSchedule.getTaskInterval.mockResolvedValue({ type: 'daily', intervalMs: 86400000 });+ taskSchedule.shouldRunTask.mockResolvedValue(true);++ const response = await request(app).get('/api/cos/schedule/task/review');++ expect(response.status).toBe(200);+ expect(response.body.taskType).toBe('review');+ expect(response.body.shouldRun).toBe(true);+ });+ });++ describe('PUT /api/cos/schedule/task/:taskType', () => {+ it('should update interval for task type', async () => {+ taskSchedule.updateTaskInterval.mockResolvedValue({ type: 'daily' });++ const response = await request(app)+ .put('/api/cos/schedule/task/review')+ .send({ type: 'daily', enabled: true });++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 400 for invalid enabled type', async () => {+ const response = await request(app)+ .put('/api/cos/schedule/task/review')+ .send({ enabled: 'not-bool' });++ expect(response.status).toBe(400);+ });++ it('should return 400 for negative intervalMs', async () => {+ const response = await request(app)+ .put('/api/cos/schedule/task/review')+ .send({ intervalMs: -1 });++ expect(response.status).toBe(400);+ });++ it('should filter self-references from runAfter', async () => {+ taskSchedule.updateTaskInterval.mockResolvedValue({ type: 'rotation' });++ const response = await request(app)+ .put('/api/cos/schedule/task/review')+ .send({ runAfter: ['review', 'deploy'] });++ expect(response.status).toBe(200);+ expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('review', expect.objectContaining({+ runAfter: ['deploy']+ }));+ });++ it('should set runAfter to null when only self-reference remains', async () => {+ taskSchedule.updateTaskInterval.mockResolvedValue({ type: 'rotation' });++ const response = await request(app)+ .put('/api/cos/schedule/task/review')+ .send({ runAfter: ['review'] });++ expect(response.status).toBe(200);+ expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('review', expect.objectContaining({+ runAfter: null+ }));+ });+ });++ describe('GET /api/cos/schedule/due', () => {+ it('should return due tasks', async () => {+ taskSchedule.getDueTasks.mockResolvedValue([{ taskType: 'review' }]);++ const response = await request(app).get('/api/cos/schedule/due');++ expect(response.status).toBe(200);+ expect(response.body.tasks).toHaveLength(1);+ });+ });++ describe('GET /api/cos/schedule/due/:appId', () => {+ it('should return due tasks for specific app', async () => {+ taskSchedule.getDueTasks.mockResolvedValue([]);++ const response = await request(app).get('/api/cos/schedule/due/my-app');++ expect(response.status).toBe(200);+ expect(response.body.appId).toBe('my-app');+ expect(taskSchedule.getDueTasks).toHaveBeenCalledWith('my-app');+ });+ });++ describe('POST /api/cos/schedule/trigger', () => {+ it('should trigger an on-demand task', async () => {+ taskSchedule.triggerOnDemandTask.mockResolvedValue({ id: 'req-1' });++ const response = await request(app)+ .post('/api/cos/schedule/trigger')+ .send({ taskType: 'review', appId: 'my-app' });++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 400 if taskType is missing', async () => {+ const response = await request(app)+ .post('/api/cos/schedule/trigger')+ .send({});++ expect(response.status).toBe(400);+ });+ });++ describe('GET /api/cos/schedule/on-demand', () => {+ it('should return pending on-demand requests', async () => {+ taskSchedule.getOnDemandRequests.mockResolvedValue([{ id: 'req-1' }]);++ const response = await request(app).get('/api/cos/schedule/on-demand');++ expect(response.status).toBe(200);+ expect(response.body.requests).toHaveLength(1);+ });+ });++ describe('DELETE /api/cos/schedule/on-demand/:requestId', () => {+ it('should clear on-demand request', async () => {+ taskSchedule.clearOnDemandRequest.mockResolvedValue({ id: 'req-1' });++ const response = await request(app).delete('/api/cos/schedule/on-demand/req-1');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 404 if request not found', async () => {+ taskSchedule.clearOnDemandRequest.mockResolvedValue(null);++ const response = await request(app).delete('/api/cos/schedule/on-demand/req-999');++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/cos/schedule/reset', () => {+ it('should reset execution history', async () => {+ taskSchedule.resetExecutionHistory.mockResolvedValue({ success: true });++ const response = await request(app)+ .post('/api/cos/schedule/reset')+ .send({ taskType: 'review' });++ expect(response.status).toBe(200);+ });++ it('should return 400 if taskType is missing', async () => {+ const response = await request(app)+ .post('/api/cos/schedule/reset')+ .send({});++ expect(response.status).toBe(400);+ });++ it('should return 404 on reset error', async () => {+ taskSchedule.resetExecutionHistory.mockResolvedValue({ error: 'Task type not found' });++ const response = await request(app)+ .post('/api/cos/schedule/reset')+ .send({ taskType: 'unknown' });++ expect(response.status).toBe(404);+ });+ });++ describe('GET /api/cos/schedule/templates', () => {+ it('should return template tasks', async () => {+ taskSchedule.getTemplateTasks.mockResolvedValue([{ id: 'tmpl-1' }]);++ const response = await request(app).get('/api/cos/schedule/templates');++ expect(response.status).toBe(200);+ expect(response.body.templates).toHaveLength(1);+ });+ });++ describe('POST /api/cos/schedule/templates', () => {+ it('should add a template task', async () => {+ taskSchedule.addTemplateTask.mockResolvedValue({ id: 'tmpl-1', name: 'Review' });++ const response = await request(app)+ .post('/api/cos/schedule/templates')+ .send({ name: 'Review', description: 'Code review task' });++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 400 if name is missing', async () => {+ const response = await request(app)+ .post('/api/cos/schedule/templates')+ .send({ description: 'No name' });++ expect(response.status).toBe(400);+ });++ it('should return 400 if description is missing', async () => {+ const response = await request(app)+ .post('/api/cos/schedule/templates')+ .send({ name: 'No description' });++ expect(response.status).toBe(400);+ });+ });++ describe('DELETE /api/cos/schedule/templates/:templateId', () => {+ it('should delete a template task', async () => {+ taskSchedule.deleteTemplateTask.mockResolvedValue({ success: true });++ const response = await request(app).delete('/api/cos/schedule/templates/tmpl-1');++ expect(response.status).toBe(200);+ });++ it('should return 404 on delete error', async () => {+ taskSchedule.deleteTemplateTask.mockResolvedValue({ error: 'Template not found' });++ const response = await request(app).delete('/api/cos/schedule/templates/tmpl-999');++ expect(response.status).toBe(404);+ });+ });++ describe('GET /api/cos/schedule/interval-types', () => {+ it('should return available interval types', async () => {+ const response = await request(app).get('/api/cos/schedule/interval-types');++ expect(response.status).toBe(200);+ expect(response.body.types).toContain('daily');+ expect(response.body.descriptions).toHaveProperty('daily');+ });+ });++ // Deprecated alias routes+ describe('GET /api/cos/schedule/self-improvement/:taskType', () => {+ it('should delegate to unified endpoint', async () => {+ taskSchedule.getTaskInterval.mockResolvedValue({ type: 'daily' });+ taskSchedule.shouldRunTask.mockResolvedValue(false);++ const response = await request(app).get('/api/cos/schedule/self-improvement/review');++ expect(response.status).toBe(200);+ expect(response.body.taskType).toBe('review');+ });+ });+});diff --git a/server/routes/cosTemplateRoutes.test.js b/server/routes/cosTemplateRoutes.test.jsnew file mode 100644index 0000000000..83809959d9--- /dev/null+++ b/server/routes/cosTemplateRoutes.test.js@@ -0,0 +1,184 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import templateRoutes from './cosTemplateRoutes.js';++vi.mock('../services/taskTemplates.js', () => ({+ getAllTemplates: vi.fn(),+ getPopularTemplates: vi.fn(),+ getCategories: vi.fn(),+ createTemplate: vi.fn(),+ createTemplateFromTask: vi.fn(),+ recordTemplateUsage: vi.fn(),+ updateTemplate: vi.fn(),+ deleteTemplate: vi.fn()+}));++import * as taskTemplates from '../services/taskTemplates.js';++describe('CoS Template Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/cos', templateRoutes);+ vi.clearAllMocks();+ });++ describe('GET /api/cos/templates', () => {+ it('should return all templates', async () => {+ taskTemplates.getAllTemplates.mockResolvedValue([{ id: 't1', name: 'Fix Bug' }]);++ const response = await request(app).get('/api/cos/templates');++ expect(response.status).toBe(200);+ expect(response.body.templates).toHaveLength(1);+ });+ });++ describe('GET /api/cos/templates/popular', () => {+ it('should return popular templates with default limit', async () => {+ taskTemplates.getPopularTemplates.mockResolvedValue([{ id: 't1', useCount: 10 }]);++ const response = await request(app).get('/api/cos/templates/popular');++ expect(response.status).toBe(200);+ expect(taskTemplates.getPopularTemplates).toHaveBeenCalledWith(5);+ });++ it('should respect custom limit', async () => {+ taskTemplates.getPopularTemplates.mockResolvedValue([]);++ const response = await request(app).get('/api/cos/templates/popular?limit=3');++ expect(response.status).toBe(200);+ expect(taskTemplates.getPopularTemplates).toHaveBeenCalledWith(3);+ });+ });++ describe('GET /api/cos/templates/categories', () => {+ it('should return template categories', async () => {+ taskTemplates.getCategories.mockResolvedValue(['bugs', 'features']);++ const response = await request(app).get('/api/cos/templates/categories');++ expect(response.status).toBe(200);+ expect(response.body.categories).toEqual(['bugs', 'features']);+ });+ });++ describe('POST /api/cos/templates', () => {+ it('should create a new template', async () => {+ const templateData = { name: 'Fix Bug', description: 'Fix a bug in the app', category: 'bugs' };+ taskTemplates.createTemplate.mockResolvedValue({ id: 't1', ...templateData });++ const response = await request(app)+ .post('/api/cos/templates')+ .send(templateData);++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ expect(response.body.template.name).toBe('Fix Bug');+ });++ it('should return 400 if name is missing', async () => {+ const response = await request(app)+ .post('/api/cos/templates')+ .send({ description: 'No name' });++ expect(response.status).toBe(400);+ });++ it('should return 400 if description is missing', async () => {+ const response = await request(app)+ .post('/api/cos/templates')+ .send({ name: 'No description' });++ expect(response.status).toBe(400);+ });+ });++ describe('POST /api/cos/templates/from-task', () => {+ it('should create template from task', async () => {+ taskTemplates.createTemplateFromTask.mockResolvedValue({ id: 't2', name: 'From Task' });++ const response = await request(app)+ .post('/api/cos/templates/from-task')+ .send({ task: { description: 'Fix login' }, templateName: 'Login Fix' });++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 400 if task is missing', async () => {+ const response = await request(app)+ .post('/api/cos/templates/from-task')+ .send({});++ expect(response.status).toBe(400);+ });++ it('should return 400 if task has no description', async () => {+ const response = await request(app)+ .post('/api/cos/templates/from-task')+ .send({ task: {} });++ expect(response.status).toBe(400);+ });+ });++ describe('POST /api/cos/templates/:id/use', () => {+ it('should record template usage', async () => {+ taskTemplates.recordTemplateUsage.mockResolvedValue(5);++ const response = await request(app).post('/api/cos/templates/t1/use');++ expect(response.status).toBe(200);+ expect(response.body.useCount).toBe(5);+ expect(taskTemplates.recordTemplateUsage).toHaveBeenCalledWith('t1');+ });+ });++ describe('PUT /api/cos/templates/:id', () => {+ it('should update a template', async () => {+ taskTemplates.updateTemplate.mockResolvedValue({ id: 't1', name: 'Updated' });++ const response = await request(app)+ .put('/api/cos/templates/t1')+ .send({ name: 'Updated' });++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 400 on update error', async () => {+ taskTemplates.updateTemplate.mockResolvedValue({ error: 'Template not found' });++ const response = await request(app)+ .put('/api/cos/templates/t999')+ .send({ name: 'Fail' });++ expect(response.status).toBe(400);+ });+ });++ describe('DELETE /api/cos/templates/:id', () => {+ it('should delete a template', async () => {+ taskTemplates.deleteTemplate.mockResolvedValue({ success: true });++ const response = await request(app).delete('/api/cos/templates/t1');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 400 on delete error', async () => {+ taskTemplates.deleteTemplate.mockResolvedValue({ error: 'Template not found' });++ const response = await request(app).delete('/api/cos/templates/t999');++ expect(response.status).toBe(400);+ });+ });+});