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: queue self-improvement tasks as system tasks
Adam Eivye2bf9f2134e5
diff --git a/PLAN.md b/PLAN.mdindex bc204ed11f..7be1d1562a 100644--- a/PLAN.md+++ b/PLAN.md@@ -1549,3 +1549,96 @@ Repository: /Users/user/projects/myappUse model: claude-opus-4-5-20251101```++---++## M31: LLM-based Memory Classification (2026-01-09)++Replaced pattern-based memory extraction with intelligent LLM-based evaluation using local LM Studio.++### Problem++The existing memory extraction system used simple regex patterns to extract memories from agent output. This produced low-quality memories like "Task 'fix button': ## Summary" which just echoed task descriptions without any useful information.++### Solution++Created an LLM-based memory classifier that uses LM Studio's gptoss-20b model to intelligently evaluate agent output and extract only genuinely useful memories.++### Key Features++1. **LLM Evaluation**: Uses local LM Studio to analyze agent output+2. **Quality Filtering**: Rejects task echoes, generic summaries, and incomplete content+3. **Configurable**: Model, endpoint, confidence thresholds all configurable+4. **Fallback Support**: Falls back to pattern-based extraction if LLM unavailable+5. **Reasoning Capture**: Stores LLM's reasoning for why each memory is useful++### Memory Evaluation Criteria++**Good memories:**+- Codebase facts: File locations, architecture patterns, dependencies+- User preferences: Coding style, tool preferences, workflow patterns+- Learnings: Discovered behaviors, gotchas, workarounds+- Decisions: Architectural choices with reasoning++**Rejected memories:**+- Task echoes: Just restating what the task was+- Generic summaries: "The task was successful"+- Temporary info: Session-specific data, timestamps+- Truncated/incomplete content++### Configuration++```json+// data/memory-classifier-config.json+{+ "enabled": true,+ "provider": "lmstudio",+ "endpoint": "http://localhost:1234/v1/chat/completions",+ "model": "gptoss-20b",+ "timeout": 60000,+ "maxOutputLength": 10000,+ "minConfidence": 0.6,+ "fallbackToPatterns": true+}+```++### Prompt Template++The `memory-evaluate.md` prompt template guides the LLM to:+1. Analyze the task context and agent output+2. Identify genuinely reusable knowledge+3. Return structured JSON with memories and rejections+4. Include reasoning for each decision++### Implementation Files++| File | Purpose |+|------|---------|+| `server/services/memoryClassifier.js` | LLM-based classification service |+| `data/prompts/stages/memory-evaluate.md` | Prompt template for memory evaluation |+| `data/memory-classifier-config.json` | Classifier configuration |+| `server/services/memoryExtractor.js` | Updated to use classifier when available |+| `data/prompts/stage-config.json` | Added memory-evaluate stage |+| `data/providers.json` | Added gptoss-20b model to LM Studio provider |++### API++The classifier exports:+- `classifyMemories(task, agentOutput)` - Main classification function+- `isAvailable()` - Check if LM Studio is reachable+- `getConfig()` - Get current configuration+- `updateConfig(updates)` - Update configuration++### Flow++```+Agent completes task+ └─► memoryExtractor.extractAndStoreMemories()+ └─► Check if LLM classifier available+ ├─► Yes: Call classifyMemories() with LM Studio+ │ └─► Parse JSON response, filter by confidence+ └─► No: Fall back to pattern-based extraction+ └─► Create memories with embeddings+ └─► Auto-approve high confidence (≥0.8)+ └─► Queue medium confidence for approval+```diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 94d3c50378..7c4f754849 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -6,7 +6,8 @@ import {Activity,Settings,Calendar,- Clock+ Clock,+ GraduationCap} from 'lucide-react';export const TABS = [@@ -15,6 +16,7 @@ export const TABS = [{ id: 'scripts', label: 'Scripts', icon: Terminal },{ id: 'schedule', label: 'Schedule', icon: Clock },{ id: 'digest', label: 'Digest', icon: Calendar },+ { id: 'learning', label: 'Learning', icon: GraduationCap },{ id: 'memory', label: 'Memory', icon: Brain },{ id: 'health', label: 'Health', icon: Activity },{ id: 'config', label: 'Config', icon: Settings }diff --git a/client/src/components/cos/index.js b/client/src/components/cos/index.jsindex 6abd54137e..115de0d64e 100644--- a/client/src/components/cos/index.js+++ b/client/src/components/cos/index.js@@ -20,6 +20,7 @@ export { default as TasksTab } from './tabs/TasksTab';export { default as AgentsTab } from './tabs/AgentsTab';export { default as ScriptsTab } from './tabs/ScriptsTab';export { default as ScheduleTab } from './tabs/ScheduleTab';+export { default as LearningTab } from './tabs/LearningTab';export { default as MemoryTab } from './tabs/MemoryTab';export { default as HealthTab } from './tabs/HealthTab';export { default as ConfigTab } from './tabs/ConfigTab';diff --git a/client/src/components/cos/tabs/LearningTab.jsx b/client/src/components/cos/tabs/LearningTab.jsxnew file mode 100644index 0000000000..2ea27faff4--- /dev/null+++ b/client/src/components/cos/tabs/LearningTab.jsx@@ -0,0 +1,498 @@+import { useState, useEffect } from 'react';+import {+ Brain,+ RefreshCw,+ TrendingUp,+ TrendingDown,+ Clock,+ AlertTriangle,+ CheckCircle,+ XCircle,+ SkipForward,+ Zap,+ BarChart2,+ Timer,+ Target,+ ChevronDown,+ ChevronRight,+ Database+} from 'lucide-react';+import * as api from '../../../services/api';++export default function LearningTab() {+ const [learning, setLearning] = useState(null);+ const [performance, setPerformance] = useState(null);+ const [skipped, setSkipped] = useState(null);+ const [durations, setDurations] = useState(null);+ const [loading, setLoading] = useState(true);+ const [backfilling, setBackfilling] = useState(false);+ const [expandedSections, setExpandedSections] = useState({+ taskTypes: true,+ skipped: true,+ durations: false,+ models: true,+ errors: false+ });++ useEffect(() => {+ loadData();+ }, []);++ const loadData = async () => {+ setLoading(true);+ const [learningData, performanceData, skippedData, durationsData] = await Promise.all([+ api.getCosLearning().catch(() => null),+ api.getCosLearningPerformance().catch(() => null),+ api.getCosLearningSkipped().catch(() => null),+ api.getCosLearningDurations().catch(() => null)+ ]);+ setLearning(learningData);+ setPerformance(performanceData);+ setSkipped(skippedData);+ setDurations(durationsData);+ setLoading(false);+ };++ const handleBackfill = async () => {+ setBackfilling(true);+ const result = await api.backfillCosLearning().catch(() => null);+ if (result?.success) {+ await loadData();+ }+ setBackfilling(false);+ };++ const toggleSection = (section) => {+ setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));+ };++ const getSuccessRateColor = (rate) => {+ if (rate >= 80) return 'text-port-success';+ if (rate >= 60) return 'text-port-warning';+ return 'text-port-error';+ };++ const getSuccessRateBg = (rate) => {+ if (rate >= 80) return 'bg-port-success';+ if (rate >= 60) return 'bg-port-warning';+ return 'bg-port-error';+ };++ const formatDuration = (ms) => {+ if (!ms) return '—';+ const minutes = Math.round(ms / 60000);+ if (minutes < 60) return `${minutes}m`;+ const hours = Math.floor(minutes / 60);+ const mins = minutes % 60;+ return `${hours}h ${mins}m`;+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center py-12">+ <RefreshCw className="w-6 h-6 animate-spin text-port-accent" />+ </div>+ );+ }++ const hasData = learning?.totals?.completed > 0;++ return (+ <div className="space-y-6">+ {/* Header */}+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">+ <div className="flex items-center gap-3">+ <Brain className="w-5 h-5 text-purple-400" />+ <h3 className="text-lg font-semibold text-white">Learning Analytics</h3>+ </div>+ <div className="flex gap-2">+ {!hasData && (+ <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={loadData}+ disabled={loading}+ 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={loading ? 'animate-spin' : ''} />+ Refresh+ </button>+ </div>+ </div>++ {!hasData ? (+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">+ <Brain className="w-12 h-12 text-gray-600 mx-auto mb-3" />+ <p className="text-gray-400">No learning data available yet.</p>+ <p className="text-gray-500 text-sm mt-1">+ Complete some tasks to see performance analytics, or click "Backfill History" to import existing data.+ </p>+ </div>+ ) : (+ <>+ {/* Overview 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-4">+ <div className="flex items-center gap-2 mb-1">+ <Target size={14} className="text-port-accent" />+ <span className="text-xs text-gray-500">Tasks Analyzed</span>+ </div>+ <div className="text-2xl font-bold text-white">{learning.totals.completed}</div>+ <div className="text-xs text-gray-500">+ {learning.totals.succeeded} success / {learning.totals.failed} failed+ </div>+ </div>++ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-1">+ <TrendingUp size={14} className={getSuccessRateColor(learning.totals.successRate)} />+ <span className="text-xs text-gray-500">Success Rate</span>+ </div>+ <div className={`text-2xl font-bold ${getSuccessRateColor(learning.totals.successRate)}`}>+ {learning.totals.successRate}%+ </div>+ <div className="w-full bg-port-border rounded-full h-1.5 mt-2">+ <div+ className={`h-1.5 rounded-full ${getSuccessRateBg(learning.totals.successRate)}`}+ style={{ width: `${learning.totals.successRate}%` }}+ />+ </div>+ </div>++ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-1">+ <Clock size={14} className="text-cyan-400" />+ <span className="text-xs text-gray-500">Avg Duration</span>+ </div>+ <div className="text-2xl font-bold text-cyan-400">{learning.totals.avgDurationMin}m</div>+ <div className="text-xs text-gray-500">per task</div>+ </div>++ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-1">+ <SkipForward size={14} className={skipped?.skippedCount > 0 ? 'text-port-warning' : 'text-gray-500'} />+ <span className="text-xs text-gray-500">Skipped Types</span>+ </div>+ <div className={`text-2xl font-bold ${skipped?.skippedCount > 0 ? 'text-port-warning' : 'text-gray-500'}`}>+ {skipped?.skippedCount || 0}+ </div>+ <div className="text-xs text-gray-500">due to low success</div>+ </div>+ </div>++ {/* Recommendations */}+ {learning.recommendations?.length > 0 && (+ <div className="bg-gradient-to-r from-purple-500/10 to-blue-500/10 border border-purple-500/30 rounded-lg p-4">+ <h4 className="text-sm font-medium text-white mb-3 flex items-center gap-2">+ <Zap size={14} className="text-yellow-400" />+ AI Recommendations+ </h4>+ <div className="space-y-2">+ {learning.recommendations.map((rec, idx) => (+ <div+ key={idx}+ className={`text-sm p-2 rounded flex items-start gap-2 ${+ rec.type === 'warning' ? 'bg-yellow-500/10 text-yellow-400' :+ rec.type === 'action' ? 'bg-red-500/10 text-red-400' :+ rec.type === 'optimization' ? 'bg-green-500/10 text-green-400' :+ rec.type === 'suggestion' ? 'bg-blue-500/10 text-blue-400' :+ 'bg-gray-500/10 text-gray-400'+ }`}+ >+ {rec.type === 'warning' && <AlertTriangle size={14} className="mt-0.5 shrink-0" />}+ {rec.type === 'action' && <XCircle size={14} className="mt-0.5 shrink-0" />}+ {rec.type === 'optimization' && <CheckCircle size={14} className="mt-0.5 shrink-0" />}+ {rec.type === 'suggestion' && <Zap size={14} className="mt-0.5 shrink-0" />}+ {rec.type === 'info' && <Target size={14} className="mt-0.5 shrink-0" />}+ <span>{rec.message}</span>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Task Type Performance */}+ <div>+ <button+ onClick={() => toggleSection('taskTypes')}+ className="flex items-center gap-2 w-full text-left mb-3"+ >+ {expandedSections.taskTypes ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ <BarChart2 size={16} className="text-port-accent" />+ <span className="font-medium text-white">Task Type Performance</span>+ <span className="text-xs text-gray-500">+ ({performance?.topPerformers?.length || 0} top, {performance?.needsAttention?.length || 0} need attention)+ </span>+ </button>+ {expandedSections.taskTypes && (+ <div className="space-y-4">+ {/* Top Performers */}+ {performance?.topPerformers?.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">+ <div className="px-4 py-2 bg-port-success/10 border-b border-port-border">+ <span className="text-sm font-medium text-port-success flex items-center gap-2">+ <TrendingUp size={14} />+ Top Performers (80%+ success)+ </span>+ </div>+ <div className="divide-y divide-port-border">+ {performance.topPerformers.map((item, idx) => (+ <div key={idx} className="p-3 flex items-center justify-between">+ <div className="flex-1 min-w-0">+ <div className="text-sm text-white truncate">{item.taskType}</div>+ <div className="text-xs text-gray-500">+ {item.completed} tasks • {item.avgDurationMin}m avg+ </div>+ </div>+ <div className="flex items-center gap-3">+ <div className="w-24 bg-port-border rounded-full h-2">+ <div+ className="h-2 rounded-full bg-port-success"+ style={{ width: `${item.successRate}%` }}+ />+ </div>+ <span className="text-sm font-mono text-port-success w-12 text-right">+ {item.successRate}%+ </span>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Needs Attention */}+ {performance?.needsAttention?.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">+ <div className="px-4 py-2 bg-port-error/10 border-b border-port-border">+ <span className="text-sm font-medium text-port-error flex items-center gap-2">+ <TrendingDown size={14} />+ Needs Attention (<50% success)+ </span>+ </div>+ <div className="divide-y divide-port-border">+ {performance.needsAttention.map((item, idx) => (+ <div key={idx} className="p-3 flex items-center justify-between">+ <div className="flex-1 min-w-0">+ <div className="text-sm text-white truncate">{item.taskType}</div>+ <div className="text-xs text-gray-500">+ {item.completed} tasks • {item.avgDurationMin}m avg+ </div>+ </div>+ <div className="flex items-center gap-3">+ <div className="w-24 bg-port-border rounded-full h-2">+ <div+ className="h-2 rounded-full bg-port-error"+ style={{ width: `${item.successRate}%` }}+ />+ </div>+ <span className="text-sm font-mono text-port-error w-12 text-right">+ {item.successRate}%+ </span>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ {performance?.topPerformers?.length === 0 && performance?.needsAttention?.length === 0 && (+ <div className="text-center py-4 text-gray-500 text-sm">+ Need at least 3 completed tasks per type to show performance data+ </div>+ )}+ </div>+ )}+ </div>++ {/* Skipped Task Types */}+ {skipped?.skippedCount > 0 && (+ <div>+ <button+ onClick={() => toggleSection('skipped')}+ className="flex items-center gap-2 w-full text-left mb-3"+ >+ {expandedSections.skipped ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ <SkipForward size={16} className="text-port-warning" />+ <span className="font-medium text-white">Skipped Task Types</span>+ <span className="text-xs text-port-warning">({skipped.skippedCount})</span>+ </button>+ {expandedSections.skipped && (+ <div className="bg-port-warning/10 border border-port-warning/30 rounded-lg p-4">+ <p className="text-sm text-gray-400 mb-3">+ These task types have been automatically skipped due to very low success rates (<30% with 5+ attempts).+ </p>+ <div className="space-y-2">+ {skipped.skippedTypes.map((item, idx) => (+ <div key={idx} className="flex items-center justify-between p-2 bg-port-bg rounded">+ <div>+ <span className="text-sm text-white">{item.taskType}</span>+ <span className="text-xs text-gray-500 ml-2">+ ({item.completed} attempts)+ </span>+ </div>+ <span className="text-sm text-port-error font-mono">{item.successRate}%</span>+ </div>+ ))}+ </div>+ <p className="text-xs text-gray-500 mt-3">+ Fix underlying issues to re-enable these task types+ </p>+ </div>+ )}+ </div>+ )}++ {/* Duration Estimates */}+ {durations && Object.keys(durations).length > 1 && (+ <div>+ <button+ onClick={() => toggleSection('durations')}+ className="flex items-center gap-2 w-full text-left mb-3"+ >+ {expandedSections.durations ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ <Timer size={16} className="text-cyan-400" />+ <span className="font-medium text-white">Duration Estimates</span>+ <span className="text-xs text-gray-500">+ ({Object.keys(durations).length - 1} task types)+ </span>+ </button>+ {expandedSections.durations && (+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">+ <table className="w-full text-sm">+ <thead className="bg-port-bg">+ <tr>+ <th className="text-left p-3 text-gray-500 font-medium">Task Type</th>+ <th className="text-right p-3 text-gray-500 font-medium">Avg Duration</th>+ <th className="text-right p-3 text-gray-500 font-medium hidden sm:table-cell">Samples</th>+ <th className="text-right p-3 text-gray-500 font-medium hidden sm:table-cell">Success</th>+ </tr>+ </thead>+ <tbody>+ {Object.entries(durations)+ .filter(([key]) => key !== '_overall')+ .sort((a, b) => b[1].avgDurationMs - a[1].avgDurationMs)+ .map(([taskType, data], idx) => (+ <tr key={idx} className="border-t border-port-border">+ <td className="p-3 text-gray-300 truncate max-w-[200px]">{taskType}</td>+ <td className="p-3 text-right text-cyan-400 font-mono">+ {formatDuration(data.avgDurationMs)}+ </td>+ <td className="p-3 text-right text-gray-500 hidden sm:table-cell">+ {data.completed}+ </td>+ <td className={`p-3 text-right font-mono hidden sm:table-cell ${getSuccessRateColor(data.successRate)}`}>+ {data.successRate}%+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </div>+ )}++ {/* Model Performance */}+ {learning.insights?.modelEffectiveness?.length > 0 && (+ <div>+ <button+ onClick={() => toggleSection('models')}+ className="flex items-center gap-2 w-full text-left mb-3"+ >+ {expandedSections.models ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ <Zap size={16} className="text-yellow-400" />+ <span className="font-medium text-white">Model Performance</span>+ <span className="text-xs text-gray-500">+ ({learning.insights.modelEffectiveness.length} tiers)+ </span>+ </button>+ {expandedSections.models && (+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ {learning.insights.modelEffectiveness.map((model, idx) => {+ const tierLabels = {+ 'light': { label: 'Haiku', desc: 'Fast, simple tasks' },+ 'medium': { label: 'Sonnet', desc: 'Balanced performance' },+ 'heavy': { label: 'Opus', desc: 'Complex tasks' },+ 'user-specified': { label: 'User Selected', desc: 'Manual override' }+ };+ const info = tierLabels[model.tier] || { label: model.tier, desc: '' };++ return (+ <div key={idx} className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between mb-2">+ <span className="text-sm font-medium text-white">{info.label}</span>+ <span className={`text-lg font-bold ${getSuccessRateColor(model.successRate)}`}>+ {model.successRate}%+ </span>+ </div>+ <div className="w-full bg-port-border rounded-full h-2 mb-2">+ <div+ className={`h-2 rounded-full ${getSuccessRateBg(model.successRate)}`}+ style={{ width: `${model.successRate}%` }}+ />+ </div>+ <div className="flex justify-between text-xs text-gray-500">+ <span>{info.desc}</span>+ <span>{model.completed} tasks • {model.avgDurationMin}m avg</span>+ </div>+ </div>+ );+ })}+ </div>+ )}+ </div>+ )}++ {/* Error Patterns */}+ {learning.insights?.commonErrors?.length > 0 && (+ <div>+ <button+ onClick={() => toggleSection('errors')}+ className="flex items-center gap-2 w-full text-left mb-3"+ >+ {expandedSections.errors ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ <AlertTriangle size={16} className="text-port-error" />+ <span className="font-medium text-white">Error Patterns</span>+ <span className="text-xs text-gray-500">+ ({learning.insights.commonErrors.length} categories)+ </span>+ </button>+ {expandedSections.errors && (+ <div className="bg-port-card border border-port-border rounded-lg divide-y divide-port-border">+ {learning.insights.commonErrors.map((error, idx) => (+ <div key={idx} className="p-3">+ <div className="flex items-center justify-between mb-1">+ <span className="text-sm text-port-error font-medium">{error.category}</span>+ <span className="text-xs text-gray-500">{error.count} occurrences</span>+ </div>+ {error.affectedTypes?.length > 0 && (+ <div className="text-xs text-gray-500">+ Affects: {error.affectedTypes.join(', ')}+ </div>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ )}++ {/* Last Updated */}+ {learning.lastUpdated && (+ <div className="text-xs text-gray-600 text-center pt-4 border-t border-port-border">+ Learning data last updated: {new Date(learning.lastUpdated).toLocaleString()}+ </div>+ )}+ </>+ )}+ </div>+ );+}diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 88f80b134d..6af8f0c952 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -22,6 +22,7 @@ import {ScriptsTab,ScheduleTab,DigestTab,+ LearningTab,MemoryTab,HealthTab,ConfigTab@@ -501,6 +502,11 @@ export default function ChiefOfStaff() {<DigestTab /></div>)}+ {activeTab === 'learning' && (+ <div role="tabpanel" id="tabpanel-learning" aria-labelledby="tab-learning">+ <LearningTab />+ </div>+ )}{activeTab === 'memory' && (<div role="tabpanel" id="tabpanel-memory" aria-labelledby="tab-memory"><MemoryTab />diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 3d87df1f87..220f70fb35 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -259,6 +259,8 @@ export const getCosTodayActivity = () => request('/cos/activity/today');// CoS Learningexport const getCosLearning = () => request('/cos/learning');export const getCosLearningDurations = () => request('/cos/learning/durations');+export const getCosLearningSkipped = () => request('/cos/learning/skipped');+export const getCosLearningPerformance = () => request('/cos/learning/performance');export const backfillCosLearning = () => request('/cos/learning/backfill', { method: 'POST' });// CoS Scriptsdiff --git a/data.sample/memory-classifier-config.json b/data.sample/memory-classifier-config.jsonnew file mode 100644index 0000000000..ff0d507420--- /dev/null+++ b/data.sample/memory-classifier-config.json@@ -0,0 +1,10 @@+{+ "enabled": true,+ "provider": "lmstudio",+ "endpoint": "http://localhost:1234/v1/chat/completions",+ "model": "gptoss-20b",+ "timeout": 60000,+ "maxOutputLength": 10000,+ "minConfidence": 0.6,+ "fallbackToPatterns": true+}diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.jsonindex 718a50c5b9..bfcd2ff03f 100644--- a/data.sample/prompts/stage-config.json+++ b/data.sample/prompts/stage-config.json@@ -48,6 +48,14 @@"model": "heavy","returnsJson": true,"variables": []+ },+ "memory-evaluate": {+ "name": "Memory Evaluation",+ "description": "Evaluate agent output to extract useful memories",+ "model": "lmstudio:gptoss-20b",+ "provider": "lmstudio",+ "returnsJson": true,+ "variables": []}}}diff --git a/data.sample/prompts/stages/memory-evaluate.md b/data.sample/prompts/stages/memory-evaluate.mdnew file mode 100644index 0000000000..7e0244aaf5--- /dev/null+++ b/data.sample/prompts/stages/memory-evaluate.md@@ -0,0 +1,89 @@+# Memory Classification++You are evaluating an AI agent's task output to extract useful, reusable knowledge.++## Task Information+**Task ID**: {{taskId}}+**Description**: {{taskDescription}}+**Status**: {{taskStatus}}+**App**: {{appName}}++## Agent Output+```+{{agentOutput}}+```++## Your Job++Analyze the agent output and determine if there are any **reusable learnings** worth saving as memories.++**Good memories are:**+- Codebase facts: File locations, architecture patterns, naming conventions, dependencies+- User preferences: Coding style, tool preferences, workflow patterns+- Learnings: Discovered behaviors, gotchas, workarounds that apply broadly+- Decisions: Architectural choices with reasoning that future tasks should respect++**Bad memories are:**+- Task echoes: Just restating what the task was (e.g., "Task 'fix button' was completed")+- Generic summaries: "The task was successful" or "Changes were made"+- Temporary info: Session-specific data, timestamps, one-time fixes+- Already known: Common programming knowledge, standard library usage+- Truncated/incomplete: Content that got cut off mid-sentence++## Output Format++Return a JSON array of memories to create. If there are no useful memories, return an empty array.++```json+{+ "memories": [+ {+ "type": "fact|learning|observation|decision|preference",+ "category": "codebase|workflow|tools|architecture|patterns|conventions|preferences",+ "content": "The actual memory content - concise but complete",+ "confidence": 0.6-1.0,+ "tags": ["tag1", "tag2"],+ "reasoning": "Brief explanation of why this is worth remembering"+ }+ ],+ "rejected": [+ {+ "content": "What was rejected",+ "reason": "Why it's not useful as a memory"+ }+ ]+}+```++## Confidence Guidelines++- **0.9-1.0**: Clear, verified facts from code exploration+- **0.8-0.9**: Strong patterns with evidence+- **0.7-0.8**: Useful learnings that may have edge cases+- **0.6-0.7**: Tentative observations worth reviewing++Only include memories with confidence >= 0.6. Be selective - fewer high-quality memories are better than many low-quality ones.++## Examples++### Good Memory (from a code fix task):+```json+{+ "type": "fact",+ "category": "codebase",+ "content": "Video components in Media.jsx require explicit poster prop to prevent flash of empty player",+ "confidence": 0.9,+ "tags": ["react", "video", "media-page"],+ "reasoning": "Discovered during bug fix - will prevent similar issues"+}+```++### Bad Memory (would be rejected):+```json+{+ "content": "Task 'fix video display' was completed successfully",+ "reason": "Just echoes the task description - no reusable knowledge"+}+```++Now analyze the agent output above and extract any useful memories.diff --git a/data.sample/providers.json b/data.sample/providers.jsonindex 6af1339333..8ed6f128dd 100644--- a/data.sample/providers.json+++ b/data.sample/providers.json@@ -49,8 +49,9 @@"type": "api","endpoint": "http://localhost:1234/v1","apiKey": "lm-studio",- "models": [],- "defaultModel": null,+ "models": ["gptoss-20b"],+ "defaultModel": "gptoss-20b",+ "memoryClassifierModel": "gptoss-20b","timeout": 300000,"enabled": true,"envVars": {}diff --git a/server/services/cos.js b/server/services/cos.jsindex 8336abb7fd..3ccd3b01cc 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -552,11 +552,23 @@ export async function evaluateTasks() {}}- // Priority 3: Generate idle review task if no other work and idle review enabled+ // Background: Queue eligible self-improvement tasks as system tasks (runs regardless of user tasks)+ // These will be picked up in Priority 2 on subsequent evaluations+ if (state.config.idleReviewEnabled) {+ await queueEligibleImprovementTasks(state, cosTaskData);+ }++ // Priority 3: Only generate direct idle task if nothing else to do AND no system tasks queued+ // This is a fallback - normally self-improvement tasks should be queued as system tasksif (tasksToSpawn.length === 0 && state.config.idleReviewEnabled) {- const idleTask = await generateIdleReviewTask(state);- if (idleTask) {- tasksToSpawn.push(idleTask);+ // Check if we have any pending system tasks that just got queued+ const freshCosTasks = await getCosTasks();+ const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;+ if (pendingSystemTasks === 0) {+ const idleTask = await generateIdleReviewTask(state);+ if (idleTask) {+ tasksToSpawn.push(idleTask);+ }}}@@ -706,6 +718,156 @@ async function generateIdleReviewTask(state) {return null;}+/**+ * Queue eligible self-improvement and app improvement tasks as system tasks+ * Called during every evaluation to ensure system tasks are queued even when user tasks exist+ * Tasks are queued to COS-TASKS.md and will be picked up in Priority 2+ */+async function queueEligibleImprovementTasks(state, cosTaskData) {+ const { getDueSelfImprovementTasks, shouldRunSelfImprovementTask, getNextAppImprovementTaskType } = await import('./taskSchedule.js');++ // Get existing pending/in_progress system tasks to avoid duplicates+ const existingTasks = cosTaskData.tasks || [];+ const existingTaskTypes = new Set();++ for (const task of existingTasks) {+ if (task.status === 'pending' || task.status === 'in_progress') {+ // Check for self-improvement type in metadata or description+ const selfImpType = task.metadata?.selfImprovementType ||+ task.description?.match(/\[self-improvement\]\s*(\w[\w-]*)/i)?.[1];+ if (selfImpType) {+ existingTaskTypes.add(selfImpType);+ }+ // Check for app improvement type+ const appImpType = task.metadata?.analysisType;+ const appId = task.metadata?.app;+ if (appImpType && appId) {+ existingTaskTypes.add(`app:${appId}:${appImpType}`);+ }+ }+ }++ let queued = 0;++ // Queue eligible self-improvement tasks for PortOS+ if (state.config.selfImprovementEnabled) {+ const dueTasks = await getDueSelfImprovementTasks().catch(() => []);++ for (const taskType of dueTasks) {+ // Skip if already queued+ if (existingTaskTypes.has(taskType)) {+ emitLog('debug', `Self-improvement task ${taskType} already queued`);+ continue;+ }++ // Double-check eligibility+ const eligible = await shouldRunSelfImprovementTask(taskType).catch(() => false);+ if (!eligible) continue;++ // Generate task description+ const taskDesc = getSelfImprovementTaskDescription(taskType);+ if (!taskDesc) continue;++ // Add to COS-TASKS.md+ const newTask = await addTask({+ id: `sys-${taskType}-${Date.now().toString(36)}`,+ description: `[self-improvement] ${taskType}: ${taskDesc}`,+ priority: 'LOW',+ app: null,+ context: `Auto-generated self-improvement task. Type: ${taskType}`,+ approvalRequired: false+ }, 'internal');++ emitLog('info', `Queued self-improvement task: ${taskType}`, { taskId: newTask.id });+ existingTaskTypes.add(taskType);+ queued++;+ }+ }++ // Queue eligible app improvement tasks for managed apps+ const apps = await getAllApps().catch(() => []);+ for (const app of apps) {+ // Check if app is on cooldown+ const onCooldown = await isAppOnCooldown(app.id, state.config.appReviewCooldownMs);+ if (onCooldown) continue;++ // Get next eligible improvement type for this app+ const nextType = await getNextAppImprovementTaskType(app.id).catch(() => null);+ if (!nextType) continue;++ const taskKey = `app:${app.id}:${nextType}`;+ if (existingTaskTypes.has(taskKey)) {+ emitLog('debug', `App improvement task ${nextType} for ${app.name} already queued`);+ continue;+ }++ // Generate task description+ const taskDesc = getAppImprovementTaskDescription(nextType, app);+ if (!taskDesc) continue;++ // Add to COS-TASKS.md+ const newTask = await addTask({+ id: `sys-app-${app.id.slice(0, 8)}-${nextType}-${Date.now().toString(36)}`,+ description: taskDesc,+ priority: 'LOW',+ app: app.id,+ context: `Auto-generated app improvement task for ${app.name}. Type: ${nextType}`,+ approvalRequired: false+ }, 'internal');++ emitLog('info', `Queued app improvement task: ${nextType} for ${app.name}`, { taskId: newTask.id, appId: app.id });+ existingTaskTypes.add(taskKey);+ queued++;++ // Only queue one task per app per evaluation to avoid flooding+ break;+ }++ if (queued > 0) {+ emitLog('info', `Queued ${queued} improvement task(s) to system tasks`);+ }+}++/**+ * Get task description for a self-improvement type+ */+function getSelfImprovementTaskDescription(taskType) {+ const descriptions = {+ 'ui-bugs': 'Review PortOS UI for visual bugs, layout issues, and UX improvements',+ 'mobile-responsive': 'Check mobile responsiveness and fix layout issues on smaller screens',+ 'security': 'Audit PortOS for security vulnerabilities (XSS, injection, auth issues)',+ 'code-quality': 'Review code for DRY violations, dead code, and refactoring opportunities',+ 'console-errors': 'Check browser console and fix JavaScript errors and warnings',+ 'performance': 'Profile and optimize slow components, queries, and renders',+ 'cos-enhancement': 'Improve CoS capabilities, prompts, and task handling logic',+ 'test-coverage': 'Add missing tests for uncovered code paths',+ 'documentation': 'Update documentation, comments, and README files',+ 'feature-ideas': 'Brainstorm and document potential new features for PortOS',+ 'accessibility': 'Audit and fix accessibility issues (ARIA, keyboard nav, contrast)',+ 'dependency-updates': 'Check for and safely update outdated dependencies'+ };+ return descriptions[taskType] || null;+}++/**+ * Get task description for an app improvement type+ */+function getAppImprovementTaskDescription(taskType, app) {+ const descriptions = {+ 'security-audit': `Security audit for ${app.name}: check for vulnerabilities`,+ 'code-quality': `Code quality review for ${app.name}: DRY violations, dead code`,+ 'test-coverage': `Add missing tests for ${app.name}`,+ 'performance': `Performance optimization for ${app.name}`,+ 'accessibility': `Accessibility audit for ${app.name}`,+ 'console-errors': `Fix console errors in ${app.name}`,+ 'dependency-updates': `Update dependencies for ${app.name}`,+ 'documentation': `Update documentation for ${app.name}`,+ 'error-handling': `Improve error handling in ${app.name}`,+ 'typing': `Add/fix TypeScript types in ${app.name}`+ };+ return descriptions[taskType] || null;+}+// Self-improvement task types (rotates through these)// Organized by goal priority from COS-GOALS.mdconst SELF_IMPROVEMENT_TYPES = [diff --git a/server/services/memoryClassifier.js b/server/services/memoryClassifier.jsnew file mode 100644index 0000000000..d70ccf9609--- /dev/null+++ b/server/services/memoryClassifier.js@@ -0,0 +1,289 @@+/**+ * Memory Classifier Service+ *+ * Uses an LLM to intelligently evaluate agent output and extract useful memories.+ * Falls back to pattern-based extraction if LLM is unavailable.+ */++import { readFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { getStageTemplate } from './promptService.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const CONFIG_DIR = join(__dirname, '../../data');+const MEMORY_CONFIG_FILE = join(CONFIG_DIR, 'memory-classifier-config.json');++// Default configuration+const DEFAULT_CONFIG = {+ enabled: true,+ provider: 'lmstudio',+ endpoint: 'http://localhost:1234/v1/chat/completions',+ model: 'gptoss-20b',+ timeout: 60000,+ maxOutputLength: 10000,+ minConfidence: 0.6,+ fallbackToPatterns: true+};++let configCache = null;++/**+ * Load classifier configuration+ */+async function loadConfig() {+ if (configCache) return configCache;++ if (existsSync(MEMORY_CONFIG_FILE)) {+ const content = await readFile(MEMORY_CONFIG_FILE, 'utf-8');+ configCache = { ...DEFAULT_CONFIG, ...JSON.parse(content) };+ } else {+ configCache = DEFAULT_CONFIG;+ }++ return configCache;+}++/**+ * Get current configuration+ */+export async function getConfig() {+ return loadConfig();+}++/**+ * Update configuration+ */+export async function updateConfig(updates) {+ const { writeFile, mkdir } = await import('fs/promises');++ const config = await loadConfig();+ const newConfig = { ...config, ...updates };++ if (!existsSync(CONFIG_DIR)) {+ await mkdir(CONFIG_DIR, { recursive: true });+ }++ const { writeFile: write } = await import('fs/promises');+ await write(MEMORY_CONFIG_FILE, JSON.stringify(newConfig, null, 2));+ configCache = newConfig;++ return newConfig;+}++/**+ * Build the classification prompt+ */+async function buildClassificationPrompt(task, agentOutput, config) {+ // Try to load the template+ const template = await getStageTemplate('memory-evaluate').catch(() => null);++ if (!template) {+ // Fallback inline template+ return buildFallbackPrompt(task, agentOutput);+ }++ // Apply variables to template+ const variables = {+ taskId: task.id || 'unknown',+ taskDescription: task.description || 'No description',+ taskStatus: task.status || 'completed',+ appName: task.metadata?.app || 'PortOS',+ agentOutput: agentOutput.substring(0, config.maxOutputLength || 10000)+ };++ let prompt = template;+ for (const [key, value] of Object.entries(variables)) {+ prompt = prompt.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), value);+ }++ return prompt;+}++/**+ * Fallback prompt if template not found+ */+function buildFallbackPrompt(task, agentOutput) {+ return `Analyze this agent output and extract useful memories.++Task: ${task.description || 'Unknown task'}+Output:+${agentOutput.substring(0, 8000)}++Return JSON with memories array. Each memory should have:+- type: fact|learning|observation|decision|preference+- category: codebase|workflow|tools|architecture|patterns|conventions|preferences+- content: the actual memory+- confidence: 0.6-1.0+- tags: relevant tags+- reasoning: why this is worth remembering++Only include memories with genuine reusable value. Do not include:+- Task echoes (e.g., "Task X was completed")+- Generic summaries+- Temporary or session-specific info++Return: {"memories": [...], "rejected": [...]}`;+}++/**+ * Call LM Studio API for classification+ */+async function callLLM(prompt, config) {+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), config.timeout);++ const response = await fetch(config.endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'Authorization': `Bearer lm-studio`+ },+ body: JSON.stringify({+ model: config.model,+ messages: [+ {+ role: 'system',+ content: 'You are a memory classification assistant. Return only valid JSON.'+ },+ {+ role: 'user',+ content: prompt+ }+ ],+ temperature: 0.1,+ max_tokens: 2000+ }),+ signal: controller.signal+ }).finally(() => clearTimeout(timeoutId));++ if (!response.ok) {+ const error = await response.text().catch(() => 'Unknown error');+ throw new Error(`LLM API error ${response.status}: ${error}`);+ }++ const data = await response.json();+ return data.choices?.[0]?.message?.content || '';+}++/**+ * Parse LLM response to extract memories+ */+function parseLLMResponse(response) {+ // Extract JSON from response (may be wrapped in markdown code blocks)+ const jsonMatch = response.match(/```(?:json)?\s*([\s\S]*?)```/) ||+ response.match(/(\{[\s\S]*\})/);++ if (!jsonMatch) {+ console.log('⚠️ Could not find JSON in LLM response');+ return { memories: [], rejected: [], parseError: true };+ }++ const parsed = JSON.parse(jsonMatch[1]);++ // Validate structure+ if (!Array.isArray(parsed.memories)) {+ return { memories: [], rejected: parsed.rejected || [], parseError: false };+ }++ // Validate each memory+ const validMemories = parsed.memories.filter(m => {+ if (!m.type || !m.content || typeof m.confidence !== 'number') return false;+ if (m.confidence < 0.6) return false;+ if (m.content.length < 10) return false;++ // Reject obvious task echoes+ if (/^Task\s+['"].*['"]\s*:/i.test(m.content)) return false;+ if (/was\s+(completed|successful|done)/i.test(m.content) && m.content.length < 50) return false;++ return true;+ });++ return {+ memories: validMemories,+ rejected: parsed.rejected || [],+ parseError: false+ };+}++/**+ * Main classification function+ *+ * @param {Object} task - Task object with id, description, metadata+ * @param {string} agentOutput - The agent's output text+ * @returns {Object} { memories: [], rejected: [], usedLLM: boolean, error?: string }+ */+export async function classifyMemories(task, agentOutput) {+ const config = await loadConfig();++ // Skip if output is too short+ if (!agentOutput || agentOutput.length < 100) {+ return { memories: [], rejected: [], usedLLM: false, skipped: 'output-too-short' };+ }++ // Skip if disabled+ if (!config.enabled) {+ return { memories: [], rejected: [], usedLLM: false, skipped: 'classifier-disabled' };+ }++ const prompt = await buildClassificationPrompt(task, agentOutput, config);++ // Call LLM for classification+ const llmResponse = await callLLM(prompt, config).catch(err => {+ console.log(`⚠️ LLM classification failed: ${err.message}`);+ return null;+ });++ if (!llmResponse) {+ return {+ memories: [],+ rejected: [],+ usedLLM: false,+ error: 'LLM call failed',+ fallbackAvailable: config.fallbackToPatterns+ };+ }++ const result = parseLLMResponse(llmResponse);++ if (result.parseError) {+ console.log('⚠️ Failed to parse LLM response, raw:', llmResponse.substring(0, 200));+ return {+ memories: [],+ rejected: [],+ usedLLM: true,+ error: 'Failed to parse LLM response',+ fallbackAvailable: config.fallbackToPatterns+ };+ }++ console.log(`🧠 LLM classified ${result.memories.length} memories, rejected ${result.rejected.length}`);++ return {+ memories: result.memories,+ rejected: result.rejected,+ usedLLM: true+ };+}++/**+ * Check if the classifier is available (LLM endpoint reachable)+ */+export async function isAvailable() {+ const config = await loadConfig();++ if (!config.enabled) return false;++ // Quick health check+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 5000);++ const response = await fetch(config.endpoint.replace('/chat/completions', '/models'), {+ method: 'GET',+ signal: controller.signal+ }).catch(() => null).finally(() => clearTimeout(timeoutId));++ return response?.ok === true;+}diff --git a/server/services/memoryExtractor.js b/server/services/memoryExtractor.jsindex a6e8ca6950..6389d38160 100644--- a/server/services/memoryExtractor.js+++ b/server/services/memoryExtractor.js@@ -9,6 +9,7 @@ import { createMemory } from './memory.js';import { generateMemoryEmbedding } from './memoryEmbeddings.js';import { cosEvents } from './cos.js';import * as notifications from './notifications.js';+import { classifyMemories, isAvailable as isClassifierAvailable } from './memoryClassifier.js';/*** Parse structured MEMORY blocks from agent output@@ -228,22 +229,65 @@ function deduplicateMemories(memories) {/*** Main extraction function* Processes agent output and creates memories+ *+ * Uses LLM-based classification when available, falls back to pattern matching.*/export async function extractAndStoreMemories(agentId, taskId, output, task = null) {const allMemories = [];+ let usedLLM = false;- // Parse structured memory blocks- const structured = parseMemoryBlocks(output);- allMemories.push(...structured);+ // Try LLM-based classification first (if available)+ const classifierAvailable = await isClassifierAvailable().catch(() => false);- // Extract patterns from text- const patterns = extractPatterns(output);- allMemories.push(...patterns);+ if (classifierAvailable && task) {+ const llmResult = await classifyMemories(task, output).catch(err => {+ console.log(`⚠️ LLM memory classification failed: ${err.message}`);+ return null;+ });- // Extract task context- if (task) {- const taskContext = extractTaskContext(task, output, true);- allMemories.push(...taskContext);+ if (llmResult?.memories?.length > 0) {+ usedLLM = true;+ console.log(`🧠 LLM classified ${llmResult.memories.length} memories`);++ // Convert LLM results to our format+ for (const mem of llmResult.memories) {+ allMemories.push({+ type: mem.type || 'observation',+ category: mem.category || 'other',+ content: mem.content,+ confidence: mem.confidence || 0.7,+ tags: mem.tags || [],+ reasoning: mem.reasoning+ });+ }+ }+ }++ // Fall back to pattern-based extraction if LLM didn't produce results+ if (!usedLLM) {+ // Parse structured memory blocks+ const structured = parseMemoryBlocks(output);+ allMemories.push(...structured);++ // Extract patterns from text+ const patterns = extractPatterns(output);+ allMemories.push(...patterns);++ // Extract task context (but only if meaningful, not just task echoes)+ if (task) {+ const taskContext = extractTaskContext(task, output, true);+ // Filter out low-quality task context memories+ const filtered = taskContext.filter(m => {+ // Reject memories that just echo the task description+ if (m.content.startsWith(`Task "${task.description.substring(0, 50)}`)) return false;+ // Reject memories that are just "## Summary" or similar+ if (/^(##?\s*)?Summary\s*$/i.test(m.content)) return false;+ // Reject very short memories+ if (m.content.length < 30) return false;+ return true;+ });+ allMemories.push(...filtered);+ }}// Deduplicate