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: extend comprehensive self-improvement to managed apps

Adam Eivya03894d75b0b
diff --git a/PLAN.md b/PLAN.md
index 64a03183cc..007a145fb6 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -54,6 +54,7 @@ pm2 logs
- [x] M25: Task Learning System (completion tracking, success rate analysis, model effectiveness, recommendations)
- [x] M26: Scheduled Scripts (cron scheduling, agent triggers, command allowlist, run history)
- [x] M28: Weekly Digest UI (visual digest tab with insights, accomplishments, week-over-week comparisons)
+- [x] M29: Comprehensive App Improvement (self-improvement operations extended to managed apps, 10 analysis types, rotation system)
### Documentation
- [Architecture Overview](./docs/ARCHITECTURE.md) - System design, data flow
@@ -1461,3 +1462,89 @@ Uses existing Weekly Digest backend endpoints:
| `client/src/components/cos/index.js` | Added DigestTab export |
| `client/src/components/cos/constants.js` | Added digest tab to TABS array |
| `client/src/pages/ChiefOfStaff.jsx` | Import and render DigestTab |
+
+---
+
+## M29: Comprehensive App Improvement (2026-01-09)
+
+Extended the CoS self-improvement system to apply the same comprehensive analysis to managed apps (not just PortOS itself).
+
+### Problem
+
+The CoS had a sophisticated self-improvement system with 12 different analysis types (security, code quality, performance, etc.) for PortOS itself, but managed apps only received simple idle reviews (formatting, dead code, typos). This meant managed apps weren't getting the same level of thorough analysis and improvement.
+
+### Solution
+
+Created an app-agnostic self-improvement system that applies comprehensive analysis to any managed app:
+
+1. **10 Analysis Types for Apps**: Security audit, code quality, test coverage, performance, accessibility, console errors, dependency updates, documentation, error handling, and TypeScript typing
+2. **Rotation System**: Each app tracks its last improvement type and rotates through all 10 types
+3. **App Activity Tracking**: Extended `appActivity.js` to track `lastImprovementType` per app
+4. **Configuration Toggle**: New `comprehensiveAppImprovement` config option (default: true)
+5. **Backward Compatible**: Can fall back to simple idle reviews by disabling the config
+
+### Key Features
+
+- **App-Specific Context**: Each task template includes the app's name and repo path
+- **Opus Model**: All comprehensive improvements use claude-opus-4-5-20251101 for thorough analysis
+- **Auto-Approved**: Tasks run without requiring manual approval
+- **Cooldown Management**: Respects existing 30-minute cooldown between working on the same app
+
+### Analysis Types
+
+| Type | Description |
+|------|-------------|
+| security-audit | Command injection, XSS, path traversal, authentication |
+| code-quality | DRY violations, dead code, magic numbers |
+| test-coverage | Add missing tests for critical paths |
+| performance | N+1 queries, unnecessary re-renders, bundle size |
+| accessibility | ARIA labels, color contrast, keyboard navigation |
+| console-errors | Fix JavaScript and server errors |
+| dependency-updates | npm audit, update packages safely |
+| documentation | README, JSDoc, inline comments |
+| error-handling | Try-catch blocks, error logging |
+| typing | TypeScript type improvements |
+
+### Configuration
+
+```javascript
+comprehensiveAppImprovement: true // Enable comprehensive analysis for managed apps
+```
+
+### Implementation Files
+
+| File | Changes |
+|------|---------|
+| `server/services/cos.js` | Added `MANAGED_APP_IMPROVEMENT_TYPES` array, `generateManagedAppImprovementTask()` function, updated `generateIdleReviewTask()` |
+| `server/services/appActivity.js` | Added `lastImprovementType` field to app activity tracking |
+
+### Task Flow
+
+```
+CoS Idle → No user/system tasks
+ └─► Try PortOS self-improvement (if older than last app review)
+ └─► Try managed app improvement
+ ├─► Get next app off cooldown
+ ├─► Check comprehensiveAppImprovement config
+ │ ├─► true: Generate comprehensive improvement task (rotates through 10 types)
+ │ └─► false: Generate simple idle review (formatting, dead code, typos)
+ └─► Mark app as reviewed, start cooldown
+```
+
+### Example Task
+
+```
+[App Improvement: MyApp] Security Audit
+
+Analyze the MyApp codebase for security vulnerabilities:
+
+Repository: /Users/user/projects/myapp
+
+1. Review routes/controllers for:
+ - Command injection in exec/spawn calls
+ - Path traversal in file operations
+ - Missing input validation
+ ...
+
+Use model: claude-opus-4-5-20251101
+```
diff --git a/server/services/appActivity.js b/server/services/appActivity.js
index 976eb075e2..8ef3bb00cc 100644
--- a/server/services/appActivity.js
+++ b/server/services/appActivity.js
@@ -74,6 +74,7 @@ export async function updateAppActivity(appId, updates) {
lastTaskCompletedAt: null,
activeAgentId: null,
cooldownUntil: null,
+ lastImprovementType: null, // Track last self-improvement analysis type
stats: {
reviewCount: 0,
issuesFound: 0,
diff --git a/server/services/cos.js b/server/services/cos.js
index 6ace479a06..a407fb25b8 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -98,6 +98,7 @@ const DEFAULT_CONFIG = {
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)
+ comprehensiveAppImprovement: true, // Use comprehensive analysis for managed apps (same as PortOS self-improvement)
immediateExecution: true, // Execute new tasks immediately, don't wait for interval
proactiveMode: true, // Be proactive about finding work
autoFixThresholds: {
@@ -665,25 +666,31 @@ async function generateIdleReviewTask(state) {
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. Commit each fix with a clear description.`,
- metadata: {
- app: nextApp.id,
- appName: nextApp.name,
- repoPath: nextApp.repoPath,
- reviewType: 'idle',
- autoGenerated: true
- },
- taskType: 'internal',
- autoApproved: true
- };
+ // Use comprehensive improvement if enabled, otherwise use simple idle review
+ if (state.config.comprehensiveAppImprovement) {
+ emitLog('info', `Generating comprehensive improvement task for ${nextApp.name}`, { appId: nextApp.id });
+ return await generateManagedAppImprovementTask(nextApp, state);
+ } else {
+ emitLog('info', `Generating idle review task for ${nextApp.name}`, { appId: nextApp.id });
+
+ // Create a simple idle review task (legacy behavior)
+ 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. Commit each fix with a clear description.`,
+ metadata: {
+ app: nextApp.id,
+ appName: nextApp.name,
+ repoPath: nextApp.repoPath,
+ reviewType: 'idle',
+ autoGenerated: true
+ },
+ taskType: 'internal',
+ autoApproved: true
+ };
+ }
}
}
@@ -720,6 +727,21 @@ const SELF_IMPROVEMENT_TYPES = [
'dependency-updates'
];
+// App-agnostic self-improvement types for managed apps
+// These can be applied to any codebase, not just PortOS
+const MANAGED_APP_IMPROVEMENT_TYPES = [
+ 'security-audit', // Security vulnerabilities
+ 'code-quality', // DRY violations, dead code
+ 'test-coverage', // Add missing tests
+ 'performance', // Optimize queries, re-renders
+ 'accessibility', // A11y issues
+ 'console-errors', // Fix JavaScript errors
+ 'dependency-updates', // Update packages
+ 'documentation', // Update docs and comments
+ 'error-handling', // Improve error handling
+ 'typing' // Add/fix TypeScript types
+];
+
/**
* Generate a self-improvement task for PortOS itself
* Uses Playwright and Opus to analyze and fix issues
@@ -1109,6 +1131,323 @@ Use model: claude-opus-4-5-20251101 for thorough security analysis`
return task;
}
+/**
+ * Generate a comprehensive self-improvement task for a managed app
+ * Rotates through analysis types similar to PortOS self-improvement
+ *
+ * @param {Object} app - The managed app object
+ * @param {Object} state - Current CoS state
+ * @returns {Object} Generated task
+ */
+async function generateManagedAppImprovementTask(app, state) {
+ const { getAppActivityById, updateAppActivity } = await import('./appActivity.js');
+
+ // Get last improvement type for this app
+ const appActivity = await getAppActivityById(app.id);
+ const lastType = appActivity?.lastImprovementType || '';
+
+ // Find next type in rotation
+ let currentIndex = MANAGED_APP_IMPROVEMENT_TYPES.indexOf(lastType);
+ currentIndex = (currentIndex + 1) % MANAGED_APP_IMPROVEMENT_TYPES.length;
+ const nextType = MANAGED_APP_IMPROVEMENT_TYPES[currentIndex];
+
+ // Update app activity with new type
+ await updateAppActivity(app.id, {
+ lastImprovementType: nextType
+ });
+
+ emitLog('info', `Generating comprehensive improvement task for ${app.name}: ${nextType}`, { appId: app.id, analysisType: nextType });
+
+ // Task descriptions for each analysis type
+ const taskDescriptions = {
+ 'security-audit': `[App Improvement: ${app.name}] Security Audit
+
+Analyze the ${app.name} codebase for security vulnerabilities:
+
+Repository: ${app.repoPath}
+
+1. Review routes/controllers for:
+ - Command injection in exec/spawn calls
+ - Path traversal in file operations
+ - Missing input validation
+ - XSS vulnerabilities
+ - SQL/NoSQL injection
+
+2. Review services for:
+ - Unsafe eval() or Function()
+ - Hardcoded credentials
+ - Insecure dependencies
+
+3. Review client code for:
+ - XSS vulnerabilities
+ - Sensitive data in localStorage
+ - CSRF protection
+
+4. Check authentication and authorization:
+ - Secure password handling
+ - Token management
+ - Access control
+
+Fix any vulnerabilities found and commit with security advisory notes.
+
+Use model: claude-opus-4-5-20251101 for thorough security analysis`,
+
+ 'code-quality': `[App Improvement: ${app.name}] Code Quality Review
+
+Analyze ${app.name} for maintainability improvements:
+
+Repository: ${app.repoPath}
+
+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
+7. Identify magic numbers that should be constants
+
+Focus on the main source directories. Refactor issues found and commit improvements.
+
+Use model: claude-opus-4-5-20251101 for quality refactoring`,
+
+ 'test-coverage': `[App Improvement: ${app.name}] Improve Test Coverage
+
+Analyze and improve test coverage for ${app.name}:
+
+Repository: ${app.repoPath}
+
+1. Check existing tests and identify untested critical paths
+2. Look for:
+ - API routes without tests
+ - Services with complex logic
+ - Error handling paths
+ - Edge cases
+
+3. Add tests following existing patterns in the project
+4. Ensure tests:
+ - Use appropriate mocks
+ - Test edge cases
+ - Follow naming conventions
+
+5. Run tests to verify all pass
+6. Commit test additions with clear message describing coverage
+
+Use model: claude-opus-4-5-20251101 for comprehensive test design`,
+
+ 'performance': `[App Improvement: ${app.name}] Performance Analysis
+
+Analyze ${app.name} for performance issues:
+
+Repository: ${app.repoPath}
+
+1. Review components/views for:
+ - Unnecessary re-renders
+ - Missing memoization
+ - Large files that should be split
+
+2. Review backend for:
+ - N+1 query patterns
+ - Missing caching opportunities
+ - Inefficient file operations
+ - Slow API endpoints
+
+3. Review build/bundle for:
+ - Missing code splitting
+ - Large dependencies that could be optimized
+
+4. Check for:
+ - Memory leaks
+ - Unnecessary broadcasts/events
+
+Optimize and commit improvements.
+
+Use model: claude-opus-4-5-20251101 for performance optimization`,
+
+ 'accessibility': `[App Improvement: ${app.name}] Accessibility Audit
+
+Audit ${app.name} for accessibility issues:
+
+Repository: ${app.repoPath}
+
+If the app has a web UI:
+1. Navigate to the app's UI
+2. Check for:
+ - Missing ARIA labels
+ - Missing alt text on images
+ - Insufficient color contrast
+ - Keyboard navigation issues
+ - Focus indicators
+ - Semantic HTML usage
+
+3. Fix accessibility issues in components
+4. Add appropriate aria-* attributes
+5. Test and commit changes
+
+Use model: claude-opus-4-5-20251101 for comprehensive a11y fixes`,
+
+ 'console-errors': `[App Improvement: ${app.name}] Console Error Investigation
+
+Find and fix console errors in ${app.name}:
+
+Repository: ${app.repoPath}
+
+1. If the app has a UI, check browser console for errors
+2. Check server logs for errors
+3. For each error:
+ - Identify the source file and line
+ - Understand the root cause
+ - Implement a fix
+
+4. Test fixes and commit changes
+
+Use model: claude-opus-4-5-20251101 for thorough debugging`,
+
+ 'dependency-updates': `[App Improvement: ${app.name}] Dependency Updates
+
+Check ${app.name} dependencies for updates and security vulnerabilities:
+
+Repository: ${app.repoPath}
+
+1. Run npm audit (or equivalent package manager)
+2. Check for outdated packages
+3. Review CRITICAL and HIGH severity vulnerabilities
+4. For each vulnerability:
+ - Assess actual risk
+ - Check if update available
+ - Test updates don't break functionality
+
+5. Update dependencies carefully:
+ - Patch versions first (safest)
+ - Then minor versions
+ - Major versions need careful review
+
+6. After updating:
+ - Run tests
+ - Verify the app starts correctly
+
+7. Commit with clear changelog
+
+IMPORTANT: Only update one major version bump at a time.
+
+Use model: claude-opus-4-5-20251101 for thorough security analysis`,
+
+ 'documentation': `[App Improvement: ${app.name}] Update Documentation
+
+Review and improve ${app.name} documentation:
+
+Repository: ${app.repoPath}
+
+1. Check README.md:
+ - Installation instructions current?
+ - Quick start guide clear?
+ - Feature overview complete?
+
+2. Review inline documentation:
+ - Add JSDoc to exported functions
+ - Document complex algorithms
+ - Explain non-obvious code
+
+3. Check for docs/ folder:
+ - Are all features documented?
+ - Is information current?
+ - Add missing guides if needed
+
+4. Update PLAN.md or similar if present:
+ - Mark completed milestones
+ - Document architectural decisions
+
+Commit documentation improvements.
+
+Use model: claude-opus-4-5-20251101 for clear documentation`,
+
+ 'error-handling': `[App Improvement: ${app.name}] Improve Error Handling
+
+Enhance error handling in ${app.name}:
+
+Repository: ${app.repoPath}
+
+1. Review code for:
+ - Missing try-catch blocks where needed
+ - Silent failures (empty catch blocks)
+ - Errors that should be logged
+ - User-facing error messages
+
+2. Add error handling for:
+ - Network requests
+ - File operations
+ - Database queries
+ - External API calls
+
+3. Ensure errors are:
+ - Logged appropriately
+ - Have clear messages
+ - Include relevant context
+ - Don't expose sensitive data
+
+4. Test error paths and commit improvements
+
+Use model: claude-opus-4-5-20251101 for comprehensive error handling`,
+
+ 'typing': `[App Improvement: ${app.name}] TypeScript Type Improvements
+
+Improve TypeScript types in ${app.name}:
+
+Repository: ${app.repoPath}
+
+1. Review TypeScript files for:
+ - 'any' types that should be specific
+ - Missing type annotations
+ - Type assertions that could be avoided
+ - Missing interfaces/types for objects
+
+2. Add types for:
+ - Function parameters and returns
+ - Component props
+ - API responses
+ - Configuration objects
+
+3. Ensure:
+ - Types are properly exported
+ - No implicit any
+ - Types are reusable
+
+4. Run type checking and commit improvements
+
+Use model: claude-opus-4-5-20251101 for thorough typing`
+ };
+
+ const description = taskDescriptions[nextType] || `[App Improvement: ${app.name}] ${nextType}
+
+Perform ${nextType} analysis on ${app.name}.
+
+Repository: ${app.repoPath}
+
+Analyze the codebase and make improvements. Commit changes with clear descriptions.
+
+Use model: claude-opus-4-5-20251101`;
+
+ const task = {
+ id: `app-improve-${app.id}-${nextType}-${Date.now().toString(36)}`,
+ status: 'pending',
+ priority: state.config.idleReviewPriority || 'MEDIUM',
+ priorityValue: PRIORITY_VALUES[state.config.idleReviewPriority] || 2,
+ description,
+ metadata: {
+ app: app.id,
+ appName: app.name,
+ repoPath: app.repoPath,
+ analysisType: nextType,
+ autoGenerated: true,
+ comprehensiveImprovement: true,
+ model: 'claude-opus-4-5-20251101'
+ },
+ taskType: 'internal',
+ autoApproved: true
+ };
+
+ return task;
+}
+
/**
* Run system health check
*/