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
refactor([issue-805]): remove dead self-improvement task generator
[._.]/ Adam Eivy1f6f5e644431
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 0be4b1bc4a..58682c780e 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -30,10 +30,9 @@ import { addTask, updateTask, getAllTasks, getCosTasks, firstLine, PRIORITY_VALUimport { recordDecision, DECISION_TYPES } from './decisionLog.js';import { isAppOnCooldown, markAppReviewStarted, markIdleReviewStarted, getNextAppForReview, loadAppActivity, isAppActivityOnCooldown } from './appActivity.js';import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';-import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getTaskTypeConfidence } from './taskLearning.js';+import { getTaskTypeConfidence } from './taskLearning.js';import { generateProactiveTasks as generateMissionTasks } from './missions.js';import { isRecoveryTask } from './recoveryTasks.js';-import { PORTOS_UI_URL } from '../lib/ports.js';/*** Block a task that has exceeded the max spawn limit. Returns true if blocked.@@ -710,182 +709,6 @@ export async function queueEligibleImprovementTasks(state, cosTaskData) {}}-// Unified improvement task types (rotates through these)-// Organized by goal priority from GOALS.md-const IMPROVEMENT_TYPES = [- // Goal 1: Codebase Quality- 'ui-bugs',- 'mobile-responsive',- 'security',- 'code-quality',- 'console-errors',- 'performance',- // Goal 2: Self-Improvement- 'test-coverage',- 'error-handling',- 'typing',- // Goal 3: Documentation- 'documentation',- // Goal 4: User Engagement- 'feature-ideas',- 'plan-task',- // Goal 5: System Health- 'accessibility',- 'dependency-updates',- 'release-check'-];-// Backward compat alias-const SELF_IMPROVEMENT_TYPES = IMPROVEMENT_TYPES;--/**- * Generate a self-improvement task for PortOS itself- * Uses Playwright and Opus to analyze and fix issues- *- * Enhanced with adaptive learning and configurable intervals:- * - Respects per-task-type interval settings (daily, weekly, once, etc.)- * - Skips task types with consistently poor success rates- * - Logs learning-based recommendations- * - Falls back to next available task type if current is skipped- * - Checks for on-demand task requests first- */-async function generateSelfImprovementTask(state) {- // Import task schedule service dynamically to avoid circular dependency- const taskSchedule = await import('./taskSchedule.js');-- // First, check for any on-demand task requests (no category filter — unified)- const onDemandRequests = await taskSchedule.getOnDemandRequests();- const selfRequests = onDemandRequests.filter(r => !r.appId);-- if (selfRequests.length > 0) {- const request = selfRequests[0];- await taskSchedule.clearOnDemandRequest(request.id);- emitLog('info', `Processing on-demand task request: ${request.taskType}`, { requestId: request.id });-- // Record execution and generate the requested task- await taskSchedule.recordExecution(`task:${request.taskType}`);-- // Update state- await withStateLock(async () => {- const s = await loadState();- s.stats.lastSelfImprovement = new Date().toISOString();- s.stats.lastSelfImprovementType = request.taskType;- await saveState(s);- });-- return await generateSelfImprovementTaskForType(request.taskType, state);- }-- // Use the schedule service to determine the next task type- const lastType = state.stats.lastSelfImprovementType || '';- const nextTypeResult = await taskSchedule.getNextTaskType(null, lastType);-- if (!nextTypeResult) {- emitLog('debug', 'No improvement tasks are eligible to run based on schedule');- await recordDecision(- DECISION_TYPES.NOT_DUE,- 'No improvement tasks are eligible based on schedule',- {}- );- return null;- }-- let nextType = nextTypeResult.taskType;- const selectionReason = nextTypeResult.reason;-- // Additional check: skip if learning data suggests poor performance- const taskTypeKey = `task:${nextType}`;- const cooldownInfo = await getAdaptiveCooldownMultiplier(taskTypeKey).catch(() => ({ skip: false }));-- if (cooldownInfo.skip) {- emitLog('warn', `Skipping ${nextType} - poor success rate (${cooldownInfo.successRate}% after ${cooldownInfo.completed} attempts)`, {- taskType: nextType,- successRate: cooldownInfo.successRate,- completed: cooldownInfo.completed,- reason: cooldownInfo.reason- });-- // Record the skip decision- await recordDecision(- DECISION_TYPES.TASK_SKIPPED,- `Poor success rate (${cooldownInfo.successRate}% after ${cooldownInfo.completed} attempts)`,- { taskType: nextType, successRate: cooldownInfo.successRate, attempts: cooldownInfo.completed }- );-- // Try to find another eligible task type- const dueTasks = await taskSchedule.getDueTasks();- const alternativeTask = dueTasks.find(t => t.taskType !== nextType);-- if (alternativeTask) {- const originalType = nextType;- nextType = alternativeTask.taskType;- emitLog('info', `Switched to alternative task type: ${nextType}`);-- // Record the switch decision- await recordDecision(- DECISION_TYPES.TASK_SWITCHED,- `Switched from ${originalType} to ${nextType}`,- { fromTask: originalType, toTask: nextType, reason: 'poor-success-rate' }- );- } else {- // Fall back to the skipped types logic- const skippedTypes = await getSkippedTaskTypes().catch(() => []);- if (skippedTypes.length > 0) {- skippedTypes.sort((a, b) => new Date(a.lastCompleted || 0) - new Date(b.lastCompleted || 0));- const oldestType = skippedTypes[0].taskType.replace(/^(self-improve|app-improve|task):/, '');- nextType = oldestType;- emitLog('info', `Retrying ${oldestType} as it hasn't been attempted recently`);-- // Record rehabilitation decision- await recordDecision(- DECISION_TYPES.REHABILITATION,- `Retrying ${oldestType} after period of inactivity`,- { taskType: oldestType, reason: 'oldest-skipped-type' }- );- } else {- nextType = IMPROVEMENT_TYPES[0];- }- }- }-- // Log if there's a recommendation from learning system- if (cooldownInfo.recommendation) {- emitLog('debug', `Learning insight for ${nextType}: ${cooldownInfo.recommendation}`, {- taskType: nextType,- multiplier: cooldownInfo.multiplier- });- }-- // Record execution in the schedule service- await taskSchedule.recordExecution(`task:${nextType}`);-- // Update state with new timestamp and type- await withStateLock(async () => {- const s = await loadState();- s.stats.lastSelfImprovement = new Date().toISOString();- s.stats.lastSelfImprovementType = nextType;- await saveState(s);- });-- emitLog('info', `Generating improvement task: ${nextType} (${selectionReason})`);-- // Record task selection decision- await recordDecision(- DECISION_TYPES.TASK_SELECTED,- `Selected ${nextType} for improvement`,- {- taskType: nextType,- reason: selectionReason,- multiplier: cooldownInfo.multiplier,- successRate: cooldownInfo.successRate- }- );-- // Get task descriptions from the centralized helper function- const taskDescriptions = getSelfImprovementTaskDescriptions();-- return await generateSelfImprovementTaskForType(nextType, state, taskDescriptions);-}-/*** Resolve auto-approval for a task based on confidence scoring.* Returns { autoApproved, approvalRequired } ready to spread into task objects.@@ -905,7 +728,7 @@ async function resolveConfidenceApproval(state, taskTypeKey, logLabel) {* Helper function to generate a self-improvement task for a specific type* Used by both normal rotation and on-demand task requests*/-export async function generateSelfImprovementTaskForType(taskType, state, taskDescriptions = null) {+export async function generateSelfImprovementTaskForType(taskType, state) {const taskSchedule = await import('./taskSchedule.js');const interval = await taskSchedule.getTaskInterval(taskType);@@ -951,298 +774,6 @@ export async function generateSelfImprovementTaskForType(taskType, state, taskDereturn task;}-/**- * Get task descriptions for all self-improvement types- * Extracted for reuse by on-demand task generation- */-function getSelfImprovementTaskDescriptions() {- return {- 'ui-bugs': `[Self-Improvement] UI Bug Analysis--Use Playwright MCP (browser_navigate, browser_snapshot, browser_console_messages) to analyze PortOS UI:--1. Navigate to ${PORTOS_UI_URL}/-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 ${PORTOS_UI_URL}/-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 ${PORTOS_UI_URL}/-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--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 ${PORTOS_UI_URL}/-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`,-- '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--5. Run npm test to verify all tests pass-6. Commit test additions with clear message describing what's covered--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:- - Remove completed milestones from PLAN.md outright (do NOT archive to a DONE.md — that file is retired; \`git log\` and \`.changelog/\` are the audit trail)- - Add any new features implemented as entries in \`.changelog/NEXT.md\` (mirror the prose style of recent entries)- - Keep PLAN.md focused on next actions and future work--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] Implement a Feature Idea--Your goal is to implement ONE feature.--## Research Phase--1. Read GOALS.md for context on user goals and priorities-2. Read PLAN.md for the current roadmap and planned work (next actions, audit findings, future ideas)-3. Skim recent \`.changelog/\` entries and \`git log\` to understand what has already shipped (avoid re-implementing existing features)-4. Search for existing feature idea documents:- - Check .planning/research/FEATURES.md for planned features- - Check .planning/ directory for any feature specs or research docs- - Check data/COS-GOALS.md for CoS-specific goals-5. Review recent completed tasks to understand what's already been done-6. Review recent git log to see what's been implemented recently--## Selection Phase--7. Choose ONE feature to implement that:- - Aligns with GOALS.md priorities- - Is NOT already shipped per recent \`.changelog/\` entries or \`git log\` (avoid re-implementing shipped features)- - Is NOT already planned in PLAN.md (avoid duplicating roadmap work)- - Is NOT already documented in existing feature idea files- - Is a small, self-contained improvement (completable in one session)- - Saves user time, improves developer experience, or makes CoS more helpful--## Implementation Phase--8. Implement the feature:- - Write clean, tested code- - Follow existing patterns in the codebase- - Run tests to ensure nothing is broken--9. **Review your changed code for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix any findings. Claude Code can run \`/simplify\` for this pass; on other CLIs, do the equivalent diff review by hand.--10. Commit with a clear description of the feature and rationale--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`- };-}--/**- * Generate a comprehensive self-improvement task for a managed app- * Rotates through analysis types similar to PortOS self-improvement- *- * Enhanced with configurable intervals:- * - Respects per-task-type interval settings (daily, weekly, once per app, etc.)- * - Checks for on-demand task requests first- * - Records execution history for interval tracking- *- * @param {Object} app - The managed app object- * @param {Object} state - Current CoS state- * @returns {Object} Generated task- *//*** Check if a pipeline stage's precondition is met.* Supports { fileExists: 'path' } and { fileNotExists: 'path' }.