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: add CoS today's activity dashboard and script command validation

Adam Eivy56b87a0a4638
diff --git a/client/src/components/cos/tabs/HealthTab.jsx b/client/src/components/cos/tabs/HealthTab.jsx
index 681caf69f6..aa8a4a938a 100644
--- a/client/src/components/cos/tabs/HealthTab.jsx
+++ b/client/src/components/cos/tabs/HealthTab.jsx
@@ -1,16 +1,26 @@
import { useState, useEffect } from 'react';
-import { RefreshCw, CheckCircle, AlertCircle, TrendingUp, Brain, Zap, Database } from 'lucide-react';
+import { RefreshCw, CheckCircle, AlertCircle, TrendingUp, Brain, Zap, Database, Clock, Trophy, Activity } from 'lucide-react';
import * as api from '../../../services/api';
export default function HealthTab({ health, onCheck }) {
const [learning, setLearning] = useState(null);
const [loadingLearning, setLoadingLearning] = useState(true);
const [backfilling, setBackfilling] = useState(false);
+ const [todayActivity, setTodayActivity] = useState(null);
+ const [loadingActivity, setLoadingActivity] = useState(true);
useEffect(() => {
loadLearning();
+ loadTodayActivity();
}, []);
+ const loadTodayActivity = async () => {
+ setLoadingActivity(true);
+ const data = await api.getCosTodayActivity().catch(() => null);
+ setTodayActivity(data);
+ setLoadingActivity(false);
+ };
+
const loadLearning = async () => {
setLoadingLearning(true);
const data = await api.getCosLearning().catch(() => null);
@@ -29,6 +39,115 @@ export default function HealthTab({ health, onCheck }) {
return (
<div className="space-y-6">
+ {/* Today's Activity Section */}
+ <div>
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-2">
+ <Activity className="w-5 h-5 text-port-accent" />
+ <h3 className="text-lg font-semibold text-white">Today's Activity</h3>
+ </div>
+ <button
+ onClick={loadTodayActivity}
+ className="text-gray-500 hover:text-white transition-colors"
+ >
+ <RefreshCw size={14} className={loadingActivity ? 'animate-spin' : ''} />
+ </button>
+ </div>
+
+ {loadingActivity ? (
+ <div className="text-center py-4 text-gray-500">Loading activity...</div>
+ ) : !todayActivity ? (
+ <div className="text-center py-4 text-gray-500">Could not load activity data</div>
+ ) : (
+ <div className="space-y-4">
+ {/* Stats Grid */}
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
+ <div className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex items-center gap-2 mb-1">
+ <CheckCircle size={14} className="text-port-success" />
+ <span className="text-xs text-gray-500">Completed</span>
+ </div>
+ <div className="text-2xl font-bold text-white">{todayActivity.stats.completed}</div>
+ <div className="text-xs text-gray-500">
+ {todayActivity.stats.succeeded} success / {todayActivity.stats.failed} failed
+ </div>
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex items-center gap-2 mb-1">
+ <TrendingUp size={14} className="text-port-accent" />
+ <span className="text-xs text-gray-500">Success Rate</span>
+ </div>
+ <div className={`text-2xl font-bold ${
+ todayActivity.stats.successRate >= 80 ? 'text-port-success' :
+ todayActivity.stats.successRate >= 50 ? 'text-port-warning' : 'text-port-error'
+ }`}>
+ {todayActivity.stats.successRate}%
+ </div>
+ <div className="text-xs text-gray-500">today</div>
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex items-center gap-2 mb-1">
+ <Clock size={14} className="text-cyan-400" />
+ <span className="text-xs text-gray-500">Time Worked</span>
+ </div>
+ <div className="text-2xl font-bold text-cyan-400">{todayActivity.time.combined}</div>
+ <div className="text-xs text-gray-500">
+ {todayActivity.stats.running > 0 && `${todayActivity.stats.running} active`}
+ </div>
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex items-center gap-2 mb-1">
+ <Trophy size={14} className="text-yellow-400" />
+ <span className="text-xs text-gray-500">Status</span>
+ </div>
+ <div className={`text-lg font-bold ${
+ todayActivity.isPaused ? 'text-port-warning' :
+ todayActivity.isRunning ? 'text-port-success' : 'text-gray-500'
+ }`}>
+ {todayActivity.isPaused ? 'Paused' :
+ todayActivity.isRunning ? 'Active' : 'Stopped'}
+ </div>
+ <div className="text-xs text-gray-500">
+ {todayActivity.stats.running > 0 ? `${todayActivity.stats.running} running` : 'idle'}
+ </div>
+ </div>
+ </div>
+
+ {/* Recent Accomplishments */}
+ {todayActivity.accomplishments.length > 0 && (
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <h4 className="text-sm font-medium text-gray-400 mb-3 flex items-center gap-2">
+ <Trophy size={14} className="text-yellow-400" />
+ Recent Accomplishments
+ </h4>
+ <div className="space-y-2">
+ {todayActivity.accomplishments.map((item, idx) => (
+ <div key={idx} className="flex items-start justify-between text-sm p-2 bg-port-bg rounded">
+ <div className="flex-1 min-w-0">
+ <span className="text-gray-300 block truncate">{item.description}</span>
+ <span className="text-xs text-gray-500">{item.taskType}</span>
+ </div>
+ <span className="text-xs text-gray-500 ml-2 whitespace-nowrap">
+ {Math.round(item.duration / 60000)}m
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {todayActivity.stats.completed === 0 && (
+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">
+ No tasks completed today yet. CoS will start working when tasks are available.
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
{/* System Health Section */}
<div className="flex items-center justify-between">
<div>
diff --git a/client/src/components/cos/tabs/ScriptCard.jsx b/client/src/components/cos/tabs/ScriptCard.jsx
index fc78013f21..f013600149 100644
--- a/client/src/components/cos/tabs/ScriptCard.jsx
+++ b/client/src/components/cos/tabs/ScriptCard.jsx
@@ -11,6 +11,7 @@ import {
} from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../../services/api';
+import { formatTime } from '../../../utils/formatters';
const scheduleLabels = {
'on-demand': 'On Demand',
@@ -47,17 +48,6 @@ export default function ScriptCard({ script, onRun, onToggle, onDelete, onUpdate
onUpdate?.();
};
- const formatTime = (timestamp) => {
- if (!timestamp) return 'Never';
- const date = new Date(timestamp);
- const now = new Date();
- const diff = now - date;
- if (diff < 60000) return 'Just now';
- if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
- if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
- return date.toLocaleDateString();
- };
-
return (
<div className={`bg-port-card border rounded-lg overflow-hidden ${
script.enabled ? 'border-port-border' : 'border-port-border opacity-60'
diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsx
index 18cac79185..0697fbca25 100644
--- a/client/src/pages/DevTools.jsx
+++ b/client/src/pages/DevTools.jsx
@@ -4,6 +4,7 @@ import { GitBranch, Plus, Minus, FileText, Clock, RefreshCw, Activity, Image, X,
import toast from 'react-hot-toast';
import * as api from '../services/api';
import socket from '../services/socket';
+import { formatTime, formatRuntime } from '../utils/formatters';
export function HistoryPage() {
const [history, setHistory] = useState([]);
@@ -47,17 +48,6 @@ export function HistoryPage() {
loadData();
};
- const formatTime = (timestamp) => {
- const date = new Date(timestamp);
- const now = new Date();
- const diff = now - date;
-
- if (diff < 60000) return 'Just now';
- if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
- if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
- return date.toLocaleDateString();
- };
-
const getActionIcon = (action) => {
const icons = {
start: '▶️',
@@ -70,13 +60,6 @@ export function HistoryPage() {
return icons[action] || '📋';
};
- const formatRuntime = (ms) => {
- if (!ms) return null;
- if (ms < 1000) return `${ms}ms`;
- if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
- return `${(ms / 60000).toFixed(1)}m`;
- };
-
const toggleExpand = (id) => {
setExpandedId(prev => prev === id ? null : id);
};
@@ -372,24 +355,6 @@ export function RunsHistoryPage() {
});
};
- const formatTime = (timestamp) => {
- const date = new Date(timestamp);
- const now = new Date();
- const diff = now - date;
-
- if (diff < 60000) return 'Just now';
- if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
- if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
- return date.toLocaleDateString();
- };
-
- const formatRuntime = (ms) => {
- if (!ms) return null;
- if (ms < 1000) return `${ms}ms`;
- if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
- return `${(ms / 60000).toFixed(1)}m`;
- };
-
const getExitCodeInfo = (exitCode) => {
const codeInfo = {
1: { label: 'Error', description: 'Generic error - check the output for details' },
diff --git a/client/src/services/api.js b/client/src/services/api.js
index c778b9fbab..04c37b66a0 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -253,6 +253,9 @@ export const getCosReports = () => request('/cos/reports');
export const getCosTodayReport = () => request('/cos/reports/today');
export const getCosReport = (date) => request(`/cos/reports/${date}`);
+// CoS Activity
+export const getCosTodayActivity = () => request('/cos/activity/today');
+
// CoS Learning
export const getCosLearning = () => request('/cos/learning');
export const getCosLearningDurations = () => request('/cos/learning/durations');
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
new file mode 100644
index 0000000000..9ea5ea3a5c
--- /dev/null
+++ b/client/src/utils/formatters.js
@@ -0,0 +1,48 @@
+/**
+ * Shared formatting utilities for the client
+ * These functions are used across multiple pages and components
+ */
+
+/**
+ * Format a timestamp as a relative time string
+ * @param {string|Date} timestamp - ISO timestamp or Date object
+ * @returns {string} Formatted relative time (e.g., "Just now", "5m ago", "2h ago")
+ */
+export function formatTime(timestamp) {
+ const date = new Date(timestamp);
+ const now = new Date();
+ const diff = now - date;
+
+ if (diff < 60000) return 'Just now';
+ if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
+ if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
+ return date.toLocaleDateString();
+}
+
+/**
+ * Format a duration in milliseconds as a human-readable string
+ * @param {number} ms - Duration in milliseconds
+ * @returns {string|null} Formatted duration (e.g., "500ms", "1.5s", "2.0m")
+ */
+export function formatRuntime(ms) {
+ if (!ms) return null;
+ if (ms < 1000) return `${ms}ms`;
+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
+ return `${(ms / 60000).toFixed(1)}m`;
+}
+
+/**
+ * Format bytes as a human-readable string
+ * @param {number} bytes - Size in bytes
+ * @param {number} decimals - Number of decimal places
+ * @returns {string} Formatted size (e.g., "1.5 KB", "2.3 MB")
+ */
+export function formatBytes(bytes, decimals = 1) {
+ if (!bytes || bytes === 0) return '0 B';
+
+ const k = 1024;
+ const sizes = ['B', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
+}
diff --git a/server/routes/apps.test.js b/server/routes/apps.test.js
new file mode 100644
index 0000000000..7b6060c31c
--- /dev/null
+++ b/server/routes/apps.test.js
@@ -0,0 +1,343 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import request from 'supertest';
+import appsRoutes from './apps.js';
+
+// Mock the services
+vi.mock('../services/apps.js', () => ({
+ getAllApps: vi.fn(),
+ getAppById: vi.fn(),
+ createApp: vi.fn(),
+ updateApp: vi.fn(),
+ deleteApp: vi.fn()
+}));
+
+vi.mock('../services/pm2.js', () => ({
+ listProcesses: vi.fn(),
+ getAppStatus: vi.fn(),
+ startWithCommand: vi.fn(),
+ stopApp: vi.fn(),
+ restartApp: vi.fn(),
+ getLogs: vi.fn()
+}));
+
+vi.mock('../services/history.js', () => ({
+ logAction: vi.fn()
+}));
+
+vi.mock('../services/streamingDetect.js', () => ({
+ parseEcosystemFromPath: vi.fn()
+}));
+
+// Import mocked modules
+import * as appsService from '../services/apps.js';
+import * as pm2Service from '../services/pm2.js';
+import * as history from '../services/history.js';
+import * as streamingDetect from '../services/streamingDetect.js';
+
+describe('Apps Routes', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/apps', appsRoutes);
+
+ // Reset all mocks
+ vi.clearAllMocks();
+ });
+
+ describe('GET /api/apps', () => {
+ it('should return list of apps with PM2 status', async () => {
+ const mockApps = [
+ { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'], repoPath: '/tmp/test' }
+ ];
+ const mockPm2Processes = [
+ { name: 'test-app', status: 'online' }
+ ];
+
+ appsService.getAllApps.mockResolvedValue(mockApps);
+ pm2Service.listProcesses.mockResolvedValue(mockPm2Processes);
+ streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);
+
+ const response = await request(app).get('/api/apps');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toHaveLength(1);
+ expect(response.body[0].overallStatus).toBe('online');
+ });
+
+ it('should handle apps with no PM2 processes', async () => {
+ const mockApps = [
+ { id: 'app-001', name: 'Test App', pm2ProcessNames: [], repoPath: '/tmp/test' }
+ ];
+
+ appsService.getAllApps.mockResolvedValue(mockApps);
+ pm2Service.listProcesses.mockResolvedValue([]);
+ streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);
+
+ const response = await request(app).get('/api/apps');
+
+ expect(response.status).toBe(200);
+ expect(response.body[0].overallStatus).toBe('not_started');
+ });
+
+ it('should return empty array when no apps exist', async () => {
+ appsService.getAllApps.mockResolvedValue([]);
+ pm2Service.listProcesses.mockResolvedValue([]);
+
+ const response = await request(app).get('/api/apps');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toHaveLength(0);
+ });
+ });
+
+ describe('GET /api/apps/:id', () => {
+ it('should return app by ID', async () => {
+ const mockApp = {
+ id: 'app-001',
+ name: 'Test App',
+ pm2ProcessNames: ['test-app']
+ };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ pm2Service.getAppStatus.mockResolvedValue({ status: 'online' });
+
+ const response = await request(app).get('/api/apps/app-001');
+
+ expect(response.status).toBe(200);
+ expect(response.body.id).toBe('app-001');
+ expect(response.body.pm2Status).toBeDefined();
+ });
+
+ it('should return 404 if app not found', async () => {
+ appsService.getAppById.mockResolvedValue(null);
+
+ const response = await request(app).get('/api/apps/app-999');
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe('POST /api/apps', () => {
+ it('should create a new app', async () => {
+ const newApp = {
+ name: 'New App',
+ repoPath: '/path/to/repo'
+ };
+ appsService.createApp.mockResolvedValue({ id: 'app-001', ...newApp });
+
+ const response = await request(app)
+ .post('/api/apps')
+ .send(newApp);
+
+ expect(response.status).toBe(201);
+ expect(response.body.id).toBe('app-001');
+ expect(appsService.createApp).toHaveBeenCalledWith(expect.objectContaining({ name: 'New App' }));
+ });
+
+ it('should return 400 if validation fails', async () => {
+ // Missing required fields
+ const response = await request(app)
+ .post('/api/apps')
+ .send({});
+
+ expect(response.status).toBe(400);
+ });
+ });
+
+ describe('PUT /api/apps/:id', () => {
+ it('should update an app', async () => {
+ const updates = { name: 'Updated Name' };
+ appsService.updateApp.mockResolvedValue({ id: 'app-001', name: 'Updated Name' });
+
+ const response = await request(app)
+ .put('/api/apps/app-001')
+ .send(updates);
+
+ expect(response.status).toBe(200);
+ expect(appsService.updateApp).toHaveBeenCalledWith('app-001', expect.objectContaining({ name: 'Updated Name' }));
+ });
+
+ it('should return 404 if app not found', async () => {
+ appsService.updateApp.mockResolvedValue(null);
+
+ const response = await request(app)
+ .put('/api/apps/app-999')
+ .send({ name: 'Test' });
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe('DELETE /api/apps/:id', () => {
+ it('should delete an app', async () => {
+ appsService.deleteApp.mockResolvedValue(true);
+
+ const response = await request(app).delete('/api/apps/app-001');
+
+ expect(response.status).toBe(204);
+ expect(appsService.deleteApp).toHaveBeenCalledWith('app-001');
+ });
+
+ it('should return 404 if app not found', async () => {
+ appsService.deleteApp.mockResolvedValue(false);
+
+ const response = await request(app).delete('/api/apps/app-999');
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe('POST /api/apps/:id/start', () => {
+ it('should start an app', async () => {
+ const mockApp = {
+ id: 'app-001',
+ name: 'Test App',
+ repoPath: '/path/to/repo',
+ pm2ProcessNames: ['test-app'],
+ startCommands: ['npm run dev']
+ };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ pm2Service.startWithCommand.mockResolvedValue({ success: true });
+ history.logAction.mockResolvedValue();
+
+ const response = await request(app).post('/api/apps/app-001/start');
+
+ expect(response.status).toBe(200);
+ expect(response.body.success).toBe(true);
+ expect(pm2Service.startWithCommand).toHaveBeenCalled();
+ expect(history.logAction).toHaveBeenCalledWith('start', 'app-001', 'Test App', expect.any(Object), true);
+ });
+
+ it('should return 404 if app not found', async () => {
+ appsService.getAppById.mockResolvedValue(null);
+
+ const response = await request(app).post('/api/apps/app-999/start');
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe('POST /api/apps/:id/stop', () => {
+ it('should stop an app', async () => {
+ const mockApp = {
+ id: 'app-001',
+ name: 'Test App',
+ pm2ProcessNames: ['test-app']
+ };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ pm2Service.stopApp.mockResolvedValue({ success: true });
+ history.logAction.mockResolvedValue();
+
+ const response = await request(app).post('/api/apps/app-001/stop');
+
+ expect(response.status).toBe(200);
+ expect(response.body.success).toBe(true);
+ expect(pm2Service.stopApp).toHaveBeenCalledWith('test-app');
+ });
+
+ it('should return 404 if app not found', async () => {
+ appsService.getAppById.mockResolvedValue(null);
+
+ const response = await request(app).post('/api/apps/app-999/stop');
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe('POST /api/apps/:id/restart', () => {
+ it('should restart an app', async () => {
+ const mockApp = {
+ id: 'app-001',
+ name: 'Test App',
+ pm2ProcessNames: ['test-app']
+ };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ pm2Service.restartApp.mockResolvedValue({ success: true });
+ history.logAction.mockResolvedValue();
+
+ const response = await request(app).post('/api/apps/app-001/restart');
+
+ expect(response.status).toBe(200);
+ expect(response.body.success).toBe(true);
+ expect(pm2Service.restartApp).toHaveBeenCalledWith('test-app');
+ });
+
+ it('should return 404 if app not found', async () => {
+ appsService.getAppById.mockResolvedValue(null);
+
+ const response = await request(app).post('/api/apps/app-999/restart');
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe('GET /api/apps/:id/status', () => {
+ it('should return PM2 status for app processes', async () => {
+ const mockApp = {
+ id: 'app-001',
+ name: 'Test App',
+ pm2ProcessNames: ['test-api', 'test-worker']
+ };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ pm2Service.getAppStatus
+ .mockResolvedValueOnce({ status: 'online', cpu: 2.5 })
+ .mockResolvedValueOnce({ status: 'stopped' });
+
+ const response = await request(app).get('/api/apps/app-001/status');
+
+ expect(response.status).toBe(200);
+ expect(response.body['test-api']).toEqual({ status: 'online', cpu: 2.5 });
+ expect(response.body['test-worker']).toEqual({ status: 'stopped' });
+ });
+
+ it('should return 404 if app not found', async () => {
+ appsService.getAppById.mockResolvedValue(null);
+
+ const response = await request(app).get('/api/apps/app-999/status');
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe('GET /api/apps/:id/logs', () => {
+ it('should return logs for app process', async () => {
+ const mockApp = {
+ id: 'app-001',
+ name: 'Test App',
+ pm2ProcessNames: ['test-app']
+ };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ pm2Service.getLogs.mockResolvedValue('Log line 1\nLog line 2');
+
+ const response = await request(app).get('/api/apps/app-001/logs?lines=50');
+
+ expect(response.status).toBe(200);
+ expect(response.body.processName).toBe('test-app');
+ expect(response.body.lines).toBe(50);
+ expect(response.body.logs).toBe('Log line 1\nLog line 2');
+ });
+
+ it('should return 404 if app not found', async () => {
+ appsService.getAppById.mockResolvedValue(null);
+
+ const response = await request(app).get('/api/apps/app-999/logs');
+
+ expect(response.status).toBe(404);
+ });
+
+ it('should return 400 if no process name available', async () => {
+ const mockApp = {
+ id: 'app-001',
+ name: 'Test App',
+ pm2ProcessNames: []
+ };
+ appsService.getAppById.mockResolvedValue(mockApp);
+
+ const response = await request(app).get('/api/apps/app-001/logs');
+
+ expect(response.status).toBe(400);
+ });
+ });
+});
diff --git a/server/routes/cos.js b/server/routes/cos.js
index 3e09a30887..9a58b8e525 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -291,6 +291,12 @@ router.post('/app-activity/:appId/clear-cooldown', asyncHandler(async (req, res)
res.json({ success: true, appId: req.params.appId, activity: result });
}));
+// GET /api/cos/activity/today - Get today's activity summary
+router.get('/activity/today', asyncHandler(async (req, res) => {
+ const activity = await cos.getTodayActivity();
+ res.json(activity);
+}));
+
// GET /api/cos/learning - Get learning insights
router.get('/learning', asyncHandler(async (req, res) => {
const insights = await taskLearning.getLearningInsights();
diff --git a/server/routes/history.test.js b/server/routes/history.test.js
new file mode 100644
index 0000000000..a265076250
--- /dev/null
+++ b/server/routes/history.test.js
@@ -0,0 +1,202 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import request from 'supertest';
+import historyRoutes from './history.js';
+
+// Mock the history service
+vi.mock('../services/history.js', () => ({
+ getHistory: vi.fn(),
+ getHistoryStats: vi.fn(),
+ getActionTypes: vi.fn(),
+ deleteEntry: vi.fn(),
+ clearHistory: vi.fn()
+}));
+
+// Import mocked modules
+import * as history from '../services/history.js';
+
+describe('History Routes', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/history', historyRoutes);
+
+ // Reset all mocks
+ vi.clearAllMocks();
+ });
+
+ describe('GET /api/history', () => {
+ it('should return history entries', async () => {
+ const mockHistory = {
+ entries: [
+ { id: 'h1', action: 'start', target: 'app-001', success: true, timestamp: '2024-01-15T10:00:00Z' },
+ { id: 'h2', action: 'stop', target: 'app-001', success: true, timestamp: '2024-01-15T11:00:00Z' }
+ ],
+ total: 2,
+ limit: 100,
+ offset: 0
+ };
+ history.getHistory.mockResolvedValue(mockHistory);
+
+ const response = await request(app).get('/api/history');
+
+ expect(response.status).toBe(200);
+ expect(response.body.entries).toHaveLength(2);
+ expect(response.body.total).toBe(2);
+ });
+
+ it('should respect limit parameter', async () => {
+ history.getHistory.mockResolvedValue({ entries: [], total: 0, limit: 50, offset: 0 });
+
+ await request(app).get('/api/history?limit=50');
+
+ expect(history.getHistory).toHaveBeenCalledWith(expect.objectContaining({ limit: 50 }));
+ });
+
+ it('should respect offset parameter', async () => {
+ history.getHistory.mockResolvedValue({ entries: [], total: 0, limit: 100, offset: 10 });
+
+ await request(app).get('/api/history?offset=10');
+
+ expect(history.getHistory).toHaveBeenCalledWith(expect.objectContaining({ offset: 10 }));
+ });
+
+ it('should filter by action', async () => {
+ history.getHistory.mockResolvedValue({ entries: [], total: 0, limit: 100, offset: 0 });
+
+ await request(app).get('/api/history?action=start');
+
+ expect(history.getHistory).toHaveBeenCalledWith(expect.objectContaining({ action: 'start' }));
+ });
+
+ it('should filter by target', async () => {
+ history.getHistory.mockResolvedValue({ entries: [], total: 0, limit: 100, offset: 0 });
+
+ await request(app).get('/api/history?target=app-001');
+
+ expect(history.getHistory).toHaveBeenCalledWith(expect.objectContaining({ target: 'app-001' }));
+ });
+
+ it('should filter by success status', async () => {
+ history.getHistory.mockResolvedValue({ entries: [], total: 0, limit: 100, offset: 0 });
+
+ await request(app).get('/api/history?success=true');
+
+ expect(history.getHistory).toHaveBeenCalledWith(expect.objectContaining({ success: true }));
+ });
+
+ it('should use default limit and offset', async () => {
+ history.getHistory.mockResolvedValue({ entries: [], total: 0 });
+
+ await request(app).get('/api/history');
+
+ expect(history.getHistory).toHaveBeenCalledWith(expect.objectContaining({
+ limit: 100,
+ offset: 0
+ }));
+ });
+ });
+
+ describe('GET /api/history/stats', () => {
+ it('should return history statistics', async () => {
+ const mockStats = {
+ totalEntries: 150,
+ successRate: 0.95,
+ byAction: {
+ start: 50,
+ stop: 40,
+ restart: 60
+ },
+ byApp: {
+ 'app-001': 80,
+ 'app-002': 70
+ }
+ };
+ history.getHistoryStats.mockResolvedValue(mockStats);
+
+ const response = await request(app).get('/api/history/stats');
+
+ expect(response.status).toBe(200);
+ expect(response.body.totalEntries).toBe(150);
+ expect(response.body.successRate).toBe(0.95);
+ expect(response.body.byAction).toBeDefined();
+ });
+ });
+
+ describe('GET /api/history/actions', () => {
+ it('should return unique action types', async () => {
+ const mockActions = ['start', 'stop', 'restart', 'deploy', 'rollback'];
+ history.getActionTypes.mockResolvedValue(mockActions);
+
+ const response = await request(app).get('/api/history/actions');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual(mockActions);
+ expect(response.body).toContain('start');
+ expect(response.body).toContain('stop');
+ });
+
+ it('should return empty array when no actions', async () => {
+ history.getActionTypes.mockResolvedValue([]);
+
+ const response = await request(app).get('/api/history/actions');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual([]);
+ });
+ });
+
+ describe('DELETE /api/history/:id', () => {
+ it('should delete a history entry', async () => {
+ history.deleteEntry.mockResolvedValue({ success: true, deleted: 'h1' });
+
+ const response = await request(app).delete('/api/history/h1');
+
+ expect(response.status).toBe(200);
+ expect(response.body.success).toBe(true);
+ expect(history.deleteEntry).toHaveBeenCalledWith('h1');
+ });
+
+ it('should handle deletion of non-existent entry', async () => {
+ history.deleteEntry.mockResolvedValue({ success: false, error: 'Entry not found' });
+
+ const response = await request(app).delete('/api/history/h-nonexistent');
+
+ expect(response.status).toBe(200);
+ expect(history.deleteEntry).toHaveBeenCalledWith('h-nonexistent');
+ });
+ });
+
+ describe('DELETE /api/history', () => {
+ it('should clear all history', async () => {
+ history.clearHistory.mockResolvedValue({ success: true, deletedCount: 150 });
+
+ const response = await request(app).delete('/api/history');
+
+ expect(response.status).toBe(200);
+ expect(response.body.success).toBe(true);
+ expect(response.body.deletedCount).toBe(150);
+ expect(history.clearHistory).toHaveBeenCalledWith(null);
+ });
+
+ it('should clear history older than specified days', async () => {
+ history.clearHistory.mockResolvedValue({ success: true, deletedCount: 50 });
+
+ const response = await request(app).delete('/api/history?olderThanDays=7');
+
+ expect(response.status).toBe(200);
+ expect(history.clearHistory).toHaveBeenCalledWith(7);
+ });
+
+ it('should handle empty history', async () => {
+ history.clearHistory.mockResolvedValue({ success: true, deletedCount: 0 });
+
+ const response = await request(app).delete('/api/history');
+
+ expect(response.status).toBe(200);
+ expect(response.body.deletedCount).toBe(0);
+ });
+ });
+});
diff --git a/server/routes/scripts.js b/server/routes/scripts.js
index 11575e07d0..31af03d072 100644
--- a/server/routes/scripts.js
+++ b/server/routes/scripts.js
@@ -1,5 +1,4 @@
/**
-import { asyncHandler, ServerError } from '../lib/errorHandler.js';
* Scripts API Routes
*
* Endpoints for managing scheduled scripts
@@ -21,6 +20,11 @@ router.get('/presets', (req, res) => {
res.json({ presets: scriptRunner.getSchedulePresets() });
});
+// GET /api/cos/scripts/allowed-commands - Get allowed commands for scripts
+router.get('/allowed-commands', (req, res) => {
+ res.json({ commands: scriptRunner.getAllowedScriptCommands() });
+});
+
// GET /api/cos/scripts/jobs - Get scheduled job info
router.get('/jobs', (req, res) => {
res.json({ jobs: scriptRunner.getScheduledJobs() });
diff --git a/server/services/agents.test.js b/server/services/agents.test.js
new file mode 100644
index 0000000000..e18cebe1a0
--- /dev/null
+++ b/server/services/agents.test.js
@@ -0,0 +1,367 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+/**
+ * Tests for the agents service logic
+ *
+ * Note: We test the pure functions and logic patterns from agents.js
+ * without spawning actual processes.
+ */
+
+// Simulate the agent service logic
+describe('Agent Service Logic', () => {
+ describe('Agent Pattern Matching', () => {
+ const AGENT_PATTERNS = [
+ { name: 'Claude', pattern: 'claude', command: 'claude' },
+ { name: 'Codex', pattern: 'codex', command: 'codex' },
+ { name: 'Gemini', pattern: 'gemini', command: 'gemini' },
+ { name: 'Aider', pattern: 'aider', command: 'aider' },
+ { name: 'Cursor', pattern: 'cursor', command: 'cursor' },
+ { name: 'Copilot', pattern: 'copilot', command: 'copilot' }
+ ];
+
+ function matchAgentPattern(command) {
+ const lowerCommand = command.toLowerCase();
+ for (const agent of AGENT_PATTERNS) {
+ if (lowerCommand.includes(agent.pattern)) {
+ return agent;
+ }
+ }
+ return null;
+ }
+
+ it('should match Claude agent process', () => {
+ const result = matchAgentPattern('/usr/local/bin/claude --model opus');
+ expect(result.name).toBe('Claude');
+ });
+
+ it('should match Codex agent process', () => {
+ const result = matchAgentPattern('npx codex run task');
+ expect(result.name).toBe('Codex');
+ });
+
+ it('should match Gemini agent process', () => {
+ const result = matchAgentPattern('gemini-cli chat');
+ expect(result.name).toBe('Gemini');
+ });
+
+ it('should match Aider agent process', () => {
+ const result = matchAgentPattern('python -m aider');
+ expect(result.name).toBe('Aider');
+ });
+
+ it('should return null for non-agent processes', () => {
+ const result = matchAgentPattern('node server.js');
+ expect(result).toBeNull();
+ });
+
+ it('should be case-insensitive', () => {
+ const result = matchAgentPattern('CLAUDE --model sonnet');
+ expect(result.name).toBe('Claude');
+ });
+ });
+
+ describe('Elapsed Time Parsing', () => {
+ // Unix ps etime format: [[DD-]HH:]MM:SS
+ function parseElapsedTime(etime) {
+ const parts = etime.split(':').map(p => parseInt(p.replace(/-/g, '')));
+
+ if (etime.includes('-')) {
+ // Days-HH:MM:SS format
+ const [days, rest] = etime.split('-');
+ const timeParts = rest.split(':').map(p => parseInt(p));
+ const d = parseInt(days);
+ const [h, m, s] = timeParts.length === 3 ? timeParts : [0, ...timeParts];
+ return ((d * 24 + h) * 60 + m) * 60 * 1000 + s * 1000;
+ }
+
+ if (parts.length === 3) {
+ // HH:MM:SS
+ return (parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000;
+ } else if (parts.length === 2) {
+ // MM:SS
+ return (parts[0] * 60 + parts[1]) * 1000;
+ }
+
+ return parts[0] * 1000;
+ }
+
+ it('should parse MM:SS format', () => {
+ expect(parseElapsedTime('05:30')).toBe((5 * 60 + 30) * 1000);
+ });
+
+ it('should parse HH:MM:SS format', () => {
+ expect(parseElapsedTime('02:15:45')).toBe((2 * 3600 + 15 * 60 + 45) * 1000);
+ });
+
+ it('should parse days-HH:MM:SS format', () => {
+ expect(parseElapsedTime('1-02:30:00')).toBe((26 * 3600 + 30 * 60) * 1000);
+ });
+
+ it('should parse single digit seconds', () => {
+ expect(parseElapsedTime('00:05')).toBe(5 * 1000);
+ });
+
+ it('should handle zero time', () => {
+ expect(parseElapsedTime('00:00')).toBe(0);
+ });
+ });
+
+ describe('Runtime Formatting', () => {
+ function formatRuntime(ms) {
+ const seconds = Math.floor(ms / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+ const days = Math.floor(hours / 24);
+
+ if (days > 0) return `${days}d ${hours % 24}h`;
+ if (hours > 0) return `${hours}h ${minutes % 60}m`;
+ if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
+ return `${seconds}s`;
+ }
+
+ it('should format seconds', () => {
+ expect(formatRuntime(45 * 1000)).toBe('45s');
+ });
+
+ it('should format minutes and seconds', () => {
+ expect(formatRuntime((5 * 60 + 30) * 1000)).toBe('5m 30s');
+ });
+
+ it('should format hours and minutes', () => {
+ expect(formatRuntime((2 * 3600 + 15 * 60) * 1000)).toBe('2h 15m');
+ });
+
+ it('should format days and hours', () => {
+ expect(formatRuntime((26 * 3600) * 1000)).toBe('1d 2h');
+ });
+
+ it('should handle zero', () => {
+ expect(formatRuntime(0)).toBe('0s');
+ });
+ });
+
+ describe('Spawned Agent Registry', () => {
+ let registry;
+
+ beforeEach(() => {
+ registry = new Map();
+ });
+
+ function registerAgent(pid, data) {
+ registry.set(pid, {
+ ...data,
+ registeredAt: Date.now()
+ });
+ }
+
+ function unregisterAgent(pid) {
+ registry.delete(pid);
+ }
+
+ function getAgentData(pid) {
+ return registry.get(pid);
+ }
+
+ it('should register agent with data', () => {
+ registerAgent(12345, {
+ agentId: 'agent-001',
+ taskId: 'task-001',
+ model: 'opus'
+ });
+
+ const data = getAgentData(12345);
+ expect(data.agentId).toBe('agent-001');
+ expect(data.taskId).toBe('task-001');
+ expect(data.model).toBe('opus');
+ expect(data.registeredAt).toBeDefined();
+ });
+
+ it('should unregister agent', () => {
+ registerAgent(12345, { agentId: 'agent-001' });
+ unregisterAgent(12345);
+
+ expect(getAgentData(12345)).toBeUndefined();
+ });
+
+ it('should allow multiple agents', () => {
+ registerAgent(111, { agentId: 'agent-001' });
+ registerAgent(222, { agentId: 'agent-002' });
+ registerAgent(333, { agentId: 'agent-003' });
+
+ expect(registry.size).toBe(3);
+ });
+
+ it('should overwrite existing agent with same PID', () => {
+ registerAgent(12345, { agentId: 'old-agent' });
+ registerAgent(12345, { agentId: 'new-agent' });
+
+ const data = getAgentData(12345);
+ expect(data.agentId).toBe('new-agent');
+ });
+ });
+
+ describe('Process Info Parsing (Unix)', () => {
+ function parseProcessLine(line) {
+ const parts = line.trim().split(/\s+/);
+ if (parts.length < 6) return null;
+
+ const pid = parseInt(parts[0]);
+ const ppid = parseInt(parts[1]);
+ const cpu = parseFloat(parts[2]);
+ const mem = parseFloat(parts[3]);
+ const etime = parts[4];
+ const command = parts.slice(5).join(' ');
+
+ return {
+ pid,
+ ppid,
+ cpu,
+ memory: mem,
+ etime,
+ command
+ };
+ }
+
+ it('should parse standard ps output line', () => {
+ const line = '12345 1001 2.5 0.3 05:30 /usr/bin/claude --model opus';
+ const result = parseProcessLine(line);
+
+ expect(result.pid).toBe(12345);
+ expect(result.ppid).toBe(1001);
+ expect(result.cpu).toBe(2.5);
+ expect(result.memory).toBe(0.3);
+ expect(result.etime).toBe('05:30');
+ expect(result.command).toBe('/usr/bin/claude --model opus');
+ });
+
+ it('should handle commands with spaces', () => {
+ const line = '12345 1001 0.0 0.1 00:30 node /path/to/script.js --flag value';
+ const result = parseProcessLine(line);
+
+ expect(result.command).toBe('node /path/to/script.js --flag value');
+ });
+
+ it('should return null for short lines', () => {
+ const line = '12345 1001';
+ const result = parseProcessLine(line);
+
+ expect(result).toBeNull();
+ });
+ });
+
+ describe('Process Filtering', () => {
+ const mockProcesses = [
+ { pid: 1, command: '/usr/bin/claude --model opus' },
+ { pid: 2, command: 'grep claude' },
+ { pid: 3, command: 'ps -eo pid,command' },
+ { pid: 4, command: 'node claude-helper.js' },
+ { pid: 5, command: '/bin/aider --edit' }
+ ];
+
+ function filterAgentProcesses(processes) {
+ return processes.filter(proc => {
+ // Skip grep and ps processes
+ if (proc.command.includes('grep') || proc.command.includes('ps -eo')) {
+ return false;
+ }
+ return true;
+ });
+ }
+
+ it('should filter out grep processes', () => {
+ const filtered = filterAgentProcesses(mockProcesses);
+
+ expect(filtered.find(p => p.command.includes('grep'))).toBeUndefined();
+ });
+
+ it('should filter out ps processes', () => {
+ const filtered = filterAgentProcesses(mockProcesses);
+
+ expect(filtered.find(p => p.command.includes('ps -eo'))).toBeUndefined();
+ });
+
+ it('should keep actual agent processes', () => {
+ const filtered = filterAgentProcesses(mockProcesses);
+
+ expect(filtered.find(p => p.pid === 1)).toBeDefined();
+ expect(filtered.find(p => p.pid === 5)).toBeDefined();
+ });
+ });
+
+ describe('Agent Sorting', () => {
+ const mockAgents = [
+ { pid: 1, startTime: 1000 },
+ { pid: 2, startTime: 3000 },
+ { pid: 3, startTime: 2000 }
+ ];
+
+ function sortByStartTime(agents) {
+ return [...agents].sort((a, b) => b.startTime - a.startTime);
+ }
+
+ it('should sort agents by start time (newest first)', () => {
+ const sorted = sortByStartTime(mockAgents);
+
+ expect(sorted[0].pid).toBe(2);
+ expect(sorted[1].pid).toBe(3);
+ expect(sorted[2].pid).toBe(1);
+ });
+
+ it('should not mutate original array', () => {
+ const original = [...mockAgents];
+ sortByStartTime(mockAgents);
+
+ expect(mockAgents[0].pid).toBe(original[0].pid);
+ });
+ });
+
+ describe('Process Info Enrichment', () => {
+ function enrichProcess(proc, spawnedData) {
+ if (!spawnedData) return proc;
+
+ return {
+ ...proc,
+ command: spawnedData.fullCommand || proc.command,
+ agentId: spawnedData.agentId,
+ taskId: spawnedData.taskId,
+ model: spawnedData.model,
+ workspacePath: spawnedData.workspacePath,
+ source: 'cos'
+ };
+ }
+
+ it('should add spawned data to process', () => {
+ const proc = { pid: 12345, command: 'claude' };
+ const spawnedData = {
+ fullCommand: 'claude --model opus --print',
+ agentId: 'agent-001',
+ taskId: 'task-001',
+ model: 'opus'
+ };
+
+ const enriched = enrichProcess(proc, spawnedData);
+
+ expect(enriched.agentId).toBe('agent-001');
+ expect(enriched.taskId).toBe('task-001');
+ expect(enriched.model).toBe('opus');
+ expect(enriched.source).toBe('cos');
+ });
+
+ it('should override command with full command', () => {
+ const proc = { pid: 12345, command: 'claude' };
+ const spawnedData = { fullCommand: 'claude --model opus --print' };
+
+ const enriched = enrichProcess(proc, spawnedData);
+
+ expect(enriched.command).toBe('claude --model opus --print');
+ });
+
+ it('should return original process if no spawned data', () => {
+ const proc = { pid: 12345, command: 'claude' };
+
+ const enriched = enrichProcess(proc, null);
+
+ expect(enriched).toEqual(proc);
+ });
+ });
+});
diff --git a/server/services/cos.js b/server/services/cos.js
index b3837ee7a0..3239e476fe 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1476,6 +1476,89 @@ export async function listReports() {
.reverse();
}
+/**
+ * Get today's activity summary
+ * Returns completed tasks, success rate, time worked, and top accomplishments
+ */
+export async function getTodayActivity() {
+ const state = await loadState();
+ const today = new Date().toISOString().split('T')[0];
+
+ // Filter agents completed today
+ const todayAgents = Object.values(state.agents).filter(a => {
+ if (!a.completedAt) return false;
+ return a.completedAt.startsWith(today);
+ });
+
+ const succeeded = todayAgents.filter(a => a.result?.success);
+ const failed = todayAgents.filter(a => !a.result?.success);
+
+ // Calculate total time worked (sum of agent durations)
+ const totalDurationMs = todayAgents.reduce((sum, a) => {
+ const duration = a.result?.duration || 0;
+ return sum + duration;
+ }, 0);
+
+ // Get currently running agents
+ const runningAgents = Object.values(state.agents).filter(a => a.status === 'running');
+ const activeTimeMs = runningAgents.reduce((sum, a) => {
+ if (!a.startedAt) return sum;
+ return sum + (Date.now() - new Date(a.startedAt).getTime());
+ }, 0);
+
+ // Format duration as human-readable
+ const formatDuration = (ms) => {
+ const mins = Math.floor(ms / 60000);
+ const hours = Math.floor(mins / 60);
+ const remainingMins = mins % 60;
+ if (hours > 0) {
+ return `${hours}h ${remainingMins}m`;
+ }
+ return `${mins}m`;
+ };
+
+ // Get top accomplishments (successful tasks with description snippets)
+ const accomplishments = succeeded
+ .map(a => ({
+ id: a.id,
+ taskId: a.taskId,
+ description: a.metadata?.taskDescription?.substring(0, 100) || a.taskId,
+ taskType: a.metadata?.analysisType || a.metadata?.taskType || 'task',
+ duration: a.result?.duration || 0,
+ completedAt: a.completedAt
+ }))
+ .sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt))
+ .slice(0, 5);
+
+ // Calculate success rate
+ const successRate = todayAgents.length > 0
+ ? Math.round((succeeded.length / todayAgents.length) * 100)
+ : 0;
+
+ return {
+ date: today,
+ stats: {
+ completed: todayAgents.length,
+ succeeded: succeeded.length,
+ failed: failed.length,
+ successRate,
+ running: runningAgents.length
+ },
+ time: {
+ totalDurationMs,
+ totalDuration: formatDuration(totalDurationMs),
+ activeDurationMs: activeTimeMs,
+ activeDuration: formatDuration(activeTimeMs),
+ combinedMs: totalDurationMs + activeTimeMs,
+ combined: formatDuration(totalDurationMs + activeTimeMs)
+ },
+ accomplishments,
+ lastEvaluation: state.stats.lastEvaluation,
+ isRunning: daemonRunning,
+ isPaused: state.paused
+ };
+}
+
/**
* Clear completed agents from state (keep in files)
*/
diff --git a/server/services/scriptRunner.js b/server/services/scriptRunner.js
index b94d4ca744..2144ac2b51 100644
--- a/server/services/scriptRunner.js
+++ b/server/services/scriptRunner.js
@@ -22,6 +22,48 @@ const SCRIPTS_STATE_FILE = join(__dirname, '../../data/cos/scripts-state.json');
// Active scheduled jobs
const scheduledJobs = new Map();
+// Allowlist of safe commands for scripts (mirrors commands.js allowlist)
+const ALLOWED_SCRIPT_COMMANDS = new Set([
+ 'npm', 'npx', 'pnpm', 'yarn', 'bun',
+ 'node', 'deno',
+ 'git', 'gh',
+ 'pm2',
+ 'ls', 'cat', 'head', 'tail', 'grep', 'find', 'wc',
+ 'pwd', 'which', 'echo', 'env',
+ 'curl', 'wget',
+ 'docker', 'docker-compose',
+ 'make', 'cargo', 'go', 'python', 'python3', 'pip', 'pip3',
+ 'brew'
+]);
+
+/**
+ * Validate a script command against the allowlist
+ * Returns { valid: boolean, error?: string, baseCommand?: string }
+ */
+function validateScriptCommand(command) {
+ if (!command || typeof command !== 'string') {
+ return { valid: false, error: 'Command is required' };
+ }
+
+ const trimmed = command.trim();
+ if (!trimmed) {
+ return { valid: false, error: 'Command cannot be empty' };
+ }
+
+ // Extract the base command (first word before space or pipe)
+ const parts = trimmed.split(/\s+/);
+ const baseCommand = parts[0];
+
+ if (!ALLOWED_SCRIPT_COMMANDS.has(baseCommand)) {
+ return {
+ valid: false,
+ error: `Command '${baseCommand}' is not in the allowlist. Allowed: ${Array.from(ALLOWED_SCRIPT_COMMANDS).sort().join(', ')}`
+ };
+ }
+
+ return { valid: true, baseCommand };
+}
+
// Schedule presets to cron expressions
const SCHEDULE_PRESETS = {
'every-5-min': '*/5 * * * *',
@@ -119,6 +161,12 @@ export function unscheduleScript(scriptId) {
* Create a new script
*/
export async function createScript(data) {
+ // Security: Validate command against allowlist before creating
+ const validation = validateScriptCommand(data.command);
+ if (!validation.valid) {
+ throw new Error(`Invalid script command: ${validation.error}`);
+ }
+
const id = `script-${uuidv4().slice(0, 8)}`;
const script = {
@@ -157,6 +205,14 @@ export async function createScript(data) {
* Update a script
*/
export async function updateScript(id, data) {
+ // Security: Validate command against allowlist if being updated
+ if (data.command !== undefined) {
+ const validation = validateScriptCommand(data.command);
+ if (!validation.valid) {
+ throw new Error(`Invalid script command: ${validation.error}`);
+ }
+ }
+
const state = await loadScriptsState();
const script = state.scripts[id];
@@ -240,6 +296,14 @@ export async function executeScript(scriptId) {
return { success: false, error: 'Script not found' };
}
+ // Security: Defense in depth - validate command at execution time
+ // (in case state file was manually modified)
+ const validation = validateScriptCommand(script.command);
+ if (!validation.valid) {
+ console.error(`❌ Script ${script.name} has invalid command: ${validation.error}`);
+ return { success: false, error: `Invalid command: ${validation.error}` };
+ }
+
console.log(`▶️ Executing script: ${script.name} (${scriptId})`);
cosEvents.emit('script:started', { scriptId, name: script.name });
@@ -375,3 +439,10 @@ export function getScheduledJobs() {
}
return jobs;
}
+
+/**
+ * Get list of allowed commands for scripts
+ */
+export function getAllowedScriptCommands() {
+ return Array.from(ALLOWED_SCRIPT_COMMANDS).sort();
+}
diff --git a/server/services/taskClassifier.test.js b/server/services/taskClassifier.test.js
new file mode 100644
index 0000000000..5294c5e33a
--- /dev/null
+++ b/server/services/taskClassifier.test.js
@@ -0,0 +1,557 @@
+import { describe, it, expect } from 'vitest';
+import {
+ classifyTask,
+ classifyReviewFindings,
+ getClassificationRules,
+ isIdleReviewTask,
+ estimateTaskComplexity
+} from './taskClassifier.js';
+
+describe('Task Classifier Service', () => {
+ describe('classifyTask', () => {
+ const defaultConfig = {
+ autoFixThresholds: {
+ maxLinesChanged: 50,
+ allowedCategories: ['formatting', 'dry-violations', 'dead-code', 'typo-fix', 'import-cleanup', 'documentation']
+ }
+ };
+
+ describe('auto-approve patterns', () => {
+ it('should auto-approve formatting tasks within line limit', () => {
+ const task = { description: 'Format code with prettier' };
+ const analysis = { linesChanged: 30 };
+
+ const result = classifyTask(task, analysis, defaultConfig);
+
+ expect(result.autoApprove).toBe(true);
+ expect(result.category).toBe('formatting');
+ expect(result.confidence).toBe('high');
+ });
+
+ it('should auto-approve lint fixes', () => {
+ const task = { description: 'Fix ESLint errors' };
+ const analysis = { linesChanged: 20 };
+
+ const result = classifyTask(task, analysis, defaultConfig);
+
+ expect(result.autoApprove).toBe(true);
+ expect(result.category).toBe('formatting');
+ });
+
+ it('should auto-approve DRY violation fixes', () => {
+ const task = { description: 'Remove duplicate code in helpers' };
+ const analysis = { linesChanged: 25 };
+
+ const result = classifyTask(task, analysis, defaultConfig);
+
+ expect(result.autoApprove).toBe(true);
+ expect(result.category).toBe('dry-violations');
+ });
+
+ it('should auto-approve dead code removal', () => {
+ const task = { description: 'Remove unused functions' };
+ const analysis = { linesChanged: 15 };
+
+ const result = classifyTask(task, analysis, defaultConfig);
+
+ expect(result.autoApprove).toBe(true);
+ expect(result.category).toBe('dead-code');
+ });
+
+ it('should auto-approve typo fixes', () => {
+ const task = { description: 'Fix typo in error message' };
+ const analysis = { linesChanged: 5 };
+
+ const result = classifyTask(task, analysis, defaultConfig);
+
+ expect(result.autoApprove).toBe(true);
+ expect(result.category).toBe('typo-fix');
+ });
+
+ it('should auto-approve import cleanup', () => {
+ // "import" keyword triggers import-cleanup pattern
+ const task = { description: 'Fix broken import statements' };
+ const analysis = { linesChanged: 20 };
+
+ const result = classifyTask(task, analysis, defaultConfig);
+
+ expect(result.autoApprove).toBe(true);
+ expect(result.category).toBe('import-cleanup');
+ });
+
+ it('should auto-approve documentation updates', () => {
+ // "doc" keyword triggers documentation pattern (not "comment" which triggers typo-fix)
+ const task = { description: 'Update the documentation' };
+ const analysis = { linesChanged: 50 };
+
+ const result = classifyTask(task, analysis, defaultConfig);
+
+ expect(result.autoApprove).toBe(true);
+ expect(result.category).toBe('documentation');
+ });
+ });
+
+ describe('line limit enforcement', () => {
+ it('should reject auto-approve when exceeding category line limit', () => {
+ const task = { description: 'Fix typo in comments' };
+ const analysis = { linesChanged: 25 }; // typo-fix limit is 20
+
+ const result = classifyTask(task, analysis, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('typo-fix');
+ expect(result.reason).toContain('exceed auto-approve limit');
+ });
+
+ it('should reject auto-approve when exceeding global max lines', () => {
+ const configWithLowLimit = {
+ autoFixThresholds: {
+ maxLinesChanged: 10,
+ allowedCategories: ['formatting']
+ }
+ };
+ const task = { description: 'Format all files' };
+ const analysis = { linesChanged: 15 };
+
+ const result = classifyTask(task, analysis, configWithLowLimit);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.reason).toContain('exceed');
+ });
+
+ it('should use category line limit if lower than global', () => {
+ const task = { description: 'Remove dead code' };
+ const analysis = { linesChanged: 40 }; // dead-code limit is 30
+
+ const result = classifyTask(task, analysis, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ });
+ });
+
+ describe('category allowlist enforcement', () => {
+ it('should reject categories not in allowlist', () => {
+ const restrictedConfig = {
+ autoFixThresholds: {
+ maxLinesChanged: 100,
+ allowedCategories: ['typo-fix'] // Only typo-fix allowed
+ }
+ };
+ const task = { description: 'Format code' };
+ const analysis = { linesChanged: 10 };
+
+ const result = classifyTask(task, analysis, restrictedConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.reason).toContain('not in auto-approve list');
+ });
+ });
+
+ describe('require-approval patterns (high priority)', () => {
+ it('should require approval for security-related tasks', () => {
+ const task = { description: 'Update authentication logic' };
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('security');
+ expect(result.confidence).toBe('high');
+ });
+
+ it('should require approval for password handling', () => {
+ const task = { description: 'Change password validation' };
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('security');
+ });
+
+ it('should require approval for database changes', () => {
+ const task = { description: 'Update database schema' };
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('database');
+ });
+
+ it('should require approval for migrations', () => {
+ const task = { description: 'Create prisma migration' };
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('database');
+ });
+
+ it('should require approval for API changes', () => {
+ const task = { description: 'Make breaking change to API' };
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('api-change');
+ });
+
+ it('should require approval for dependency updates', () => {
+ const task = { description: 'Update package.json dependencies' };
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('dependency');
+ });
+
+ it('should require approval for architecture changes', () => {
+ const task = { description: 'Restructure the entire module' };
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('architecture');
+ });
+
+ it('should require approval for config changes', () => {
+ const task = { description: 'Modify ecosystem.config settings' };
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('config');
+ });
+
+ it('should require approval for deployment tasks', () => {
+ const task = { description: 'Deploy to production' };
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('deployment');
+ });
+ });
+
+ describe('priority of require-approval over auto-approve', () => {
+ it('should require approval even if description also matches auto-approve', () => {
+ // Task mentions both security (require) and typo (auto)
+ const task = { description: 'Fix typo in security token' };
+
+ const result = classifyTask(task, { linesChanged: 1 }, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('security');
+ });
+ });
+
+ describe('unknown category handling', () => {
+ it('should default to require approval for unknown patterns', () => {
+ const task = { description: 'Do something completely unrelated' };
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('unknown');
+ expect(result.confidence).toBe('low');
+ });
+ });
+
+ describe('empty/null handling', () => {
+ it('should handle task with no description', () => {
+ const task = {};
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ expect(result.autoApprove).toBe(false);
+ expect(result.category).toBe('unknown');
+ });
+
+ it('should handle null analysis result', () => {
+ const task = { description: 'Format code' };
+
+ const result = classifyTask(task, null, defaultConfig);
+
+ // Should still work without analysis (line count = 0)
+ expect(result.category).toBe('formatting');
+ });
+
+ it('should handle null config', () => {
+ const task = { description: 'Format code' };
+ const analysis = { linesChanged: 10 };
+
+ // Should use defaults
+ const result = classifyTask(task, analysis, null);
+
+ expect(result.category).toBe('formatting');
+ expect(result.autoApprove).toBe(false); // No allowed categories in null config
+ });
+ });
+ });
+
+ describe('classifyReviewFindings', () => {
+ const defaultConfig = {
+ autoFixThresholds: {
+ maxLinesChanged: 50,
+ allowedCategories: ['typo-fix', 'dead-code']
+ }
+ };
+
+ it('should classify array of findings', () => {
+ const findings = [
+ { title: 'Fix typo', estimatedLines: 5 },
+ { title: 'Security issue', estimatedLines: 10 }
+ ];
+
+ const results = classifyReviewFindings(findings, defaultConfig);
+
+ expect(results).toHaveLength(2);
+ expect(results[0].autoApprove).toBe(true);
+ expect(results[0].category).toBe('typo-fix');
+ expect(results[1].autoApprove).toBe(false);
+ expect(results[1].category).toBe('security');
+ });
+
+ it('should preserve original finding data', () => {
+ const findings = [
+ { title: 'Fix typo', estimatedLines: 5, file: 'test.js', line: 42 }
+ ];
+
+ const results = classifyReviewFindings(findings, defaultConfig);
+
+ expect(results[0].file).toBe('test.js');
+ expect(results[0].line).toBe(42);
+ });
+
+ it('should handle findings with description instead of title', () => {
+ const findings = [
+ { description: 'Remove dead code', estimatedLines: 10 }
+ ];
+
+ const results = classifyReviewFindings(findings, defaultConfig);
+
+ expect(results[0].category).toBe('dead-code');
+ });
+ });
+
+ describe('getClassificationRules', () => {
+ it('should return both auto-approve and require-approval rules', () => {
+ const rules = getClassificationRules();
+
+ expect(rules).toHaveProperty('autoApprove');
+ expect(rules).toHaveProperty('requireApproval');
+ expect(Array.isArray(rules.autoApprove)).toBe(true);
+ expect(Array.isArray(rules.requireApproval)).toBe(true);
+ });
+
+ it('should include all auto-approve categories', () => {
+ const rules = getClassificationRules();
+ const categories = rules.autoApprove.map(r => r.category);
+
+ expect(categories).toContain('formatting');
+ expect(categories).toContain('dry-violations');
+ expect(categories).toContain('dead-code');
+ expect(categories).toContain('typo-fix');
+ expect(categories).toContain('import-cleanup');
+ expect(categories).toContain('documentation');
+ });
+
+ it('should include all require-approval categories', () => {
+ const rules = getClassificationRules();
+ const categories = rules.requireApproval.map(r => r.category);
+
+ expect(categories).toContain('security');
+ expect(categories).toContain('database');
+ expect(categories).toContain('api-change');
+ expect(categories).toContain('dependency');
+ expect(categories).toContain('architecture');
+ expect(categories).toContain('config');
+ expect(categories).toContain('deployment');
+ });
+
+ it('should include max lines for auto-approve rules', () => {
+ const rules = getClassificationRules();
+
+ rules.autoApprove.forEach(rule => {
+ expect(rule.maxLines).toBeDefined();
+ expect(typeof rule.maxLines).toBe('number');
+ });
+ });
+
+ it('should include reason for require-approval rules', () => {
+ const rules = getClassificationRules();
+
+ rules.requireApproval.forEach(rule => {
+ expect(rule.reason).toBeDefined();
+ expect(typeof rule.reason).toBe('string');
+ });
+ });
+ });
+
+ describe('isIdleReviewTask', () => {
+ it('should identify tasks with [Idle Review] in description', () => {
+ const task = { description: '[Idle Review] Check codebase' };
+
+ expect(isIdleReviewTask(task)).toBe(true);
+ });
+
+ it('should identify tasks with autonomous code review in description', () => {
+ const task = { description: 'Autonomous code review of the project' };
+
+ expect(isIdleReviewTask(task)).toBe(true);
+ });
+
+ it('should identify tasks with reviewType: idle metadata', () => {
+ const task = {
+ description: 'Review something',
+ metadata: { reviewType: 'idle' }
+ };
+
+ expect(isIdleReviewTask(task)).toBe(true);
+ });
+
+ it('should identify tasks with autoGenerated: true metadata', () => {
+ const task = {
+ description: 'Some generated task',
+ metadata: { autoGenerated: true }
+ };
+
+ expect(isIdleReviewTask(task)).toBe(true);
+ });
+
+ it('should return false for regular user tasks', () => {
+ const task = {
+ description: 'Fix the login bug',
+ metadata: {}
+ };
+
+ expect(isIdleReviewTask(task)).toBe(false);
+ });
+
+ it('should handle task with no description', () => {
+ const task = { metadata: {} };
+
+ expect(isIdleReviewTask(task)).toBe(false);
+ });
+ });
+
+ describe('estimateTaskComplexity', () => {
+ describe('high complexity detection', () => {
+ it('should detect multi-file tasks', () => {
+ const task = { description: 'Update multiple files across codebase' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('high');
+ });
+
+ it('should detect codebase-wide tasks', () => {
+ const task = { description: 'Refactor pattern across codebase' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('high');
+ });
+
+ it('should detect restructuring tasks', () => {
+ const task = { description: 'Restructure the component hierarchy' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('high');
+ });
+
+ it('should detect migration tasks', () => {
+ const task = { description: 'Migration to new API version' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('high');
+ });
+
+ it('should detect integration tasks', () => {
+ const task = { description: 'Integration with external service' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('high');
+ });
+ });
+
+ describe('low complexity detection', () => {
+ it('should detect single-file tasks', () => {
+ const task = { description: 'Update single file' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('low');
+ });
+
+ it('should detect one-line changes', () => {
+ const task = { description: 'Change one line in config' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('low');
+ });
+
+ it('should detect simple tasks', () => {
+ const task = { description: 'Simple fix for button' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('low');
+ });
+
+ it('should detect typo tasks', () => {
+ const task = { description: 'Fix typo in message' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('low');
+ });
+
+ it('should detect comment tasks', () => {
+ const task = { description: 'Add comment to function' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('low');
+ });
+
+ it('should detect rename tasks', () => {
+ const task = { description: 'Rename variable foo to bar' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('low');
+ });
+ });
+
+ describe('medium complexity (default)', () => {
+ it('should return medium for standard tasks', () => {
+ const task = { description: 'Implement user authentication' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('medium');
+ });
+
+ it('should return medium for tasks without complexity indicators', () => {
+ const task = { description: 'Add new feature to dashboard' };
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('medium');
+ });
+ });
+
+ describe('empty/null handling', () => {
+ it('should handle task with no description', () => {
+ const task = {};
+
+ const result = estimateTaskComplexity(task);
+
+ expect(result.level).toBe('medium');
+ });
+ });
+ });
+});