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: add proactive CoS with goal-driven self-improvement
Adam Eivyc2575d873d71
diff --git a/README.md b/README.mdindex b16f5c697a..ab637071cb 100644--- a/README.md+++ b/README.md@@ -39,6 +39,8 @@ Autonomous task manager that monitors your TASKS.md and dispatches AI agents to++### App ImportAuto-detect project configuration from your codebase — ports, start commands, and PM2 process names.diff --git a/client/src/App.jsx b/client/src/App.jsxindex 1750f3a54e..2c31354503 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -1,36 +1,55 @@+import { Suspense, lazy } from 'react';import { Routes, Route, Navigate } from 'react-router-dom';import Layout from './components/Layout';import Dashboard from './pages/Dashboard';import Apps from './pages/Apps';import CreateApp from './pages/CreateApp';import Templates from './pages/Templates';-import AIProviders from './pages/AIProviders';-import { HistoryPage, RunsHistoryPage, RunnerPage, GitPage, UsagePage, ProcessesPage, AgentsPage } from './pages/DevTools';import PromptManager from './pages/PromptManager';import ChiefOfStaff from './pages/ChiefOfStaff';+// Lazy load heavier pages for code splitting+// DevTools pages are large (~2300 lines total) so lazy load them+const AIProviders = lazy(() => import('./pages/AIProviders'));+const HistoryPage = lazy(() => import('./pages/DevTools').then(m => ({ default: m.HistoryPage })));+const RunsHistoryPage = lazy(() => import('./pages/DevTools').then(m => ({ default: m.RunsHistoryPage })));+const RunnerPage = lazy(() => import('./pages/DevTools').then(m => ({ default: m.RunnerPage })));+const GitPage = lazy(() => import('./pages/DevTools').then(m => ({ default: m.GitPage })));+const UsagePage = lazy(() => import('./pages/DevTools').then(m => ({ default: m.UsagePage })));+const ProcessesPage = lazy(() => import('./pages/DevTools').then(m => ({ default: m.ProcessesPage })));+const AgentsPage = lazy(() => import('./pages/DevTools').then(m => ({ default: m.AgentsPage })));++// Loading fallback for lazy-loaded pages+const PageLoader = () => (+ <div className="flex items-center justify-center h-64">+ <div className="text-gray-500">Loading...</div>+ </div>+);+export default function App() {return (- <Routes>- <Route path="/" element={<Layout />}>- <Route index element={<Dashboard />} />- <Route path="apps" element={<Apps />} />- <Route path="devtools" element={<Navigate to="/devtools/runs" replace />} />- <Route path="devtools/history" element={<HistoryPage />} />- <Route path="devtools/runs" element={<RunsHistoryPage />} />- <Route path="devtools/runner" element={<RunnerPage />} />- <Route path="devtools/git" element={<GitPage />} />- <Route path="devtools/usage" element={<UsagePage />} />- <Route path="devtools/processes" element={<ProcessesPage />} />- <Route path="devtools/agents" element={<AgentsPage />} />- <Route path="ai" element={<AIProviders />} />- <Route path="prompts" element={<PromptManager />} />- <Route path="cos" element={<Navigate to="/cos/tasks" replace />} />- <Route path="cos/:tab" element={<ChiefOfStaff />} />- <Route path="apps/create" element={<CreateApp />} />- <Route path="templates" element={<Templates />} />- <Route path="*" element={<Navigate to="/" replace />} />- </Route>- </Routes>+ <Suspense fallback={<PageLoader />}>+ <Routes>+ <Route path="/" element={<Layout />}>+ <Route index element={<Dashboard />} />+ <Route path="apps" element={<Apps />} />+ <Route path="devtools" element={<Navigate to="/devtools/runs" replace />} />+ <Route path="devtools/history" element={<HistoryPage />} />+ <Route path="devtools/runs" element={<RunsHistoryPage />} />+ <Route path="devtools/runner" element={<RunnerPage />} />+ <Route path="devtools/git" element={<GitPage />} />+ <Route path="devtools/usage" element={<UsagePage />} />+ <Route path="devtools/processes" element={<ProcessesPage />} />+ <Route path="devtools/agents" element={<AgentsPage />} />+ <Route path="ai" element={<AIProviders />} />+ <Route path="prompts" element={<PromptManager />} />+ <Route path="cos" element={<Navigate to="/cos/tasks" replace />} />+ <Route path="cos/:tab" element={<ChiefOfStaff />} />+ <Route path="apps/create" element={<CreateApp />} />+ <Route path="templates" element={<Templates />} />+ <Route path="*" element={<Navigate to="/" replace />} />+ </Route>+ </Routes>+ </Suspense>);}diff --git a/client/src/components/AppIcon.jsx b/client/src/components/AppIcon.jsxindex dc54c2b2c8..665890ae48 100644--- a/client/src/components/AppIcon.jsx+++ b/client/src/components/AppIcon.jsx@@ -166,7 +166,12 @@ const icons = {// List of available icon names for the pickerexport const iconNames = Object.keys(icons);-export default function AppIcon({ icon, size = 24, className = '' }) {+export default function AppIcon({ icon, size = 24, className = '', ariaLabel }) {const IconComponent = icons[icon] || icons.package;- return <IconComponent size={size} className={className} />;+ const iconName = icon || 'package';+ return (+ <span role="img" aria-label={ariaLabel || `${iconName} icon`} aria-hidden={!ariaLabel ? 'true' : undefined}>+ <IconComponent size={size} className={className} />+ </span>+ );}diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex ec72053276..459adecda7 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -238,8 +238,12 @@ export default function Layout() {{/* Mobile overlay */}{mobileOpen && (<div+ role="button"+ tabIndex={0}+ aria-label="Close sidebar"className="fixed inset-0 bg-black/50 z-40 lg:hidden"onClick={() => setMobileOpen(false)}+ onKeyDown={(e) => e.key === 'Escape' && setMobileOpen(false)}/>)}@@ -267,8 +271,9 @@ export default function Layout() {onClick={() => setCollapsed(false)}className="hidden lg:block text-port-accent hover:text-port-accent/80 transition-colors"title="Expand sidebar"+ aria-label="Expand sidebar">- <Logo size={24} />+ <Logo size={24} ariaLabel="PortOS logo - click to expand sidebar" /></button>)}{/* Expanded: collapse button */}@@ -277,16 +282,18 @@ export default function Layout() {onClick={() => setCollapsed(true)}className="hidden lg:flex p-1 text-gray-500 hover:text-white transition-colors"title="Collapse sidebar"+ aria-label="Collapse sidebar">- <ChevronLeft size={20} />+ <ChevronLeft size={20} aria-hidden="true" /></button>)}{/* Mobile close button */}<buttononClick={() => setMobileOpen(false)}className="lg:hidden p-1 text-gray-500 hover:text-white"+ aria-label="Close sidebar">- ✕+ <span aria-hidden="true">✕</span></button></div>@@ -308,8 +315,10 @@ export default function Layout() {<buttononClick={() => setMobileOpen(true)}className="p-1.5 -ml-1 text-gray-400 hover:text-white"+ aria-label="Open navigation menu"+ aria-expanded={mobileOpen}>- <Menu size={20} />+ <Menu size={20} aria-hidden="true" /></button><div className="flex items-center gap-1.5"><Logo size={18} className="text-port-accent" />diff --git a/client/src/components/Logo.jsx b/client/src/components/Logo.jsxindex 3a6fbee613..16b1bcf2b0 100644--- a/client/src/components/Logo.jsx+++ b/client/src/components/Logo.jsx@@ -1,6 +1,6 @@// PortOS Logo - A portal/gateway with connected nodes representing apps and ports-export default function Logo({ size = 24, className = '' }) {+export default function Logo({ size = 24, className = '', ariaLabel = 'PortOS logo' }) {return (<svgwidth={size}@@ -9,6 +9,8 @@ export default function Logo({ size = 24, className = '' }) {fill="none"xmlns="http://www.w3.org/2000/svg"className={className}+ role="img"+ aria-label={ariaLabel}>{/* Outer portal ring */}<circlediff --git a/client/src/components/StatusBadge.jsx b/client/src/components/StatusBadge.jsxindex 4e4a221dab..34dea61742 100644--- a/client/src/components/StatusBadge.jsx+++ b/client/src/components/StatusBadge.jsx@@ -42,10 +42,12 @@ export default function StatusBadge({ status, size = 'md' }) {return (<span+ role="status"+ aria-label={`Status: ${config.text}`}className={`inline-flex items-center gap-1.5 rounded-full font-medium text-white ${config.color} ${sizeClasses[size]}`}>{config.pulse && (- <span className="w-2 h-2 rounded-full bg-white animate-pulse-soft" />+ <span className="w-2 h-2 rounded-full bg-white animate-pulse-soft" aria-hidden="true" />)}{config.text}</span>diff --git a/client/src/components/cos/StatCard.jsx b/client/src/components/cos/StatCard.jsxindex 77368bb434..17d627ccc3 100644--- a/client/src/components/cos/StatCard.jsx+++ b/client/src/components/cos/StatCard.jsx@@ -1,10 +1,16 @@export default function StatCard({ label, value, icon, active, activeLabel, compact, mini }) {+ const ariaLabel = `${label}: ${value}${active && activeLabel ? `, ${activeLabel}` : ''}`;+if (compact) {return (- <div className={`bg-port-card/80 border rounded-lg px-3 py-2 flex items-center gap-3 ${- active ? 'border-port-accent shadow-md shadow-port-accent/20' : 'border-port-border'- }`}>- <div className={`shrink-0 ${active ? 'animate-pulse' : ''}`}>+ <div+ role="group"+ aria-label={ariaLabel}+ className={`bg-port-card/80 border rounded-lg px-3 py-2 flex items-center gap-3 ${+ active ? 'border-port-accent shadow-md shadow-port-accent/20' : 'border-port-border'+ }`}+ >+ <div className={`shrink-0 ${active ? 'animate-pulse' : ''}`} aria-hidden="true">{icon}</div><div className="flex-1 min-w-0">@@ -17,12 +23,16 @@ export default function StatCard({ label, value, icon, active, activeLabel, compif (mini) {return (- <div className={`bg-port-card border rounded p-1.5 sm:p-2 lg:p-3 transition-all ${- active ? 'border-port-accent shadow-md shadow-port-accent/20' : 'border-port-border'- }`}>+ <div+ role="group"+ aria-label={ariaLabel}+ className={`bg-port-card border rounded p-1.5 sm:p-2 lg:p-3 transition-all ${+ active ? 'border-port-accent shadow-md shadow-port-accent/20' : 'border-port-border'+ }`}+ ><div className="flex items-center justify-between mb-0.5"><span className="text-[10px] sm:text-xs text-gray-500 truncate">{label}</span>- <div className={`shrink-0 ${active ? 'animate-pulse' : ''}`}>+ <div className={`shrink-0 ${active ? 'animate-pulse' : ''}`} aria-hidden="true">{icon}</div></div>@@ -32,18 +42,22 @@ export default function StatCard({ label, value, icon, active, activeLabel, comp}return (- <div className={`bg-port-card border rounded-lg p-2 sm:p-3 lg:p-4 transition-all ${- active ? 'border-port-accent shadow-lg shadow-port-accent/20' : 'border-port-border'- }`}>+ <div+ role="group"+ aria-label={ariaLabel}+ className={`bg-port-card border rounded-lg p-2 sm:p-3 lg:p-4 transition-all ${+ active ? 'border-port-accent shadow-lg shadow-port-accent/20' : 'border-port-border'+ }`}+ ><div className="flex items-center justify-between mb-0.5 sm:mb-1 lg:mb-2"><span className="text-xs sm:text-sm text-gray-500 truncate mr-1">{label}</span>- <div className={`shrink-0 ${active ? 'animate-pulse' : ''}`}>+ <div className={`shrink-0 ${active ? 'animate-pulse' : ''}`} aria-hidden="true">{icon}</div></div><div className="text-lg sm:text-xl lg:text-2xl font-bold text-white">{value}</div>{active && activeLabel && (- <div className="text-xs text-port-accent mt-0.5 sm:mt-1 truncate animate-pulse">+ <div className="text-xs text-port-accent mt-0.5 sm:mt-1 truncate animate-pulse" aria-live="polite">{activeLabel}</div>)}diff --git a/client/src/components/cos/TerminalCoSPanel.jsx b/client/src/components/cos/TerminalCoSPanel.jsxindex c59d285d5e..5a1f26aa30 100644--- a/client/src/components/cos/TerminalCoSPanel.jsx+++ b/client/src/components/cos/TerminalCoSPanel.jsx@@ -160,17 +160,17 @@ export default function TerminalCoSPanel({ state, speaking, statusMessage, event<span className="text-gray-400">{stateConfig.icon}</span></div>- {/* Message bubble as terminal output */}- <div className="mb-1 lg:mb-4 px-2 py-1 lg:py-1.5 bg-gray-800/50 rounded border-l-2 border-cyan-500/50">- <div className="flex items-center gap-1 lg:block">- <span className="text-cyan-400 text-xs">$</span>- <span className="text-gray-300 text-xs lg:ml-2 truncate lg:line-clamp-none flex-1">{statusMessage}</span>- {evalCountdown && (- <span className="text-[10px] lg:text-xs text-cyan-500/60 font-mono whitespace-nowrap lg:block lg:mt-1">- <span className="hidden lg:inline"># next: </span>({evalCountdown.formatted})- </span>- )}+ {/* Message bubble as terminal output - compact two-line layout */}+ <div className="mb-1 lg:mb-2 px-2 py-1 bg-gray-800/50 rounded border-l-2 border-cyan-500/50 text-xs">+ <div className="flex items-center gap-1">+ <span className="text-cyan-400">$</span>+ <span className="text-gray-300 truncate">{statusMessage}</span></div>+ {evalCountdown && (+ <div className="text-cyan-500/60 font-mono mt-0.5">+ # next: ({evalCountdown.formatted})+ </div>+ )}</div>{/* Stats as terminal output - desktop only */}diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 5e41461c22..a78ec201e1 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -26,14 +26,15 @@ export const AGENT_STATES = {ideating: { label: 'Ideating', color: '#f97316', icon: '💡' },};+// Default messages shown when no specific event message is availableexport const STATE_MESSAGES = {- sleeping: ["Resting... Wake me if you need anything!", "💤 Power saving mode..."],- thinking: ["Processing your request...", "Analyzing the situation...", "Let me think about this..."],- coding: ["Writing some code...", "Implementing the solution...", "Building something cool..."],- investigating: ["Looking into this...", "Researching the topic...", "Gathering information..."],- reviewing: ["Checking the details...", "Reviewing for quality...", "Making sure everything's right..."],- planning: ["Organizing the approach...", "Mapping out the strategy...", "Creating a plan..."],- ideating: ["Brainstorming ideas...", "Getting creative!", "Inspiration incoming..."],+ sleeping: "Idle - waiting for tasks...",+ thinking: "Processing...",+ coding: "Working on task...",+ investigating: "Investigating issue...",+ reviewing: "Reviewing results...",+ planning: "Planning next steps...",+ ideating: "Analyzing options...",};export const MEMORY_TYPES = ['fact', 'learning', 'observation', 'decision', 'preference', 'context'];diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 847e5e0b6e..bfb0f758f3 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react';+import { useState, useEffect, useMemo } from 'react';import {Cpu,Square,@@ -8,11 +8,33 @@ import {RotateCcw,Loader2,Skull,- Activity+ Activity,+ Clock} from 'lucide-react';import * as api from '../../../services/api';-export default function AgentCard({ agent, onTerminate, onKill, onDelete, onResume, completed, liveOutput }) {+// Extract task type from description (matches server-side extractTaskType)+function extractTaskType(description) {+ if (!description) return 'general';+ const d = description.toLowerCase();+ if (d.includes('fix') || d.includes('bug') || d.includes('error') || d.includes('issue')) return 'bug-fix';+ if (d.includes('refactor') || d.includes('clean up') || d.includes('improve') || d.includes('optimize')) return 'refactor';+ if (d.includes('test')) return 'testing';+ if (d.includes('document') || d.includes('readme') || d.includes('docs')) return 'documentation';+ if (d.includes('review') || d.includes('audit')) return 'code-review';+ if (d.includes('mobile') || d.includes('responsive')) return 'mobile-responsive';+ if (d.includes('security') || d.includes('vulnerability')) return 'security';+ if (d.includes('performance') || d.includes('speed')) return 'performance';+ if (d.includes('ui') || d.includes('ux') || d.includes('design') || d.includes('style')) return 'ui-ux';+ if (d.includes('api') || d.includes('endpoint') || d.includes('route')) return 'api';+ if (d.includes('database') || d.includes('migration')) return 'database';+ if (d.includes('deploy') || d.includes('ci') || d.includes('cd')) return 'devops';+ if (d.includes('investigate') || d.includes('debug')) return 'investigation';+ if (d.includes('self-improvement') || d.includes('feature idea')) return 'self-improvement';+ return 'feature';+}++export default function AgentCard({ agent, onTerminate, onKill, onDelete, onResume, completed, liveOutput, durations }) {const [expanded, setExpanded] = useState(false);const [now, setNow] = useState(Date.now());const [fullOutput, setFullOutput] = useState(null);@@ -78,6 +100,42 @@ export default function AgentCard({ agent, onTerminate, onKill, onDelete, onResureturn `${seconds}s`;};+ // Calculate duration estimate for running agents+ const durationEstimate = useMemo(() => {+ if (completed || !durations) return null;++ const taskType = extractTaskType(agent.metadata?.taskDescription);+ const typeData = durations[taskType];+ const overallData = durations._overall;++ if (typeData && typeData.avgDurationMs) {+ return {+ estimatedMs: typeData.avgDurationMs,+ basedOn: typeData.completed,+ taskType,+ isTypeSpecific: true+ };+ }++ if (overallData && overallData.avgDurationMs) {+ return {+ estimatedMs: overallData.avgDurationMs,+ basedOn: overallData.completed,+ taskType: 'all tasks',+ isTypeSpecific: false+ };+ }++ return null;+ }, [completed, durations, agent.metadata?.taskDescription]);++ // Calculate progress percentage+ const progress = useMemo(() => {+ if (!durationEstimate) return null;+ const percent = Math.min(100, Math.round((duration / durationEstimate.estimatedMs) * 100));+ return percent;+ }, [duration, durationEstimate]);+// For running agents, use live output; for completed, use fetched full output or storedconst output = completed? (fullOutput || agent.output || [])@@ -133,7 +191,18 @@ export default function AgentCard({ agent, onTerminate, onKill, onDelete, onResu)}</div><div className="flex items-center gap-2">- <span className="text-sm text-gray-500">{formatDuration(duration)}</span>+ {/* Duration with estimate for running agents */}+ {!completed && durationEstimate ? (+ <span+ className="flex items-center gap-1 text-sm text-gray-500"+ title={`Based on ${durationEstimate.basedOn} completed ${durationEstimate.taskType} tasks`}+ >+ <Clock size={12} />+ {formatDuration(duration)} / ~{formatDuration(durationEstimate.estimatedMs)}+ </span>+ ) : (+ <span className="text-sm text-gray-500">{formatDuration(duration)}</span>+ )}{(output.length > 0 || completed) && (<buttononClick={() => setExpanded(!expanded)}@@ -193,6 +262,26 @@ export default function AgentCard({ agent, onTerminate, onKill, onDelete, onResu</div>)}+ {/* Progress bar for running agents with estimates */}+ {!completed && durationEstimate && progress !== null && (+ <div className="mt-2">+ <div className="h-1 bg-port-border rounded-full overflow-hidden">+ <div+ className={`h-full transition-all duration-1000 ease-linear ${+ progress >= 100 ? 'bg-yellow-500' : 'bg-port-accent'+ }`}+ style={{ width: `${Math.min(progress, 100)}%` }}+ />+ </div>+ <div className="flex justify-between mt-1 text-xs text-gray-600">+ <span>{progress}% of typical duration</span>+ {progress >= 100 && (+ <span className="text-yellow-500">Running longer than average</span>+ )}+ </div>+ </div>+ )}+{agent.result && (<div className={`text-sm flex items-center gap-2 ${agent.result.success ? 'text-port-success' : 'text-port-error'}`}>{agent.result.success ? (diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsxindex da951561c9..fdc903b53b 100644--- a/client/src/components/cos/tabs/AgentsTab.jsx+++ b/client/src/components/cos/tabs/AgentsTab.jsx@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useState, useEffect } from 'react';import { Trash2 } from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../../../services/api';@@ -7,6 +7,12 @@ import ResumeAgentModal from './ResumeAgentModal';export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, apps }) {const [resumingAgent, setResumingAgent] = useState(null);+ const [durations, setDurations] = useState(null);++ // Fetch duration estimates for progress indicators+ useEffect(() => {+ api.getCosLearningDurations().then(setDurations).catch(() => {});+ }, []);const handleTerminate = async (agentId) => {await api.terminateCosAgent(agentId).catch(err => toast.error(err.message));@@ -83,6 +89,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, aonTerminate={handleTerminate}onKill={handleKill}liveOutput={liveOutputs[agent.id]}+ durations={durations}/>))}</div>diff --git a/client/src/components/cos/tabs/HealthTab.jsx b/client/src/components/cos/tabs/HealthTab.jsxindex 3ee4f9d6e3..681caf69f6 100644--- a/client/src/components/cos/tabs/HealthTab.jsx+++ b/client/src/components/cos/tabs/HealthTab.jsx@@ -1,8 +1,35 @@-import { RefreshCw, CheckCircle, AlertCircle } from 'lucide-react';+import { useState, useEffect } from 'react';+import { RefreshCw, CheckCircle, AlertCircle, TrendingUp, Brain, Zap, Database } 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);++ useEffect(() => {+ loadLearning();+ }, []);++ const loadLearning = async () => {+ setLoadingLearning(true);+ const data = await api.getCosLearning().catch(() => null);+ setLearning(data);+ setLoadingLearning(false);+ };++ const handleBackfill = async () => {+ setBackfilling(true);+ const result = await api.backfillCosLearning().catch(() => null);+ if (result?.success) {+ await loadLearning();+ }+ setBackfilling(false);+ };+return (<div className="space-y-6">+ {/* System Health Section */}<div className="flex items-center justify-between"><div><h3 className="text-lg font-semibold text-white">System Health</h3>@@ -51,6 +78,166 @@ export default function HealthTab({ health, onCheck }) {))}</div>)}++ {/* Task Learning Section */}+ <div className="pt-6 border-t border-port-border">+ <div className="flex items-center justify-between mb-4">+ <div className="flex items-center gap-2">+ <Brain className="w-5 h-5 text-purple-400" />+ <h3 className="text-lg font-semibold text-white">Task Learning</h3>+ </div>+ <div className="flex gap-2">+ {learning?.totals?.completed === 0 && (+ <button+ onClick={handleBackfill}+ disabled={backfilling}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-purple-500/20 hover:bg-purple-500/30 text-purple-400 rounded-lg transition-colors disabled:opacity-50"+ >+ <Database size={14} />+ {backfilling ? 'Backfilling...' : 'Backfill History'}+ </button>+ )}+ <button+ onClick={loadLearning}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"+ >+ <RefreshCw size={14} className={loadingLearning ? 'animate-spin' : ''} />+ Refresh+ </button>+ </div>+ </div>++ {loadingLearning ? (+ <div className="text-center py-8 text-gray-500">Loading learning data...</div>+ ) : !learning ? (+ <div className="text-center py-8 text-gray-500">No learning data available yet</div>+ ) : (+ <div className="space-y-4">+ {/* Overall Stats */}+ <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="text-2xl font-bold text-white">{learning.totals?.completed || 0}</div>+ <div className="text-xs text-gray-500">Tasks Tracked</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-3">+ <div className="text-2xl font-bold text-port-success">{learning.totals?.successRate || 0}%</div>+ <div className="text-xs text-gray-500">Success Rate</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-3">+ <div className="text-2xl font-bold text-cyan-400">{learning.totals?.avgDurationMin || 0}m</div>+ <div className="text-xs text-gray-500">Avg Duration</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-3">+ <div className="text-2xl font-bold text-port-error">{learning.totals?.failed || 0}</div>+ <div className="text-xs text-gray-500">Failed Tasks</div>+ </div>+ </div>++ {/* Recommendations */}+ {learning.recommendations?.length > 0 && (+ <div className="space-y-2">+ <h4 className="text-sm font-medium text-gray-400 flex items-center gap-2">+ <Zap size={14} className="text-yellow-400" />+ Recommendations+ </h4>+ {learning.recommendations.map((rec, idx) => (+ <div+ key={idx}+ className={`text-sm p-3 rounded-lg border ${+ rec.type === 'warning' ? 'bg-yellow-500/10 border-yellow-500/30 text-yellow-400' :+ rec.type === 'action' ? 'bg-red-500/10 border-red-500/30 text-red-400' :+ rec.type === 'optimization' ? 'bg-green-500/10 border-green-500/30 text-green-400' :+ rec.type === 'suggestion' ? 'bg-blue-500/10 border-blue-500/30 text-blue-400' :+ 'bg-gray-500/10 border-gray-500/30 text-gray-400'+ }`}+ >+ {rec.message}+ </div>+ ))}+ </div>+ )}++ {/* Best/Worst Performing Task Types */}+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">+ {learning.insights?.bestPerforming?.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">+ <TrendingUp size={14} className="text-green-400" />+ Best Performing+ </h4>+ <div className="space-y-2">+ {learning.insights.bestPerforming.map((item, idx) => (+ <div key={idx} className="flex items-center justify-between text-sm">+ <span className="text-gray-300 truncate">{item.type}</span>+ <span className="text-green-400 font-mono">{item.successRate}%</span>+ </div>+ ))}+ </div>+ </div>+ )}++ {learning.insights?.worstPerforming?.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">+ <AlertCircle size={14} className="text-red-400" />+ Needs Improvement+ </h4>+ <div className="space-y-2">+ {learning.insights.worstPerforming.map((item, idx) => (+ <div key={idx} className="flex items-center justify-between text-sm">+ <span className="text-gray-300 truncate">{item.type}</span>+ <span className="text-red-400 font-mono">{item.successRate}%</span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>++ {/* Model Effectiveness */}+ {learning.insights?.modelEffectiveness?.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">Model Performance</h4>+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ {learning.insights.modelEffectiveness.map((model, idx) => (+ <div key={idx} className="flex items-center justify-between text-sm p-2 bg-port-bg rounded">+ <span className="text-gray-300 capitalize">{model.tier}</span>+ <div className="flex items-center gap-2">+ <span className={`font-mono ${model.successRate >= 80 ? 'text-green-400' : model.successRate >= 60 ? 'text-yellow-400' : 'text-red-400'}`}>+ {model.successRate}%+ </span>+ <span className="text-gray-500 text-xs">({model.completed})</span>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Common Errors */}+ {learning.insights?.commonErrors?.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">Common Error Patterns</h4>+ <div className="space-y-2">+ {learning.insights.commonErrors.map((error, idx) => (+ <div key={idx} className="flex items-center justify-between text-sm p-2 bg-port-bg rounded">+ <span className="text-red-400">{error.category}</span>+ <span className="text-gray-500">{error.count} occurrences</span>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Last Updated */}+ {learning.lastUpdated && (+ <p className="text-xs text-gray-600 text-center">+ Learning data updated: {new Date(learning.lastUpdated).toLocaleString()}+ </p>+ )}+ </div>+ )}+ </div></div>);}diff --git a/client/src/components/cos/tabs/MemoryTab.jsx b/client/src/components/cos/tabs/MemoryTab.jsxindex 583da2c3b5..cdfdea5cb3 100644--- a/client/src/components/cos/tabs/MemoryTab.jsx+++ b/client/src/components/cos/tabs/MemoryTab.jsx@@ -145,7 +145,31 @@ export default function MemoryTab() {<div className="space-y-3">{displayMemories.length === 0 ? (<div className="text-center py-12 text-gray-500">- {searchQuery ? 'No memories found for this search' : 'No memories yet. Memories are extracted from agent task completions.'}+ {searchQuery ? (+ 'No memories found for this search'+ ) : (+ <div className="space-y-4">+ <p>No memories yet.</p>+ {!embeddingStatus?.available && (+ <div className="bg-port-warning/10 border border-port-warning/30 rounded-lg p-4 text-left max-w-md mx-auto">+ <p className="text-port-warning font-medium mb-2">LM Studio Required</p>+ <p className="text-sm text-gray-400">+ For the memory system to work, LM Studio must be running with an embedding model:+ </p>+ <ol className="text-sm text-gray-400 mt-2 list-decimal list-inside space-y-1">+ <li>Open LM Studio</li>+ <li>Load <code className="text-port-accent">text-embedding-nomic-embed-text-v2-moe</code></li>+ <li>Start the local server (port 1234)</li>+ </ol>+ </div>+ )}+ {embeddingStatus?.available && (+ <p className="text-sm">+ Memories are automatically extracted when CoS agents complete tasks successfully.+ </p>+ )}+ </div>+ )}</div>) : (displayMemories.map(memory => (diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex 3e04069a53..cb23c56ff8 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -69,16 +69,19 @@ export default function TaskItem({ task, isSystem, awaitingApproval, onRefresh,{...dragHandleProps}className="mt-0.5 cursor-grab active:cursor-grabbing text-gray-500 hover:text-gray-300 transition-colors touch-none"title="Drag to reorder"+ aria-label="Drag to reorder">- <GripVertical size={16} />+ <GripVertical size={16} aria-hidden="true" /></button>)}<buttononClick={() => handleStatusChange(task.status === 'completed' ? 'pending' : 'completed')}className="mt-0.5 hover:scale-110 transition-transform"title={task.status === 'completed' ? 'Mark as pending' : 'Mark as completed'}+ aria-label={task.status === 'completed' ? 'Mark as pending' : 'Mark as completed'}>- {statusIcons[task.status]}+ <span aria-hidden="true">{statusIcons[task.status]}</span>+ <span className="sr-only">Status: {task.status}</span></button><div className="flex-1 min-w-0"><div className="flex items-center gap-2 mb-1 flex-wrap">@@ -181,15 +184,17 @@ export default function TaskItem({ task, isSystem, awaitingApproval, onRefresh,onClick={() => setEditing(true)}className="p-1 text-gray-500 hover:text-white transition-colors"title="Edit"+ aria-label="Edit task">- <Edit3 size={14} />+ <Edit3 size={14} aria-hidden="true" /></button><buttononClick={handleDelete}className="p-1 text-gray-500 hover:text-port-error transition-colors"title="Delete"+ aria-label="Delete task">- <Trash2 size={14} />+ <Trash2 size={14} aria-hidden="true" /></button></>)}diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsxindex 1a39ac03f6..0931f70523 100644--- a/client/src/components/cos/tabs/TasksTab.jsx+++ b/client/src/components/cos/tabs/TasksTab.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useRef } from 'react';+import { useState, useEffect, useRef, useMemo, useCallback } from 'react';import { Plus, RefreshCw, Image, X } from 'lucide-react';import toast from 'react-hot-toast';import {@@ -25,8 +25,23 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {const [userTasksLocal, setUserTasksLocal] = useState([]);const [screenshots, setScreenshots] = useState([]);const fileInputRef = useRef(null);- const userTasks = tasks.user?.tasks || [];- const cosTasks = tasks.cos?.tasks || [];++ // Memoize task arrays to prevent unnecessary re-renders+ const userTasks = useMemo(() => tasks.user?.tasks || [], [tasks.user?.tasks]);+ const cosTasks = useMemo(() => tasks.cos?.tasks || [], [tasks.cos?.tasks]);+ const awaitingApproval = useMemo(() => tasks.cos?.awaitingApproval || [], [tasks.cos?.awaitingApproval]);++ // Memoize enabled providers for dropdown+ const enabledProviders = useMemo(() =>+ providers?.filter(p => p.enabled) || [],+ [providers]+ );++ // Memoize sortable item IDs for DndContext+ const sortableIds = useMemo(() =>+ userTasksLocal.map(t => t.id),+ [userTasksLocal]+ );// Keep local state in sync with server stateuseEffect(() => {@@ -217,7 +232,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {className="w-40 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"><option value="">Auto (default)</option>- {providers?.filter(p => p.enabled).map(p => (+ {enabledProviders.map(p => (<option key={p.id} value={p.id}>{p.name}</option>))}</select>@@ -309,7 +324,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {onDragEnd={handleDragEnd}><SortableContext- items={userTasksLocal.map(t => t.id)}+ items={sortableIds}strategy={verticalListSortingStrategy}><div className="space-y-2">@@ -340,11 +355,11 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {</div>{/* Awaiting Approval */}- {tasks.cos?.awaitingApproval?.length > 0 && (+ {awaitingApproval.length > 0 && (<div><h3 className="text-lg font-semibold text-yellow-500 mb-3">Awaiting Approval</h3><div className="space-y-2">- {tasks.cos.awaitingApproval.map(task => (+ {awaitingApproval.map(task => (<TaskItem key={task.id} task={task} awaitingApproval onRefresh={onRefresh} providers={providers} />))}</div>diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex fd6924ebce..4303f92a0d 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback } from 'react';+import { useState, useEffect, useCallback, useMemo } from 'react';import { useParams, useNavigate } from 'react-router-dom';import { useSocket } from '../hooks/useSocket';import * as api from '../services/api';@@ -40,7 +40,7 @@ export default function ChiefOfStaff() {const [loading, setLoading] = useState(true);const [agentState, setAgentState] = useState('sleeping');const [speaking, setSpeaking] = useState(false);- const [statusMessage, setStatusMessage] = useState("Ready to help organize your day!");+ const [statusMessage, setStatusMessage] = useState("Idle - waiting for tasks...");const [liveOutputs, setLiveOutputs] = useState({});const [eventLogs, setEventLogs] = useState([]);const socket = useSocket();@@ -96,8 +96,8 @@ export default function ChiefOfStaff() {const newState = deriveAgentState(statusData, agentsData, healthData);setAgentState(newState);- const messages = STATE_MESSAGES[newState];- setStatusMessage(messages[Math.floor(Math.random() * messages.length)]);+ // Use default state message - real messages come from socket events+ setStatusMessage(STATE_MESSAGES[newState]);}, [deriveAgentState]);useEffect(() => {@@ -124,7 +124,7 @@ export default function ChiefOfStaff() {setStatus(prev => ({ ...prev, running: data.running }));if (!data.running) {setAgentState('sleeping');- setStatusMessage(STATE_MESSAGES.sleeping[0]);+ setStatusMessage("Stopped - daemon not running");}});@@ -134,12 +134,15 @@ export default function ChiefOfStaff() {socket.on('cos:agent:spawned', (data) => {setAgentState('coding');- setStatusMessage("Working on a task...");+ // Show actual task description if available+ const taskDesc = data?.metadata?.taskDescription;+ const shortDesc = taskDesc ? taskDesc.substring(0, 60) + (taskDesc.length > 60 ? '...' : '') : 'Working on task...';+ setStatusMessage(`Running: ${shortDesc}`);setSpeaking(true);setTimeout(() => setSpeaking(false), 2000);// Initialize empty output buffer for new agent- if (data?.agentId) {- setLiveOutputs(prev => ({ ...prev, [data.agentId]: [] }));+ if (data?.agentId || data?.id) {+ setLiveOutputs(prev => ({ ...prev, [data.agentId || data.id]: [] }));}fetchData();});@@ -163,9 +166,10 @@ export default function ChiefOfStaff() {}});- socket.on('cos:agent:completed', () => {+ socket.on('cos:agent:completed', (data) => {setAgentState('reviewing');- setStatusMessage("Task completed! Checking results...");+ const success = data?.result?.success;+ setStatusMessage(success ? "Task completed successfully" : "Task failed - checking errors...");setSpeaking(true);setTimeout(() => setSpeaking(false), 2000);fetchData();@@ -175,7 +179,7 @@ export default function ChiefOfStaff() {setHealth({ lastCheck: data.metrics?.timestamp, issues: data.issues });if (data.issues?.length > 0) {setAgentState('investigating');- setStatusMessage("Found some issues to look into...");+ setStatusMessage(`Health check: ${data.issues.length} issue${data.issues.length > 1 ? 's' : ''} found`);setSpeaking(true);setTimeout(() => setSpeaking(false), 2000);}@@ -218,7 +222,7 @@ export default function ChiefOfStaff() {if (result?.success) {toast.success('Chief of Staff started');setAgentState('thinking');- setStatusMessage("Starting up... Let me see what needs to be done!");+ setStatusMessage("Starting daemon - scanning for tasks...");setSpeaking(true);setTimeout(() => setSpeaking(false), 2000);fetchData();@@ -233,7 +237,7 @@ export default function ChiefOfStaff() {if (result?.success) {toast.success('Chief of Staff stopped');setAgentState('sleeping');- setStatusMessage(STATE_MESSAGES.sleeping[0]);+ setStatusMessage("Stopped - daemon not running");fetchData();}};@@ -249,7 +253,7 @@ export default function ChiefOfStaff() {const handleHealthCheck = async () => {setAgentState('investigating');- setStatusMessage("Running health check...");+ setStatusMessage("Running system health check...");setSpeaking(true);const result = await api.forceHealthCheck().catch(err => {toast.error(err.message);@@ -260,14 +264,31 @@ export default function ChiefOfStaff() {setHealth({ lastCheck: result.metrics?.timestamp, issues: result.issues });toast.success('Health check complete');if (result.issues?.length > 0) {- setStatusMessage("Found some issues!");+ setStatusMessage(`Health: ${result.issues.length} issue${result.issues.length > 1 ? 's' : ''} detected`);} else {- setAgentState('reviewing');- setStatusMessage("All systems healthy!");+ setAgentState('sleeping');+ setStatusMessage("Health check passed - all systems OK");}}};+ // Memoize expensive derived state to prevent recalculation on every render+ // Note: These must be before any early returns to follow React's Rules of Hooks+ const activeAgentCount = useMemo(() =>+ agents.filter(a => a.status === 'running').length,+ [agents]+ );+ const hasIssues = useMemo(() =>+ (health?.issues?.length || 0) > 0,+ [health?.issues?.length]+ );++ // Memoize pending task count+ const pendingTaskCount = useMemo(() =>+ (tasks.user?.grouped?.pending?.length || 0) + (tasks.cos?.grouped?.pending?.length || 0),+ [tasks.user?.grouped?.pending?.length, tasks.cos?.grouped?.pending?.length]+ );+if (loading) {return (<div className="flex items-center justify-center h-64">@@ -276,9 +297,6 @@ export default function ChiefOfStaff() {);}- const activeAgentCount = agents.filter(a => a.status === 'running').length;- const hasIssues = (health?.issues?.length || 0) > 0;-return (<div className="flex flex-col lg:grid lg:grid-cols-[320px_1fr] h-screen overflow-hidden">{/* Agent Panel */}@@ -367,7 +385,7 @@ export default function ChiefOfStaff() {/><StatCardlabel="Pending"- value={(tasks.user?.grouped?.pending?.length || 0) + (tasks.cos?.grouped?.pending?.length || 0)}+ value={pendingTaskCount}icon={<Clock className="w-4 h-4 text-yellow-500" />}compact/>@@ -401,7 +419,7 @@ export default function ChiefOfStaff() {/><StatCardlabel="Pending"- value={(tasks.user?.grouped?.pending?.length || 0) + (tasks.cos?.grouped?.pending?.length || 0)}+ value={pendingTaskCount}icon={<Clock className="w-3 h-3 sm:w-4 sm:h-4 lg:w-5 lg:h-5 text-yellow-500" />}mini/>diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex e3087c00ff..460f0fa050 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -112,9 +112,9 @@ export default function Dashboard() {function StatCard({ label, value, icon }) {return (- <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="bg-port-card border border-port-border rounded-lg p-4" role="group" aria-label={`${label}: ${value}`}><div className="flex items-center gap-2 mb-1">- <span>{icon}</span>+ <span aria-hidden="true">{icon}</span><span className="text-sm text-gray-500">{label}</span></div><div className="text-2xl font-bold text-white">{value}</div>diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 43ff636e4b..c778b9fbab 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -253,6 +253,11 @@ export const getCosReports = () => request('/cos/reports');export const getCosTodayReport = () => request('/cos/reports/today');export const getCosReport = (date) => request(`/cos/reports/${date}`);+// CoS Learning+export const getCosLearning = () => request('/cos/learning');+export const getCosLearningDurations = () => request('/cos/learning/durations');+export const backfillCosLearning = () => request('/cos/learning/backfill', { method: 'POST' });+// CoS Scriptsexport const getCosScripts = () => request('/cos/scripts');export const getCosScript = (id) => request(`/cos/scripts/${id}`);diff --git a/client/vite.config.js b/client/vite.config.jsindex 275b5e057e..dc87c11f62 100644--- a/client/vite.config.js+++ b/client/vite.config.js@@ -17,5 +17,25 @@ export default defineConfig({ws: true}}+ },+ build: {+ rollupOptions: {+ output: {+ manualChunks: {+ // Core React dependencies+ 'vendor-react': ['react', 'react-dom', 'react-router-dom'],+ // Socket and toast dependencies+ 'vendor-realtime': ['socket.io-client', 'react-hot-toast'],+ // Drag and drop library (only used in CoS)+ 'vendor-dnd': ['@dnd-kit/core', '@dnd-kit/sortable', '@dnd-kit/utilities'],+ // Icon library (largest dependency)+ 'vendor-icons': ['lucide-react']+ }+ }+ },+ // Enable source maps for debugging in production+ sourcemap: false,+ // Increase chunk size warning limit (icons are large)+ chunkSizeWarningLimit: 600}});diff --git a/docs/media/portos_7.png b/docs/media/portos_7.pngnew file mode 100644index 0000000000..142efd07a9Binary files /dev/null and b/docs/media/portos_7.png differdiff --git a/server/index.js b/server/index.jsindex 11e3536752..193a53490b 100644--- a/server/index.js+++ b/server/index.js@@ -29,6 +29,7 @@ import { initSocket } from './services/socket.js';import { initScriptRunner } from './services/scriptRunner.js';import { errorMiddleware, setupProcessErrorHandlers } from './lib/errorHandler.js';import { initAutoFixer } from './services/autoFixer.js';+import { initTaskLearning } from './services/taskLearning.js';import './services/subAgentSpawner.js'; // Initialize CoS agent spawnerconst __filename = fileURLToPath(import.meta.url);@@ -54,6 +55,9 @@ initSocket(io);// Initialize auto-fixer for error recoveryinitAutoFixer();+// Initialize task learning system to track agent completions+initTaskLearning();+// Middleware - allow any origin for Tailscale accessapp.use(cors({origin: true,diff --git a/server/lib/taskParser.test.js b/server/lib/taskParser.test.jsnew file mode 100644index 0000000000..6c55970176--- /dev/null+++ b/server/lib/taskParser.test.js@@ -0,0 +1,525 @@+import { describe, it, expect } from 'vitest';+import {+ parseTasksMarkdown,+ groupTasksByStatus,+ sortByPriority,+ generateTasksMarkdown,+ getAutoApprovedTasks,+ getAwaitingApprovalTasks,+ updateTaskStatus,+ addTask,+ removeTask,+ getNextTask,+ validateTask+} from './taskParser.js';++describe('Task Parser', () => {+ describe('parseTasksMarkdown', () => {+ it('should parse a simple pending task', () => {+ const markdown = `# Tasks++## Pending+- [ ] #task-001 | HIGH | Fix the login bug`;++ const tasks = parseTasksMarkdown(markdown);++ expect(tasks).toHaveLength(1);+ expect(tasks[0].id).toBe('task-001');+ expect(tasks[0].status).toBe('pending');+ expect(tasks[0].priority).toBe('HIGH');+ expect(tasks[0].priorityValue).toBe(3);+ expect(tasks[0].description).toBe('Fix the login bug');+ });++ it('should parse all priority levels', () => {+ const markdown = `# Tasks++## Pending+- [ ] #task-001 | CRITICAL | Critical task+- [ ] #task-002 | HIGH | High task+- [ ] #task-003 | MEDIUM | Medium task+- [ ] #task-004 | LOW | Low task`;++ const tasks = parseTasksMarkdown(markdown);++ expect(tasks).toHaveLength(4);+ expect(tasks[0].priority).toBe('CRITICAL');+ expect(tasks[0].priorityValue).toBe(4);+ expect(tasks[1].priority).toBe('HIGH');+ expect(tasks[1].priorityValue).toBe(3);+ expect(tasks[2].priority).toBe('MEDIUM');+ expect(tasks[2].priorityValue).toBe(2);+ expect(tasks[3].priority).toBe('LOW');+ expect(tasks[3].priorityValue).toBe(1);+ });++ it('should parse all status types', () => {+ const markdown = `# Tasks++## Pending+- [ ] #task-001 | MEDIUM | Pending task++## In Progress+- [~] #task-002 | MEDIUM | In progress task++## Blocked+- [!] #task-003 | MEDIUM | Blocked task++## Completed+- [x] #task-004 | MEDIUM | Completed task`;++ const tasks = parseTasksMarkdown(markdown);++ expect(tasks).toHaveLength(4);+ expect(tasks[0].status).toBe('pending');+ expect(tasks[1].status).toBe('in_progress');+ expect(tasks[2].status).toBe('blocked');+ expect(tasks[3].status).toBe('completed');+ });++ it('should parse tasks with approval flags', () => {+ const markdown = `# Tasks++## Pending+- [ ] #sys-001 | HIGH | AUTO | Auto-approved task+- [ ] #sys-002 | MEDIUM | APPROVAL | Needs approval task`;++ const tasks = parseTasksMarkdown(markdown);++ expect(tasks).toHaveLength(2);+ expect(tasks[0].autoApproved).toBe(true);+ expect(tasks[0].approvalRequired).toBe(false);+ expect(tasks[1].autoApproved).toBe(false);+ expect(tasks[1].approvalRequired).toBe(true);+ });++ it('should parse metadata under tasks', () => {+ const markdown = `# Tasks++## Pending+- [ ] #task-001 | HIGH | Fix the bug+ - Context: User reported issue+ - App: my-app+ - Model: claude-sonnet`;++ const tasks = parseTasksMarkdown(markdown);++ expect(tasks).toHaveLength(1);+ expect(tasks[0].metadata.context).toBe('User reported issue');+ expect(tasks[0].metadata.app).toBe('my-app');+ expect(tasks[0].metadata.model).toBe('claude-sonnet');+ });++ it('should handle empty content', () => {+ const tasks = parseTasksMarkdown('');+ expect(tasks).toHaveLength(0);+ });++ it('should handle content with only headers', () => {+ const markdown = `# Tasks++## Pending++## Completed`;++ const tasks = parseTasksMarkdown(markdown);+ expect(tasks).toHaveLength(0);+ });++ it('should preserve section information', () => {+ const markdown = `# Tasks++## Pending+- [ ] #task-001 | MEDIUM | Pending task++## In Progress+- [~] #task-002 | MEDIUM | In progress task`;++ const tasks = parseTasksMarkdown(markdown);++ expect(tasks[0].section).toBe('pending');+ expect(tasks[1].section).toBe('in_progress');+ });++ it('should add task- prefix if not present', () => {+ const markdown = `# Tasks++## Pending+- [ ] #001 | MEDIUM | Task without prefix`;++ const tasks = parseTasksMarkdown(markdown);+ expect(tasks[0].id).toBe('task-001');+ });++ it('should not double-prefix sys- tasks', () => {+ const markdown = `# Tasks++## Pending+- [ ] #sys-001 | MEDIUM | System task`;++ const tasks = parseTasksMarkdown(markdown);+ expect(tasks[0].id).toBe('sys-001');+ });+ });++ describe('groupTasksByStatus', () => {+ it('should group tasks by status', () => {+ const tasks = [+ { id: 'task-001', status: 'pending' },+ { id: 'task-002', status: 'pending' },+ { id: 'task-003', status: 'in_progress' },+ { id: 'task-004', status: 'completed' },+ { id: 'task-005', status: 'blocked' }+ ];++ const grouped = groupTasksByStatus(tasks);++ expect(grouped.pending).toHaveLength(2);+ expect(grouped.in_progress).toHaveLength(1);+ expect(grouped.completed).toHaveLength(1);+ expect(grouped.blocked).toHaveLength(1);+ });++ it('should return empty arrays for missing statuses', () => {+ const tasks = [{ id: 'task-001', status: 'pending' }];+ const grouped = groupTasksByStatus(tasks);++ expect(grouped.in_progress).toHaveLength(0);+ expect(grouped.completed).toHaveLength(0);+ expect(grouped.blocked).toHaveLength(0);+ });++ it('should handle empty array', () => {+ const grouped = groupTasksByStatus([]);++ expect(grouped.pending).toHaveLength(0);+ expect(grouped.in_progress).toHaveLength(0);+ expect(grouped.completed).toHaveLength(0);+ expect(grouped.blocked).toHaveLength(0);+ });+ });++ describe('sortByPriority', () => {+ it('should sort tasks by priority (highest first)', () => {+ const tasks = [+ { id: 'task-001', priorityValue: 1 },+ { id: 'task-002', priorityValue: 4 },+ { id: 'task-003', priorityValue: 2 },+ { id: 'task-004', priorityValue: 3 }+ ];++ const sorted = sortByPriority(tasks);++ expect(sorted[0].priorityValue).toBe(4);+ expect(sorted[1].priorityValue).toBe(3);+ expect(sorted[2].priorityValue).toBe(2);+ expect(sorted[3].priorityValue).toBe(1);+ });++ it('should not mutate original array', () => {+ const tasks = [+ { id: 'task-001', priorityValue: 1 },+ { id: 'task-002', priorityValue: 4 }+ ];+ const original = [...tasks];++ sortByPriority(tasks);++ expect(tasks[0].id).toBe(original[0].id);+ });+ });++ describe('generateTasksMarkdown', () => {+ it('should generate markdown from tasks', () => {+ const tasks = [+ { id: 'task-001', status: 'pending', priority: 'HIGH', priorityValue: 3, description: 'Test task', metadata: {} }+ ];++ const markdown = generateTasksMarkdown(tasks);++ expect(markdown).toContain('# Tasks');+ expect(markdown).toContain('## Pending');+ expect(markdown).toContain('- [ ] #task-001 | HIGH | Test task');+ });++ it('should include approval flags when requested', () => {+ const tasks = [+ { id: 'sys-001', status: 'pending', priority: 'HIGH', priorityValue: 3, description: 'Auto task', metadata: {}, autoApproved: true },+ { id: 'sys-002', status: 'pending', priority: 'MEDIUM', priorityValue: 2, description: 'Approval task', metadata: {}, approvalRequired: true }+ ];++ const markdown = generateTasksMarkdown(tasks, true);++ expect(markdown).toContain('| AUTO |');+ expect(markdown).toContain('| APPROVAL |');+ });++ it('should include metadata in output', () => {+ const tasks = [+ { id: 'task-001', status: 'pending', priority: 'MEDIUM', priorityValue: 2, description: 'Test', metadata: { context: 'Some context', app: 'my-app' } }+ ];++ const markdown = generateTasksMarkdown(tasks);++ expect(markdown).toContain('- Context: Some context');+ expect(markdown).toContain('- App: my-app');+ });++ it('should sort tasks by priority within sections', () => {+ const tasks = [+ { id: 'task-001', status: 'pending', priority: 'LOW', priorityValue: 1, description: 'Low', metadata: {} },+ { id: 'task-002', status: 'pending', priority: 'HIGH', priorityValue: 3, description: 'High', metadata: {} }+ ];++ const markdown = generateTasksMarkdown(tasks);+ const highIndex = markdown.indexOf('High');+ const lowIndex = markdown.indexOf('Low');++ expect(highIndex).toBeLessThan(lowIndex);+ });++ it('should skip empty sections', () => {+ const tasks = [+ { id: 'task-001', status: 'pending', priority: 'MEDIUM', priorityValue: 2, description: 'Test', metadata: {} }+ ];++ const markdown = generateTasksMarkdown(tasks);++ expect(markdown).toContain('## Pending');+ expect(markdown).not.toContain('## In Progress');+ expect(markdown).not.toContain('## Completed');+ });+ });++ describe('getAutoApprovedTasks', () => {+ it('should return only auto-approved pending tasks', () => {+ const tasks = [+ { id: 'sys-001', status: 'pending', autoApproved: true, approvalRequired: false },+ { id: 'sys-002', status: 'pending', autoApproved: false, approvalRequired: true },+ { id: 'sys-003', status: 'completed', autoApproved: true, approvalRequired: false }+ ];++ const autoApproved = getAutoApprovedTasks(tasks);++ expect(autoApproved).toHaveLength(1);+ expect(autoApproved[0].id).toBe('sys-001');+ });+ });++ describe('getAwaitingApprovalTasks', () => {+ it('should return only tasks awaiting approval', () => {+ const tasks = [+ { id: 'sys-001', status: 'pending', autoApproved: true, approvalRequired: false },+ { id: 'sys-002', status: 'pending', autoApproved: false, approvalRequired: true },+ { id: 'sys-003', status: 'pending', autoApproved: false, approvalRequired: true }+ ];++ const awaiting = getAwaitingApprovalTasks(tasks);++ expect(awaiting).toHaveLength(2);+ });+ });++ describe('updateTaskStatus', () => {+ it('should update task status', () => {+ const tasks = [+ { id: 'task-001', status: 'pending', metadata: {} },+ { id: 'task-002', status: 'pending', metadata: {} }+ ];++ const updated = updateTaskStatus(tasks, 'task-001', 'in_progress');++ expect(updated[0].status).toBe('in_progress');+ expect(updated[1].status).toBe('pending');+ });++ it('should merge metadata when updating', () => {+ const tasks = [+ { id: 'task-001', status: 'pending', metadata: { context: 'old' } }+ ];++ const updated = updateTaskStatus(tasks, 'task-001', 'in_progress', { agent: 'agent-123' });++ expect(updated[0].metadata.context).toBe('old');+ expect(updated[0].metadata.agent).toBe('agent-123');+ });++ it('should not mutate original array', () => {+ const tasks = [{ id: 'task-001', status: 'pending', metadata: {} }];+ const updated = updateTaskStatus(tasks, 'task-001', 'completed');++ expect(tasks[0].status).toBe('pending');+ expect(updated[0].status).toBe('completed');+ });+ });++ describe('addTask', () => {+ it('should add a new task', () => {+ const tasks = [];+ const newTasks = addTask(tasks, {+ id: 'new-task',+ priority: 'HIGH',+ description: 'New task'+ });++ expect(newTasks).toHaveLength(1);+ expect(newTasks[0].id).toBe('task-new-task');+ expect(newTasks[0].status).toBe('pending');+ expect(newTasks[0].priority).toBe('HIGH');+ });++ it('should not double-prefix task- ids', () => {+ const tasks = [];+ const newTasks = addTask(tasks, {+ id: 'task-001',+ description: 'Test'+ });++ expect(newTasks[0].id).toBe('task-001');+ });++ it('should default to MEDIUM priority', () => {+ const tasks = [];+ const newTasks = addTask(tasks, {+ id: '001',+ description: 'Test'+ });++ expect(newTasks[0].priority).toBe('MEDIUM');+ expect(newTasks[0].priorityValue).toBe(2);+ });+ });++ describe('removeTask', () => {+ it('should remove task by ID', () => {+ const tasks = [+ { id: 'task-001' },+ { id: 'task-002' },+ { id: 'task-003' }+ ];++ const remaining = removeTask(tasks, 'task-002');++ expect(remaining).toHaveLength(2);+ expect(remaining.find(t => t.id === 'task-002')).toBeUndefined();+ });++ it('should return same array if task not found', () => {+ const tasks = [{ id: 'task-001' }];+ const remaining = removeTask(tasks, 'task-999');++ expect(remaining).toHaveLength(1);+ });+ });++ describe('getNextTask', () => {+ it('should return highest priority pending task', () => {+ const tasks = [+ { id: 'task-001', status: 'pending', priorityValue: 1 },+ { id: 'task-002', status: 'pending', priorityValue: 4 },+ { id: 'task-003', status: 'pending', priorityValue: 2 }+ ];++ const next = getNextTask(tasks);++ expect(next.id).toBe('task-002');+ });++ it('should return null if no pending tasks', () => {+ const tasks = [+ { id: 'task-001', status: 'completed', priorityValue: 4 }+ ];++ const next = getNextTask(tasks);++ expect(next).toBeNull();+ });++ it('should return null for empty array', () => {+ const next = getNextTask([]);+ expect(next).toBeNull();+ });+ });++ describe('validateTask', () => {+ it('should validate a correct task', () => {+ const task = {+ id: 'task-001',+ description: 'Test task',+ status: 'pending',+ priority: 'HIGH'+ };++ const result = validateTask(task);++ expect(result.valid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should reject task without id', () => {+ const task = {+ description: 'Test',+ status: 'pending',+ priority: 'HIGH'+ };++ const result = validateTask(task);++ expect(result.valid).toBe(false);+ expect(result.errors).toContain('Task must have a valid id');+ });++ it('should reject task without description', () => {+ const task = {+ id: 'task-001',+ status: 'pending',+ priority: 'HIGH'+ };++ const result = validateTask(task);++ expect(result.valid).toBe(false);+ expect(result.errors).toContain('Task must have a description');+ });++ it('should reject task with invalid status', () => {+ const task = {+ id: 'task-001',+ description: 'Test',+ status: 'invalid',+ priority: 'HIGH'+ };++ const result = validateTask(task);++ expect(result.valid).toBe(false);+ expect(result.errors).toContain('Invalid task status');+ });++ it('should reject task with invalid priority', () => {+ const task = {+ id: 'task-001',+ description: 'Test',+ status: 'pending',+ priority: 'INVALID'+ };++ const result = validateTask(task);++ expect(result.valid).toBe(false);+ expect(result.errors).toContain('Invalid priority (must be CRITICAL, HIGH, MEDIUM, or LOW)');+ });++ it('should collect multiple errors', () => {+ const task = {+ status: 'invalid',+ priority: 'INVALID'+ };++ const result = validateTask(task);++ expect(result.valid).toBe(false);+ expect(result.errors.length).toBeGreaterThan(2);+ });+ });+});diff --git a/server/routes/cos.js b/server/routes/cos.jsindex 0917c4b77f..3e09a30887 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -6,6 +6,7 @@ import { Router } from 'express';import * as cos from '../services/cos.js';import * as taskWatcher from '../services/taskWatcher.js';import * as appActivity from '../services/appActivity.js';+import * as taskLearning from '../services/taskLearning.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();@@ -290,4 +291,22 @@ router.post('/app-activity/:appId/clear-cooldown', asyncHandler(async (req, res)res.json({ success: true, appId: req.params.appId, activity: result });}));+// GET /api/cos/learning - Get learning insights+router.get('/learning', asyncHandler(async (req, res) => {+ const insights = await taskLearning.getLearningInsights();+ res.json(insights);+}));++// GET /api/cos/learning/durations - Get all task type duration estimates+router.get('/learning/durations', asyncHandler(async (req, res) => {+ const durations = await taskLearning.getAllTaskDurations();+ res.json(durations);+}));++// POST /api/cos/learning/backfill - Backfill learning data from history+router.post('/learning/backfill', asyncHandler(async (req, res) => {+ const count = await taskLearning.backfillFromHistory();+ res.json({ success: true, backfilledCount: count });+}));+export default router;diff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsnew file mode 100644index 0000000000..5ffc03b1a2--- /dev/null+++ b/server/routes/cos.test.js@@ -0,0 +1,571 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import express from 'express';+import request from 'supertest';+import cosRoutes from './cos.js';++// Mock the cos service+vi.mock('../services/cos.js', () => ({+ getStatus: vi.fn(),+ start: vi.fn(),+ stop: vi.fn(),+ pause: vi.fn(),+ resume: vi.fn(),+ getConfig: vi.fn(),+ updateConfig: vi.fn(),+ getAllTasks: vi.fn(),+ getUserTasks: vi.fn(),+ getCosTasks: vi.fn(),+ reorderTasks: vi.fn(),+ addTask: vi.fn(),+ updateTask: vi.fn(),+ deleteTask: vi.fn(),+ approveTask: vi.fn(),+ evaluateTasks: vi.fn(),+ getHealthStatus: vi.fn(),+ runHealthCheck: vi.fn(),+ cleanupZombieAgents: vi.fn(),+ getAgents: vi.fn(),+ getAgent: vi.fn(),+ terminateAgent: vi.fn(),+ killAgent: vi.fn(),+ getAgentProcessStats: vi.fn(),+ deleteAgent: vi.fn(),+ clearCompletedAgents: vi.fn(),+ listReports: vi.fn(),+ getTodayReport: vi.fn(),+ getReport: vi.fn(),+ generateReport: vi.fn(),+ listScripts: vi.fn(),+ getScript: vi.fn()+}));++// Mock the taskWatcher service+vi.mock('../services/taskWatcher.js', () => ({+ startWatching: vi.fn(),+ stopWatching: vi.fn(),+ refreshTasks: vi.fn(),+ getWatcherStatus: vi.fn()+}));++// Mock the appActivity service+vi.mock('../services/appActivity.js', () => ({+ loadAppActivity: vi.fn(),+ getAppActivityById: vi.fn(),+ clearAppCooldown: vi.fn()+}));++// Import mocked modules+import * as cos from '../services/cos.js';+import * as taskWatcher from '../services/taskWatcher.js';+import * as appActivity from '../services/appActivity.js';++describe('CoS Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/cos', cosRoutes);++ // Reset all mocks+ vi.clearAllMocks();+ });++ describe('GET /api/cos', () => {+ it('should return CoS status', async () => {+ const mockStatus = {+ running: true,+ paused: false,+ activeAgents: 2,+ config: {},+ stats: {}+ };+ cos.getStatus.mockResolvedValue(mockStatus);++ const response = await request(app).get('/api/cos');++ expect(response.status).toBe(200);+ expect(response.body.running).toBe(true);+ expect(response.body.activeAgents).toBe(2);+ });+ });++ describe('POST /api/cos/start', () => {+ it('should start CoS daemon', async () => {+ cos.start.mockResolvedValue({ success: true });+ taskWatcher.startWatching.mockResolvedValue();++ const response = await request(app).post('/api/cos/start');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ expect(cos.start).toHaveBeenCalled();+ expect(taskWatcher.startWatching).toHaveBeenCalled();+ });+ });++ describe('POST /api/cos/stop', () => {+ it('should stop CoS daemon', async () => {+ cos.stop.mockResolvedValue({ success: true });+ taskWatcher.stopWatching.mockResolvedValue();++ const response = await request(app).post('/api/cos/stop');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ expect(cos.stop).toHaveBeenCalled();+ expect(taskWatcher.stopWatching).toHaveBeenCalled();+ });+ });++ describe('POST /api/cos/pause', () => {+ it('should pause CoS daemon with reason', async () => {+ cos.pause.mockResolvedValue({ success: true, pausedAt: '2024-01-15T10:00:00Z' });++ const response = await request(app)+ .post('/api/cos/pause')+ .send({ reason: 'User requested pause' });++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ expect(cos.pause).toHaveBeenCalledWith('User requested pause');+ });+ });++ describe('POST /api/cos/resume', () => {+ it('should resume CoS daemon', async () => {+ cos.resume.mockResolvedValue({ success: true });++ const response = await request(app).post('/api/cos/resume');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });+ });++ describe('GET /api/cos/config', () => {+ it('should return configuration', async () => {+ const mockConfig = {+ maxConcurrentAgents: 3,+ evaluationIntervalMs: 60000+ };+ cos.getConfig.mockResolvedValue(mockConfig);++ const response = await request(app).get('/api/cos/config');++ expect(response.status).toBe(200);+ expect(response.body.maxConcurrentAgents).toBe(3);+ });+ });++ describe('PUT /api/cos/config', () => {+ it('should update configuration', async () => {+ const updates = { maxConcurrentAgents: 5 };+ cos.updateConfig.mockResolvedValue({ ...updates });++ const response = await request(app)+ .put('/api/cos/config')+ .send(updates);++ expect(response.status).toBe(200);+ expect(cos.updateConfig).toHaveBeenCalledWith(updates);+ });+ });++ describe('GET /api/cos/tasks', () => {+ it('should return all tasks', async () => {+ const mockTasks = {+ user: { tasks: [], grouped: {} },+ cos: { tasks: [], grouped: {} }+ };+ cos.getAllTasks.mockResolvedValue(mockTasks);++ const response = await request(app).get('/api/cos/tasks');++ expect(response.status).toBe(200);+ expect(response.body).toHaveProperty('user');+ expect(response.body).toHaveProperty('cos');+ });+ });++ describe('POST /api/cos/tasks', () => {+ it('should add a new task', async () => {+ const taskData = {+ description: 'Test task',+ priority: 'HIGH'+ };+ cos.addTask.mockResolvedValue({+ id: 'task-001',+ ...taskData,+ status: 'pending'+ });++ const response = await request(app)+ .post('/api/cos/tasks')+ .send(taskData);++ expect(response.status).toBe(200);+ expect(response.body.id).toBe('task-001');+ expect(cos.addTask).toHaveBeenCalledWith(+ expect.objectContaining({ description: 'Test task' }),+ 'user'+ );+ });++ it('should return 400 if description is missing', async () => {+ const response = await request(app)+ .post('/api/cos/tasks')+ .send({ priority: 'HIGH' });++ expect(response.status).toBe(400);+ });+ });++ describe('POST /api/cos/tasks/reorder', () => {+ it('should reorder tasks', async () => {+ const taskIds = ['task-002', 'task-001', 'task-003'];+ cos.reorderTasks.mockResolvedValue({ success: true, order: taskIds });++ const response = await request(app)+ .post('/api/cos/tasks/reorder')+ .send({ taskIds });++ expect(response.status).toBe(200);+ expect(cos.reorderTasks).toHaveBeenCalledWith(taskIds);+ });++ it('should return 400 if taskIds is missing', async () => {+ const response = await request(app)+ .post('/api/cos/tasks/reorder')+ .send({});++ expect(response.status).toBe(400);+ });++ it('should return 400 if taskIds is not an array', async () => {+ const response = await request(app)+ .post('/api/cos/tasks/reorder')+ .send({ taskIds: 'not-an-array' });++ expect(response.status).toBe(400);+ });+ });++ describe('PUT /api/cos/tasks/:id', () => {+ it('should update a task', async () => {+ const updates = { status: 'completed' };+ cos.updateTask.mockResolvedValue({ id: 'task-001', ...updates });++ const response = await request(app)+ .put('/api/cos/tasks/task-001')+ .send(updates);++ expect(response.status).toBe(200);+ expect(cos.updateTask).toHaveBeenCalledWith('task-001', expect.objectContaining({ status: 'completed' }), 'user');+ });++ it('should return 404 if task not found', async () => {+ cos.updateTask.mockResolvedValue({ error: 'Task not found' });++ const response = await request(app)+ .put('/api/cos/tasks/task-999')+ .send({ status: 'completed' });++ expect(response.status).toBe(404);+ });+ });++ describe('DELETE /api/cos/tasks/:id', () => {+ it('should delete a task', async () => {+ cos.deleteTask.mockResolvedValue({ success: true, taskId: 'task-001' });++ const response = await request(app).delete('/api/cos/tasks/task-001');++ expect(response.status).toBe(200);+ expect(cos.deleteTask).toHaveBeenCalledWith('task-001', 'user');+ });++ it('should return 404 if task not found', async () => {+ cos.deleteTask.mockResolvedValue({ error: 'Task not found' });++ const response = await request(app).delete('/api/cos/tasks/task-999');++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/cos/tasks/:id/approve', () => {+ it('should approve a task', async () => {+ cos.approveTask.mockResolvedValue({ id: 'sys-001', autoApproved: true });++ const response = await request(app).post('/api/cos/tasks/sys-001/approve');++ expect(response.status).toBe(200);+ expect(cos.approveTask).toHaveBeenCalledWith('sys-001');+ });++ it('should return 400 if task does not require approval', async () => {+ cos.approveTask.mockResolvedValue({ error: 'Task does not require approval' });++ const response = await request(app).post('/api/cos/tasks/task-001/approve');++ expect(response.status).toBe(400);+ });+ });++ describe('POST /api/cos/evaluate', () => {+ it('should trigger task evaluation', async () => {+ cos.evaluateTasks.mockResolvedValue();++ const response = await request(app).post('/api/cos/evaluate');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ expect(cos.evaluateTasks).toHaveBeenCalled();+ });+ });++ describe('GET /api/cos/agents', () => {+ it('should return all agents after cleaning zombies', async () => {+ cos.cleanupZombieAgents.mockResolvedValue({ cleaned: [], count: 0 });+ cos.getAgents.mockResolvedValue([+ { id: 'agent-001', status: 'running' },+ { id: 'agent-002', status: 'completed' }+ ]);++ const response = await request(app).get('/api/cos/agents');++ expect(response.status).toBe(200);+ expect(response.body).toHaveLength(2);+ expect(cos.cleanupZombieAgents).toHaveBeenCalled();+ });+ });++ describe('GET /api/cos/agents/:id', () => {+ it('should return agent by ID', async () => {+ cos.getAgent.mockResolvedValue({ id: 'agent-001', status: 'running' });++ const response = await request(app).get('/api/cos/agents/agent-001');++ expect(response.status).toBe(200);+ expect(response.body.id).toBe('agent-001');+ });++ it('should return 404 if agent not found', async () => {+ cos.getAgent.mockResolvedValue(null);++ const response = await request(app).get('/api/cos/agents/agent-999');++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/cos/agents/:id/terminate', () => {+ it('should terminate agent', async () => {+ cos.terminateAgent.mockResolvedValue({ success: true, agentId: 'agent-001' });++ const response = await request(app).post('/api/cos/agents/agent-001/terminate');++ expect(response.status).toBe(200);+ expect(cos.terminateAgent).toHaveBeenCalledWith('agent-001');+ });+ });++ describe('POST /api/cos/agents/:id/kill', () => {+ it('should force kill agent', async () => {+ cos.killAgent.mockResolvedValue({ success: true, agentId: 'agent-001', signal: 'SIGKILL' });++ const response = await request(app).post('/api/cos/agents/agent-001/kill');++ expect(response.status).toBe(200);+ expect(cos.killAgent).toHaveBeenCalledWith('agent-001');+ });++ it('should return 404 if agent not found', async () => {+ cos.killAgent.mockResolvedValue({ error: 'Agent not found or not running' });++ const response = await request(app).post('/api/cos/agents/agent-999/kill');++ expect(response.status).toBe(404);+ });+ });++ describe('GET /api/cos/agents/:id/stats', () => {+ it('should return agent process stats', async () => {+ cos.getAgentProcessStats.mockResolvedValue({+ active: true,+ pid: 12345,+ cpu: 5.2,+ memoryMb: 128+ });++ const response = await request(app).get('/api/cos/agents/agent-001/stats');++ expect(response.status).toBe(200);+ expect(response.body.active).toBe(true);+ });++ it('should return active:false if no stats available', async () => {+ cos.getAgentProcessStats.mockResolvedValue(null);++ const response = await request(app).get('/api/cos/agents/agent-999/stats');++ expect(response.status).toBe(200);+ expect(response.body.active).toBe(false);+ });+ });++ describe('DELETE /api/cos/agents/:id', () => {+ it('should delete an agent', async () => {+ cos.deleteAgent.mockResolvedValue({ success: true, agentId: 'agent-001' });++ const response = await request(app).delete('/api/cos/agents/agent-001');++ expect(response.status).toBe(200);+ expect(cos.deleteAgent).toHaveBeenCalledWith('agent-001');+ });++ it('should return 404 if agent not found', async () => {+ cos.deleteAgent.mockResolvedValue({ error: 'Agent not found' });++ const response = await request(app).delete('/api/cos/agents/agent-999');++ expect(response.status).toBe(404);+ });+ });++ describe('GET /api/cos/health', () => {+ it('should return health status', async () => {+ cos.getHealthStatus.mockResolvedValue({+ lastCheck: '2024-01-15T10:00:00Z',+ issues: []+ });++ const response = await request(app).get('/api/cos/health');++ expect(response.status).toBe(200);+ expect(response.body).toHaveProperty('lastCheck');+ });+ });++ describe('POST /api/cos/health/check', () => {+ it('should force health check', async () => {+ cos.runHealthCheck.mockResolvedValue({+ metrics: {},+ issues: []+ });++ const response = await request(app).post('/api/cos/health/check');++ expect(response.status).toBe(200);+ expect(cos.runHealthCheck).toHaveBeenCalled();+ });+ });++ describe('GET /api/cos/reports', () => {+ it('should list all reports', async () => {+ cos.listReports.mockResolvedValue(['2024-01-15', '2024-01-14']);++ const response = await request(app).get('/api/cos/reports');++ expect(response.status).toBe(200);+ expect(response.body).toHaveLength(2);+ });+ });++ describe('GET /api/cos/reports/today', () => {+ it('should return today report', async () => {+ cos.getTodayReport.mockResolvedValue({+ date: '2024-01-15',+ summary: { tasksCompleted: 5 }+ });++ const response = await request(app).get('/api/cos/reports/today');++ expect(response.status).toBe(200);+ expect(response.body).toHaveProperty('summary');+ });+ });++ describe('GET /api/cos/reports/:date', () => {+ it('should return report by date', async () => {+ cos.getReport.mockResolvedValue({+ date: '2024-01-14',+ summary: {}+ });++ const response = await request(app).get('/api/cos/reports/2024-01-14');++ expect(response.status).toBe(200);+ });++ it('should return 404 if report not found', async () => {+ cos.getReport.mockResolvedValue(null);++ const response = await request(app).get('/api/cos/reports/1999-01-01');++ expect(response.status).toBe(404);+ });+ });++ describe('GET /api/cos/watcher', () => {+ it('should return watcher status', async () => {+ taskWatcher.getWatcherStatus.mockReturnValue({+ watching: true,+ files: ['TASKS.md']+ });++ const response = await request(app).get('/api/cos/watcher');++ expect(response.status).toBe(200);+ expect(response.body.watching).toBe(true);+ });+ });++ describe('GET /api/cos/app-activity', () => {+ it('should return app activity data', async () => {+ appActivity.loadAppActivity.mockResolvedValue({+ 'app-001': { lastReview: '2024-01-15T10:00:00Z' }+ });++ const response = await request(app).get('/api/cos/app-activity');++ expect(response.status).toBe(200);+ });+ });++ describe('GET /api/cos/app-activity/:appId', () => {+ it('should return activity for specific app', async () => {+ appActivity.getAppActivityById.mockResolvedValue({+ lastReview: '2024-01-15T10:00:00Z'+ });++ const response = await request(app).get('/api/cos/app-activity/app-001');++ expect(response.status).toBe(200);+ expect(response.body.appId).toBe('app-001');+ });++ it('should return message if no activity', async () => {+ appActivity.getAppActivityById.mockResolvedValue(null);++ const response = await request(app).get('/api/cos/app-activity/app-999');++ expect(response.status).toBe(200);+ expect(response.body.activity).toBeNull();+ expect(response.body.message).toBeDefined();+ });+ });++ describe('POST /api/cos/app-activity/:appId/clear-cooldown', () => {+ it('should clear cooldown for app', async () => {+ appActivity.clearAppCooldown.mockResolvedValue({ cooldownCleared: true });++ const response = await request(app).post('/api/cos/app-activity/app-001/clear-cooldown');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ expect(appActivity.clearAppCooldown).toHaveBeenCalledWith('app-001');+ });+ });+});diff --git a/server/routes/screenshots.js b/server/routes/screenshots.jsindex f3b65ec3e5..c7318a7414 100644--- a/server/routes/screenshots.js+++ b/server/routes/screenshots.js@@ -1,17 +1,34 @@import { Router } from 'express';import { writeFile, mkdir } from 'fs/promises';import { existsSync } from 'fs';-import { join, dirname } from 'path';+import { join, dirname, resolve, basename } from 'path';import { fileURLToPath } from 'url';import { v4 as uuidv4 } from 'uuid';import { asyncHandler, ServerError } from '../lib/errorHandler.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);-const SCREENSHOTS_DIR = join(__dirname, '../../data/screenshots');+const SCREENSHOTS_DIR = resolve(__dirname, '../../data/screenshots');const router = Router();+/**+ * Validate and sanitize filename to prevent path traversal+ * @param {string} filename - User-provided filename+ * @returns {string} - Safe filename+ */+function sanitizeFilename(filename) {+ // Get just the base filename, removing any path components+ const base = basename(filename);+ // Remove any remaining path traversal attempts or special characters+ const sanitized = base.replace(/[^a-zA-Z0-9._-]/g, '_');+ // Ensure it doesn't start with a dot (hidden files)+ if (sanitized.startsWith('.')) {+ return '_' + sanitized.slice(1);+ }+ return sanitized;+}+// Max file size: 10MBconst MAX_FILE_SIZE = 10 * 1024 * 1024;@@ -72,9 +89,18 @@ router.post('/', asyncHandler(async (req, res) => {const id = uuidv4();const ext = detectedType; // Use detected type, not client-provided- const fname = filename || `screenshot-${id}.${ext}`;+ // Sanitize user-provided filename or generate a safe one+ const safeName = filename ? sanitizeFilename(filename) : `screenshot-${id}.${ext}`;+ // Ensure extension matches detected type+ const fname = safeName.endsWith(`.${ext}`) ? safeName : `${safeName}.${ext}`;const filepath = join(SCREENSHOTS_DIR, fname);+ // Double-check path is within screenshots directory (defense in depth)+ const resolvedPath = resolve(filepath);+ if (!resolvedPath.startsWith(SCREENSHOTS_DIR)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }+await writeFile(filepath, buffer);console.log(`📸 Screenshot saved: ${fname} (${buffer.length} bytes)`);@@ -90,14 +116,22 @@ router.post('/', asyncHandler(async (req, res) => {// GET /api/screenshots/:filename - Serve a screenshotrouter.get('/:filename', asyncHandler(async (req, res) => {const { filename } = req.params;- const filepath = join(SCREENSHOTS_DIR, filename);+ // Sanitize filename to prevent path traversal+ const safeFilename = sanitizeFilename(filename);+ const filepath = resolve(SCREENSHOTS_DIR, safeFilename);++ // Verify the resolved path is within screenshots directory+ if (!filepath.startsWith(SCREENSHOTS_DIR)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }if (!existsSync(filepath)) {throw new ServerError('Screenshot not found', { status: 404, code: 'NOT_FOUND' });}- const ext = filename.split('.').pop().toLowerCase();- const mimeType = ext === 'png' ? 'image/png' : 'image/jpeg';+ const ext = safeFilename.split('.').pop().toLowerCase();+ const mimeTypes = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp' };+ const mimeType = mimeTypes[ext] || 'application/octet-stream';res.type(mimeType).sendFile(filepath);}));diff --git a/server/services/cos.js b/server/services/cos.jsindex c6e3e1ab7f..b3837ee7a0 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -35,15 +35,22 @@ export const cosEvents = new EventEmitter();/*** Emit a log event for UI display+ * Exported for use by other CoS-related services+ * @param {string} level - Log level: 'info', 'warn', 'error', 'success', 'debug'+ * @param {string} message - Log message+ * @param {Object} data - Additional data to include in log entry+ * @param {string} prefix - Optional prefix for console output (e.g., '[SelfImprovement]')*/-function emitLog(level, message, data = {}) {+export function emitLog(level, message, data = {}, prefix = '') {const logEntry = {timestamp: new Date().toISOString(),- level, // 'info', 'warn', 'error', 'success', 'debug'+ level,message,...data};- console.log(`${level === 'error' ? '❌' : level === 'warn' ? '⚠️' : level === 'success' ? '✅' : 'ℹ️'} ${message}`);+ const emoji = level === 'error' ? '❌' : level === 'warn' ? '⚠️' : level === 'success' ? '✅' : 'ℹ️';+ const prefixStr = prefix ? ` ${prefix}` : '';+ console.log(`${emoji}${prefixStr} ${message}`);cosEvents.emit('log', logEntry);}@@ -72,27 +79,29 @@ async function withStateLock(fn) {const DEFAULT_CONFIG = {userTasksFile: 'data/TASKS.md', // User-defined taskscosTasksFile: 'data/COS-TASKS.md', // CoS internal/system tasks- evaluationIntervalMs: 60000, // 1 minute (also used for idle check frequency)- healthCheckIntervalMs: 900000, // 15 minutes+ goalsFile: 'data/COS-GOALS.md', // Mission and goals file+ evaluationIntervalMs: 60000, // 1 minute - stay active, check frequently+ healthCheckIntervalMs: 900000, // 15 minutesmaxConcurrentAgents: 3,- maxProcessMemoryMb: 2048, // Alert if any process exceeds this- maxTotalProcesses: 50, // Alert if total PM2 processes exceed this+ maxProcessMemoryMb: 2048, // Alert if any process exceeds this+ maxTotalProcesses: 50, // Alert if total PM2 processes exceed thismcpServers: [{ name: 'filesystem', command: 'npx', args: ['-y', '@anthropic/mcp-server-filesystem'] },{ name: 'puppeteer', command: 'npx', args: ['-y', '@anthropic/mcp-puppeteer', '--isolated'] }],- autoStart: false, // Legacy: use alwaysOn instead- selfImprovementEnabled: true, // Allow CoS to suggest improvements to its own prompts- avatarStyle: 'svg', // UI preference: 'svg' or 'ascii'+ autoStart: false, // Legacy: use alwaysOn instead+ selfImprovementEnabled: true, // Allow CoS to suggest improvements to its own prompts+ avatarStyle: 'svg', // UI preference: 'svg' or 'ascii'// Always-on mode settings- alwaysOn: true, // CoS starts automatically and stays active- appReviewCooldownMs: 3600000, // 1 hour between working on same app- idleReviewEnabled: true, // Review apps for improvements when no user tasks- idleReviewPriority: 'LOW', // Priority for auto-generated review tasks- immediateExecution: true, // Execute new tasks immediately, don't wait for interval+ alwaysOn: true, // CoS starts automatically and stays active+ appReviewCooldownMs: 1800000, // 30 min between working on same app (was 1 hour)+ idleReviewEnabled: true, // Review apps for improvements when no user tasks+ idleReviewPriority: 'MEDIUM', // Priority for auto-generated tasks (was LOW)+ immediateExecution: true, // Execute new tasks immediately, don't wait for interval+ proactiveMode: true, // Be proactive about finding workautoFixThresholds: {- maxLinesChanged: 50, // Auto-approve if <= this many lines changed- allowedCategories: [ // Categories that can auto-execute+ maxLinesChanged: 50, // Auto-approve if <= this many lines changed+ allowedCategories: [ // Categories that can auto-execute'formatting','dry-violations','dead-code',@@ -410,6 +419,27 @@ export async function getAllTasks() {*/export const getTasks = getUserTasks;+/**+ * Get a specific task by ID from any task source+ */+export async function getTaskById(taskId) {+ const { user: userTasks, cos: cosTasks } = await getAllTasks();++ // Search user tasks+ const userTask = userTasks.tasks?.find(t => t.id === taskId);+ if (userTask) {+ return { ...userTask, taskType: 'user' };+ }++ // Search CoS internal tasks+ const cosTask = cosTasks.tasks?.find(t => t.id === taskId);+ if (cosTask) {+ return { ...cosTask, taskType: 'internal' };+ }++ return null;+}+/*** Reset orphaned in_progress tasks back to pending* (tasks marked in_progress but no running agent)@@ -566,60 +596,407 @@ export async function evaluateTasks() {}/**- * Generate an idle review task when no user/system tasks are pending+ * Generate an idle task when no user/system tasks are pending+ * Alternates between:+ * 1. Self-improvement tasks (UI analysis, security, code quality)+ * 2. App reviews for managed apps** @param {Object} state - Current CoS state- * @returns {Object|null} Generated task or null if no apps eligible+ * @returns {Object|null} Generated task or null if nothing to do*/async function generateIdleReviewTask(state) {+ // Check if we should run self-improvement (alternates with app reviews)+ const lastSelfImprovementTime = state.stats.lastSelfImprovement+ ? new Date(state.stats.lastSelfImprovement).getTime()+ : 0;+ const lastIdleReviewTime = state.stats.lastIdleReview+ ? new Date(state.stats.lastIdleReview).getTime()+ : 0;++ // Prioritize self-improvement if it hasn't run recently (or ever)+ const shouldRunSelfImprovement = lastSelfImprovementTime <= lastIdleReviewTime;++ if (shouldRunSelfImprovement && state.config.selfImprovementEnabled) {+ const selfImprovementTask = await generateSelfImprovementTask(state);+ if (selfImprovementTask) {+ return selfImprovementTask;+ }+ }++ // Try app reviews// Get all managed appsconst apps = await getAllApps().catch(() => []);- if (apps.length === 0) {- emitLog('debug', 'No managed apps found for idle review');- return null;- }+ if (apps.length > 0) {+ // Find next app eligible for review (not on cooldown, oldest review first)+ const nextApp = await getNextAppForReview(apps, state.config.appReviewCooldownMs);- // Find next app eligible for review (not on cooldown, oldest review first)- const nextApp = await getNextAppForReview(apps, state.config.appReviewCooldownMs);+ if (nextApp) {+ // Mark that we're starting an idle review+ await markIdleReviewStarted();+ await markAppReviewStarted(nextApp.id, `idle-review-${Date.now()}`);- if (!nextApp) {- emitLog('debug', 'All apps on cooldown - no idle review possible');- return null;+ // Update lastIdleReview timestamp+ await withStateLock(async () => {+ const s = await loadState();+ s.stats.lastIdleReview = new Date().toISOString();+ await saveState(s);+ });++ emitLog('info', `Generating idle review task for ${nextApp.name}`, { appId: nextApp.id });++ // Create an idle review task+ return {+ id: `idle-review-${nextApp.id}-${Date.now().toString(36)}`,+ status: 'pending',+ priority: state.config.idleReviewPriority || 'MEDIUM',+ priorityValue: PRIORITY_VALUES[state.config.idleReviewPriority] || 2,+ description: `[Idle Review] Review ${nextApp.name} codebase for improvements: formatting issues, dead code, DRY violations, typos, and other small fixes that can be auto-approved`,+ metadata: {+ app: nextApp.id,+ appName: nextApp.name,+ repoPath: nextApp.repoPath,+ reviewType: 'idle',+ autoGenerated: true+ },+ taskType: 'internal',+ autoApproved: true+ };+ }}- // Mark that we're starting an idle review- await markIdleReviewStarted();- await markAppReviewStarted(nextApp.id, `idle-review-${Date.now()}`);+ // All apps on cooldown or no apps - fall back to self-improvement+ // This ensures CoS is ALWAYS working on something+ if (state.config.selfImprovementEnabled) {+ emitLog('info', 'No apps available for review - running self-improvement instead');+ return await generateSelfImprovementTask(state);+ }++ emitLog('debug', 'No idle tasks available');+ return null;+}++// Self-improvement task types (rotates through these)+// Organized by goal priority from COS-GOALS.md+const SELF_IMPROVEMENT_TYPES = [+ // Goal 1: Codebase Quality+ 'ui-bugs',+ 'mobile-responsive',+ 'security',+ 'code-quality',+ 'console-errors',+ 'performance',+ // Goal 2: Self-Improvement (CoS enhancing itself)+ 'cos-enhancement',+ 'test-coverage',+ // Goal 3: Documentation+ 'documentation',+ // Goal 4: User Engagement+ 'feature-ideas',+ // Goal 5: System Health+ 'accessibility'+];++/**+ * Generate a self-improvement task for PortOS itself+ * Uses Playwright and Opus to analyze and fix issues+ */+async function generateSelfImprovementTask(state) {+ // Get the next analysis type in rotation+ const lastType = state.stats.lastSelfImprovementType || '';+ const currentIndex = SELF_IMPROVEMENT_TYPES.indexOf(lastType);+ const nextType = SELF_IMPROVEMENT_TYPES[(currentIndex + 1) % SELF_IMPROVEMENT_TYPES.length];- // Update lastIdleReview timestamp+ // Update state with new timestamp and typeawait withStateLock(async () => {const s = await loadState();- s.stats.lastIdleReview = new Date().toISOString();+ s.stats.lastSelfImprovement = new Date().toISOString();+ s.stats.lastSelfImprovementType = nextType;await saveState(s);});- emitLog('info', `Generating idle review task for ${nextApp.name}`, { appId: nextApp.id });+ emitLog('info', `Generating self-improvement task: ${nextType}`);++ const taskDescriptions = {+ 'ui-bugs': `[Self-Improvement] UI Bug Analysis++Use Playwright MCP (browser_navigate, browser_snapshot, browser_console_messages) to analyze PortOS UI:++1. Navigate to http://localhost:5555/+2. Check each main route: /, /apps, /cos, /cos/tasks, /cos/agents, /devtools, /devtools/history, /providers, /usage+3. For each route:+ - Take a browser_snapshot to see the page structure+ - Check browser_console_messages for JavaScript errors+ - Look for broken UI elements, missing data, failed requests+4. Fix any bugs found in the React components or API routes+5. Run tests and commit changes++Use model: claude-opus-4-5-20251101 for thorough analysis`,++ 'mobile-responsive': `[Self-Improvement] Mobile Responsiveness Analysis++Use Playwright MCP to test PortOS at different viewport sizes:++1. browser_resize to mobile (375x812), then navigate to http://localhost:5555/+2. Take browser_snapshot and analyze for:+ - Text overflow or truncation+ - Buttons too small to tap (< 44px)+ - Horizontal scrolling issues+ - Elements overlapping+ - Navigation usability+3. Repeat at tablet (768x1024) and desktop (1440x900)+4. Fix Tailwind CSS responsive classes (sm:, md:, lg:) as needed+5. Test fixes and commit changes++Focus on these routes: /cos, /cos/tasks, /devtools, /providers++Use model: claude-opus-4-5-20251101 for comprehensive fixes`,++ 'security': `[Self-Improvement] Security Audit++Analyze PortOS codebase for security vulnerabilities:++1. Review server/routes/*.js for:+ - Command injection in exec/spawn calls+ - Path traversal in file operations+ - Missing input validation+ - XSS in rendered content++2. Review server/services/*.js for:+ - Unsafe eval() or Function()+ - Hardcoded credentials+ - SQL/NoSQL injection++3. Review client/src/ for:+ - XSS vulnerabilities in React+ - Sensitive data in localStorage+ - CSRF protection++4. Check server/lib/commandAllowlist.js is comprehensive++Fix any vulnerabilities and commit with security advisory notes.++Use model: claude-opus-4-5-20251101 for thorough security analysis`,++ 'code-quality': `[Self-Improvement] Code Quality Review++Analyze PortOS codebase for maintainability:++1. Find DRY violations - similar code in multiple places+2. Identify functions >50 lines that should be split+3. Look for missing error handling+4. Find dead code and unused imports+5. Check for console.log that should be removed+6. Look for TODO/FIXME that need addressing++Focus on:+- server/services/*.js+- client/src/pages/*.jsx+- client/src/components/*.jsx++Refactor issues found and commit improvements.++Use model: claude-opus-4-5-20251101 for quality refactoring`,++ 'accessibility': `[Self-Improvement] Accessibility Audit++Use Playwright MCP to audit PortOS accessibility:++1. Navigate to http://localhost:5555/+2. Use browser_snapshot to get accessibility tree+3. Check each main route for:+ - Missing ARIA labels+ - Missing alt text on images+ - Insufficient color contrast+ - Keyboard navigation issues+ - Focus indicators- // Create an idle review task- const reviewTask = {- id: `idle-review-${nextApp.id}-${Date.now().toString(36)}`,+4. Fix accessibility issues in React components+5. Add appropriate aria-* attributes+6. Test and commit changes++Use model: claude-opus-4-5-20251101 for comprehensive a11y fixes`,++ 'console-errors': `[Self-Improvement] Console Error Investigation++Use Playwright MCP to find and fix console errors:++1. Navigate to http://localhost:5555/+2. Call browser_console_messages with level: "error"+3. Visit each route and capture errors:+ - /, /apps, /cos, /cos/tasks, /cos/agents+ - /devtools, /devtools/history, /devtools/runner+ - /providers, /usage, /prompts++4. For each error:+ - Identify the source file and line+ - Understand the root cause+ - Implement a fix++5. Test fixes and commit changes++Use model: claude-opus-4-5-20251101 for thorough debugging`,++ 'performance': `[Self-Improvement] Performance Analysis++Analyze PortOS for performance issues:++1. Review React components for:+ - Unnecessary re-renders+ - Missing useMemo/useCallback+ - Large component files that should be split++2. Review server code for:+ - N+1 query patterns+ - Missing caching opportunities+ - Inefficient file operations++3. Review client bundle for:+ - Missing code splitting+ - Large dependencies that could be tree-shaken++4. Check Socket.IO for:+ - Event handler memory leaks+ - Unnecessary broadcasts++Optimize and commit improvements.++Use model: claude-opus-4-5-20251101 for performance optimization`,++ 'cos-enhancement': `[Self-Improvement] Enhance CoS Capabilities++Review the CoS system and add new capabilities:++1. Read data/COS-GOALS.md to understand the mission and goals+2. Review server/services/cos.js for improvement opportunities:+ - Better task prioritization logic+ - Smarter model selection+ - More informative status messages+ - Better error recovery++3. Review the self-improvement task prompts:+ - Are they comprehensive enough?+ - Do they lead to quality fixes?+ - What new analysis types could be added?++4. Consider adding:+ - New MCP server integrations+ - Better metrics tracking+ - Learning from completed tasks+ - Smarter cooldown logic++5. Implement ONE meaningful enhancement and commit it++Focus on making CoS more autonomous and effective.++Use model: claude-opus-4-5-20251101 for thoughtful enhancement`,++ 'test-coverage': `[Self-Improvement] Improve Test Coverage++Analyze and improve test coverage for PortOS:++1. Check existing tests in server/tests/ and client/tests/+2. Identify untested critical paths:+ - API routes without tests+ - Services with complex logic+ - Error handling paths++3. Add tests for:+ - CoS task evaluation logic+ - Agent spawning and lifecycle+ - Socket.IO event handlers+ - API endpoints++4. Ensure tests:+ - Follow existing patterns+ - Use appropriate mocks+ - Test edge cases++Run npm test to verify all tests pass.++Use model: claude-opus-4-5-20251101 for comprehensive test design`,++ 'documentation': `[Self-Improvement] Update Documentation++Review and improve PortOS documentation:++1. Update PLAN.md:+ - Mark completed milestones+ - Add any new features implemented+ - Document architectural decisions++2. Check docs/ folder:+ - Are all features documented?+ - Is the information current?+ - Add any missing guides++3. Review code comments:+ - Add JSDoc to exported functions+ - Document complex algorithms+ - Explain non-obvious code++4. Update README.md if needed:+ - Installation instructions+ - Quick start guide+ - Feature overview++5. Consider adding:+ - Architecture diagrams+ - API documentation+ - Troubleshooting guide++Commit documentation improvements.++Use model: claude-opus-4-5-20251101 for clear documentation`,++ 'feature-ideas': `[Self-Improvement] Brainstorm and Implement Feature++Think about ways to make PortOS more useful:++1. Read data/COS-GOALS.md for context on user goals+2. Review recent completed tasks to understand patterns+3. Consider these areas:+ - User task management improvements+ - Better progress visualization+ - New automation capabilities+ - Enhanced monitoring features++4. Choose ONE small, high-impact feature to implement:+ - Something that saves user time+ - Improves the developer experience+ - Makes CoS more helpful++5. Implement it:+ - Write clean, tested code+ - Follow existing patterns+ - Update relevant documentation++6. Commit with a clear description of the new feature++Think creatively but implement practically.++Use model: claude-opus-4-5-20251101 for creative feature development`+ };++ const description = taskDescriptions[nextType];++ const task = {+ id: `self-improve-${nextType}-${Date.now().toString(36)}`,status: 'pending',- priority: state.config.idleReviewPriority || 'LOW',- priorityValue: PRIORITY_VALUES[state.config.idleReviewPriority] || 1,- description: `[Idle Review] Review ${nextApp.name} codebase for improvements: formatting issues, dead code, DRY violations, typos, and other small fixes that can be auto-approved`,+ priority: 'MEDIUM',+ priorityValue: PRIORITY_VALUES['MEDIUM'],+ description,metadata: {- app: nextApp.id,- appName: nextApp.name,- repoPath: nextApp.repoPath,- reviewType: 'idle',- autoGenerated: true+ analysisType: nextType,+ autoGenerated: true,+ selfImprovement: true,+ model: 'claude-opus-4-5-20251101'},taskType: 'internal',- autoApproved: true // Idle reviews are auto-approved to start, but individual fixes need classification+ autoApproved: true};- return reviewTask;+ return task;}/**@@ -1205,8 +1582,12 @@ export async function updateTask(taskId, updates, taskType = 'user') {return { error: 'Task not found' };}- // Build updated metadata- const updatedMetadata = { ...tasks[taskIndex].metadata };+ // Build updated metadata - merge existing with any new metadata+ const updatedMetadata = {+ ...tasks[taskIndex].metadata,+ ...(updates.metadata || {})+ };+ // Handle legacy fields that may be passed directly in updatesif (updates.context !== undefined) updatedMetadata.context = updates.context || undefined;if (updates.model !== undefined) updatedMetadata.model = updates.model || undefined;if (updates.provider !== undefined) updatedMetadata.provider = updates.provider || undefined;diff --git a/server/services/git.js b/server/services/git.jsindex 50c5698351..a315c35d1f 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -1,13 +1,50 @@-import { exec } from 'child_process';-import { promisify } from 'util';+import { spawn } from 'child_process';-const execAsync = promisify(exec);+/**+ * Execute a git command safely using spawn (prevents shell injection)+ * @param {string[]} args - Git command arguments+ * @param {string} cwd - Working directory+ * @param {object} options - Additional options+ * @returns {Promise<{stdout: string, stderr: string}>}+ */+function execGit(args, cwd, options = {}) {+ return new Promise((resolve, reject) => {+ const child = spawn('git', args, {+ cwd,+ shell: false,+ maxBuffer: options.maxBuffer || 10 * 1024 * 1024+ });++ let stdout = '';+ let stderr = '';++ child.stdout.on('data', (data) => {+ stdout += data.toString();+ });++ child.stderr.on('data', (data) => {+ stderr += data.toString();+ });++ child.on('close', (code) => {+ if (code !== 0 && !options.ignoreExitCode) {+ reject(new Error(stderr || `git exited with code ${code}`));+ } else {+ resolve({ stdout, stderr });+ }+ });++ child.on('error', (err) => {+ reject(err);+ });+ });+}/*** Get git status for a directory*/export async function getStatus(dir) {- const result = await execAsync('git status --porcelain', { cwd: dir });+ const result = await execGit(['status', '--porcelain'], dir);const lines = result.stdout.trim().split('\n').filter(Boolean);const files = lines.map(line => {@@ -52,7 +89,7 @@ function parseStatus(status) {* Get current branch name*/export async function getBranch(dir) {- const result = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: dir });+ const result = await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], dir);return result.stdout.trim();}@@ -60,8 +97,10 @@ export async function getBranch(dir) {* Get recent commits*/export async function getCommits(dir, limit = 10) {+ // Validate limit is a positive integer to prevent injection+ const safeLimit = Math.max(1, Math.min(100, parseInt(limit, 10) || 10));const format = '--format={"hash":"%h","message":"%s","author":"%an","date":"%ci"}';- const result = await execAsync(`git log ${format} -n ${limit}`, { cwd: dir });+ const result = await execGit(['log', format, '-n', String(safeLimit)], dir);const commits = result.stdout.trim().split('\n').filter(Boolean).map(line => {return JSON.parse(line);@@ -74,8 +113,8 @@ export async function getCommits(dir, limit = 10) {* Get diff for unstaged changes*/export async function getDiff(dir, staged = false) {- const cmd = staged ? 'git diff --cached' : 'git diff';- const result = await execAsync(cmd, { cwd: dir, maxBuffer: 10 * 1024 * 1024 });+ const args = staged ? ['diff', '--cached'] : ['diff'];+ const result = await execGit(args, dir, { maxBuffer: 10 * 1024 * 1024 });return result.stdout;}@@ -83,7 +122,7 @@ export async function getDiff(dir, staged = false) {* Get diff stats*/export async function getDiffStats(dir) {- const result = await execAsync('git diff --stat', { cwd: dir });+ const result = await execGit(['diff', '--stat'], dir);const statsLine = result.stdout.trim().split('\n').pop() || '';const filesMatch = statsLine.match(/(\d+) files? changed/);@@ -97,12 +136,32 @@ export async function getDiffStats(dir) {};}+/**+ * Validate file paths to prevent command injection and path traversal+ * @param {string[]} files - Array of file paths+ * @returns {string[]} - Sanitized file paths+ */+function validateFilePaths(files) {+ const fileList = Array.isArray(files) ? files : [files];+ return fileList.map(f => {+ // Reject paths with null bytes or command separators+ if (/[\0;|&`$]/.test(f)) {+ throw new Error(`Invalid character in file path: ${f}`);+ }+ // Reject absolute paths or parent directory traversal+ if (f.startsWith('/') || f.includes('..')) {+ throw new Error(`Invalid file path: ${f}`);+ }+ return f;+ });+}+/*** Stage files*/export async function stageFiles(dir, files) {- const paths = Array.isArray(files) ? files.join(' ') : files;- await execAsync(`git add ${paths}`, { cwd: dir });+ const safePaths = validateFilePaths(files);+ await execGit(['add', '--', ...safePaths], dir);return true;}@@ -110,8 +169,8 @@ export async function stageFiles(dir, files) {* Unstage files*/export async function unstageFiles(dir, files) {- const paths = Array.isArray(files) ? files.join(' ') : files;- await execAsync(`git reset HEAD ${paths}`, { cwd: dir });+ const safePaths = validateFilePaths(files);+ await execGit(['reset', 'HEAD', '--', ...safePaths], dir);return true;}@@ -119,7 +178,8 @@ export async function unstageFiles(dir, files) {* Create commit*/export async function commit(dir, message) {- const result = await execAsync(`git commit -m "${message.replace(/"/g, '\\"')}"`, { cwd: dir });+ // Using spawn with -m argument passes message safely without shell interpretation+ const result = await execGit(['commit', '-m', message], dir);const hashMatch = result.stdout.match(/\[[\w-]+ ([a-f0-9]+)\]/);return {hash: hashMatch ? hashMatch[1] : null,@@ -131,7 +191,7 @@ export async function commit(dir, message) {* Check if directory is a git repo*/export async function isRepo(dir) {- const result = await execAsync('git rev-parse --is-inside-work-tree', { cwd: dir }).catch(() => null);+ const result = await execGit(['rev-parse', '--is-inside-work-tree'], dir, { ignoreExitCode: true }).catch(() => null);return result?.stdout.trim() === 'true';}@@ -139,7 +199,7 @@ export async function isRepo(dir) {* Get remote info*/export async function getRemote(dir) {- const result = await execAsync('git remote -v', { cwd: dir }).catch(() => null);+ const result = await execGit(['remote', '-v'], dir, { ignoreExitCode: true }).catch(() => null);if (!result) return null;const lines = result.stdout.trim().split('\n');diff --git a/server/services/memory.js b/server/services/memory.jsindex 84d1eb77fb..9ae86e5b19 100644--- a/server/services/memory.js+++ b/server/services/memory.js@@ -26,7 +26,7 @@ export const DEFAULT_MEMORY_CONFIG = {enabled: true,embeddingProvider: 'lmstudio',embeddingEndpoint: 'http://localhost:1234/v1/embeddings',- embeddingModel: 'nomic-embed-text-v1.5',+ embeddingModel: 'text-embedding-nomic-embed-text-v2-moe',embeddingDimension: 768,maxMemories: 10000,maxContextTokens: 2000,diff --git a/server/services/selfImprovement.js b/server/services/selfImprovement.jsnew file mode 100644index 0000000000..27e05a7c09--- /dev/null+++ b/server/services/selfImprovement.js@@ -0,0 +1,345 @@+/**+ * Self-Improvement Service+ *+ * Automated system for analyzing PortOS UI and codebase,+ * generating improvement tasks for the CoS to execute.+ *+ * Uses Playwright MCP or direct Playwright to:+ * - Navigate to all known routes+ * - Capture accessibility snapshots+ * - Check mobile responsiveness+ * - Capture console/network errors+ * - Generate improvement tasks+ */++import { cosEvents, addTask, getConfig } from './cos.js';++// Known routes to analyze+const ROUTES = [+ { path: '/', name: 'Dashboard', critical: true },+ { path: '/apps', name: 'Apps', critical: true },+ { path: '/cos', name: 'Chief of Staff', critical: true },+ { path: '/cos/tasks', name: 'CoS Tasks', critical: true },+ { path: '/cos/agents', name: 'CoS Agents', critical: true },+ { path: '/cos/health', name: 'CoS Health', critical: false },+ { path: '/cos/config', name: 'CoS Config', critical: false },+ { path: '/cos/memory', name: 'CoS Memory', critical: false },+ { path: '/devtools', name: 'DevTools', critical: true },+ { path: '/devtools/history', name: 'DevTools History', critical: true },+ { path: '/devtools/runner', name: 'DevTools Runner', critical: true },+ { path: '/providers', name: 'AI Providers', critical: true },+ { path: '/usage', name: 'Usage Metrics', critical: false },+ { path: '/prompts', name: 'Prompts', critical: false },+ { path: '/logs', name: 'Logs', critical: false }+];++// Viewport sizes for responsive testing+const VIEWPORTS = [+ { name: 'mobile', width: 375, height: 812 },+ { name: 'tablet', width: 768, height: 1024 },+ { name: 'desktop', width: 1440, height: 900 }+];++// Analysis task types+const ANALYSIS_TYPES = {+ UI_BUGS: 'ui-bugs',+ MOBILE_RESPONSIVE: 'mobile-responsive',+ ACCESSIBILITY: 'accessibility',+ CONSOLE_ERRORS: 'console-errors',+ SECURITY: 'security',+ PERFORMANCE: 'performance',+ CODE_QUALITY: 'code-quality'+};++/**+ * Emit log event for CoS UI+ */+function emitLog(level, message, data = {}) {+ const logEntry = {+ timestamp: new Date().toISOString(),+ level,+ message,+ ...data+ };+ console.log(`${level === 'error' ? '❌' : level === 'warn' ? '⚠️' : level === 'success' ? '✅' : 'ℹ️'} [SelfImprovement] ${message}`);+ cosEvents.emit('log', logEntry);+}++/**+ * Generate a self-improvement analysis prompt for Opus+ */+function generateAnalysisPrompt(analysisType, context) {+ const baseInstructions = `You are analyzing PortOS, a developer dashboard application. Your goal is to identify real, actionable improvements.++CRITICAL RULES:+1. Only report issues you can actually see or detect+2. Be specific - include exact file paths, line numbers, component names+3. Prioritize issues by impact (security > functionality > UX > style)+4. For each issue, provide a concrete fix, not just a description+5. Use the heavy/opus model for all coding tasks - quality matters more than cost`;++ const typePrompts = {+ [ANALYSIS_TYPES.UI_BUGS]: `${baseInstructions}++TASK: Analyze the UI for bugs and issues.++Page Context:+${context.pageSnapshot || 'No snapshot available'}++Console Messages:+${context.consoleMessages || 'None captured'}++Network Errors:+${context.networkErrors || 'None captured'}++Look for:+- JavaScript errors in console+- Failed network requests+- Broken links or missing images+- Form validation issues+- State management bugs+- Race conditions in data loading`,++ [ANALYSIS_TYPES.MOBILE_RESPONSIVE]: `${baseInstructions}++TASK: Analyze mobile responsiveness issues.++Desktop Snapshot (1440px):+${context.desktopSnapshot || 'No snapshot'}++Tablet Snapshot (768px):+${context.tabletSnapshot || 'No snapshot'}++Mobile Snapshot (375px):+${context.mobileSnapshot || 'No snapshot'}++Look for:+- Text overflow or truncation+- Buttons too small to tap+- Horizontal scrolling+- Elements overlapping+- Navigation issues on small screens+- Touch target sizing+- Font sizes too small on mobile`,++ [ANALYSIS_TYPES.SECURITY]: `${baseInstructions}++TASK: Security audit of the codebase.++Focus on:+- XSS vulnerabilities (especially in React components)+- Command injection (check all exec/spawn calls)+- Path traversal in file operations+- Hardcoded secrets or API keys+- Missing input validation+- CSRF protection+- Unsafe eval or Function() usage+- SQL/NoSQL injection points++Examine these critical areas:+- server/routes/*.js - all API endpoints+- server/services/*.js - business logic+- client/src/services/api.js - client API calls`,++ [ANALYSIS_TYPES.CODE_QUALITY]: `${baseInstructions}++TASK: Code quality and maintainability review.++Focus on:+- DRY violations (duplicated code)+- Functions over 50 lines that should be split+- Missing error handling+- Inconsistent patterns+- Dead code or unused imports+- TODO/FIXME comments that need addressing+- Console.log statements that should be removed+- Missing or outdated comments`+ };++ return typePrompts[analysisType] || baseInstructions;+}++/**+ * Create a self-improvement task for CoS+ */+async function createImprovementTask(analysisType, description, priority = 'MEDIUM') {+ const taskDescription = `[Self-Improvement] ${description}++Analysis Type: ${analysisType}+Model: Use claude-opus-4-5-20251101 (heavy)++Instructions:+- Thoroughly analyze the issue+- Implement a fix if possible+- Run tests to verify the fix+- Commit the changes with a clear message`;++ const task = await addTask({+ description: taskDescription,+ priority,+ context: `Auto-generated by self-improvement system`,+ model: 'claude-opus-4-5-20251101',+ approvalRequired: false // Auto-approved for self-improvement+ }, 'internal');++ emitLog('success', `Created improvement task: ${task.id}`, { taskId: task.id, type: analysisType });+ return task;+}++/**+ * Run a full self-improvement cycle+ * This is called when CoS is idle and wants to improve itself+ */+export async function runSelfImprovementCycle() {+ const config = await getConfig();++ if (!config.selfImprovementEnabled) {+ emitLog('debug', 'Self-improvement is disabled');+ return null;+ }++ emitLog('info', 'Starting self-improvement cycle');++ // Rotate through analysis types+ const analysisTypes = Object.values(ANALYSIS_TYPES);+ const lastAnalysis = config.lastSelfImprovementType || '';+ const currentIndex = analysisTypes.indexOf(lastAnalysis);+ const nextType = analysisTypes[(currentIndex + 1) % analysisTypes.length];++ emitLog('info', `Running ${nextType} analysis`);++ // Generate the task based on type+ const task = await generateSelfImprovementTask(nextType);++ return task;+}++/**+ * Generate a self-improvement task based on analysis type+ */+async function generateSelfImprovementTask(analysisType) {+ const taskDescriptions = {+ [ANALYSIS_TYPES.UI_BUGS]: `Analyze PortOS UI at http://localhost:5555 for bugs and issues++Use Playwright MCP to:+1. Navigate to each main route (/, /apps, /cos, /devtools, /providers, /usage)+2. Capture browser snapshots and console messages+3. Look for JavaScript errors, failed requests, broken UI elements+4. Fix any bugs found and commit the changes++Model: claude-opus-4-5-20251101`,++ [ANALYSIS_TYPES.MOBILE_RESPONSIVE]: `Analyze PortOS UI for mobile responsiveness issues++Use Playwright MCP to:+1. Navigate to http://localhost:5555 and its sub-routes+2. Test at mobile (375px), tablet (768px), and desktop (1440px) viewports+3. Capture snapshots at each viewport size+4. Identify layout issues, overflow, touch targets, font sizes+5. Fix responsiveness issues in the Tailwind CSS classes+6. Commit fixes with clear descriptions++Model: claude-opus-4-5-20251101`,++ [ANALYSIS_TYPES.SECURITY]: `Security audit of PortOS codebase++Analyze the following for security vulnerabilities:+1. server/routes/*.js - Check all API endpoints for injection vulnerabilities+2. server/services/*.js - Check for command injection, path traversal+3. server/lib/commandAllowlist.js - Verify allowlist is comprehensive+4. client/src/services/api.js - Check for XSS, CSRF protection+5. Check for hardcoded secrets, unsafe eval, missing validation++Fix any issues found with secure alternatives and commit changes.++Model: claude-opus-4-5-20251101`,++ [ANALYSIS_TYPES.CODE_QUALITY]: `Code quality review of PortOS++Analyze the codebase for:+1. DRY violations - Find and consolidate duplicated code+2. Large functions (>50 lines) that should be split+3. Missing error handling+4. Dead code and unused imports+5. Inconsistent patterns between files+6. TODO/FIXME comments that need addressing++Focus on server/ and client/src/ directories.+Make improvements and commit with clear messages.++Model: claude-opus-4-5-20251101`,++ [ANALYSIS_TYPES.ACCESSIBILITY]: `Accessibility audit of PortOS UI++Use Playwright MCP to:+1. Navigate to http://localhost:5555 and sub-routes+2. Capture accessibility snapshots+3. Check for missing ARIA labels, alt text, keyboard navigation+4. Verify color contrast ratios+5. Test screen reader compatibility++Fix accessibility issues and commit changes.++Model: claude-opus-4-5-20251101`,++ [ANALYSIS_TYPES.CONSOLE_ERRORS]: `Check PortOS for console errors and warnings++Use Playwright MCP to:+1. Navigate to http://localhost:5555+2. Open each main route and interact with key features+3. Capture all console messages (errors, warnings)+4. Identify the source of each error+5. Fix the underlying issues in the code++Model: claude-opus-4-5-20251101`,++ [ANALYSIS_TYPES.PERFORMANCE]: `Performance analysis of PortOS++Analyze for performance issues:+1. Check component re-renders in React DevTools patterns+2. Look for N+1 query patterns in API calls+3. Identify large bundle sizes or missing code splitting+4. Check for memory leaks in useEffect hooks+5. Analyze Socket.IO event handling efficiency++Optimize and commit improvements.++Model: claude-opus-4-5-20251101`+ };++ const description = taskDescriptions[analysisType] || taskDescriptions[ANALYSIS_TYPES.CODE_QUALITY];++ const task = {+ id: `self-improve-${analysisType}-${Date.now().toString(36)}`,+ status: 'pending',+ priority: 'MEDIUM',+ priorityValue: 2,+ description: `[Self-Improvement] ${description}`,+ metadata: {+ analysisType,+ autoGenerated: true,+ selfImprovement: true,+ model: 'claude-opus-4-5-20251101'+ },+ taskType: 'internal',+ autoApproved: true,+ model: 'claude-opus-4-5-20251101'+ };++ emitLog('info', `Generated self-improvement task: ${analysisType}`, { taskId: task.id });+ return task;+}++/**+ * Get the next self-improvement task type based on rotation+ */+export function getNextImprovementType(lastType) {+ const types = Object.values(ANALYSIS_TYPES);+ const currentIndex = types.indexOf(lastType);+ return types[(currentIndex + 1) % types.length];+}++/**+ * Export analysis types for configuration+ */+export { ANALYSIS_TYPES, ROUTES, VIEWPORTS };diff --git a/server/services/socket.test.js b/server/services/socket.test.jsnew file mode 100644index 0000000000..1fe10faa93--- /dev/null+++ b/server/services/socket.test.js@@ -0,0 +1,329 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'events';++/**+ * Tests for the socket service event handling logic+ *+ * Note: We test the event forwarding and subscription management logic+ * without spinning up actual Socket.IO servers.+ */++// Mock cosEvents+const mockCosEvents = new EventEmitter();++// Mock errorEvents+const mockErrorEvents = new EventEmitter();++describe('Socket Service Logic', () => {+ let mockSocket;+ let mockIo;+ let cosSubscribers;+ let errorSubscribers;+ let activeStreams;++ beforeEach(() => {+ // Create fresh sets for each test+ cosSubscribers = new Set();+ errorSubscribers = new Set();+ activeStreams = new Map();++ // Mock socket+ mockSocket = {+ id: 'socket-123',+ emit: vi.fn(),+ on: vi.fn()+ };++ // Mock io+ mockIo = {+ emit: vi.fn(),+ on: vi.fn()+ };+ });++ afterEach(() => {+ vi.clearAllMocks();+ mockCosEvents.removeAllListeners();+ mockErrorEvents.removeAllListeners();+ });++ describe('CoS Event Subscription', () => {+ it('should add socket to subscribers on cos:subscribe', () => {+ // Simulate subscribe handler+ cosSubscribers.add(mockSocket);+ mockSocket.emit('cos:subscribed');++ expect(cosSubscribers.has(mockSocket)).toBe(true);+ expect(mockSocket.emit).toHaveBeenCalledWith('cos:subscribed');+ });++ it('should remove socket from subscribers on cos:unsubscribe', () => {+ cosSubscribers.add(mockSocket);++ // Simulate unsubscribe handler+ cosSubscribers.delete(mockSocket);+ mockSocket.emit('cos:unsubscribed');++ expect(cosSubscribers.has(mockSocket)).toBe(false);+ expect(mockSocket.emit).toHaveBeenCalledWith('cos:unsubscribed');+ });++ it('should remove socket from subscribers on disconnect', () => {+ cosSubscribers.add(mockSocket);++ // Simulate disconnect cleanup+ cosSubscribers.delete(mockSocket);++ expect(cosSubscribers.has(mockSocket)).toBe(false);+ });+ });++ describe('Error Event Subscription', () => {+ it('should add socket to error subscribers', () => {+ errorSubscribers.add(mockSocket);+ mockSocket.emit('errors:subscribed');++ expect(errorSubscribers.has(mockSocket)).toBe(true);+ expect(mockSocket.emit).toHaveBeenCalledWith('errors:subscribed');+ });++ it('should remove socket from error subscribers', () => {+ errorSubscribers.add(mockSocket);+ errorSubscribers.delete(mockSocket);+ mockSocket.emit('errors:unsubscribed');++ expect(errorSubscribers.has(mockSocket)).toBe(false);+ });+ });++ describe('CoS Event Forwarding', () => {+ function broadcastToCos(event, data) {+ for (const socket of cosSubscribers) {+ socket.emit(event, data);+ }+ }++ it('should forward status events to subscribers', () => {+ cosSubscribers.add(mockSocket);++ broadcastToCos('cos:status', { running: true });++ expect(mockSocket.emit).toHaveBeenCalledWith('cos:status', { running: true });+ });++ it('should forward log events to subscribers', () => {+ cosSubscribers.add(mockSocket);++ broadcastToCos('cos:log', { level: 'info', message: 'Test' });++ expect(mockSocket.emit).toHaveBeenCalledWith('cos:log', { level: 'info', message: 'Test' });+ });++ it('should forward agent events to subscribers', () => {+ cosSubscribers.add(mockSocket);++ const agentData = { id: 'agent-001', status: 'running' };+ broadcastToCos('cos:agent:spawned', agentData);++ expect(mockSocket.emit).toHaveBeenCalledWith('cos:agent:spawned', agentData);+ });++ it('should forward to multiple subscribers', () => {+ const mockSocket2 = { ...mockSocket, id: 'socket-456', emit: vi.fn() };+ cosSubscribers.add(mockSocket);+ cosSubscribers.add(mockSocket2);++ broadcastToCos('cos:status', { running: true });++ expect(mockSocket.emit).toHaveBeenCalled();+ expect(mockSocket2.emit).toHaveBeenCalled();+ });++ it('should not emit to non-subscribers', () => {+ // Don't add socket to subscribers++ broadcastToCos('cos:status', { running: true });++ expect(mockSocket.emit).not.toHaveBeenCalled();+ });+ });++ describe('Error Event Forwarding', () => {+ function broadcastToErrors(event, data) {+ for (const socket of errorSubscribers) {+ socket.emit(event, data);+ }+ }++ it('should forward error notifications to subscribers', () => {+ errorSubscribers.add(mockSocket);++ const errorData = {+ message: 'Test error',+ code: 'TEST_ERROR',+ severity: 'error',+ timestamp: Date.now()+ };++ broadcastToErrors('error:notified', errorData);++ expect(mockSocket.emit).toHaveBeenCalledWith('error:notified', errorData);+ });+ });++ describe('Log Stream Management', () => {+ function cleanupStream(socketId) {+ const stream = activeStreams.get(socketId);+ if (stream) {+ stream.killed = true;+ activeStreams.delete(socketId);+ }+ }++ it('should track active log streams', () => {+ const mockStream = { process: { kill: vi.fn() }, processName: 'test-app' };+ activeStreams.set(mockSocket.id, mockStream);++ expect(activeStreams.has(mockSocket.id)).toBe(true);+ expect(activeStreams.get(mockSocket.id).processName).toBe('test-app');+ });++ it('should cleanup stream on unsubscribe', () => {+ const mockStream = { process: { kill: vi.fn() }, processName: 'test-app', killed: false };+ activeStreams.set(mockSocket.id, mockStream);++ cleanupStream(mockSocket.id);++ expect(activeStreams.has(mockSocket.id)).toBe(false);+ expect(mockStream.killed).toBe(true);+ });++ it('should cleanup stream on disconnect', () => {+ const mockStream = { process: { kill: vi.fn() }, processName: 'test-app', killed: false };+ activeStreams.set(mockSocket.id, mockStream);++ // Simulate disconnect+ cleanupStream(mockSocket.id);++ expect(activeStreams.has(mockSocket.id)).toBe(false);+ });++ it('should handle cleanup when no stream exists', () => {+ // Should not throw+ expect(() => cleanupStream('non-existent')).not.toThrow();+ });+ });++ describe('PM2 Standardization Events', () => {+ it('should emit step events during standardization', () => {+ const emit = (step, status, data = {}) => {+ mockSocket.emit('standardize:step', { step, status, data, timestamp: Date.now() });+ };++ emit('analyze', 'running', { message: 'Analyzing...' });++ expect(mockSocket.emit).toHaveBeenCalledWith('standardize:step', expect.objectContaining({+ step: 'analyze',+ status: 'running',+ data: { message: 'Analyzing...' }+ }));+ });++ it('should emit completion event', () => {+ mockSocket.emit('standardize:complete', {+ success: true,+ result: { filesModified: ['ecosystem.config.cjs'] }+ });++ expect(mockSocket.emit).toHaveBeenCalledWith('standardize:complete', expect.objectContaining({+ success: true+ }));+ });++ it('should emit error on failure', () => {+ mockSocket.emit('standardize:complete', {+ success: false,+ error: 'Analysis failed'+ });++ expect(mockSocket.emit).toHaveBeenCalledWith('standardize:complete', expect.objectContaining({+ success: false,+ error: 'Analysis failed'+ }));+ });+ });++ describe('Log Line Parsing', () => {+ it('should emit stdout log lines', () => {+ const logData = {+ line: '[2024-01-15 10:00:00] App started',+ type: 'stdout',+ timestamp: Date.now(),+ processName: 'test-app'+ };++ mockSocket.emit('logs:line', logData);++ expect(mockSocket.emit).toHaveBeenCalledWith('logs:line', expect.objectContaining({+ type: 'stdout',+ processName: 'test-app'+ }));+ });++ it('should emit stderr log lines', () => {+ const logData = {+ line: 'Error: Something went wrong',+ type: 'stderr',+ timestamp: Date.now(),+ processName: 'test-app'+ };++ mockSocket.emit('logs:line', logData);++ expect(mockSocket.emit).toHaveBeenCalledWith('logs:line', expect.objectContaining({+ type: 'stderr'+ }));+ });+ });++ describe('CoS Event Types Coverage', () => {+ // Test all the event types that get forwarded+ const eventTypes = [+ ['status', { running: true }],+ ['log', { level: 'info', message: 'test' }],+ ['tasks:user:changed', { action: 'added' }],+ ['tasks:user:added', { task: { id: 'task-001' } }],+ ['tasks:user:completed', { taskId: 'task-001' }],+ ['tasks:cos:changed', { action: 'updated' }],+ ['agent:spawned', { id: 'agent-001' }],+ ['agent:updated', { id: 'agent-001', status: 'working' }],+ ['agent:completed', { id: 'agent-001', success: true }],+ ['agent:output', { agentId: 'agent-001', line: 'output' }],+ ['memory:created', { id: 'mem-001' }],+ ['memory:updated', { id: 'mem-001' }],+ ['memory:deleted', { id: 'mem-001' }],+ ['memory:extracted', { count: 5 }],+ ['memory:approval-needed', { memories: [] }],+ ['health:check', { metrics: {}, issues: [] }],+ ['health:critical', [{ type: 'error', message: 'test' }]],+ ['evaluation', { message: 'Evaluation complete' }],+ ['task:ready', { id: 'task-001' }],+ ['watcher:started', { files: ['TASKS.md'] }],+ ['watcher:stopped', {}]+ ];++ function broadcastToCos(event, data) {+ for (const socket of cosSubscribers) {+ socket.emit(event, data);+ }+ }++ it.each(eventTypes)('should forward %s event', (eventType, data) => {+ cosSubscribers.add(mockSocket);++ broadcastToCos(`cos:${eventType}`, data);++ expect(mockSocket.emit).toHaveBeenCalledWith(`cos:${eventType}`, data);+ });+ });+});diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 734d96f638..976022e0f2 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -12,24 +12,10 @@ import { fileURLToPath } from 'url';import { writeFile, mkdir, readFile } from 'fs/promises';import { existsSync } from 'fs';import { v4 as uuidv4 } from 'uuid';-import { cosEvents, registerAgent, updateAgent, completeAgent, appendAgentOutput, getConfig, updateTask, addTask } from './cos.js';+import { cosEvents, registerAgent, updateAgent, completeAgent, appendAgentOutput, getConfig, updateTask, addTask, emitLog } from './cos.js';import { startAppCooldown, markAppReviewCompleted } from './appActivity.js';import { isRunnerAvailable, spawnAgentViaRunner, terminateAgentViaRunner, killAgentViaRunner, getAgentStatsFromRunner, initCosRunnerConnection, onCosRunnerEvent, getActiveAgentsFromRunner } from './cosRunnerClient.js';--/**- * Emit a log event for UI display (mirrors cos.js helper)- */-function emitLog(level, message, data = {}) {- const logEntry = {- timestamp: new Date().toISOString(),- level,- message,- ...data- };- console.log(`${level === 'error' ? '❌' : level === 'warn' ? '⚠️' : level === 'success' ? '✅' : 'ℹ️'} ${message}`);- cosEvents.emit('log', logEntry);-}-import { getActiveProvider, getProviderById } from './providers.js';+import { getActiveProvider } from './providers.js';import { recordSession, recordMessages } from './usage.js';import { buildPrompt } from './promptService.js';import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';@@ -1165,6 +1151,9 @@ export async function killAllAgents() {return { killed: directIds.length + runnerIds.length };}+// Max retries before creating investigation task+const MAX_ORPHAN_RETRIES = 3;+/*** Clean up orphaned agents on startup* Agents marked as "running" in state but not tracked anywhere are orphaned@@ -1173,11 +1162,17 @@ export async function killAllAgents() {* 1. Local activeAgents map (direct-spawned)* 2. Local runnerAgents map (recently spawned via runner)* 3. CoS Runner service (may have agents from before server restart)+ *+ * After cleanup:+ * - Resets associated tasks to pending for auto-retry+ * - Creates investigation task after max retries exceeded+ * - Triggers evaluation to spawn new agents*/export async function cleanupOrphanedAgents() {- const { getAgents, completeAgent: markComplete } = await import('./cos.js');+ const { getAgents, completeAgent: markComplete, evaluateTasks, getTaskById } = await import('./cos.js');const agents = await getAgents();let cleanedCount = 0;+ const orphanedTaskIds = [];// Get list of agents actively running in the CoS Runnerconst runnerActiveIds = new Set();@@ -1209,17 +1204,119 @@ export async function cleanupOrphanedAgents() {orphaned: true});cleanedCount++;++ // Track the task for retry+ if (agent.taskId) {+ orphanedTaskIds.push({ taskId: agent.taskId, agentId: agent.id });+ }}}}+ // Handle orphaned tasks - reset for retry or create investigation task+ for (const { taskId, agentId } of orphanedTaskIds) {+ await handleOrphanedTask(taskId, agentId, getTaskById);+ }++ // Trigger evaluation to spawn new agents for retried tasks+ if (cleanedCount > 0) {+ emitLog('info', `Cleaned up ${cleanedCount} orphaned agents, triggering evaluation`, { cleanedCount });+ // Small delay to let state settle before evaluation+ setTimeout(() => {+ evaluateTasks().catch(err => {+ console.error(`❌ Failed to evaluate tasks after orphan cleanup: ${err.message}`);+ });+ }, 1000);+ }+return cleanedCount;}+/**+ * Handle an orphaned task - retry or create investigation+ */+async function handleOrphanedTask(taskId, agentId, getTaskById) {+ const task = await getTaskById(taskId).catch(() => null);+ if (!task) {+ emitLog('warn', `Could not find task ${taskId} for orphaned agent ${agentId}`, { taskId, agentId });+ return;+ }++ // Get current retry count from task metadata+ const retryCount = (task.metadata?.orphanRetryCount || 0) + 1;+ const taskType = task.taskType || 'user';++ if (retryCount < MAX_ORPHAN_RETRIES) {+ // Reset task to pending for automatic retry+ emitLog('info', `Resetting orphaned task ${taskId} for retry (attempt ${retryCount}/${MAX_ORPHAN_RETRIES})`, {+ taskId,+ retryCount,+ maxRetries: MAX_ORPHAN_RETRIES+ });++ await updateTask(taskId, {+ status: 'pending',+ metadata: {+ ...task.metadata,+ orphanRetryCount: retryCount,+ lastOrphanedAt: new Date().toISOString(),+ lastOrphanedAgentId: agentId+ }+ }, taskType);+ } else {+ // Max retries exceeded - create auto-approved investigation task+ emitLog('warn', `Task ${taskId} exceeded max orphan retries (${MAX_ORPHAN_RETRIES}), creating investigation task`, {+ taskId,+ retryCount+ });++ // Mark task as blocked+ await updateTask(taskId, {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ orphanRetryCount: retryCount,+ blockedReason: 'Max orphan retries exceeded'+ }+ }, taskType);++ // Create auto-approved investigation task (no approval required for orphan issues)+ const description = `[Auto-Fix] Investigate repeated agent orphaning for task ${taskId}++**Original Task**: ${(task.description || '').substring(0, 200)}+**Retry Attempts**: ${retryCount}+**Last Orphaned Agent**: ${agentId}++This task has failed ${retryCount} times due to agent orphaning. Investigate:+1. Check CoS Runner logs for errors+2. Verify process spawning is working correctly+3. Look for resource constraints (memory, CPU)+4. Check for network/connection issues between services++Once the issue is resolved, reset the original task to pending.`;++ await addTask({+ description,+ priority: 'HIGH',+ context: `Auto-generated from repeated orphan failures for task ${taskId}`,+ approvalRequired: false // Auto-approved for orphan issues+ }, 'internal').catch(err => {+ emitLog('error', `Failed to create investigation task: ${err.message}`, { taskId, error: err.message });+ });+ }+}+// Initialize spawner when module loads (async)initSpawner().catch(err => {console.error(`❌ Failed to initialize spawner: ${err.message}`);});+// Initialize task learning system+import('./taskLearning.js').then(taskLearning => {+ taskLearning.initTaskLearning();+}).catch(err => {+ console.error(`❌ Failed to initialize task learning: ${err.message}`);+});+// Clean up orphaned agents after a short delay (let other services init first)setTimeout(cleanupOrphanedAgents, 2000);diff --git a/server/services/taskLearning.js b/server/services/taskLearning.jsnew file mode 100644index 0000000000..7bb70e7b9b--- /dev/null+++ b/server/services/taskLearning.js@@ -0,0 +1,510 @@+/**+ * Task Learning Service+ *+ * Tracks patterns from completed tasks to improve future task execution.+ * Learns from success/failure rates, duration patterns, and error categories+ * to provide smarter task prioritization and model selection.+ */++import { readFile, writeFile, mkdir } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { cosEvents, emitLog } from './cos.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const DATA_DIR = join(__dirname, '../../data/cos');+const LEARNING_FILE = join(DATA_DIR, 'learning.json');++/**+ * Default learning data structure+ */+const DEFAULT_LEARNING_DATA = {+ version: 1,+ lastUpdated: null,++ // Metrics by self-improvement task type+ byTaskType: {},++ // Metrics by model tier+ byModelTier: {},++ // Metrics by error category+ errorPatterns: {},++ // Overall stats+ totals: {+ completed: 0,+ succeeded: 0,+ failed: 0,+ totalDurationMs: 0,+ avgDurationMs: 0+ }+};++/**+ * Load learning data from file+ */+async function loadLearningData() {+ if (!existsSync(DATA_DIR)) {+ await mkdir(DATA_DIR, { recursive: true });+ }++ if (!existsSync(LEARNING_FILE)) {+ return { ...DEFAULT_LEARNING_DATA };+ }++ const content = await readFile(LEARNING_FILE, 'utf-8');+ return JSON.parse(content);+}++/**+ * Save learning data to file+ */+async function saveLearningData(data) {+ data.lastUpdated = new Date().toISOString();+ await writeFile(LEARNING_FILE, JSON.stringify(data, null, 2));+}++/**+ * Extract task type from task description or metadata+ */+function extractTaskType(task) {+ // Check for self-improvement type in metadata+ if (task?.metadata?.analysisType) {+ return `self-improve:${task.metadata.analysisType}`;+ }++ // Check for idle review+ if (task?.metadata?.reviewType === 'idle') {+ return 'idle-review';+ }++ // Check description patterns+ const desc = (task?.description || '').toLowerCase();++ if (desc.includes('[self-improvement]')) {+ const typeMatch = desc.match(/\[self-improvement\]\s*(\w+)/i);+ if (typeMatch) return `self-improve:${typeMatch[1]}`;+ }++ if (desc.includes('[idle review]')) {+ return 'idle-review';+ }++ if (desc.includes('[auto-fix]') || desc.includes('[auto]')) {+ return 'auto-fix';+ }++ // User task classification+ if (task?.taskType === 'user') {+ return 'user-task';+ }++ return 'unknown';+}++/**+ * Record a completed task for learning+ */+export async function recordTaskCompletion(agent, task) {+ const data = await loadLearningData();++ const taskType = extractTaskType(task);+ const modelTier = agent.metadata?.modelTier || 'unknown';+ const success = agent.result?.success || false;+ const duration = agent.result?.duration || 0;+ const errorCategory = agent.result?.errorAnalysis?.category || null;++ // Initialize task type bucket if needed+ if (!data.byTaskType[taskType]) {+ data.byTaskType[taskType] = {+ completed: 0,+ succeeded: 0,+ failed: 0,+ totalDurationMs: 0,+ avgDurationMs: 0,+ lastCompleted: null,+ successRate: 0+ };+ }++ // Initialize model tier bucket if needed+ if (!data.byModelTier[modelTier]) {+ data.byModelTier[modelTier] = {+ completed: 0,+ succeeded: 0,+ failed: 0,+ totalDurationMs: 0,+ avgDurationMs: 0+ };+ }++ // Update task type metrics+ const typeMetrics = data.byTaskType[taskType];+ typeMetrics.completed++;+ if (success) {+ typeMetrics.succeeded++;+ } else {+ typeMetrics.failed++;+ }+ typeMetrics.totalDurationMs += duration;+ typeMetrics.avgDurationMs = Math.round(typeMetrics.totalDurationMs / typeMetrics.completed);+ typeMetrics.lastCompleted = new Date().toISOString();+ typeMetrics.successRate = Math.round((typeMetrics.succeeded / typeMetrics.completed) * 100);++ // Update model tier metrics+ const tierMetrics = data.byModelTier[modelTier];+ tierMetrics.completed++;+ if (success) {+ tierMetrics.succeeded++;+ } else {+ tierMetrics.failed++;+ }+ tierMetrics.totalDurationMs += duration;+ tierMetrics.avgDurationMs = Math.round(tierMetrics.totalDurationMs / tierMetrics.completed);++ // Track error patterns+ if (!success && errorCategory) {+ if (!data.errorPatterns[errorCategory]) {+ data.errorPatterns[errorCategory] = {+ count: 0,+ taskTypes: {},+ lastOccurred: null+ };+ }+ data.errorPatterns[errorCategory].count++;+ data.errorPatterns[errorCategory].lastOccurred = new Date().toISOString();++ // Track which task types produce this error+ if (!data.errorPatterns[errorCategory].taskTypes[taskType]) {+ data.errorPatterns[errorCategory].taskTypes[taskType] = 0;+ }+ data.errorPatterns[errorCategory].taskTypes[taskType]++;+ }++ // Update totals+ data.totals.completed++;+ if (success) {+ data.totals.succeeded++;+ } else {+ data.totals.failed++;+ }+ data.totals.totalDurationMs += duration;+ data.totals.avgDurationMs = Math.round(data.totals.totalDurationMs / data.totals.completed);++ await saveLearningData(data);++ emitLog('debug', `Recorded task completion: ${taskType} (${success ? 'success' : 'failed'})`, {+ taskType,+ modelTier,+ success,+ duration: Math.round(duration / 1000) + 's'+ }, '[TaskLearning]');++ return data;+}++/**+ * Get learning insights for display+ */+export async function getLearningInsights() {+ const data = await loadLearningData();++ // Calculate overall success rate+ const overallSuccessRate = data.totals.completed > 0+ ? Math.round((data.totals.succeeded / data.totals.completed) * 100)+ : 0;++ // Find best and worst performing task types+ const taskTypes = Object.entries(data.byTaskType)+ .map(([type, metrics]) => ({+ type,+ ...metrics+ }))+ .filter(t => t.completed >= 3) // Only include types with enough data+ .sort((a, b) => b.successRate - a.successRate);++ const bestPerforming = taskTypes.slice(0, 3);+ const worstPerforming = taskTypes.slice(-3).reverse();++ // Find most common errors+ const commonErrors = Object.entries(data.errorPatterns)+ .map(([category, info]) => ({+ category,+ count: info.count,+ lastOccurred: info.lastOccurred,+ affectedTypes: Object.keys(info.taskTypes)+ }))+ .sort((a, b) => b.count - a.count)+ .slice(0, 5);++ // Model tier effectiveness+ const modelEffectiveness = Object.entries(data.byModelTier)+ .map(([tier, metrics]) => ({+ tier,+ successRate: metrics.completed > 0+ ? Math.round((metrics.succeeded / metrics.completed) * 100)+ : 0,+ avgDurationMin: Math.round(metrics.avgDurationMs / 60000),+ completed: metrics.completed+ }))+ .sort((a, b) => b.successRate - a.successRate);++ return {+ lastUpdated: data.lastUpdated,+ totals: {+ ...data.totals,+ successRate: overallSuccessRate,+ avgDurationMin: Math.round(data.totals.avgDurationMs / 60000)+ },+ insights: {+ bestPerforming: bestPerforming.map(t => ({+ type: t.type,+ successRate: t.successRate,+ avgDurationMin: Math.round(t.avgDurationMs / 60000),+ completed: t.completed+ })),+ worstPerforming: worstPerforming.map(t => ({+ type: t.type,+ successRate: t.successRate,+ avgDurationMin: Math.round(t.avgDurationMs / 60000),+ completed: t.completed+ })),+ commonErrors,+ modelEffectiveness+ },+ recommendations: generateRecommendations(data, bestPerforming, worstPerforming, commonErrors)+ };+}++/**+ * Generate actionable recommendations based on learning data+ */+function generateRecommendations(data, bestPerforming, worstPerforming, commonErrors) {+ const recommendations = [];++ // Recommend focusing on high-success task types+ if (bestPerforming.length > 0 && bestPerforming[0].successRate >= 90) {+ recommendations.push({+ type: 'optimization',+ message: `${bestPerforming[0].type} tasks have ${bestPerforming[0].successRate}% success rate - consider increasing frequency`+ });+ }++ // Warn about low-success task types+ if (worstPerforming.length > 0 && worstPerforming[0].successRate < 50 && worstPerforming[0].completed >= 5) {+ recommendations.push({+ type: 'warning',+ message: `${worstPerforming[0].type} tasks have only ${worstPerforming[0].successRate}% success rate - may need prompt improvements`+ });+ }++ // Check for recurring errors+ if (commonErrors.length > 0 && commonErrors[0].count >= 3) {+ recommendations.push({+ type: 'action',+ message: `"${commonErrors[0].category}" errors occurred ${commonErrors[0].count} times - investigate root cause`+ });+ }++ // Check model tier usage+ const heavyTier = data.byModelTier['heavy'];+ const lightTier = data.byModelTier['light'];++ if (lightTier && lightTier.completed > 0) {+ const lightSuccessRate = Math.round((lightTier.succeeded / lightTier.completed) * 100);+ if (lightSuccessRate < 70) {+ recommendations.push({+ type: 'suggestion',+ message: `Light model (haiku) has ${lightSuccessRate}% success rate - consider routing more tasks to medium tier`+ });+ }+ }++ if (heavyTier && heavyTier.completed > 10) {+ const heavySuccessRate = Math.round((heavyTier.succeeded / heavyTier.completed) * 100);+ if (heavySuccessRate >= 95) {+ recommendations.push({+ type: 'info',+ message: `Heavy model (opus) has ${heavySuccessRate}% success rate - excellent for complex tasks`+ });+ }+ }++ return recommendations;+}++/**+ * Get suggested priority boost for a task type based on historical success+ * Returns a multiplier: >1 for boost, <1 for demotion+ */+export async function getTaskTypePriorityMultiplier(taskType) {+ const data = await loadLearningData();++ const metrics = data.byTaskType[taskType];+ if (!metrics || metrics.completed < 3) {+ return 1.0; // Not enough data, use default priority+ }++ // High success rate = boost priority+ if (metrics.successRate >= 90) return 1.2;+ if (metrics.successRate >= 75) return 1.1;++ // Low success rate = demote priority slightly (but not too much, as we want to retry)+ if (metrics.successRate < 50) return 0.9;++ return 1.0;+}++/**+ * Suggest model tier based on historical performance for a task type+ */+export async function suggestModelTier(taskType) {+ const data = await loadLearningData();++ const metrics = data.byTaskType[taskType];+ if (!metrics || metrics.completed < 5) {+ return null; // Not enough data to suggest+ }++ // If success rate is low, suggest heavier model+ if (metrics.successRate < 60) {+ return {+ suggested: 'heavy',+ reason: `${taskType} has ${metrics.successRate}% success rate - heavier model may help`+ };+ }++ return null; // Current selection is working fine+}++/**+ * Get estimated duration for a task based on historical averages+ * @param {string} taskDescription - The task description to analyze+ * @returns {Object} Duration estimate with confidence+ */+export async function getTaskDurationEstimate(taskDescription) {+ const data = await loadLearningData();++ // Extract task type from description+ const taskType = extractTaskType({ description: taskDescription });++ const metrics = data.byTaskType[taskType];++ // If we have data for this specific task type+ if (metrics && metrics.completed >= 2) {+ return {+ estimatedDurationMs: metrics.avgDurationMs,+ estimatedDurationMin: Math.round(metrics.avgDurationMs / 60000),+ confidence: metrics.completed >= 10 ? 'high' : metrics.completed >= 5 ? 'medium' : 'low',+ basedOn: metrics.completed,+ taskType,+ successRate: metrics.successRate+ };+ }++ // Fall back to overall average+ if (data.totals.completed >= 3) {+ return {+ estimatedDurationMs: data.totals.avgDurationMs,+ estimatedDurationMin: Math.round(data.totals.avgDurationMs / 60000),+ confidence: 'low',+ basedOn: data.totals.completed,+ taskType: 'all',+ successRate: Math.round((data.totals.succeeded / data.totals.completed) * 100)+ };+ }++ // Not enough data+ return {+ estimatedDurationMs: null,+ estimatedDurationMin: null,+ confidence: 'none',+ basedOn: 0,+ taskType: null,+ successRate: null+ };+}++/**+ * Get all task type durations for bulk lookup+ * @returns {Object} Map of task type to duration info+ */+export async function getAllTaskDurations() {+ const data = await loadLearningData();++ const durations = {};++ for (const [taskType, metrics] of Object.entries(data.byTaskType)) {+ if (metrics.completed >= 1) {+ durations[taskType] = {+ avgDurationMs: metrics.avgDurationMs,+ avgDurationMin: Math.round(metrics.avgDurationMs / 60000),+ completed: metrics.completed,+ successRate: metrics.successRate+ };+ }+ }++ // Add overall average+ if (data.totals.completed >= 1) {+ durations._overall = {+ avgDurationMs: data.totals.avgDurationMs,+ avgDurationMin: Math.round(data.totals.avgDurationMs / 60000),+ completed: data.totals.completed,+ successRate: Math.round((data.totals.succeeded / data.totals.completed) * 100)+ };+ }++ return durations;+}++/**+ * Initialize learning system - listen for agent completions+ */+export function initTaskLearning() {+ cosEvents.on('agent:completed', async (agent) => {+ // Get task info from agent+ const task = {+ id: agent.taskId,+ description: agent.metadata?.taskDescription,+ taskType: agent.metadata?.taskType,+ metadata: agent.metadata+ };++ await recordTaskCompletion(agent, task).catch(err => {+ console.error(`❌ [TaskLearning] Failed to record completion: ${err.message}`);+ });+ });++ emitLog('info', 'Task Learning System initialized', {}, '[TaskLearning]');+}++/**+ * Backfill learning data from existing completed agents+ * Call this once to populate historical data+ */+export async function backfillFromHistory() {+ const { getAgents } = await import('./cos.js');+ const agents = await getAgents();++ let backfilled = 0;+ for (const agent of agents) {+ if (agent.status === 'completed' && agent.result) {+ const task = {+ id: agent.taskId,+ description: agent.metadata?.taskDescription,+ taskType: agent.metadata?.taskType,+ metadata: agent.metadata+ };++ await recordTaskCompletion(agent, task).catch(() => {});+ backfilled++;+ }+ }++ emitLog('info', `Backfilled ${backfilled} completed tasks into learning system`, { backfilled }, '[TaskLearning]');+ return backfilled;+}