Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add task learning system and dependency updates task type

Adam Eivyfbd7e4e25633
diff --git a/PLAN.md b/PLAN.md
index b261ba00c1..5f0f86e07f 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -1345,3 +1345,72 @@ const ALLOWED_COMMANDS = new Set([
2. **Audit Logging**: Log all command executions for forensic analysis
3. **Content Security Policy**: Add CSP headers to client responses
4. **Command Argument Validation**: Consider validating arguments to allowed commands, not just base commands
+
+---
+
+## M27: CoS Capability Enhancements (2026-01-08)
+
+Enhancements to the Chief of Staff system for better task learning, smarter prioritization, and expanded self-improvement capabilities.
+
+### Features
+
+#### 1. New Self-Improvement Task Type: Dependency Updates
+Added `dependency-updates` task type that:
+- Runs `npm audit` in both server and client directories
+- Checks for outdated packages with `npm outdated`
+- Reviews CRITICAL and HIGH severity vulnerabilities
+- Updates dependencies carefully (patch → minor → major)
+- Runs tests and build to verify updates
+- Commits with changelog of what was updated
+
+#### 2. Enhanced Performance Tracking
+New `getPerformanceSummary()` function provides:
+- Overall success rate across all task types
+- Top performing task types (>80% success)
+- Task types needing attention (<50% success)
+- Task types being skipped (<30% success)
+- Average duration statistics
+
+#### 3. Learning Insights System
+New functions for recording and retrieving observations:
+- `recordLearningInsight()` - Store observations about what works/doesn't
+- `getRecentInsights()` - Retrieve recent learning insights
+- Insights stored with timestamp, type, and context
+
+#### 4. Periodic Performance Logging
+Every 10 evaluations, CoS logs:
+- Overall success rate and total tasks completed
+- Count of top performers and tasks needing attention
+- Evaluation count tracking in state
+
+### New API Endpoints
+
+| Route | Description |
+|-------|-------------|
+| GET /api/cos/learning/performance | Get performance summary |
+| GET /api/cos/learning/insights | Get recent learning insights |
+| POST /api/cos/learning/insights | Record a learning insight |
+
+### Self-Improvement Task Types (12 total)
+
+1. **ui-bugs** - Check UI for JavaScript errors
+2. **mobile-responsive** - Test viewport sizes
+3. **security** - Audit for vulnerabilities
+4. **code-quality** - Find DRY violations, dead code
+5. **console-errors** - Fix JS errors
+6. **performance** - Optimize re-renders, queries
+7. **cos-enhancement** - Improve CoS itself
+8. **test-coverage** - Add tests
+9. **documentation** - Update docs
+10. **feature-ideas** - Implement new features
+11. **accessibility** - Check a11y issues
+12. **dependency-updates** - Update npm packages
+
+### Implementation Files
+
+| File | Changes |
+|------|---------|
+| `server/services/cos.js` | Added dependency-updates type, performance logging |
+| `server/services/taskLearning.js` | Added getPerformanceSummary, recordLearningInsight, getRecentInsights |
+| `server/services/selfImprovement.js` | Added new analysis types to constants |
+| `server/routes/cos.js` | Added 3 new API endpoints for learning insights |
diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsx
index 0697fbca25..68a2b8d749 100644
--- a/client/src/pages/DevTools.jsx
+++ b/client/src/pages/DevTools.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useRef, Fragment } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
-import { GitBranch, Plus, Minus, FileText, Clock, RefreshCw, Activity, Image, X, XCircle, Cpu, MemoryStick, Terminal, Trash2, MessageSquarePlus, Info, Save, Maximize2 } from 'lucide-react';
+import { GitBranch, Plus, Minus, FileText, Clock, RefreshCw, Activity, Image, X, XCircle, Cpu, MemoryStick, Terminal, Trash2, MessageSquarePlus, Info, Save, Maximize2, RotateCcw } from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../services/api';
import socket from '../services/socket';
@@ -355,6 +355,37 @@ export function RunsHistoryPage() {
});
};
+ const handleResume = async (run, e) => {
+ e.stopPropagation();
+ // Fetch details if not already loaded
+ let details = expandedDetails[run.id];
+ if (!details) {
+ const [prompt, output] = await Promise.all([
+ api.getRunPrompt(run.id).catch(() => ''),
+ api.getRunOutput(run.id).catch(() => '')
+ ]);
+ details = { prompt, output };
+ }
+ navigate('/devtools/runner', {
+ state: {
+ continueFrom: {
+ prompt: details.prompt || run.prompt,
+ output: details.output || '',
+ runId: run.id,
+ providerId: run.providerId,
+ providerName: run.providerName,
+ model: run.model,
+ workspacePath: run.workspacePath,
+ workspaceName: run.workspaceName,
+ error: run.error,
+ errorCategory: run.errorCategory,
+ suggestedFix: run.suggestedFix,
+ success: run.success
+ }
+ }
+ });
+ };
+
const getExitCodeInfo = (exitCode) => {
const codeInfo = {
1: { label: 'Error', description: 'Generic error - check the output for details' },
@@ -476,6 +507,16 @@ export function RunsHistoryPage() {
<div className="flex items-center gap-3 pl-8 sm:pl-0">
<span className={`w-2 h-2 rounded-full flex-shrink-0 ${run.success ? 'bg-port-success' : run.success === false ? 'bg-port-error' : 'bg-port-warning'}`} />
<span className="text-sm text-gray-500 flex-shrink-0">{formatTime(run.startTime)}</span>
+ {run.success !== null && (
+ <button
+ onClick={(e) => handleResume(run, e)}
+ className="p-1 text-gray-500 hover:text-port-accent transition-colors sm:opacity-0 sm:group-hover:opacity-100"
+ title="Resume run"
+ data-testid={`resume-run-${run.id}`}
+ >
+ <RotateCcw size={14} />
+ </button>
+ )}
<button
onClick={(e) => handleDelete(run.id, e)}
className="p-1 text-gray-500 hover:text-port-error transition-colors sm:opacity-0 sm:group-hover:opacity-100"
@@ -756,7 +797,27 @@ export function RunnerPage() {
// Build final prompt, merging with continuation context if present
let finalPrompt = prompt.trim();
if (continueContext) {
- finalPrompt = `CONTINUATION OF PREVIOUS CONVERSATION:
+ if (continueContext.success === false) {
+ // Resuming a failed run - include error context
+ finalPrompt = `RESUMING FAILED RUN:
+
+--- PREVIOUS PROMPT ---
+${continueContext.prompt}
+${continueContext.output ? `
+--- PREVIOUS OUTPUT (BEFORE FAILURE) ---
+${continueContext.output}
+` : ''}
+--- ERROR ---
+${continueContext.error || 'Unknown error'}
+${continueContext.suggestedFix ? `
+--- SUGGESTED FIX ---
+${continueContext.suggestedFix}
+` : ''}
+--- NEW INSTRUCTIONS ---
+${prompt.trim()}`;
+ } else {
+ // Continuing a successful conversation
+ finalPrompt = `CONTINUATION OF PREVIOUS CONVERSATION:
--- PREVIOUS PROMPT ---
${continueContext.prompt}
@@ -766,6 +827,7 @@ ${continueContext.output}
--- NEW INSTRUCTIONS ---
${prompt.trim()}`;
+ }
}
setOutput('');
@@ -776,7 +838,8 @@ ${prompt.trim()}`;
model: selectedModel || undefined,
prompt: finalPrompt,
workspacePath: workspacePath || undefined,
- workspaceName: apps.find(a => a.repoPath === workspacePath)?.name
+ workspaceName: apps.find(a => a.repoPath === workspacePath)?.name,
+ timeout: timeout * 60 * 1000 // Convert minutes to milliseconds
}).catch(err => ({ error: err.message }));
if (result.error) {
@@ -874,11 +937,13 @@ ${prompt.trim()}`;
{/* Continuation Context Banner */}
{continueContext && (
- <div className="bg-port-success/10 border border-port-success/30 rounded-xl p-4" data-testid="continuation-banner">
+ <div className={`${continueContext.success === false ? 'bg-port-warning/10 border-port-warning/30' : 'bg-port-success/10 border-port-success/30'} border rounded-xl p-4`} data-testid="continuation-banner">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-2">
- <Info size={18} className="text-port-success" />
- <span className="font-medium text-port-success">Continuing Previous Conversation</span>
+ <Info size={18} className={continueContext.success === false ? 'text-port-warning' : 'text-port-success'} />
+ <span className={`font-medium ${continueContext.success === false ? 'text-port-warning' : 'text-port-success'}`}>
+ {continueContext.success === false ? 'Resuming Failed Run' : 'Continuing Previous Conversation'}
+ </span>
{continueContext.providerName && (
<span className="text-xs text-gray-400 bg-port-card px-2 py-0.5 rounded">
{continueContext.providerName}
@@ -900,15 +965,35 @@ ${prompt.trim()}`;
{continueContext.prompt?.substring(0, 500)}{continueContext.prompt?.length > 500 ? '...' : ''}
</div>
</div>
- <div>
- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Previous Output</div>
- <div className="text-gray-300 bg-port-card/50 rounded px-2 py-1 font-mono text-xs max-h-24 overflow-auto">
- {continueContext.output?.substring(0, 800)}{continueContext.output?.length > 800 ? '...' : ''}
+ {continueContext.success === false && continueContext.error && (
+ <div>
+ <div className="text-xs text-port-error uppercase tracking-wide mb-1">Error</div>
+ <div className="text-port-error/80 bg-port-error/10 rounded px-2 py-1 font-mono text-xs max-h-20 overflow-auto">
+ {continueContext.error}
+ </div>
</div>
- </div>
+ )}
+ {continueContext.success === false && continueContext.suggestedFix && (
+ <div>
+ <div className="text-xs text-port-warning uppercase tracking-wide mb-1">Suggested Fix</div>
+ <div className="text-gray-300 bg-port-warning/10 rounded px-2 py-1 text-xs max-h-20 overflow-auto">
+ {continueContext.suggestedFix}
+ </div>
+ </div>
+ )}
+ {continueContext.output && (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Previous Output</div>
+ <div className="text-gray-300 bg-port-card/50 rounded px-2 py-1 font-mono text-xs max-h-24 overflow-auto">
+ {continueContext.output?.substring(0, 800)}{continueContext.output?.length > 800 ? '...' : ''}
+ </div>
+ </div>
+ )}
</div>
<div className="text-xs text-gray-500 mt-3 italic">
- Enter your follow-up instructions below. The previous context will be included automatically.
+ {continueContext.success === false
+ ? 'Enter instructions to retry the task. The previous context and error will be included automatically.'
+ : 'Enter your follow-up instructions below. The previous context will be included automatically.'}
</div>
</div>
)}
diff --git a/server/routes/cos.js b/server/routes/cos.js
index 6495ed719d..827961d92a 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -337,4 +337,35 @@ router.get('/learning/cooldown/:taskType', asyncHandler(async (req, res) => {
});
}));
+// GET /api/cos/learning/performance - Get performance summary
+router.get('/learning/performance', asyncHandler(async (req, res) => {
+ const summary = await taskLearning.getPerformanceSummary();
+ res.json(summary);
+}));
+
+// GET /api/cos/learning/insights - Get recent learning insights
+router.get('/learning/insights', asyncHandler(async (req, res) => {
+ const limit = parseInt(req.query.limit, 10) || 10;
+ const insights = await taskLearning.getRecentInsights(limit);
+ res.json({
+ count: insights.length,
+ insights
+ });
+}));
+
+// POST /api/cos/learning/insights - Record a learning insight
+router.post('/learning/insights', asyncHandler(async (req, res) => {
+ const { type, message, taskType, context } = req.body;
+ if (!message) {
+ throw new ServerError('Insight message is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const insight = await taskLearning.recordLearningInsight({
+ type: type || 'observation',
+ message,
+ taskType,
+ context
+ });
+ res.json({ success: true, insight });
+}));
+
export default router;
diff --git a/server/routes/runs.js b/server/routes/runs.js
index 978868ce6d..9447513451 100644
--- a/server/routes/runs.js
+++ b/server/routes/runs.js
@@ -17,8 +17,8 @@ router.get('/', asyncHandler(async (req, res, next) => {
// POST /api/runs - Create and execute a new run
router.post('/', asyncHandler(async (req, res, next) => {
- const { providerId, model, prompt, workspacePath, workspaceName } = req.body;
- console.log(`🚀 POST /api/runs - provider: ${providerId}, model: ${model}, workspace: ${workspaceName}`);
+ const { providerId, model, prompt, workspacePath, workspaceName, timeout } = req.body;
+ console.log(`🚀 POST /api/runs - provider: ${providerId}, model: ${model}, workspace: ${workspaceName}, timeout: ${timeout}ms`);
if (!providerId) {
throw new ServerError('providerId is required', {
@@ -39,12 +39,13 @@ router.post('/', asyncHandler(async (req, res, next) => {
model,
prompt,
workspacePath,
- workspaceName
+ workspaceName,
+ timeout
});
- const { runId, provider, metadata } = runData;
+ const { runId, provider, metadata, timeout: effectiveTimeout } = runData;
const io = req.app.get('io');
- console.log(`🚀 Run created: ${runId}, provider type: ${provider.type}, command: ${provider.command}`);
+ console.log(`🚀 Run created: ${runId}, provider type: ${provider.type}, command: ${provider.command}, timeout: ${effectiveTimeout}ms`);
// Execute based on provider type
if (provider.type === 'cli') {
@@ -62,7 +63,8 @@ router.post('/', asyncHandler(async (req, res, next) => {
(finalMetadata) => {
console.log(`✅ Run complete: ${runId}, success: ${finalMetadata.success}`);
io?.emit(`run:${runId}:complete`, finalMetadata);
- }
+ },
+ effectiveTimeout
);
} else if (provider.type === 'api') {
runner.executeApiRun(
diff --git a/server/services/cos.js b/server/services/cos.js
index 0bd3c702fa..f088ebb65f 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -17,7 +17,7 @@ import { getActiveProvider } from './providers.js';
import { parseTasksMarkdown, groupTasksByStatus, getNextTask, getAutoApprovedTasks, getAwaitingApprovalTasks, updateTaskStatus, generateTasksMarkdown } from '../lib/taskParser.js';
import { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleReviewStarted } from './appActivity.js';
import { getAllApps } from './apps.js';
-import { shouldSkipTaskType, getAdaptiveCooldownMultiplier, getSkippedTaskTypes } from './taskLearning.js';
+import { shouldSkipTaskType, getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSummary, recordLearningInsight } from './taskLearning.js';
const execAsync = promisify(exec);
@@ -571,6 +571,27 @@ export async function evaluateTasks() {
availableSlots
});
+ // Periodically log performance summary (every 10 evaluations)
+ const evalCount = state.stats.evaluationCount || 0;
+ if (evalCount % 10 === 0 && evalCount > 0) {
+ const perfSummary = await getPerformanceSummary().catch(() => null);
+ if (perfSummary && perfSummary.totalCompleted > 0) {
+ emitLog('info', `Performance: ${perfSummary.overallSuccessRate}% success rate over ${perfSummary.totalCompleted} tasks`, {
+ successRate: perfSummary.overallSuccessRate,
+ totalCompleted: perfSummary.totalCompleted,
+ topPerformers: perfSummary.topPerformers.length,
+ needsAttention: perfSummary.needsAttention.length
+ });
+ }
+ }
+
+ // Update evaluation count
+ await withStateLock(async () => {
+ const s = await loadState();
+ s.stats.evaluationCount = (s.stats.evaluationCount || 0) + 1;
+ await saveState(s);
+ });
+
// Spawn all ready tasks (up to available slots)
for (const task of tasksToSpawn) {
emitLog('success', `Spawning task: ${task.id} (${task.priority || 'MEDIUM'})`, {
@@ -695,7 +716,8 @@ const SELF_IMPROVEMENT_TYPES = [
// Goal 4: User Engagement
'feature-ideas',
// Goal 5: System Health
- 'accessibility'
+ 'accessibility',
+ 'dependency-updates'
];
/**
@@ -1034,7 +1056,35 @@ Think about ways to make PortOS more useful:
Think creatively but implement practically.
-Use model: claude-opus-4-5-20251101 for creative feature development`
+Use model: claude-opus-4-5-20251101 for creative feature development`,
+
+ 'dependency-updates': `[Self-Improvement] Dependency Updates and Security Audit
+
+Check PortOS dependencies for updates and security vulnerabilities:
+
+1. Run npm audit in both server/ and client/ directories
+2. Check for outdated packages with npm outdated
+3. Review CRITICAL and HIGH severity vulnerabilities
+4. For each vulnerability:
+ - Assess the actual risk (is the vulnerable code path used?)
+ - Check if an update is available
+ - Test that updates don't break functionality
+
+5. Update dependencies carefully:
+ - Update patch versions first (safest)
+ - Then minor versions
+ - Major versions need more careful review
+
+6. After updating:
+ - Run npm test in server/
+ - Run npm run build in client/
+ - Verify the app starts correctly
+
+7. Commit with clear changelog of what was updated and why
+
+IMPORTANT: Only update one major version bump at a time. If multiple major updates are needed, create separate commits for each.
+
+Use model: claude-opus-4-5-20251101 for thorough security analysis`
};
const description = taskDescriptions[nextType];
diff --git a/server/services/runner.js b/server/services/runner.js
index 6df2c0ddbc..e2b33bcaef 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -306,7 +306,8 @@ export async function createRun(options) {
model,
prompt,
workspacePath,
- workspaceName
+ workspaceName,
+ timeout
} = options;
const provider = await getProviderById(providerId);
@@ -351,10 +352,13 @@ export async function createRun(options) {
console.error(`❌ Failed to record usage session: ${err.message}`);
});
- return { runId, runDir, provider, metadata };
+ // Use user-specified timeout or fall back to provider default
+ const effectiveTimeout = timeout || provider.timeout;
+
+ return { runId, runDir, provider, metadata, timeout: effectiveTimeout };
}
-export async function executeCliRun(runId, provider, prompt, workspacePath, onData, onComplete) {
+export async function executeCliRun(runId, provider, prompt, workspacePath, onData, onComplete, timeout) {
// Initialize runner events if not already done
initRunnerEvents();
@@ -393,7 +397,7 @@ export async function executeCliRun(runId, provider, prompt, workspacePath, onDa
prompt,
workspacePath: workspacePath || process.cwd(),
envVars: provider.envVars || {},
- timeout: provider.timeout
+ timeout: timeout || provider.timeout
}).catch(async (err) => {
console.error(`❌ Failed to delegate run ${runId} to cos-runner: ${err.message}`);
pendingRunCallbacks.delete(runId);
diff --git a/server/services/selfImprovement.js b/server/services/selfImprovement.js
index 27e05a7c09..20842a0872 100644
--- a/server/services/selfImprovement.js
+++ b/server/services/selfImprovement.js
@@ -48,7 +48,12 @@ const ANALYSIS_TYPES = {
CONSOLE_ERRORS: 'console-errors',
SECURITY: 'security',
PERFORMANCE: 'performance',
- CODE_QUALITY: 'code-quality'
+ CODE_QUALITY: 'code-quality',
+ COS_ENHANCEMENT: 'cos-enhancement',
+ TEST_COVERAGE: 'test-coverage',
+ DOCUMENTATION: 'documentation',
+ FEATURE_IDEAS: 'feature-ideas',
+ DEPENDENCY_UPDATES: 'dependency-updates'
};
/**
diff --git a/server/services/taskLearning.js b/server/services/taskLearning.js
index 8d8446c223..aed336d29c 100644
--- a/server/services/taskLearning.js
+++ b/server/services/taskLearning.js
@@ -380,6 +380,86 @@ export async function suggestModelTier(taskType) {
return null; // Current selection is working fine
}
+/**
+ * Get a performance summary for logging during task evaluation
+ * Provides insights about how different task types are performing
+ */
+export async function getPerformanceSummary() {
+ const data = await loadLearningData();
+
+ const summary = {
+ totalCompleted: data.totals.completed,
+ overallSuccessRate: data.totals.completed > 0
+ ? Math.round((data.totals.succeeded / data.totals.completed) * 100)
+ : 0,
+ avgDurationMin: Math.round(data.totals.avgDurationMs / 60000),
+ topPerformers: [],
+ needsAttention: [],
+ skipped: []
+ };
+
+ // Analyze each task type
+ for (const [taskType, metrics] of Object.entries(data.byTaskType)) {
+ if (metrics.completed < 3) continue;
+
+ const entry = {
+ taskType,
+ successRate: metrics.successRate,
+ completed: metrics.completed,
+ avgDurationMin: Math.round(metrics.avgDurationMs / 60000)
+ };
+
+ if (metrics.successRate >= 80) {
+ summary.topPerformers.push(entry);
+ } else if (metrics.successRate < 50 && metrics.completed >= 5) {
+ summary.needsAttention.push(entry);
+ // Also mark as skipped if very low
+ if (metrics.successRate < 30) {
+ summary.skipped.push(entry);
+ }
+ }
+ }
+
+ // Sort by success rate
+ summary.topPerformers.sort((a, b) => b.successRate - a.successRate);
+ summary.needsAttention.sort((a, b) => a.successRate - b.successRate);
+
+ return summary;
+}
+
+/**
+ * Record a learning insight for future reference
+ * Stores observations about what works and what doesn't
+ */
+export async function recordLearningInsight(insight) {
+ const data = await loadLearningData();
+
+ if (!data.insights) {
+ data.insights = [];
+ }
+
+ data.insights.push({
+ ...insight,
+ recordedAt: new Date().toISOString()
+ });
+
+ // Keep only last 50 insights
+ if (data.insights.length > 50) {
+ data.insights = data.insights.slice(-50);
+ }
+
+ await saveLearningData(data);
+ return insight;
+}
+
+/**
+ * Get recent learning insights
+ */
+export async function getRecentInsights(limit = 10) {
+ const data = await loadLearningData();
+ return (data.insights || []).slice(-limit);
+}
+
/**
* Get adaptive cooldown multiplier for a task type based on historical performance
*