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: unify self-improvement and app-improvement task schedules
Adam Eivy239f8e0e31b7
diff --git a/.changelog/v1.2.x.md b/.changelog/v1.2.x.mdnew file mode 100644index 0000000000..2cf952a349--- /dev/null+++ b/.changelog/v1.2.x.md@@ -0,0 +1,48 @@+# Release v1.2.x - Changelog++Released: Unreleased++## Overview++Unified self-improvement and app-improvement task schedules into a single system. PortOS is now treated as any other managed app for improvement tasks, eliminating the redundant split between "self-improvement" (targeting PortOS) and "app-improvement" (targeting managed apps).++## Features++### Unified improvement task schedule+- Merged 13 self-improvement + 10 app-improvement task types into 14 unified types: security, code-quality, test-coverage, performance, accessibility, console-errors, dependency-updates, documentation, ui-bugs, mobile-responsive, feature-ideas, error-handling, typing, release-check+- Removed redundant `cos-enhancement` task type (subsumed by `feature-ideas` which reads GOALS.md)+- Renamed `security-audit` → `security` for consistency+- Single `improvementEnabled` config flag replaces split `selfImprovementEnabled` + `appImprovementEnabled`+- Removed `comprehensiveAppImprovement` toggle (always comprehensive now)+- All execution keys unified to `task:X` format (migrated from `self-improve:X` / `app-improve:X`)++### Unified API endpoints+- New `GET/PUT /api/cos/schedule/task/:taskType` endpoint for all task types+- `POST /schedule/trigger` and `POST /schedule/reset` no longer require `category` param+- `GET /schedule/due` returns unified task list+- Old split endpoints kept as deprecated aliases for backward compatibility++### GOALS.md consolidation+- Merged `data/COS-GOALS.md` operational goals into root `GOALS.md`+- Goal progress service now reads from `GOALS.md` Operational Goals section+- Feature-ideas task prompt updated to reference `GOALS.md` instead of `data/COS-GOALS.md`++## Improvements++### Schedule data auto-migration+- `loadSchedule()` automatically detects v1 format and migrates to v2+- Merges execution history from both `self-improve:` and `app-improve:` keys into unified `task:` keys+- Version field bumped from 1 → 2 in `task-schedule.json`++### Simplified UI+- Removed segmented "Self-Improvement / App Improvement" toggle from Schedule tab+- Single unified task list with per-app override support for all 14 task types+- ConfigTab shows single "Improvement Tasks" toggle instead of three separate toggles+- Autonomy level presets updated to use `improvementEnabled`++## Removed++- `cos-enhancement` task type and associated prompts+- `comprehensiveAppImprovement` config flag+- Split `selfImprovementEnabled` / `appImprovementEnabled` config flags (kept as deprecated, read via `improvementEnabled ?? (selfImprovementEnabled || appImprovementEnabled)`)+- Legacy inline task description blocks in `generateManagedAppImprovementTask()` (prompts now come from `taskSchedule.getTaskPrompt()`)diff --git a/GOALS.md b/GOALS.mdindex cd0691f635..22b844cbf7 100644--- a/GOALS.md+++ b/GOALS.md@@ -87,3 +87,63 @@ PortOS is entering its **identity integration phase**. The next major work (M42)Beyond M42, the trajectory is toward deeper autonomy (agents that need less supervision), richer identity modeling (multi-modal capture, behavioral feedback loops), and knowledge preservation as a durable legacy.Recent momentum: 43 milestones shipped, security audit (S1-S10) complete, v0.18.5 on dev. The project iterates rapidly — 3 minor versions in the last month with both features and hardening in each release.++## Operational Goals++The CoS autonomous agent system reads these goals to guide its behavior and task generation.++### Goal 1: Codebase Quality+- Run security audits weekly+- Check for mobile responsiveness issues+- Find and fix DRY violations+- Remove dead code and unused imports+- Improve test coverage+- Fix console errors and warnings++### Goal 2: Self-Improvement+- Add new capabilities to the CoS system+- Improve the self-improvement task prompts+- Add new analysis types (a11y, i18n, SEO)+- Better error recovery and retry logic+- Smarter task prioritization+- Learn from completed tasks++### Goal 3: Documentation+- Keep PLAN.md up to date with completed milestones+- Document new features in /docs+- Generate daily/weekly summary reports+- Track metrics and improvements over time+- Maintain clear task descriptions++### Goal 4: User Engagement+- Prompt user for feedback on completed tasks+- Suggest new features based on usage patterns+- Help user define and track their goals+- Provide status updates and progress reports+- Ask clarifying questions when tasks are ambiguous++### Goal 5: System Health+- Monitor PM2 processes continuously+- Check for memory leaks and performance issues+- Verify all services are running correctly+- Alert on critical errors immediately+- Auto-fix common issues when safe++### Task Generation Priorities++When idle, generate tasks in this priority order:++1. **Critical Fixes**: Security vulnerabilities, crashes, data loss risks+2. **User Tasks**: Any pending tasks from TASKS.md+3. **Health Issues**: PM2 errors, failed processes, high memory+4. **Self-Improvement**: UI bugs, mobile issues, code quality+5. **Documentation**: Update docs, generate reports+6. **Feature Ideas**: New capabilities, enhancements++### Core Principles++1. **Proactive Over Reactive**: Don't wait for problems - find and fix them before they become issues+2. **Continuous Improvement**: Always look for ways to make things better+3. **User Partnership**: Prompt the user to help curate tasks and provide feedback+4. **Documentation First**: Maintain rich documentation, plans, and task tracking+5. **Quality Over Speed**: Use the heavy model (Opus) for important work - quality mattersdiff --git a/client/package-lock.json b/client/package-lock.jsonindex fb8b2c47da..1fa5fcd096 100644--- a/client/package-lock.json+++ b/client/package-lock.json@@ -1,12 +1,12 @@{"name": "portos-client",- "version": "1.1.1",+ "version": "1.1.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "portos-client",- "version": "1.1.1",+ "version": "1.1.2","dependencies": {"@dnd-kit/core": "^6.3.1","@dnd-kit/sortable": "^10.0.0",diff --git a/client/package.json b/client/package.jsonindex 6962610fa0..e2a03c600c 100644--- a/client/package.json+++ b/client/package.json@@ -1,6 +1,6 @@{"name": "portos-client",- "version": "1.1.1",+ "version": "1.1.2","private": true,"type": "module","scripts": {diff --git a/client/src/components/GoalProgressWidget.jsx b/client/src/components/GoalProgressWidget.jsxindex 3b3ef676fb..85c4594f27 100644--- a/client/src/components/GoalProgressWidget.jsx+++ b/client/src/components/GoalProgressWidget.jsx@@ -11,7 +11,7 @@ import { useAutoRefetch } from '../hooks/useAutoRefetch';/*** GoalProgressWidget - Shows progress toward user goals on the dashboard- * Maps completed CoS tasks to goal categories from COS-GOALS.md+ * Maps completed CoS tasks to goal categories from GOALS.md*/const GoalProgressWidget = memo(function GoalProgressWidget() {const { data: progress, loading } = useAutoRefetch(diff --git a/client/src/components/cos/QuickSummary.jsx b/client/src/components/cos/QuickSummary.jsxindex 425a69caa0..cd54ca0670 100644--- a/client/src/components/cos/QuickSummary.jsx+++ b/client/src/components/cos/QuickSummary.jsx@@ -259,7 +259,7 @@ export default function QuickSummary() {<Timer size={14} className={nextJob.isDue ? 'text-port-accent animate-pulse' : 'text-gray-400'} /><span className="text-gray-400">Next:</span><span className={`font-medium truncate max-w-[120px] ${nextJob.isDue ? 'text-port-accent' : 'text-white'}`} title={nextJob.jobName}>- {nextJob.jobName?.replace(/^(self-improvement|app-improvement)-/, '').replace(/-/g, ' ')}+ {nextJob.jobName?.replace(/^(self-improvement|app-improvement|task)-/, '').replace(/-/g, ' ')}</span><span className="text-gray-500 text-xs">{nextJob.isDue ? 'due' : formatTimeUntil(nextJob.nextDueAt)}diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex f51678f8e0..c8221a5f42 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -71,29 +71,25 @@ export const AUTONOMY_LEVELS = [evaluationIntervalMs: 300000, // 5 minmaxConcurrentAgents: 1,maxConcurrentAgentsPerProject: 1,- selfImprovementEnabled: false,- appImprovementEnabled: false,+ improvementEnabled: false,proactiveMode: false,idleReviewEnabled: false,- immediateExecution: false,- comprehensiveAppImprovement: false+ immediateExecution: false}},{id: 'assistant',label: 'Assistant',color: 'blue',- description: 'Processes user tasks plus self-improvement on schedule',+ description: 'Processes user tasks plus improvement tasks on schedule',params: {evaluationIntervalMs: 120000, // 2 minmaxConcurrentAgents: 2,maxConcurrentAgentsPerProject: 1,- selfImprovementEnabled: true,- appImprovementEnabled: false,+ improvementEnabled: true,proactiveMode: false,idleReviewEnabled: false,- immediateExecution: true,- comprehensiveAppImprovement: false+ immediateExecution: true}},{@@ -105,12 +101,10 @@ export const AUTONOMY_LEVELS = [evaluationIntervalMs: 60000, // 1 minmaxConcurrentAgents: 3,maxConcurrentAgentsPerProject: 2,- selfImprovementEnabled: true,- appImprovementEnabled: true,+ improvementEnabled: true,proactiveMode: false,idleReviewEnabled: true,- immediateExecution: true,- comprehensiveAppImprovement: true+ immediateExecution: true}},{@@ -122,12 +116,10 @@ export const AUTONOMY_LEVELS = [evaluationIntervalMs: 30000, // 30 secmaxConcurrentAgents: 5,maxConcurrentAgentsPerProject: 3,- selfImprovementEnabled: true,- appImprovementEnabled: true,+ improvementEnabled: true,proactiveMode: true,idleReviewEnabled: true,- immediateExecution: true,- comprehensiveAppImprovement: true+ immediateExecution: true}}];@@ -169,7 +161,7 @@ export const AVATAR_STYLE_LABELS = {};// Dynamic avatar rules - maps task context to avatar styles-// Priority order: provider > selfImprovementType > taskType > priority > fallback+// Priority order: provider > analysisType > taskType > priority > fallbackconst DYNAMIC_AVATAR_RULES = {// Provider-based: different providers get distinct visual identitiesprovider: {@@ -177,8 +169,8 @@ const DYNAMIC_AVATAR_RULES = {'lm-studio': 'sigil', // Local LM Studio → arcane/occult aesthetic'gemini-cli': 'sigil', // Gemini → arcane aesthetic},- // Self-improvement task types → cyberpunk (system working on itself)- selfImprovementType: {+ // Improvement task analysis types → cyberpunk (system working on itself)+ analysisType: {security: 'cyber','code-quality': 'cyber','test-coverage': 'cyber',@@ -187,7 +179,6 @@ const DYNAMIC_AVATAR_RULES = {},// Task analysis typestaskType: {- 'self-improve': 'cyber', // System self-improvement → cyberpunkinternal: 'sigil', // Internal CoS tasks → arcane},// Priority-based: critical tasks get a distinctive look@@ -209,10 +200,10 @@ export const resolveDynamicAvatar = (agentMetadata) => {return DYNAMIC_AVATAR_RULES.provider[providerId];}- // Check self-improvement type- if (agentMetadata.selfImprovementType &&- DYNAMIC_AVATAR_RULES.selfImprovementType[agentMetadata.selfImprovementType]) {- return DYNAMIC_AVATAR_RULES.selfImprovementType[agentMetadata.selfImprovementType];+ // Check analysis type (improvement tasks)+ const analysisType = agentMetadata.analysisType || agentMetadata.selfImprovementType;+ if (analysisType && DYNAMIC_AVATAR_RULES.analysisType[analysisType]) {+ return DYNAMIC_AVATAR_RULES.analysisType[analysisType];}// Check task typediff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex fe6c8052c5..8613f52235 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -36,7 +36,7 @@ function extractTaskType(description) {if (d.includes('database') || d.includes('migration')) return 'database';if (d.includes('deploy') || d.includes('ci') || d.includes('cd')) return 'devops';if (d.includes('investigate') || d.includes('debug')) return 'investigation';- if (d.includes('self-improvement') || d.includes('feature idea')) return 'self-improvement';+ if (d.includes('self-improvement') || d.includes('improvement') || d.includes('feature idea')) return 'self-improvement';return 'feature';}diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsxindex 0ffa67e80c..a70f0408ed 100644--- a/client/src/components/cos/tabs/ConfigTab.jsx+++ b/client/src/components/cos/tabs/ConfigTab.jsx@@ -32,12 +32,10 @@ const PARAM_LABELS = {evaluationIntervalMs: 'Eval',maxConcurrentAgents: 'Agents',maxConcurrentAgentsPerProject: 'Per Project',- selfImprovementEnabled: 'Self',- appImprovementEnabled: 'App',+ improvementEnabled: 'Improve',proactiveMode: 'Proactive',idleReviewEnabled: 'Idle',- immediateExecution: 'Immediate',- comprehensiveAppImprovement: 'Comprehensive'+ immediateExecution: 'Immediate'};// Format param value for display@@ -158,12 +156,10 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, smaxConcurrentAgentsPerProject: config?.maxConcurrentAgentsPerProject || 2,maxProcessMemoryMb: config?.maxProcessMemoryMb || 2048,autoStart: config?.autoStart || false,- selfImprovementEnabled: config?.selfImprovementEnabled ?? true,- appImprovementEnabled: config?.appImprovementEnabled ?? true,+ improvementEnabled: config?.improvementEnabled ?? config?.selfImprovementEnabled ?? true,proactiveMode: config?.proactiveMode ?? true,idleReviewEnabled: config?.idleReviewEnabled ?? true,- immediateExecution: config?.immediateExecution ?? true,- comprehensiveAppImprovement: config?.comprehensiveAppImprovement ?? true+ immediateExecution: config?.immediateExecution ?? true});const handleLevelChange = async (params) => {@@ -281,22 +277,13 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, stooltip="Automatically start the CoS daemon when the server starts"/><ConfigRow- label="Self-Improvement"- value={formData.selfImprovementEnabled ? 'Enabled' : 'Disabled'}+ label="Improvement Tasks"+ value={formData.improvementEnabled ? 'Enabled' : 'Disabled'}editing={editing}type="checkbox"- inputValue={formData.selfImprovementEnabled}- onChange={v => setFormData(f => ({ ...f, selfImprovementEnabled: v }))}- tooltip="Allow CoS to improve the PortOS codebase (security audits, code quality, etc.)"- />- <ConfigRow- label="App Improvement"- value={formData.appImprovementEnabled ? 'Enabled' : 'Disabled'}- editing={editing}- type="checkbox"- inputValue={formData.appImprovementEnabled}- onChange={v => setFormData(f => ({ ...f, appImprovementEnabled: v }))}- tooltip="Allow CoS to improve managed apps (code review, testing, documentation, etc.)"+ inputValue={formData.improvementEnabled}+ onChange={v => setFormData(f => ({ ...f, improvementEnabled: v }))}+ tooltip="Allow CoS to run improvement tasks for PortOS and managed apps (security audits, code quality, etc.)"/><ConfigRowlabel="Proactive Mode"@@ -325,15 +312,6 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, sonChange={v => setFormData(f => ({ ...f, immediateExecution: v }))}tooltip="Execute new tasks immediately instead of waiting for evaluation interval"/>- <ConfigRow- label="Comprehensive App Analysis"- value={formData.comprehensiveAppImprovement ? 'Enabled' : 'Disabled'}- editing={editing}- type="checkbox"- inputValue={formData.comprehensiveAppImprovement}- onChange={v => setFormData(f => ({ ...f, comprehensiveAppImprovement: v }))}- tooltip="Use comprehensive analysis for managed apps (same as PortOS self-improvement)"- /></div>{/* Avatar Style */}diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsxindex 450a4ed92e..93bf301fa6 100644--- a/client/src/components/cos/tabs/ScheduleTab.jsx+++ b/client/src/components/cos/tabs/ScheduleTab.jsx@@ -1,5 +1,4 @@import { useState, useEffect, useCallback, useRef } from 'react';-import { useSearchParams } from 'react-router-dom';import { Clock, Play, RotateCcw, ChevronDown, ChevronRight, CheckCircle, XCircle, AlertCircle, RefreshCw, Package } from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../../../services/api';@@ -284,7 +283,7 @@ function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset,Cancel</button></div>- {category === 'appImprovement' && (+ {activeApps.length > 0 && (<p className="text-xs text-gray-500">Use <code className="bg-port-border px-1 rounded">{'{appName}'}</code> and <code className="bg-port-border px-1 rounded">{'{repoPath}'}</code> as placeholders.</p>@@ -302,7 +301,7 @@ function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset,</div><div className="flex gap-2">- {category === 'appImprovement' && activeApps.length > 0 ? (+ {activeApps.length > 0 ? (<div className="relative" ref={appSelectorRef}><buttononClick={() => setShowAppSelector(!showAppSelector)}@@ -632,13 +631,13 @@ function AppTaskTypeSection({ tasks, onUpdate, onTrigger, onReset, providers, apreturn (<div className="space-y-3"><div className="flex items-center gap-2">- <h3 className="text-lg font-semibold text-white">App Improvement Tasks</h3>+ <h3 className="text-lg font-semibold text-white">Improvement Tasks</h3><span className="text-xs text-gray-500">{enabledCount} enabled</span></div><p className="text-sm text-gray-400">- Tasks that analyze and improve managed applications. Expand a task to configure per-app overrides.+ Tasks that analyze and improve PortOS and managed apps. Expand a task to configure per-app overrides.</p><div className="space-y-2">{taskEntries.map(([taskType, config]) => (@@ -660,20 +659,12 @@ function AppTaskTypeSection({ tasks, onUpdate, onTrigger, onReset, providers, ap}export default function ScheduleTab({ apps }) {- const [searchParams, setSearchParams] = useSearchParams();+ // searchParams no longer used — unified task listconst [schedule, setSchedule] = useState(null);const [providers, setProviders] = useState(null);const [loading, setLoading] = useState(true);- const activeView = searchParams.get('view') || 'self';-- const setView = useCallback((view) => {- setSearchParams(prev => {- const next = new URLSearchParams(prev);- next.set('view', view);- return next;- }, { replace: true });- }, [setSearchParams]);+ // View state removed — unified task list replaces segmented self/app viewsconst fetchSchedule = useCallback(async () => {const data = await api.getCosSchedule().catch(() => null);@@ -691,19 +682,8 @@ export default function ScheduleTab({ apps }) {fetchProviders();}, [fetchSchedule, fetchProviders]);- const handleUpdateSelfImprovement = async (taskType, settings) => {- const result = await api.updateCosSelfImprovementInterval(taskType, settings).catch(err => {- toast.error(err.message);- return null;- });- if (result?.success) {- toast.success(`Updated ${taskType} interval`);- fetchSchedule();- }- };-- const handleUpdateAppImprovement = async (taskType, settings) => {- const result = await api.updateCosAppImprovementInterval(taskType, settings).catch(err => {+ const handleUpdateTask = async (taskType, settings) => {+ const result = await api.updateCosTaskInterval(taskType, settings).catch(err => {toast.error(err.message);return null;});@@ -713,30 +693,19 @@ export default function ScheduleTab({ apps }) {}};- const handleTriggerSelfImprovement = async (taskType) => {- const result = await api.triggerCosOnDemandTask(taskType, 'selfImprovement').catch(err => {+ const handleTriggerTask = async (taskType, appId = null) => {+ const result = await api.triggerCosOnDemandTask(taskType, appId).catch(err => {toast.error(err.message);return null;});if (result?.success) {- toast.success(`Triggered ${taskType} task - will run on next evaluation`);+ toast.success(`Triggered ${taskType} task${appId ? ' for app' : ''} - will run on next evaluation`);fetchSchedule();}};- const handleTriggerAppImprovement = async (taskType, appId) => {- const result = await api.triggerCosOnDemandTask(taskType, 'appImprovement', appId).catch(err => {- toast.error(err.message);- return null;- });- if (result?.success) {- toast.success(`Triggered ${taskType} task for app`);- fetchSchedule();- }- };-- const handleResetSelfImprovement = async (taskType) => {- const result = await api.resetCosTaskHistory(taskType, 'selfImprovement').catch(err => {+ const handleResetTask = async (taskType) => {+ const result = await api.resetCosTaskHistory(taskType).catch(err => {toast.error(err.message);return null;});@@ -746,16 +715,13 @@ export default function ScheduleTab({ apps }) {}};- const handleResetAppImprovement = async (taskType) => {- const result = await api.resetCosTaskHistory(taskType, 'appImprovement').catch(err => {- toast.error(err.message);- return null;- });- if (result?.success) {- toast.success(`Reset execution history for ${taskType}`);- fetchSchedule();- }- };+ // Backward-compat aliases used in child components+ const handleUpdateSelfImprovement = handleUpdateTask;+ const handleUpdateAppImprovement = handleUpdateTask;+ const handleTriggerSelfImprovement = (taskType) => handleTriggerTask(taskType);+ const handleTriggerAppImprovement = (taskType, appId) => handleTriggerTask(taskType, appId);+ const handleResetSelfImprovement = handleResetTask;+ const handleResetAppImprovement = handleResetTask;const handleUpdateAppOverride = async (appId, taskType, { enabled, interval }) => {const result = await api.updateAppTaskTypeOverride(appId, taskType, { enabled, interval }).catch(err => {@@ -805,67 +771,28 @@ export default function ScheduleTab({ apps }) {</button></div>- {/* Segmented Control */}- <div className="flex bg-port-card rounded-lg p-1 border border-port-border">- <button- onClick={() => setView('self')}- className={`flex-1 px-4 py-2 text-sm font-medium rounded-md transition-colors ${- activeView === 'self'- ? 'bg-port-accent text-white'- : 'text-gray-400 hover:text-white'- }`}- >- Self-Improvement- </button>- <button- onClick={() => setView('app')}- className={`flex-1 px-4 py-2 text-sm font-medium rounded-md transition-colors ${- activeView === 'app'- ? 'bg-port-accent text-white'- : 'text-gray-400 hover:text-white'- }`}- >- App Improvement- </button>- </div>-{schedule.onDemandRequests?.length > 0 && (<div className="bg-port-accent/10 border border-port-accent/30 rounded-lg p-4"><h4 className="text-sm font-medium text-port-accent mb-2">Pending On-Demand Tasks</h4><div className="space-y-1">{schedule.onDemandRequests.map(req => (<div key={req.id} className="text-sm text-gray-300">- {req.taskType} ({req.category}) - requested {new Date(req.requestedAt).toLocaleTimeString()}+ {req.taskType}{req.appId ? ` (${req.appId})` : ''} - requested {new Date(req.requestedAt).toLocaleTimeString()}</div>))}</div></div>)}- {activeView === 'self' && (- <TaskTypeSection- title="Self-Improvement Tasks"- description="Tasks that analyze and improve PortOS itself"- tasks={schedule.selfImprovement}- onUpdate={handleUpdateSelfImprovement}- onTrigger={handleTriggerSelfImprovement}- onReset={handleResetSelfImprovement}- category="selfImprovement"- providers={providers}- />- )}-- {activeView === 'app' && (- <AppTaskTypeSection- tasks={schedule.appImprovement}- onUpdate={handleUpdateAppImprovement}- onTrigger={handleTriggerAppImprovement}- onReset={handleResetAppImprovement}- providers={providers}- apps={apps}- onUpdateOverride={handleUpdateAppOverride}- />- )}+ <AppTaskTypeSection+ tasks={schedule.tasks || schedule.appImprovement || schedule.selfImprovement}+ onUpdate={handleUpdateTask}+ onTrigger={handleTriggerAppImprovement}+ onReset={handleResetTask}+ providers={providers}+ apps={apps}+ onUpdateOverride={handleUpdateAppOverride}+ />{schedule.lastUpdated && (<div className="text-xs text-gray-500 text-right">diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex 92260bce04..cf08bea69a 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -31,19 +31,22 @@ function extractTaskType(description) {if (!description) return 'general';const d = description.toLowerCase();- // Check for self-improvement task patterns first- if (d.includes('[self-improvement]')) {- if (d.includes('ui bug')) return 'self-improve:ui-bugs';- if (d.includes('mobile')) return 'self-improve:mobile-responsive';- if (d.includes('security')) return 'self-improve:security';- if (d.includes('code quality')) return 'self-improve:code-quality';- if (d.includes('console error')) return 'self-improve:console-errors';- if (d.includes('performance')) return 'self-improve:performance';- if (d.includes('enhance cos') || d.includes('cos capabilities')) return 'self-improve:cos-enhancement';- if (d.includes('test coverage')) return 'self-improve:test-coverage';- if (d.includes('documentation')) return 'self-improve:documentation';- if (d.includes('feature idea') || d.includes('brainstorm')) return 'self-improve:feature-ideas';- if (d.includes('accessibility')) return 'self-improve:accessibility';+ // Check for improvement task patterns first+ if (d.includes('[self-improvement]') || d.includes('[improvement]')) {+ if (d.includes('ui bug')) return 'task:ui-bugs';+ if (d.includes('mobile')) return 'task:mobile-responsive';+ if (d.includes('security')) return 'task:security';+ if (d.includes('code quality')) return 'task:code-quality';+ if (d.includes('console error')) return 'task:console-errors';+ if (d.includes('performance')) return 'task:performance';+ if (d.includes('test coverage')) return 'task:test-coverage';+ if (d.includes('documentation')) return 'task:documentation';+ if (d.includes('feature idea') || d.includes('brainstorm')) return 'task:feature-ideas';+ if (d.includes('accessibility')) return 'task:accessibility';+ if (d.includes('error handling')) return 'task:error-handling';+ if (d.includes('typing') || d.includes('typescript')) return 'task:typing';+ if (d.includes('release')) return 'task:release-check';+ if (d.includes('dependency')) return 'task:dependency-updates';}// General task type classificationdiff --git a/client/src/services/api.js b/client/src/services/api.jsindex 2300080bd5..d518870246 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -670,22 +670,23 @@ export const getCosSchedule = () => request('/cos/schedule');export const getCosScheduleIntervalTypes = () => request('/cos/schedule/interval-types');export const getCosScheduleDueTasks = () => request('/cos/schedule/due');export const getCosScheduleDueAppTasks = (appId) => request(`/cos/schedule/due/${appId}`);-export const updateCosSelfImprovementInterval = (taskType, settings) => request(`/cos/schedule/self-improvement/${taskType}`, {+// Unified task interval update+export const updateCosTaskInterval = (taskType, settings) => request(`/cos/schedule/task/${taskType}`, {method: 'PUT',body: JSON.stringify(settings)});-export const updateCosAppImprovementInterval = (taskType, settings) => request(`/cos/schedule/app-improvement/${taskType}`, {- method: 'PUT',- body: JSON.stringify(settings)-});-export const triggerCosOnDemandTask = (taskType, category = 'selfImprovement', appId = null) => request('/cos/schedule/trigger', {+// Deprecated aliases — delegate to unified endpoint+export const updateCosSelfImprovementInterval = (taskType, settings) => updateCosTaskInterval(taskType, settings);+export const updateCosAppImprovementInterval = (taskType, settings) => updateCosTaskInterval(taskType, settings);++export const triggerCosOnDemandTask = (taskType, appId = null) => request('/cos/schedule/trigger', {method: 'POST',- body: JSON.stringify({ taskType, category, appId })+ body: JSON.stringify({ taskType, appId })});export const getCosOnDemandRequests = () => request('/cos/schedule/on-demand');-export const resetCosTaskHistory = (taskType, category = 'selfImprovement', appId = null) => request('/cos/schedule/reset', {+export const resetCosTaskHistory = (taskType, appId = null) => request('/cos/schedule/reset', {method: 'POST',- body: JSON.stringify({ taskType, category, appId })+ body: JSON.stringify({ taskType, appId })});export const getCosScheduleTemplates = () => request('/cos/schedule/templates');export const addCosScheduleTemplate = (template) => request('/cos/schedule/templates', {diff --git a/package.json b/package.jsonindex 24c066d6ce..c6a64f413d 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "portos",- "version": "1.2.0",+ "version": "1.3.0","private": true,"description": "Local dev machine App OS portal","author": "Adam Eivy (@antic|@atomantic)",diff --git a/server/routes/cos.js b/server/routes/cos.jsindex 25a532aa86..80e25e23ba 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -613,57 +613,66 @@ router.get('/upcoming', asyncHandler(async (req, res) => {res.json(upcoming);}));-// GET /api/cos/schedule/self-improvement/:taskType - Get interval for self-improvement task-router.get('/schedule/self-improvement/:taskType', asyncHandler(async (req, res) => {+// GET /api/cos/schedule/task/:taskType - Get interval for a task type (unified)+router.get('/schedule/task/:taskType', asyncHandler(async (req, res) => {const { taskType } = req.params;- const interval = await taskSchedule.getSelfImprovementInterval(taskType);- const shouldRun = await taskSchedule.shouldRunSelfImprovementTask(taskType);+ const interval = await taskSchedule.getTaskInterval(taskType);+ const shouldRun = await taskSchedule.shouldRunTask(taskType);res.json({ taskType, interval, shouldRun });}));-// PUT /api/cos/schedule/self-improvement/:taskType - Update interval for self-improvement task-router.put('/schedule/self-improvement/:taskType', asyncHandler(async (req, res) => {+// PUT /api/cos/schedule/task/:taskType - Update interval for a task type (unified)+router.put('/schedule/task/:taskType', asyncHandler(async (req, res) => {const { taskType } = req.params;- const result = await taskSchedule.updateSelfImprovementInterval(taskType, pickScheduleSettings(req.body));+ const result = await taskSchedule.updateTaskInterval(taskType, pickScheduleSettings(req.body));res.json({ success: true, taskType, interval: result });}));-// GET /api/cos/schedule/app-improvement/:taskType - Get interval for app improvement task+// Deprecated aliases — delegate to unified endpoints+router.get('/schedule/self-improvement/:taskType', asyncHandler(async (req, res) => {+ const { taskType } = req.params;+ const interval = await taskSchedule.getTaskInterval(taskType);+ const shouldRun = await taskSchedule.shouldRunTask(taskType);+ res.json({ taskType, interval, shouldRun });+}));+router.put('/schedule/self-improvement/:taskType', asyncHandler(async (req, res) => {+ const { taskType } = req.params;+ const result = await taskSchedule.updateTaskInterval(taskType, pickScheduleSettings(req.body));+ res.json({ success: true, taskType, interval: result });+}));router.get('/schedule/app-improvement/:taskType', asyncHandler(async (req, res) => {const { taskType } = req.params;- const interval = await taskSchedule.getAppImprovementInterval(taskType);+ const interval = await taskSchedule.getTaskInterval(taskType);res.json({ taskType, interval });}));--// PUT /api/cos/schedule/app-improvement/:taskType - Update interval for app improvement taskrouter.put('/schedule/app-improvement/:taskType', asyncHandler(async (req, res) => {const { taskType } = req.params;- const result = await taskSchedule.updateAppImprovementInterval(taskType, pickScheduleSettings(req.body));+ const result = await taskSchedule.updateTaskInterval(taskType, pickScheduleSettings(req.body));res.json({ success: true, taskType, interval: result });}));// GET /api/cos/schedule/due - Get all tasks that are due to runrouter.get('/schedule/due', asyncHandler(async (req, res) => {- const selfImprovement = await taskSchedule.getDueSelfImprovementTasks();- res.json({ selfImprovement, appImprovement: 'requires appId - use /schedule/due/:appId' });+ const tasks = await taskSchedule.getDueTasks();+ res.json({ tasks });}));-// GET /api/cos/schedule/due/:appId - Get app improvement tasks due for specific app+// GET /api/cos/schedule/due/:appId - Get tasks due for specific approuter.get('/schedule/due/:appId', asyncHandler(async (req, res) => {const { appId } = req.params;- const appImprovement = await taskSchedule.getDueAppImprovementTasks(appId);- res.json({ appId, appImprovement });+ const tasks = await taskSchedule.getDueTasks(appId);+ res.json({ appId, tasks });}));// POST /api/cos/schedule/trigger - Trigger an on-demand taskrouter.post('/schedule/trigger', asyncHandler(async (req, res) => {- const { taskType, category, appId } = req.body;+ const { taskType, appId } = req.body;if (!taskType) {throw new ServerError('taskType is required', { status: 400, code: 'VALIDATION_ERROR' });}- const request = await taskSchedule.triggerOnDemandTask(taskType, category || 'selfImprovement', appId);+ const request = await taskSchedule.triggerOnDemandTask(taskType, appId);res.json({ success: true, request });}));@@ -685,13 +694,13 @@ router.delete('/schedule/on-demand/:requestId', asyncHandler(async (req, res) =>// POST /api/cos/schedule/reset - Reset execution history for a task typerouter.post('/schedule/reset', asyncHandler(async (req, res) => {- const { taskType, category, appId } = req.body;+ const { taskType, appId } = req.body;if (!taskType) {throw new ServerError('taskType is required', { status: 400, code: 'VALIDATION_ERROR' });}- const result = await taskSchedule.resetExecutionHistory(taskType, category || 'selfImprovement', appId);+ const result = await taskSchedule.resetExecutionHistory(taskType, appId);if (result.error) {throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });}@@ -1157,7 +1166,7 @@ router.get('/quick-summary', asyncHandler(async (req, res) => {}));// GET /api/cos/goal-progress - Get progress toward user goals-// Maps completed tasks to goal categories from COS-GOALS.md+// Maps completed tasks to goal categories from GOALS.mdrouter.get('/goal-progress', asyncHandler(async (req, res) => {const progress = await goalProgress.getGoalProgress();res.json(progress);diff --git a/server/services/cos.js b/server/services/cos.jsindex a6583039e4..fc06e78e77 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -270,7 +270,7 @@ const withStateLock = createMutex();const DEFAULT_CONFIG = {userTasksFile: 'data/TASKS.md', // User-defined taskscosTasksFile: 'data/COS-TASKS.md', // CoS internal/system tasks- goalsFile: 'data/COS-GOALS.md', // Mission and goals file+ goalsFile: 'GOALS.md', // Mission and goals fileevaluationIntervalMs: 60000, // 1 minute - stay active, check frequentlyhealthCheckIntervalMs: 900000, // 15 minutesmaxConcurrentAgents: 3,@@ -282,15 +282,16 @@ const DEFAULT_CONFIG = {{ name: 'puppeteer', command: 'npx', args: ['-y', '@anthropic/mcp-puppeteer', '--isolated'] }],autoStart: false, // Legacy: use alwaysOn instead- selfImprovementEnabled: false, // Allow CoS to improve itself (PortOS codebase)- appImprovementEnabled: true, // Allow CoS to improve managed apps+ selfImprovementEnabled: true, // Deprecated: use improvementEnabled+ appImprovementEnabled: true, // Deprecated: use improvementEnabled+ improvementEnabled: true, // Allow CoS to run improvement tasks on all apps (including PortOS)avatarStyle: 'svg', // UI preference: 'svg' | 'ascii' | 'cyber' | 'sigil'// Always-on mode settingsalwaysOn: true, // CoS starts automatically and stays activeappReviewCooldownMs: 1800000, // 30 min between working on same app (was 1 hour)idleReviewEnabled: true, // Review apps for improvements when no user tasksidleReviewPriority: 'MEDIUM', // Priority for auto-generated tasks (was LOW)- comprehensiveAppImprovement: true, // Use comprehensive analysis for managed apps (same as PortOS self-improvement)+ comprehensiveAppImprovement: true, // Deprecated: always comprehensive nowimmediateExecution: true, // Execute new tasks immediately, don't wait for intervalproactiveMode: true, // Be proactive about finding workautonomousJobsEnabled: true, // Enable recurring autonomous jobs (git maintenance, brain processing, etc.)@@ -896,57 +897,46 @@ export async function evaluateTasks() {for (const request of onDemandRequests) {if (tasksToSpawn.length >= availableSlots) break;- let task = null;- if (request.category === 'selfImprovement' && state.config.selfImprovementEnabled) {- // Generate self-improvement task for the requested type+ // Unified on-demand handling (no category split)+ const improvementEnabled = state.config.improvementEnabled ??+ (state.config.selfImprovementEnabled || state.config.appImprovementEnabled);++ if (!improvementEnabled) {await taskSchedule.clearOnDemandRequest(request.id);- emitLog('info', `Processing on-demand self-improvement: ${request.taskType}`, { requestId: request.id });+ continue;+ }++ let task = null;+ // Determine target app (if any)+ const apps = await getActiveApps().catch(() => []);+ let targetApp = null;- await taskSchedule.recordExecution(`self-improve:${request.taskType}`);+ if (request.appId) {+ targetApp = apps.find(a => a.id === request.appId);+ if (!targetApp) {+ emitLog('warn', `On-demand request for unknown app: ${request.appId}`, { requestId: request.id });+ await taskSchedule.clearOnDemandRequest(request.id);+ continue;+ }+ }++ await taskSchedule.clearOnDemandRequest(request.id);++ if (targetApp) {+ emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });+ await markAppReviewStarted(targetApp.id, `on-demand-${Date.now()}`);+ await taskSchedule.recordExecution(`task:${request.taskType}`, targetApp.id);+ task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state);+ } else {+ emitLog('info', `Processing on-demand improvement: ${request.taskType}`, { requestId: request.id });+ await taskSchedule.recordExecution(`task:${request.taskType}`);await withStateLock(async () => {const s = await loadState();s.stats.lastSelfImprovement = new Date().toISOString();s.stats.lastSelfImprovementType = request.taskType;await saveState(s);});-task = await generateSelfImprovementTaskForType(request.taskType, state);- } else if (request.category === 'appImprovement' && state.config.appImprovementEnabled) {- // Generate app improvement task for the specific app requested (or next eligible if no appId)- // Only consider active (non-archived) apps for COS tasks- const apps = await getActiveApps().catch(() => []);- let targetApp = null;-- if (request.appId) {- // Specific app requested- targetApp = apps.find(a => a.id === request.appId);- if (!targetApp) {- emitLog('warn', `On-demand request for unknown app: ${request.appId}`, { requestId: request.id });- await taskSchedule.clearOnDemandRequest(request.id);- continue;- }- } else {- // No specific app - use next eligible app (bypass cooldown for on-demand)- targetApp = await getNextAppForReview(apps, 0); // 0 cooldown = no cooldown check- if (!targetApp && apps.length > 0) {- // All apps might be on cooldown - pick the first app anyway for on-demand- targetApp = apps[0];- }- if (!targetApp) {- emitLog('warn', 'On-demand app improvement requested but no apps available', { requestId: request.id });- await taskSchedule.clearOnDemandRequest(request.id);- continue;- }- }-- await taskSchedule.clearOnDemandRequest(request.id);- emitLog('info', `Processing on-demand app improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });-- // Mark app review started and record execution- await markAppReviewStarted(targetApp.id, `on-demand-${Date.now()}`);- await taskSchedule.recordExecution(`app-improve:${request.taskType}`, targetApp.id);-- task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state);}if (task && canSpawnTask(task)) {@@ -1160,30 +1150,19 @@ export async function evaluateTasks() {* @returns {Object|null} Generated task or null if nothing to do*/async function generateIdleReviewTask(state) {- // Check if we should run self-improvement (alternates with app reviews)- const lastSelfImprovementTime = state.stats.lastSelfImprovement- ? new Date(state.stats.lastSelfImprovement).getTime()- : 0;- const lastIdleReviewTime = state.stats.lastIdleReview- ? new Date(state.stats.lastIdleReview).getTime()- : 0;+ // Check if improvement tasks are enabled (unified flag, with backward compat)+ const improvementEnabled = state.config.improvementEnabled ??+ (state.config.selfImprovementEnabled || state.config.appImprovementEnabled);- // Prioritize self-improvement if it hasn't run recently (or ever)- const shouldRunSelfImprovement = lastSelfImprovementTime <= lastIdleReviewTime;-- if (shouldRunSelfImprovement && state.config.selfImprovementEnabled) {- const selfImprovementTask = await generateSelfImprovementTask(state);- if (selfImprovementTask) {- return selfImprovementTask;- }+ if (!improvementEnabled) {+ emitLog('debug', 'Improvement tasks are disabled');+ return null;}- // Try app reviews (if enabled)- if (state.config.appImprovementEnabled) {- // Get all active (non-archived) managed apps- const apps = await getActiveApps().catch(() => []);+ // Get all active (non-archived) managed apps (including PortOS)+ const apps = await getActiveApps().catch(() => []);- if (apps.length > 0) {+ if (apps.length > 0) {// Find next app eligible for review (not on cooldown, oldest review first)const nextApp = await getNextAppForReview(apps, state.config.appReviewCooldownMs);@@ -1199,41 +1178,10 @@ async function generateIdleReviewTask(state) {await saveState(s);});- // 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- };- }+ emitLog('info', `Generating improvement task for ${nextApp.name}`, { appId: nextApp.id });+ return await generateManagedAppImprovementTask(nextApp, state);}}- }-- // All apps on cooldown or no apps - fall back to self-improvement- // This ensures CoS is ALWAYS working on something- if (state.config.selfImprovementEnabled) {- emitLog('debug', 'No apps available for review - running self-improvement instead');- return await generateSelfImprovementTask(state);- }emitLog('debug', 'No idle tasks available');return null;@@ -1245,7 +1193,12 @@ async function generateIdleReviewTask(state) {* 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');+ const { getDueTasks, shouldRunTask, getNextTaskType } = await import('./taskSchedule.js');++ // Check unified improvement flag (with backward compat)+ const improvementEnabled = state.config.improvementEnabled ??+ (state.config.selfImprovementEnabled || state.config.appImprovementEnabled);+ if (!improvementEnabled) return;// Get existing pending/in_progress system tasks to avoid duplicatesconst existingTasks = cosTaskData.tasks || [];@@ -1253,74 +1206,33 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {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 analysisType = task.metadata?.analysisType ||+ task.metadata?.selfImprovementType ||+ task.description?.match(/\[(?:self-improvement|improvement)\]\s*(\w[\w-]*)/i)?.[1];const appId = task.metadata?.app;- if (appImpType && appId) {- existingTaskTypes.add(`app:${appId}:${appImpType}`);+ if (analysisType) {+ existingTaskTypes.add(appId ? `app:${appId}:${analysisType}` : analysisType);}}}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 (if enabled)- if (state.config.appImprovementEnabled) {- // Only queue tasks for active (non-archived) apps- const apps = await getActiveApps().catch(() => []);- for (const app of apps) {+ // Queue eligible improvement tasks for all managed apps (including PortOS)+ const apps = await getActiveApps().catch(() => []);+ for (const app of apps) {// Check if app is on cooldownconst 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 nextTypeResult = await getNextTaskType(app.id).catch(() => null);+ if (!nextTypeResult) continue;+ const nextType = nextTypeResult.taskType;const taskKey = `app:${app.id}:${nextType}`;if (existingTaskTypes.has(taskKey)) {- emitLog('debug', `App improvement task ${nextType} for ${app.name} already queued`);+ emitLog('debug', `Improvement task ${nextType} for ${app.name} already queued`);continue;}@@ -1330,21 +1242,19 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {// Add to COS-TASKS.mdconst newTask = await addTask({- id: `sys-app-${app.id.slice(0, 8)}-${nextType}-${Date.now().toString(36)}`,+ id: `sys-${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}`,+ context: `Auto-generated 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 });+ emitLog('info', `Queued 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) {@@ -1357,18 +1267,20 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {*/function getSelfImprovementTaskDescription(taskType) {const descriptions = {- 'ui-bugs': 'Review PortOS UI for visual bugs, layout issues, and UX improvements',+ 'ui-bugs': 'Review 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)',+ 'security': 'Audit codebase 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',+ 'feature-ideas': 'Brainstorm and document potential new features based on GOALS.md','accessibility': 'Audit and fix accessibility issues (ARIA, keyboard nav, contrast)',- 'dependency-updates': 'Check for and safely update outdated dependencies'+ 'dependency-updates': 'Check for and safely update outdated dependencies',+ 'error-handling': 'Improve error handling patterns and recovery logic',+ 'typing': 'Add or fix TypeScript/JSDoc type annotations',+ 'release-check': 'Verify release readiness (changelog, version, tests)'};return descriptions[taskType] || null;}@@ -1378,7 +1290,7 @@ function getSelfImprovementTaskDescription(taskType) {*/function getAppImprovementTaskDescription(taskType, app) {const descriptions = {- 'security-audit': `Security audit for ${app.name}: check for vulnerabilities`,+ 'security': `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}`,@@ -1387,14 +1299,18 @@ function getAppImprovementTaskDescription(taskType, app) {'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}`+ 'typing': `Add/fix TypeScript types in ${app.name}`,+ 'ui-bugs': `Review UI for visual bugs in ${app.name}`,+ 'mobile-responsive': `Check mobile responsiveness of ${app.name}`,+ 'feature-ideas': `Brainstorm features for ${app.name} based on GOALS.md`,+ 'release-check': `Verify release readiness for ${app.name}`};return descriptions[taskType] || null;}-// Self-improvement task types (rotates through these)-// Organized by goal priority from COS-GOALS.md-const SELF_IMPROVEMENT_TYPES = [+// 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',@@ -1402,17 +1318,21 @@ const SELF_IMPROVEMENT_TYPES = ['code-quality','console-errors','performance',- // Goal 2: Self-Improvement (CoS enhancing itself)- 'cos-enhancement',+ // Goal 2: Self-Improvement'test-coverage',+ 'error-handling',+ 'typing',// Goal 3: Documentation'documentation',// Goal 4: User Engagement'feature-ideas',// Goal 5: System Health'accessibility',- 'dependency-updates'+ 'dependency-updates',+ 'release-check'];+// Backward compat alias+const SELF_IMPROVEMENT_TYPES = IMPROVEMENT_TYPES;/*** Generate a self-improvement task for PortOS itself@@ -1429,17 +1349,17 @@ async function generateSelfImprovementTask(state) {// Import task schedule service dynamically to avoid circular dependencyconst taskSchedule = await import('./taskSchedule.js');- // First, check for any on-demand task requests+ // First, check for any on-demand task requests (no category filter — unified)const onDemandRequests = await taskSchedule.getOnDemandRequests();- const selfImprovementRequests = onDemandRequests.filter(r => r.category === 'selfImprovement');+ const selfRequests = onDemandRequests.filter(r => !r.appId);- if (selfImprovementRequests.length > 0) {- const request = selfImprovementRequests[0];+ 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(`self-improve:${request.taskType}`);+ await taskSchedule.recordExecution(`task:${request.taskType}`);// Update stateawait withStateLock(async () => {@@ -1454,14 +1374,14 @@ async function generateSelfImprovementTask(state) {// Use the schedule service to determine the next task typeconst lastType = state.stats.lastSelfImprovementType || '';- const nextTypeResult = await taskSchedule.getNextSelfImprovementTaskType(lastType);+ const nextTypeResult = await taskSchedule.getNextTaskType(null, lastType);if (!nextTypeResult) {- emitLog('debug', 'No self-improvement tasks are eligible to run based on schedule');+ emitLog('debug', 'No improvement tasks are eligible to run based on schedule');await recordDecision(DECISION_TYPES.NOT_DUE,- 'No self-improvement tasks are eligible based on schedule',- { category: 'selfImprovement' }+ 'No improvement tasks are eligible based on schedule',+ {});return null;}@@ -1470,7 +1390,7 @@ async function generateSelfImprovementTask(state) {const selectionReason = nextTypeResult.reason;// Additional check: skip if learning data suggests poor performance- const taskTypeKey = `self-improve:${nextType}`;+ const taskTypeKey = `task:${nextType}`;const cooldownInfo = await getAdaptiveCooldownMultiplier(taskTypeKey).catch(() => ({ skip: false }));if (cooldownInfo.skip) {@@ -1489,7 +1409,7 @@ async function generateSelfImprovementTask(state) {);// Try to find another eligible task type- const dueTasks = await taskSchedule.getDueSelfImprovementTasks();+ const dueTasks = await taskSchedule.getDueTasks();const alternativeTask = dueTasks.find(t => t.taskType !== nextType);if (alternativeTask) {@@ -1508,7 +1428,7 @@ async function generateSelfImprovementTask(state) {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:', '');+ const oldestType = skippedTypes[0].taskType.replace(/^(self-improve|app-improve|task):/, '');nextType = oldestType;emitLog('info', `Retrying ${oldestType} as it hasn't been attempted recently`);@@ -1519,7 +1439,7 @@ async function generateSelfImprovementTask(state) {{ taskType: oldestType, reason: 'oldest-skipped-type' });} else {- nextType = SELF_IMPROVEMENT_TYPES[0];+ nextType = IMPROVEMENT_TYPES[0];}}}@@ -1533,7 +1453,7 @@ async function generateSelfImprovementTask(state) {}// Record execution in the schedule service- await taskSchedule.recordExecution(`self-improve:${nextType}`);+ await taskSchedule.recordExecution(`task:${nextType}`);// Update state with new timestamp and typeawait withStateLock(async () => {@@ -1543,12 +1463,12 @@ async function generateSelfImprovementTask(state) {await saveState(s);});- emitLog('info', `Generating self-improvement task: ${nextType} (${selectionReason})`);+ emitLog('info', `Generating improvement task: ${nextType} (${selectionReason})`);// Record task selection decisionawait recordDecision(DECISION_TYPES.TASK_SELECTED,- `Selected ${nextType} for self-improvement`,+ `Selected ${nextType} for improvement`,{taskType: nextType,reason: selectionReason,@@ -1569,10 +1489,10 @@ async function generateSelfImprovementTask(state) {*/async function generateSelfImprovementTaskForType(taskType, state, taskDescriptions = null) {const taskSchedule = await import('./taskSchedule.js');- const interval = await taskSchedule.getSelfImprovementInterval(taskType);+ const interval = await taskSchedule.getTaskInterval(taskType);// Get the effective prompt (custom or default)- const description = await taskSchedule.getSelfImprovementPrompt(taskType);+ const description = await taskSchedule.getTaskPrompt(taskType);const metadata = {analysisType: taskType,@@ -1755,34 +1675,6 @@ Optimize and commit improvements.Use model: claude-opus-4-5-20251101 for performance optimization`,- 'cos-enhancement': `[Self-Improvement] Enhance CoS Capabilities--Review the CoS system and add new capabilities:--1. Read data/COS-GOALS.md to understand the mission and goals-2. Review server/services/cos.js for improvement opportunities:- - Better task prioritization logic- - Smarter model selection- - More informative status messages- - Better error recovery--3. Review the self-improvement task prompts:- - Are they comprehensive enough?- - Do they lead to quality fixes?- - What new analysis types could be added?--4. Consider adding:- - New MCP server integrations- - Better metrics tracking- - Learning from completed tasks- - Smarter cooldown logic--5. Implement ONE meaningful enhancement and commit it--Focus on making CoS more autonomous and effective.--Use model: claude-opus-4-5-20251101 for thoughtful enhancement`,-'test-coverage': `[Self-Improvement] Improve Test CoverageAnalyze and improve test coverage for PortOS:@@ -1846,7 +1738,7 @@ Use model: claude-opus-4-5-20251101 for clear documentation`,Think about ways to make PortOS more useful:-1. Read data/COS-GOALS.md for context on user goals+1. Read GOALS.md for context on user goals2. Review recent completed tasks to understand patterns3. Consider these areas:- User task management improvements@@ -1919,9 +1811,7 @@ async function generateManagedAppImprovementTask(app, state) {// First, check for any on-demand task requests for this appconst onDemandRequests = await taskSchedule.getOnDemandRequests();- const appRequests = onDemandRequests.filter(r =>- r.category === 'appImprovement' && r.appId === app.id- );+ const appRequests = onDemandRequests.filter(r => r.appId === app.id);let nextType;let selectionReason;@@ -1938,7 +1828,7 @@ async function generateManagedAppImprovementTask(app, state) {const lastType = appActivity?.lastImprovementType || '';// Use the schedule service to determine the next task type- const nextTypeResult = await taskSchedule.getNextAppImprovementTaskType(app.id, lastType);+ const nextTypeResult = await taskSchedule.getNextTaskType(app.id, lastType);if (!nextTypeResult) {emitLog('info', `No app improvement tasks are eligible for ${app.name} based on schedule`);@@ -1950,283 +1840,25 @@ async function generateManagedAppImprovementTask(app, state) {}// Record execution in the schedule service- await taskSchedule.recordExecution(`app-improve:${nextType}`, app.id);+ await taskSchedule.recordExecution(`task:${nextType}`, app.id);// Update app activity with new typeawait updateAppActivity(app.id, {lastImprovementType: nextType});- emitLog('info', `Generating comprehensive improvement task for ${app.name}: ${nextType} (${selectionReason})`, { appId: app.id, analysisType: nextType });+ emitLog('info', `Generating improvement task for ${app.name}: ${nextType} (${selectionReason})`, { appId: app.id, analysisType: nextType });// Get the effective prompt (custom or default template)- const promptTemplate = await taskSchedule.getAppImprovementPrompt(nextType);+ const promptTemplate = await taskSchedule.getTaskPrompt(nextType);// Replace template variables in the promptconst description = promptTemplate.replace(/\{appName\}/g, app.name).replace(/\{repoPath\}/g, app.repoPath);- // Legacy task descriptions - keeping for fallback but they won't be used- 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`- };-// Get interval settings to determine provider/model- const interval = await taskSchedule.getAppImprovementInterval(nextType);+ const interval = await taskSchedule.getTaskInterval(nextType);const metadata = {app: app.id,@@ -2279,10 +1911,10 @@ async function generateManagedAppImprovementTaskForType(taskType, app, state) {lastImprovementType: taskType});- emitLog('info', `Generating app improvement task for ${app.name}: ${taskType} (on-demand)`, { appId: app.id, analysisType: taskType });+ emitLog('info', `Generating improvement task for ${app.name}: ${taskType} (on-demand)`, { appId: app.id, analysisType: taskType });// Get the effective prompt (custom or default template)- const promptTemplate = await taskSchedule.getAppImprovementPrompt(taskType);+ const promptTemplate = await taskSchedule.getTaskPrompt(taskType);// Replace template variables in the promptconst description = promptTemplate@@ -2290,7 +1922,7 @@ async function generateManagedAppImprovementTaskForType(taskType, app, state) {.replace(/\{repoPath\}/g, app.repoPath);// Get interval settings to determine provider/model- const interval = await taskSchedule.getAppImprovementInterval(taskType);+ const interval = await taskSchedule.getTaskInterval(taskType);const metadata = {app: app.id,@@ -3561,11 +3193,37 @@ async function dequeueNextTask() {for (const request of onDemandRequests) {if (spawned >= availableSlots) break;- let task = null;- if (request.category === 'selfImprovement' && state.config.selfImprovementEnabled) {+ // Unified on-demand handling (no category split)+ const improvEnabled = state.config.improvementEnabled ??+ (state.config.selfImprovementEnabled || state.config.appImprovementEnabled);+ if (!improvEnabled) {await taskScheduleMod.clearOnDemandRequest(request.id);- emitLog('info', `Processing on-demand self-improvement: ${request.taskType}`, { requestId: request.id });- await taskScheduleMod.recordExecution(`self-improve:${request.taskType}`);+ continue;+ }++ let task = null;+ const apps = await getActiveApps().catch(() => []);+ let targetApp = null;++ if (request.appId) {+ targetApp = apps.find(a => a.id === request.appId);+ if (!targetApp) {+ emitLog('warn', `On-demand request for unknown app: ${request.appId}`, { requestId: request.id });+ await taskScheduleMod.clearOnDemandRequest(request.id);+ continue;+ }+ }++ await taskScheduleMod.clearOnDemandRequest(request.id);++ if (targetApp) {+ emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });+ await markAppReviewStarted(targetApp.id, `on-demand-${Date.now()}`);+ await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);+ task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state);+ } else {+ emitLog('info', `Processing on-demand improvement: ${request.taskType}`, { requestId: request.id });+ await taskScheduleMod.recordExecution(`task:${request.taskType}`);await withStateLock(async () => {const s = await loadState();s.stats.lastSelfImprovement = new Date().toISOString();@@ -3573,32 +3231,6 @@ async function dequeueNextTask() {await saveState(s);});task = await generateSelfImprovementTaskForType(request.taskType, state);- } else if (request.category === 'appImprovement' && state.config.appImprovementEnabled) {- const apps = await getActiveApps().catch(() => []);- let targetApp = null;-- if (request.appId) {- targetApp = apps.find(a => a.id === request.appId);- if (!targetApp) {- emitLog('warn', `On-demand request for unknown app: ${request.appId}`, { requestId: request.id });- await taskScheduleMod.clearOnDemandRequest(request.id);- continue;- }- } else {- targetApp = await getNextAppForReview(apps, 0);- if (!targetApp && apps.length > 0) targetApp = apps[0];- if (!targetApp) {- emitLog('warn', 'On-demand app improvement requested but no apps available', { requestId: request.id });- await taskScheduleMod.clearOnDemandRequest(request.id);- continue;- }- }-- await taskScheduleMod.clearOnDemandRequest(request.id);- emitLog('info', `Processing on-demand app improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });- await markAppReviewStarted(targetApp.id, `on-demand-${Date.now()}`);- await taskScheduleMod.recordExecution(`app-improve:${request.taskType}`, targetApp.id);- task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state);}if (task && canSpawn(task)) {diff --git a/server/services/goalProgress.js b/server/services/goalProgress.jsindex 9e423988ef..26a7b5c5e0 100644--- a/server/services/goalProgress.js+++ b/server/services/goalProgress.js@@ -1,10 +1,10 @@/*** Goal Progress Service*- * Tracks progress toward user goals defined in COS-GOALS.md by analyzing+ * Tracks progress toward user goals defined in GOALS.md by analyzing* completed CoS tasks and mapping them to goal categories.*- * Goals are extracted from COS-GOALS.md's Active Goals section.+ * Goals are extracted from GOALS.md's Operational Goals section.* Task completions are categorized by keywords and mapped to goal progress.*/@@ -12,7 +12,7 @@ import { readFile } from 'fs/promises'import { join } from 'path'import { readJSONFile, PATHS } from '../lib/fileUtils.js'-const GOALS_FILE = join(PATHS.data, 'COS-GOALS.md')+const GOALS_FILE = join(PATHS.root, 'GOALS.md')const LEARNING_FILE = join(PATHS.cos, 'learning.json')/**@@ -24,19 +24,19 @@ const GOAL_MAPPINGS = {icon: '🔧',color: 'emerald',keywords: ['security', 'audit', 'mobile', 'responsive', 'dry', 'dead-code', 'test', 'coverage', 'console', 'lint', 'refactor'],- taskTypes: ['self-improve:security-audit', 'self-improve:mobile-responsive', 'self-improve:feature', 'app-improve:security', 'app-improve:mobile']+ taskTypes: ['task:security', 'task:mobile-responsive', 'task:code-quality', 'task:test-coverage', 'task:console-errors', 'self-improve:security-audit', 'self-improve:mobile-responsive', 'app-improve:security']},'Self-Improvement': {icon: '🧠',color: 'purple',keywords: ['capability', 'improvement', 'learn', 'analysis', 'error', 'retry', 'prioritization', 'a11y', 'i18n', 'seo'],- taskTypes: ['self-improve:general', 'self-improve:brainstorm', 'idle-review']+ taskTypes: ['task:feature-ideas', 'task:error-handling', 'idle-review']},'Documentation': {icon: '📚',color: 'blue',keywords: ['document', 'docs', 'readme', 'plan', 'report', 'summary', 'changelog'],- taskTypes: ['self-improve:documentation', 'app-improve:documentation']+ taskTypes: ['task:documentation', 'self-improve:documentation', 'app-improve:documentation']},'User Engagement': {icon: '💬',@@ -48,12 +48,12 @@ const GOAL_MAPPINGS = {icon: '💚',color: 'green',keywords: ['health', 'pm2', 'memory', 'performance', 'monitor', 'alert', 'process', 'service'],- taskTypes: ['auto-fix', 'internal-task']+ taskTypes: ['task:performance', 'task:dependency-updates', 'auto-fix', 'internal-task']}}/**- * Parse COS-GOALS.md to extract active goals+ * Parse GOALS.md to extract active goals* @returns {Promise<Array>} Parsed goals with titles and items*/async function parseGoalsFile() {@@ -62,23 +62,29 @@ async function parseGoalsFile() {const goals = []const lines = content.split('\n')- let inActiveGoals = false+ let inGoalsSection = falselet currentGoal = nullfor (const line of lines) {- // Detect Active Goals section- if (line.startsWith('## Active Goals')) {- inActiveGoals = true+ // Detect Active Goals or Operational Goals section+ if (line.startsWith('## Active Goals') || line.startsWith('## Operational Goals')) {+ inGoalsSection = truecontinue}- // Stop at next major section- if (inActiveGoals && line.startsWith('## ') && !line.includes('Active Goals')) {- inActiveGoals = false+ // Stop at next major section (but not sub-sections like ### Task Generation)+ if (inGoalsSection && line.startsWith('## ') && !line.includes('Active Goals') && !line.includes('Operational Goals')) {+ inGoalsSection = falsecontinue}- if (!inActiveGoals) continue+ // Stop at non-goal sub-sections within Operational Goals+ if (inGoalsSection && line.startsWith('### ') && !line.match(/^### Goal \d+:/)) {+ // Skip non-goal subsections like "### Task Generation Priorities"+ continue+ }++ if (!inGoalsSection) continue// Parse goal headers (### Goal N: Name)const goalMatch = line.match(/^### Goal \d+:\s*(.+)/)@@ -115,7 +121,7 @@ async function getTaskStats() {/*** Calculate progress for each goal based on completed tasks- * @param {Array} goals - Parsed goals from COS-GOALS.md+ * @param {Array} goals - Parsed goals from GOALS.md* @param {Object} taskStats - Task completion statistics* @returns {Array} Goals with progress metrics*/diff --git a/server/services/selfImprovement.js b/server/services/selfImprovement.jsindex 03d9563093..d9d079a6bc 100644--- a/server/services/selfImprovement.js+++ b/server/services/selfImprovement.js@@ -51,11 +51,13 @@ const ANALYSIS_TYPES = {SECURITY: 'security',PERFORMANCE: 'performance',CODE_QUALITY: 'code-quality',- COS_ENHANCEMENT: 'cos-enhancement',TEST_COVERAGE: 'test-coverage',DOCUMENTATION: 'documentation',FEATURE_IDEAS: 'feature-ideas',- DEPENDENCY_UPDATES: 'dependency-updates'+ DEPENDENCY_UPDATES: 'dependency-updates',+ ERROR_HANDLING: 'error-handling',+ TYPING: 'typing',+ RELEASE_CHECK: 'release-check'};/**diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 12d98d1b40..5beb93e22a 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -1,11 +1,8 @@/**- * Task Schedule Service+ * Task Schedule Service (v2 - Unified)*- * Manages configurable intervals for self-improvement and managed app tasks.- * Allows setting per-task-type intervals like:- * - Run accessibility audits once per week- * - Run feature-ideas brainstorm daily- * - Run security audits once per app+ * Manages configurable intervals for improvement tasks across all apps (including PortOS).+ * All task types live in a single `tasks` object — no more selfImprovement/appImprovement split.** Interval types:* - 'rotation': Run as part of normal rotation (default)@@ -49,26 +46,9 @@ const WEEK = 7 * DAY;/*** Get learning-adjusted interval for a task type- *- * Applies adaptive multipliers based on historical task performance:- * - High success (>90%): Run 30% more often (multiplier 0.7)- * - Good success (75-89%): Run 15% more often (multiplier 0.85)- * - Moderate success (50-74%): Normal interval (multiplier 1.0)- * - Low success (30-49%): Run 50% less often (multiplier 1.5)- * - Very low (<30% with 5+ attempts): Run 100% less often (multiplier 2.0)- *- * This makes CoS more efficient by focusing on high-performing tasks- * while reducing wasted cycles on consistently failing ones.- *- * @param {string} taskType - Task type (e.g., 'ui-bugs', 'security')- * @param {string} category - 'selfImprovement' or 'appImprovement'- * @param {number} baseIntervalMs - Base interval in milliseconds- * @returns {Object} Adjusted interval info*/-async function getPerformanceAdjustedInterval(taskType, category, baseIntervalMs) {- const taskTypeKey = category === 'selfImprovement'- ? `self-improve:${taskType}`- : `app-improve:${taskType}`;+async function getPerformanceAdjustedInterval(taskType, baseIntervalMs) {+ const taskTypeKey = `task:${taskType}`;const cooldownInfo = await getAdaptiveCooldownMultiplier(taskTypeKey).catch(() => ({multiplier: 1.0,@@ -78,8 +58,26 @@ async function getPerformanceAdjustedInterval(taskType, category, baseIntervalMscompleted: 0}));- // Don't adjust if insufficient dataif (cooldownInfo.reason === 'insufficient-data' || cooldownInfo.reason === 'error-fallback') {+ // Also check legacy keys for migration period+ const legacyKeys = [`self-improve:${taskType}`, `app-improve:${taskType}`];+ for (const key of legacyKeys) {+ const legacyInfo = await getAdaptiveCooldownMultiplier(key).catch(() => null);+ if (legacyInfo && legacyInfo.reason !== 'insufficient-data' && legacyInfo.reason !== 'error-fallback') {+ const adjustedIntervalMs = Math.round(baseIntervalMs * legacyInfo.multiplier);+ return {+ adjustedIntervalMs,+ multiplier: legacyInfo.multiplier,+ reason: legacyInfo.reason,+ successRate: legacyInfo.successRate,+ dataPoints: legacyInfo.completed,+ skip: legacyInfo.skip,+ adjusted: legacyInfo.multiplier !== 1.0,+ recommendation: legacyInfo.recommendation+ };+ }+ }+return {adjustedIntervalMs: baseIntervalMs,multiplier: 1.0,@@ -92,7 +90,6 @@ async function getPerformanceAdjustedInterval(taskType, category, baseIntervalMsconst adjustedIntervalMs = Math.round(baseIntervalMs * cooldownInfo.multiplier);- // Log significant adjustmentsif (cooldownInfo.multiplier !== 1.0) {const direction = cooldownInfo.multiplier < 1 ? 'decreased' : 'increased';const percentage = Math.abs(Math.round((1 - cooldownInfo.multiplier) * 100));@@ -116,394 +113,13 @@ async function getPerformanceAdjustedInterval(taskType, category, baseIntervalMs};}-// Default prompts for self-improvement task types-const DEFAULT_SELF_IMPROVEMENT_PROMPTS = {- '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`,-- '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`,-- '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.`,-- '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.`,-- '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`,-- '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.`,-- 'cos-enhancement': `[Self-Improvement] Enhance CoS Capabilities--Review the CoS system and add new capabilities:--1. Read data/COS-GOALS.md to understand the mission and goals-2. Review server/services/cos.js for improvement opportunities:- - Better task prioritization logic- - Smarter model selection- - More informative status messages- - Better error recovery--3. Review the self-improvement task prompts:- - Are they comprehensive enough?- - Do they lead to quality fixes?- - What new analysis types could be added?--4. Consider adding:- - New MCP server integrations- - Better metrics tracking- - Learning from completed tasks- - Smarter cooldown logic--5. Implement ONE meaningful enhancement and commit it--Focus on making CoS more autonomous and effective.`,-- '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`,-- 'documentation': `[Self-Improvement] Update Documentation--Review and improve PortOS documentation:--1. Update PLAN.md:- - Mark completed milestones- - Add any new features implemented- - Document architectural decisions--2. Check docs/ folder:- - Are all features documented?- - Is the information current?- - Add any missing guides--3. Review code comments:- - Add JSDoc to exported functions- - Document complex algorithms- - Explain non-obvious code--4. Update README.md if needed:- - Installation instructions- - Quick start guide- - Feature overview--5. Consider adding:- - Architecture diagrams- - API documentation- - Troubleshooting guide--Commit documentation improvements.`,-- 'feature-ideas': `[Self-Improvement] Feature Review and Development--Evaluate existing features and consider new ones to make PortOS more useful:--1. Read data/COS-GOALS.md for context on user goals-2. Review recent completed tasks and user feedback to understand patterns-3. Assess current features:- - Are existing features working well toward our goals?- - Are there features that could be improved or refined?- - Are there features that are underperforming or causing friction?--4. Choose ONE action to take (in order of preference):- a) IMPROVE an existing feature that isn't meeting its potential- - Identify what's not working and why- - Make targeted improvements to increase effectiveness- b) ADD a new high-impact feature- - Something that saves user time, improves the developer experience, or makes CoS more helpful- c) ARCHIVE a feature that is not helping our goals- - This requires a high bar: document clear evidence of why it's not useful- - Check usage patterns, goal alignment, and whether the feature creates noise- - Move the feature config to disabled with a reason, don't delete code--5. Implement it:- - Write clean, tested code- - Follow existing patterns- - Update relevant documentation--6. Commit with a clear description of the change and rationale--Think critically about what we have before adding more.`,-- '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`,-- '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`,-- 'release-check': `[Self-Improvement] Release Check — dev → main--Check if the dev branch has accumulated enough work for a release, and if so, create a PR to main, wait for Copilot code review, iterate on feedback until clean, and merge.--NOTE: The repo has a GitHub ruleset that automatically requests a Copilot code review on every push to a PR targeting main. You do NOT need to manually request reviews — just create/push the PR and wait.--## Step 1: Evaluate Readiness--Read the current changelog and version:-- \`cat .changelog/v*.x.md\` (the one with literal "x", not a resolved version)-- \`node -p "require('./package.json').version"\`--Count substantive entries (lines starting with "###" or "- **" under Features, Fixes, Improvements sections). If fewer than 2 substantive entries exist, stop and report: "Not enough work accumulated for a release." Do NOT create a PR.--## Step 2: Verify Clean State--Run these checks (stop if any fail):-1. \`git fetch origin\` and ensure dev is up to date: \`git status -uno\` should show "Your branch is up to date"-2. \`cd server && npm test\` — all tests must pass-3. \`cd client && npm run build\` — build must succeed--## Step 3: Create or Find PR--Check for existing PR: \`gh pr list --base main --head dev --state open --json number,url\`--If a PR exists, use it. If not, create one:-\`\`\`bash-gh pr create --base main --head dev --title "Release $(node -p \\"require('./package.json').version\\")" --body "$(cat .changelog/v*.x.md | head -60)"-\`\`\`--Capture the PR number and URL.--## Step 4: Wait for Copilot Review--Copilot review is triggered automatically on push. Poll every 15 seconds until the review appears:-\`\`\`bash-gh api repos/atomantic/PortOS/pulls/PR_NUM/reviews --jq '.[] | select(.user.login == "copilot-pull-request-reviewer") | .state'-\`\`\`--Wait until you see APPROVED or CHANGES_REQUESTED. Timeout after 5 minutes of polling.--## Step 5: Address Feedback Loop (max 5 iterations)--### 5a. Fetch unresolved review threads--Use gh api graphql (JSON input to avoid shell escaping issues with GraphQL variables):--\`\`\`bash-echo '{"query":"query{repository(owner:\\"atomantic\\",name:\\"PortOS\\"){pullRequest(number:PR_NUM){reviewThreads(first:100){nodes{id,isResolved,comments(first:10){nodes{body,path,line,author{login}}}}}}}}"}' | gh api graphql --input --\`\`\`--### 5b. If no unresolved threads: skip to Step 6 (Merge).--### 5c. If unresolved threads exist, evaluate each one:--For each comment, read the referenced file and critically evaluate the suggestion:-- **If the suggestion is valid and improves the code**: apply the fix-- **If the suggestion is a false positive, overly pedantic, or would make the code worse**: do NOT change the code--Either way, resolve every thread — the goal is zero unresolved threads before merge.--After evaluating all threads:-- If any code changes were made: run \`cd server && npm test\` to verify, then commit and push:- \`git add <files> && git commit -m "fix: address Copilot review feedback"\`- \`git pull --rebase --autostash && git push\`--### 5d. Resolve ALL threads via GraphQL mutation (both fixed and dismissed):--For each thread, use the thread node id from 5a:-\`\`\`bash-echo '{"query":"mutation{resolveReviewThread(input:{threadId:\\"THREAD_NODE_ID\\"}){thread{isResolved}}}"}' | gh api graphql --input --\`\`\`--### 5e. Wait for new Copilot review if code was pushed (repeat Step 4)--If you pushed changes in 5c, the push automatically triggers a new Copilot review. Poll for it, then loop back to 5a. If no code changes were made (all threads were false positives), skip straight to Step 6.--If after 5 iterations there are still unresolved threads, stop and report what remains.--## Step 6: Merge+// ============================================================+// Unified DEFAULT_TASK_PROMPTS (14 task types)+// All prompts use {appName} and {repoPath} template variables+// ============================================================-Only merge when Copilot's most recent review has NO unresolved threads:-\`\`\`bash-gh pr merge PR_NUM --merge-\`\`\`--If merge fails (e.g., branch protections), try: \`gh pr merge PR_NUM --merge --admin\`--## Step 7: Report--Summarize:-- Version released-- Key changes (from changelog)-- Number of review iterations needed-- Any unresolved issues--IMPORTANT: Always use \`git pull --rebase --autostash\` before pushing (dev branch gets auto-bumped by CI). Never use \`git push\` alone.`-};--// Default interval settings for self-improvement task types-const DEFAULT_SELF_IMPROVEMENT_INTERVALS = {- 'ui-bugs': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },- 'mobile-responsive': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },- 'security': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },- 'code-quality': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },- 'console-errors': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },- 'performance': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },- 'cos-enhancement': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },- 'test-coverage': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },- 'documentation': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },- 'feature-ideas': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null },- 'accessibility': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },- 'dependency-updates': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },- 'release-check': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null }-};--// Default prompts for app improvement task types (templates with {appName} and {repoPath} variables)-const DEFAULT_APP_IMPROVEMENT_PROMPTS = {- 'security-audit': `[App Improvement: {appName}] Security Audit+const DEFAULT_TASK_PROMPTS = {+ 'security': `[Improvement: {appName}] Security AuditAnalyze the {appName} codebase for security vulnerabilities:@@ -526,14 +142,11 @@ Repository: {repoPath}- Sensitive data in localStorage- CSRF protection-4. Check authentication and authorization:- - Secure password handling- - Token management- - Access control+4. Check authentication and authorization where applicableFix any vulnerabilities found and commit with security advisory notes.`,- 'code-quality': `[App Improvement: {appName}] Code Quality Review+ 'code-quality': `[Improvement: {appName}] Code Quality ReviewAnalyze {appName} for maintainability improvements:@@ -549,7 +162,7 @@ Repository: {repoPath}Focus on the main source directories. Refactor issues found and commit improvements.`,- 'test-coverage': `[App Improvement: {appName}] Improve Test Coverage+ 'test-coverage': `[Improvement: {appName}] Improve Test CoverageAnalyze and improve test coverage for {appName}:@@ -571,7 +184,7 @@ Repository: {repoPath}5. Run tests to verify all pass6. Commit test additions with clear message describing coverage`,- 'performance': `[App Improvement: {appName}] Performance Analysis+ 'performance': `[Improvement: {appName}] Performance AnalysisAnalyze {appName} for performance issues:@@ -598,7 +211,7 @@ Repository: {repoPath}Optimize and commit improvements.`,- 'accessibility': `[App Improvement: {appName}] Accessibility Audit+ 'accessibility': `[Improvement: {appName}] Accessibility AuditAudit {appName} for accessibility issues:@@ -618,7 +231,7 @@ If the app has a web UI:4. Add appropriate aria-* attributes5. Test and commit changes`,- 'console-errors': `[App Improvement: {appName}] Console Error Investigation+ 'console-errors': `[Improvement: {appName}] Console Error InvestigationFind and fix console errors in {appName}:@@ -633,7 +246,7 @@ Repository: {repoPath}4. Test fixes and commit changes`,- 'dependency-updates': `[App Improvement: {appName}] Dependency Updates+ 'dependency-updates': `[Improvement: {appName}] Dependency UpdatesCheck {appName} dependencies for updates and security vulnerabilities:@@ -660,7 +273,7 @@ Repository: {repoPath}IMPORTANT: Only update one major version bump at a time.`,- 'documentation': `[App Improvement: {appName}] Update Documentation+ 'documentation': `[Improvement: {appName}] Update DocumentationReview and improve {appName} documentation:@@ -687,7 +300,63 @@ Repository: {repoPath}Commit documentation improvements.`,- 'error-handling': `[App Improvement: {appName}] Improve Error Handling+ 'ui-bugs': `[Improvement: {appName}] UI Bug Analysis++Use Playwright MCP (browser_navigate, browser_snapshot, browser_console_messages) to analyze the app UI:++1. Navigate to the app's UI+2. Check each main route+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 components or API routes+5. Run tests and commit changes`,++ 'mobile-responsive': `[Improvement: {appName}] Mobile Responsiveness Analysis++Use Playwright MCP to test the app at different viewport sizes:++1. browser_resize to mobile (375x812), then navigate to the app UI+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 CSS responsive classes as needed+5. Test fixes and commit changes`,++ 'feature-ideas': `[Improvement: {appName}] Feature Review and Development++Evaluate existing features and consider new ones to make {appName} more useful:++Repository: {repoPath}++1. Read GOALS.md from {repoPath} for context on the app's goals and priorities.+ If no GOALS.md exists, focus on general improvements.+2. Review recent completed tasks and user feedback to understand patterns+3. Assess current features:+ - Are existing features working well toward our goals?+ - Are there features that could be improved or refined?+ - Are there features that are underperforming or causing friction?++4. Choose ONE action to take (in order of preference):+ a) IMPROVE an existing feature that isn't meeting its potential+ b) ADD a new high-impact feature+ c) ARCHIVE a feature that is not helping our goals++5. Implement it:+ - Write clean, tested code+ - Follow existing patterns+ - Update relevant documentation++6. Commit with a clear description of the change and rationale++Think critically about what we have before adding more.`,++ 'error-handling': `[Improvement: {appName}] Improve Error HandlingEnhance error handling in {appName}:@@ -713,7 +382,7 @@ Repository: {repoPath}4. Test error paths and commit improvements`,- 'typing': `[App Improvement: {appName}] TypeScript Type Improvements+ 'typing': `[Improvement: {appName}] TypeScript Type ImprovementsImprove TypeScript types in {appName}:@@ -736,52 +405,145 @@ Repository: {repoPath}- No implicit any- Types are reusable-4. Run type checking and commit improvements`+4. Run type checking and commit improvements`,++ 'release-check': `[Improvement: {appName}] Release Check — dev → main++Check if the dev branch has accumulated enough work for a release, and if so, create a PR to main, wait for Copilot code review, iterate on feedback until clean, and merge.++NOTE: The repo has a GitHub ruleset that automatically requests a Copilot code review on every push to a PR targeting main. You do NOT need to manually request reviews — just create/push the PR and wait.++## Step 1: Evaluate Readiness++Read the current changelog and version:+- \`cat .changelog/v*.x.md\` (the one with literal "x", not a resolved version)+- \`node -p "require('./package.json').version"\`++Count substantive entries (lines starting with "###" or "- **" under Features, Fixes, Improvements sections). If fewer than 2 substantive entries exist, stop and report: "Not enough work accumulated for a release." Do NOT create a PR.++## Step 2: Verify Clean State++Run these checks (stop if any fail):+1. \`git fetch origin\` and ensure dev is up to date: \`git status -uno\` should show "Your branch is up to date"+2. \`cd server && npm test\` — all tests must pass+3. \`cd client && npm run build\` — build must succeed++## Step 3: Create or Find PR++Check for existing PR: \`gh pr list --base main --head dev --state open --json number,url\`++If a PR exists, use it. If not, create one:+\`\`\`bash+gh pr create --base main --head dev --title "Release $(node -p \\"require('./package.json').version\\")" --body "$(cat .changelog/v*.x.md | head -60)"+\`\`\`++Capture the PR number and URL.++## Step 4: Wait for Copilot Review++Copilot review is triggered automatically on push. Poll every 15 seconds until the review appears:+\`\`\`bash+gh api repos/atomantic/PortOS/pulls/PR_NUM/reviews --jq '.[] | select(.user.login == "copilot-pull-request-reviewer") | .state'+\`\`\`++Wait until you see APPROVED or CHANGES_REQUESTED. Timeout after 5 minutes of polling.++## Step 5: Address Feedback Loop (max 5 iterations)++### 5a. Fetch unresolved review threads++Use gh api graphql (JSON input to avoid shell escaping issues with GraphQL variables):++\`\`\`bash+echo '{"query":"query{repository(owner:\\"atomantic\\",name:\\"PortOS\\"){pullRequest(number:PR_NUM){reviewThreads(first:100){nodes{id,isResolved,comments(first:10){nodes{body,path,line,author{login}}}}}}}}"}' | gh api graphql --input -+\`\`\`++### 5b. If no unresolved threads: skip to Step 6 (Merge).++### 5c. If unresolved threads exist, evaluate each one:++For each comment, read the referenced file and critically evaluate the suggestion:+- **If the suggestion is valid and improves the code**: apply the fix+- **If the suggestion is a false positive, overly pedantic, or would make the code worse**: do NOT change the code++Either way, resolve every thread — the goal is zero unresolved threads before merge.++After evaluating all threads:+- If any code changes were made: run \`cd server && npm test\` to verify, then commit and push:+ \`git add <files> && git commit -m "fix: address Copilot review feedback"\`+ \`git pull --rebase --autostash && git push\`++### 5d. Resolve ALL threads via GraphQL mutation (both fixed and dismissed):++For each thread, use the thread node id from 5a:+\`\`\`bash+echo '{"query":"mutation{resolveReviewThread(input:{threadId:\\"THREAD_NODE_ID\\"}){thread{isResolved}}}"}' | gh api graphql --input -+\`\`\`++### 5e. Wait for new Copilot review if code was pushed (repeat Step 4)++If you pushed changes in 5c, the push automatically triggers a new Copilot review. Poll for it, then loop back to 5a. If no code changes were made (all threads were false positives), skip straight to Step 6.++If after 5 iterations there are still unresolved threads, stop and report what remains.++## Step 6: Merge++Only merge when Copilot's most recent review has NO unresolved threads:+\`\`\`bash+gh pr merge PR_NUM --merge+\`\`\`++If merge fails (e.g., branch protections), try: \`gh pr merge PR_NUM --merge --admin\`++## Step 7: Report++Summarize:+- Version released+- Key changes (from changelog)+- Number of review iterations needed+- Any unresolved issues++IMPORTANT: Always use \`git pull --rebase --autostash\` before pushing (dev branch gets auto-bumped by CI). Never use \`git push\` alone.`};-// Default interval settings for managed app improvement task types-const DEFAULT_APP_IMPROVEMENT_INTERVALS = {- 'security-audit': { type: INTERVAL_TYPES.WEEKLY, enabled: true, providerId: null, model: null, prompt: null },- 'code-quality': { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null, prompt: null },- 'test-coverage': { type: INTERVAL_TYPES.WEEKLY, enabled: true, providerId: null, model: null, prompt: null },- 'performance': { type: INTERVAL_TYPES.WEEKLY, enabled: true, providerId: null, model: null, prompt: null },- 'accessibility': { type: INTERVAL_TYPES.ONCE, enabled: true, providerId: null, model: null, prompt: null },- 'console-errors': { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null, prompt: null },- 'dependency-updates': { type: INTERVAL_TYPES.WEEKLY, enabled: true, providerId: null, model: null, prompt: null },- 'documentation': { type: INTERVAL_TYPES.ONCE, enabled: true, providerId: null, model: null, prompt: null },- 'error-handling': { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null, prompt: null },- 'typing': { type: INTERVAL_TYPES.ONCE, enabled: true, providerId: null, model: null, prompt: null }+// Unified default interval settings for all 14 task types+const DEFAULT_TASK_INTERVALS = {+ 'security': { type: INTERVAL_TYPES.WEEKLY, enabled: true, providerId: null, model: null, prompt: null },+ 'code-quality': { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null, prompt: null },+ 'test-coverage': { type: INTERVAL_TYPES.WEEKLY, enabled: true, providerId: null, model: null, prompt: null },+ 'performance': { type: INTERVAL_TYPES.WEEKLY, enabled: true, providerId: null, model: null, prompt: null },+ 'accessibility': { type: INTERVAL_TYPES.ONCE, enabled: true, providerId: null, model: null, prompt: null },+ 'console-errors': { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null, prompt: null },+ 'dependency-updates': { type: INTERVAL_TYPES.WEEKLY, enabled: true, providerId: null, model: null, prompt: null },+ 'documentation': { type: INTERVAL_TYPES.ONCE, enabled: true, providerId: null, model: null, prompt: null },+ 'ui-bugs': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null },+ 'mobile-responsive': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null },+ 'feature-ideas': { type: INTERVAL_TYPES.DAILY, enabled: true, providerId: null, model: null, prompt: null },+ 'error-handling': { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null, prompt: null },+ 'typing': { type: INTERVAL_TYPES.ONCE, enabled: true, providerId: null, model: null, prompt: null },+ 'release-check': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null }};/**- * Default schedule data structure+ * Default schedule data structure (v2 - unified)*/const DEFAULT_SCHEDULE = {- version: 1,+ version: 2,lastUpdated: null,- // Self-improvement task intervals (for PortOS)- selfImprovement: {- ...DEFAULT_SELF_IMPROVEMENT_INTERVALS- },-- // Managed app task intervals- appImprovement: {- ...DEFAULT_APP_IMPROVEMENT_INTERVALS+ // Unified task intervals (applies to all apps including PortOS)+ tasks: {+ ...DEFAULT_TASK_INTERVALS},// Track last execution times- executions: {- // Format: 'self-improve:ui-bugs': { lastRun: timestamp, count: number, perApp: {} }- },+ // Format: 'task:security': { lastRun: timestamp, count: number, perApp: {} }+ executions: {},// On-demand task templates that can be triggered manuallytemplates: []};-/**- * Ensure data directory exists- */async function ensureDir() {if (!existsSync(DATA_DIR)) {await mkdir(DATA_DIR, { recursive: true });@@ -789,7 +551,92 @@ async function ensureDir() {}/**- * Load schedule data+ * Migrate v1 schedule (selfImprovement + appImprovement) to v2 (unified tasks)+ */+function migrateScheduleV1toV2(schedule) {+ emitLog('info', 'Migrating task schedule from v1 to v2 (unified)', {}, '📅 TaskSchedule');++ const migrated = {+ version: 2,+ lastUpdated: new Date().toISOString(),+ tasks: { ...DEFAULT_TASK_INTERVALS },+ executions: {},+ templates: schedule.templates || [],+ onDemandRequests: schedule.onDemandRequests || []+ };++ // Merge selfImprovement settings into tasks (excluding cos-enhancement)+ if (schedule.selfImprovement) {+ for (const [taskType, config] of Object.entries(schedule.selfImprovement)) {+ if (taskType === 'cos-enhancement') continue; // Removed+ // security stays as 'security' (was already named this in selfImprovement)+ if (migrated.tasks[taskType]) {+ migrated.tasks[taskType] = { ...migrated.tasks[taskType], ...config };+ }+ }+ }++ // Merge appImprovement settings into tasks+ if (schedule.appImprovement) {+ for (const [taskType, config] of Object.entries(schedule.appImprovement)) {+ // Rename security-audit → security+ const unifiedType = taskType === 'security-audit' ? 'security' : taskType;+ if (migrated.tasks[unifiedType]) {+ // If selfImprovement already set a non-default config, prefer it for overlapping types+ // unless appImprovement has a different non-default config+ const existing = migrated.tasks[unifiedType];+ const isExistingDefault = existing.type === DEFAULT_TASK_INTERVALS[unifiedType]?.type;+ const isNewDifferent = config.type !== (taskType === 'security-audit'+ ? INTERVAL_TYPES.WEEKLY : DEFAULT_TASK_INTERVALS[unifiedType]?.type);+ if (isExistingDefault || isNewDifferent) {+ migrated.tasks[unifiedType] = { ...existing, ...config };+ }+ }+ }+ }++ // Migrate execution keys: self-improve:X → task:X, app-improve:X → task:X+ if (schedule.executions) {+ for (const [key, data] of Object.entries(schedule.executions)) {+ let newKey = key;+ if (key.startsWith('self-improve:')) {+ const taskType = key.replace('self-improve:', '');+ if (taskType === 'cos-enhancement') continue; // Removed+ newKey = `task:${taskType}`;+ } else if (key.startsWith('app-improve:')) {+ let taskType = key.replace('app-improve:', '');+ if (taskType === 'security-audit') taskType = 'security';+ newKey = `task:${taskType}`;+ }++ if (migrated.executions[newKey]) {+ // Merge: combine counts, keep latest lastRun, merge perApp+ const existing = migrated.executions[newKey];+ existing.count = (existing.count || 0) + (data.count || 0);+ if (data.lastRun && (!existing.lastRun || new Date(data.lastRun) > new Date(existing.lastRun))) {+ existing.lastRun = data.lastRun;+ }+ if (data.perApp) {+ existing.perApp = { ...existing.perApp, ...data.perApp };+ }+ } else {+ migrated.executions[newKey] = { ...data };+ }+ }+ }++ // Populate prompts from defaults if missing+ for (const [taskType, config] of Object.entries(migrated.tasks)) {+ if (!config.prompt && DEFAULT_TASK_PROMPTS[taskType]) {+ config.prompt = DEFAULT_TASK_PROMPTS[taskType];+ }+ }++ return migrated;+}++/**+ * Load schedule data (auto-migrates from v1 if needed)*/export async function loadSchedule() {await ensureDir();@@ -799,17 +646,20 @@ export async function loadSchedule() {return { ...DEFAULT_SCHEDULE };}- // Merge with defaults to ensure all task types have settings+ // Auto-migrate v1 → v2+ if (!loaded.version || loaded.version === 1) {+ const migrated = migrateScheduleV1toV2(loaded);+ await saveSchedule(migrated);+ return migrated;+ }++ // v2: merge with defaults to ensure all task types have settingsconst schedule = {...DEFAULT_SCHEDULE,...loaded,- selfImprovement: {- ...DEFAULT_SELF_IMPROVEMENT_INTERVALS,- ...loaded.selfImprovement- },- appImprovement: {- ...DEFAULT_APP_IMPROVEMENT_INTERVALS,- ...loaded.appImprovement+ tasks: {+ ...DEFAULT_TASK_INTERVALS,+ ...loaded.tasks},executions: loaded.executions || {},templates: loaded.templates || []@@ -817,21 +667,13 @@ export async function loadSchedule() {// Populate prompts from defaults if they don't existlet needsSave = false;- for (const [taskType, config] of Object.entries(schedule.selfImprovement)) {- if (!config.prompt && DEFAULT_SELF_IMPROVEMENT_PROMPTS[taskType]) {- config.prompt = DEFAULT_SELF_IMPROVEMENT_PROMPTS[taskType];- needsSave = true;- }- }-- for (const [taskType, config] of Object.entries(schedule.appImprovement)) {- if (!config.prompt && DEFAULT_APP_IMPROVEMENT_PROMPTS[taskType]) {- config.prompt = DEFAULT_APP_IMPROVEMENT_PROMPTS[taskType];+ for (const [taskType, config] of Object.entries(schedule.tasks)) {+ if (!config.prompt && DEFAULT_TASK_PROMPTS[taskType]) {+ config.prompt = DEFAULT_TASK_PROMPTS[taskType];needsSave = true;}}- // Save if we populated any promptsif (needsSave) {await saveSchedule(schedule);}@@ -839,73 +681,38 @@ export async function loadSchedule() {return schedule;}-/**- * Save schedule data- */async function saveSchedule(schedule) {await ensureDir();schedule.lastUpdated = new Date().toISOString();await writeFile(SCHEDULE_FILE, JSON.stringify(schedule, null, 2));}-/**- * Get interval for a self-improvement task type- */-export async function getSelfImprovementInterval(taskType) {- const schedule = await loadSchedule();- return schedule.selfImprovement[taskType] || { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null };-}--/**- * Get interval for an app improvement task type- */-export async function getAppImprovementInterval(taskType) {- const schedule = await loadSchedule();- return schedule.appImprovement[taskType] || { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null };-}+// ============================================================+// Unified getters/setters (replace split self/app functions)+// ============================================================-/**- * Update self-improvement interval for a task type- */-export async function updateSelfImprovementInterval(taskType, settings) {+export async function getTaskInterval(taskType) {const schedule = await loadSchedule();-- if (!schedule.selfImprovement[taskType]) {- schedule.selfImprovement[taskType] = { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null };- }-- schedule.selfImprovement[taskType] = {- ...schedule.selfImprovement[taskType],- ...settings- };-- await saveSchedule(schedule);- emitLog('info', `Updated self-improvement interval for ${taskType}`, { taskType, settings }, '📅 TaskSchedule');- cosEvents.emit('schedule:changed', { category: 'selfImprovement', taskType, settings });-- return schedule.selfImprovement[taskType];+ return schedule.tasks[taskType] || { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null };}-/**- * Update app improvement interval for a task type- */-export async function updateAppImprovementInterval(taskType, settings) {+export async function updateTaskInterval(taskType, settings) {const schedule = await loadSchedule();- if (!schedule.appImprovement[taskType]) {- schedule.appImprovement[taskType] = { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null };+ if (!schedule.tasks[taskType]) {+ schedule.tasks[taskType] = { type: INTERVAL_TYPES.ROTATION, enabled: true, providerId: null, model: null };}- schedule.appImprovement[taskType] = {- ...schedule.appImprovement[taskType],+ schedule.tasks[taskType] = {+ ...schedule.tasks[taskType],...settings};await saveSchedule(schedule);- emitLog('info', `Updated app improvement interval for ${taskType}`, { taskType, settings }, '📅 TaskSchedule');- cosEvents.emit('schedule:changed', { category: 'appImprovement', taskType, settings });+ emitLog('info', `Updated task interval for ${taskType}`, { taskType, settings }, '📅 TaskSchedule');+ cosEvents.emit('schedule:changed', { taskType, settings });- return schedule.appImprovement[taskType];+ return schedule.tasks[taskType];}/**@@ -913,7 +720,7 @@ export async function updateAppImprovementInterval(taskType, settings) {*/export async function recordExecution(taskType, appId = null) {const schedule = await loadSchedule();- const key = taskType;+ const key = taskType.startsWith('task:') ? taskType : `task:${taskType}`;if (!schedule.executions[key]) {schedule.executions[key] = {@@ -941,138 +748,24 @@ export async function recordExecution(taskType, appId = null) {return schedule.executions[key];}-/**- * Get execution history for a task type- */export async function getExecutionHistory(taskType) {const schedule = await loadSchedule();- return schedule.executions[taskType] || { lastRun: null, count: 0, perApp: {} };+ const key = taskType.startsWith('task:') ? taskType : `task:${taskType}`;+ return schedule.executions[key] || { lastRun: null, count: 0, perApp: {} };}/**- * Check if a self-improvement task type should run based on its interval- *- * Enhanced with learning-based interval adjustment:- * - High-performing tasks (>90% success) run more frequently- * - Low-performing tasks (<50% success) run less frequently- * - Very low performers (<30% with 5+ attempts) are significantly delayed- *- * The adjustment applies to daily, weekly, and custom intervals.- * Rotation tasks are not adjusted (they run in sequence regardless).+ * Check if a task type should run for a specific app (or globally)*/-export async function shouldRunSelfImprovementTask(taskType) {+export async function shouldRunTask(taskType, appId = null) {const schedule = await loadSchedule();- const interval = schedule.selfImprovement[taskType];+ const interval = schedule.tasks[taskType];if (!interval || !interval.enabled) {return { shouldRun: false, reason: 'disabled' };}- const execution = schedule.executions[`self-improve:${taskType}`] || { lastRun: null, count: 0 };- const now = Date.now();- const lastRun = execution.lastRun ? new Date(execution.lastRun).getTime() : 0;- const timeSinceLastRun = now - lastRun;-- // Helper to build result with learning info- const buildResult = (shouldRun, reason, baseIntervalMs, extra = {}) => {- const result = { shouldRun, reason, ...extra };-- // Add learning adjustment info if we adjusted the interval- if (extra.learningAdjustment && extra.learningAdjustment.adjusted) {- result.learningApplied = true;- result.successRate = extra.learningAdjustment.successRate;- result.adjustmentMultiplier = extra.learningAdjustment.multiplier;- result.dataPoints = extra.learningAdjustment.dataPoints;- }-- return result;- };-- switch (interval.type) {- case INTERVAL_TYPES.ROTATION:- // Rotation tasks always eligible (learning adjustment happens in getNextSelfImprovementTaskType)- return { shouldRun: true, reason: 'rotation' };-- case INTERVAL_TYPES.DAILY: {- // Apply learning-based interval adjustment- const learningAdjustment = await getPerformanceAdjustedInterval(taskType, 'selfImprovement', DAY);- const adjustedInterval = learningAdjustment.adjustedIntervalMs;-- if (timeSinceLastRun >= adjustedInterval) {- return buildResult(true, learningAdjustment.adjusted ? 'daily-due-adjusted' : 'daily-due', DAY, { learningAdjustment });- }- return buildResult(false, learningAdjustment.adjusted ? 'daily-cooldown-adjusted' : 'daily-cooldown', DAY, {- learningAdjustment,- nextRunIn: adjustedInterval - timeSinceLastRun,- nextRunAt: new Date(lastRun + adjustedInterval).toISOString(),- baseIntervalMs: DAY,- adjustedIntervalMs: adjustedInterval- });- }-- case INTERVAL_TYPES.WEEKLY: {- // Apply learning-based interval adjustment- const learningAdjustment = await getPerformanceAdjustedInterval(taskType, 'selfImprovement', WEEK);- const adjustedInterval = learningAdjustment.adjustedIntervalMs;-- if (timeSinceLastRun >= adjustedInterval) {- return buildResult(true, learningAdjustment.adjusted ? 'weekly-due-adjusted' : 'weekly-due', WEEK, { learningAdjustment });- }- return buildResult(false, learningAdjustment.adjusted ? 'weekly-cooldown-adjusted' : 'weekly-cooldown', WEEK, {- learningAdjustment,- nextRunIn: adjustedInterval - timeSinceLastRun,- nextRunAt: new Date(lastRun + adjustedInterval).toISOString(),- baseIntervalMs: WEEK,- adjustedIntervalMs: adjustedInterval- });- }-- case INTERVAL_TYPES.ONCE:- if (execution.count === 0) {- return { shouldRun: true, reason: 'once-first-run' };- }- return { shouldRun: false, reason: 'once-completed', completedAt: execution.lastRun };-- case INTERVAL_TYPES.ON_DEMAND:- return { shouldRun: false, reason: 'on-demand-only' };-- case INTERVAL_TYPES.CUSTOM: {- const baseInterval = interval.intervalMs || DAY;- // Apply learning-based interval adjustment- const learningAdjustment = await getPerformanceAdjustedInterval(taskType, 'selfImprovement', baseInterval);- const adjustedInterval = learningAdjustment.adjustedIntervalMs;-- if (timeSinceLastRun >= adjustedInterval) {- return buildResult(true, learningAdjustment.adjusted ? 'custom-due-adjusted' : 'custom-due', baseInterval, { learningAdjustment });- }- return buildResult(false, learningAdjustment.adjusted ? 'custom-cooldown-adjusted' : 'custom-cooldown', baseInterval, {- learningAdjustment,- nextRunIn: adjustedInterval - timeSinceLastRun,- nextRunAt: new Date(lastRun + adjustedInterval).toISOString(),- baseIntervalMs: baseInterval,- adjustedIntervalMs: adjustedInterval- });- }-- default:- return { shouldRun: true, reason: 'unknown-default-rotation' };- }-}--/**- * Check if an app improvement task type should run for a specific app- *- * Enhanced with learning-based interval adjustment (same as self-improvement).- */-export async function shouldRunAppImprovementTask(taskType, appId) {- const schedule = await loadSchedule();- const globalInterval = schedule.appImprovement[taskType];-- if (!globalInterval || !globalInterval.enabled) {- return { shouldRun: false, reason: 'disabled' };- }-- // Check per-app task type override+ // Check per-app overrideif (appId) {const enabledForApp = await isTaskTypeEnabledForApp(appId, taskType);if (!enabledForApp) {@@ -1080,21 +773,25 @@ export async function shouldRunAppImprovementTask(taskType, appId) {}}- // Determine effective interval type: per-app override takes precedence over global+ // Determine effective interval type: per-app override takes precedenceconst perAppInterval = appId ? await getAppTaskTypeInterval(appId, taskType) : null;- const effectiveType = perAppInterval || globalInterval.type;+ const effectiveType = perAppInterval || interval.type;- const key = `app-improve:${taskType}`;+ const key = `task:${taskType}`;const execution = schedule.executions[key] || { lastRun: null, count: 0, perApp: {} };- const appExecution = execution.perApp[appId] || { lastRun: null, count: 0 };++ // For per-app tracking, use app-specific execution data+ const appExecution = appId+ ? (execution.perApp[appId] || { lastRun: null, count: 0 })+ : execution;+const now = Date.now();const lastRun = appExecution.lastRun ? new Date(appExecution.lastRun).getTime() : 0;const timeSinceLastRun = now - lastRun;- // Helper to build result with learning infoconst buildResult = (shouldRun, reason, baseIntervalMs, extra = {}) => {const result = { shouldRun, reason, ...extra };- if (extra.learningAdjustment && extra.learningAdjustment.adjusted) {+ if (extra.learningAdjustment?.adjusted) {result.learningApplied = true;result.successRate = extra.learningAdjustment.successRate;result.adjustmentMultiplier = extra.learningAdjustment.multiplier;@@ -1108,7 +805,7 @@ export async function shouldRunAppImprovementTask(taskType, appId) {return { shouldRun: true, reason: 'rotation' };case INTERVAL_TYPES.DAILY: {- const learningAdjustment = await getPerformanceAdjustedInterval(taskType, 'appImprovement', DAY);+ const learningAdjustment = await getPerformanceAdjustedInterval(taskType, DAY);const adjustedInterval = learningAdjustment.adjustedIntervalMs;if (timeSinceLastRun >= adjustedInterval) {@@ -1124,7 +821,7 @@ export async function shouldRunAppImprovementTask(taskType, appId) {}case INTERVAL_TYPES.WEEKLY: {- const learningAdjustment = await getPerformanceAdjustedInterval(taskType, 'appImprovement', WEEK);+ const learningAdjustment = await getPerformanceAdjustedInterval(taskType, WEEK);const adjustedInterval = learningAdjustment.adjustedIntervalMs;if (timeSinceLastRun >= adjustedInterval) {@@ -1149,8 +846,8 @@ export async function shouldRunAppImprovementTask(taskType, appId) {return { shouldRun: false, reason: 'on-demand-only' };case INTERVAL_TYPES.CUSTOM: {- const baseInterval = globalInterval.intervalMs || DAY;- const learningAdjustment = await getPerformanceAdjustedInterval(taskType, 'appImprovement', baseInterval);+ const baseInterval = interval.intervalMs || DAY;+ const learningAdjustment = await getPerformanceAdjustedInterval(taskType, baseInterval);const adjustedInterval = learningAdjustment.adjustedIntervalMs;if (timeSinceLastRun >= adjustedInterval) {@@ -1171,35 +868,16 @@ export async function shouldRunAppImprovementTask(taskType, appId) {}/**- * Get all enabled self-improvement task types that are due to run- */-export async function getDueSelfImprovementTasks() {- const schedule = await loadSchedule();- const due = [];-- for (const [taskType, interval] of Object.entries(schedule.selfImprovement)) {- if (!interval.enabled) continue;-- const check = await shouldRunSelfImprovementTask(taskType);- if (check.shouldRun) {- due.push({ taskType, reason: check.reason, interval });- }- }-- return due;-}--/**- * Get all enabled app improvement task types that are due to run for a specific app+ * Get all enabled task types that are due to run (optionally for a specific app)*/-export async function getDueAppImprovementTasks(appId) {+export async function getDueTasks(appId = null) {const schedule = await loadSchedule();const due = [];- for (const [taskType, interval] of Object.entries(schedule.appImprovement)) {+ for (const [taskType, interval] of Object.entries(schedule.tasks)) {if (!interval.enabled) continue;- const check = await shouldRunAppImprovementTask(taskType, appId);+ const check = await shouldRunTask(taskType, appId);if (check.shouldRun) {due.push({ taskType, reason: check.reason, interval });}@@ -1209,55 +887,15 @@ export async function getDueAppImprovementTasks(appId) {}/**- * Get the next task type to run based on schedule priority- * Prioritizes: daily tasks due > weekly tasks due > rotation tasks- */-export async function getNextSelfImprovementTaskType(lastType) {- const schedule = await loadSchedule();- const taskTypes = Object.keys(schedule.selfImprovement);-- // First, check for daily/weekly tasks that are due- const dueTasks = await getDueSelfImprovementTasks();-- // Prioritize daily tasks first, then weekly- const dailyDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.DAILY);- if (dailyDue.length > 0) {- return { taskType: dailyDue[0].taskType, reason: 'daily-priority' };- }-- const weeklyDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.WEEKLY);- if (weeklyDue.length > 0) {- return { taskType: weeklyDue[0].taskType, reason: 'weekly-priority' };- }-- // Fall back to rotation among enabled rotation tasks- const rotationTasks = taskTypes.filter(t =>- schedule.selfImprovement[t].enabled &&- schedule.selfImprovement[t].type === INTERVAL_TYPES.ROTATION- );-- if (rotationTasks.length === 0) {- return null;- }-- // Get next in rotation- const currentIndex = rotationTasks.indexOf(lastType);- const nextIndex = (currentIndex + 1) % rotationTasks.length;-- return { taskType: rotationTasks[nextIndex], reason: 'rotation' };-}--/**- * Get the next app improvement task type to run for a specific app+ * Get the next task type to run (optionally for a specific app)*/-export async function getNextAppImprovementTaskType(appId, lastType) {+export async function getNextTaskType(appId = null, lastType = '') {const schedule = await loadSchedule();- const taskTypes = Object.keys(schedule.appImprovement);+ const taskTypes = Object.keys(schedule.tasks);- // First, check for daily/weekly tasks that are due- const dueTasks = await getDueAppImprovementTasks(appId);+ // First, check for daily/weekly/once tasks that are due+ const dueTasks = await getDueTasks(appId);- // Prioritize daily tasks first, then weekly, then onceconst dailyDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.DAILY);if (dailyDue.length > 0) {return { taskType: dailyDue[0].taskType, reason: 'daily-priority' };@@ -1273,10 +911,10 @@ export async function getNextAppImprovementTaskType(appId, lastType) {return { taskType: onceDue[0].taskType, reason: 'once-first-run' };}- // Fall back to rotation+ // Fall back to rotation among enabled rotation tasksconst rotationTasks = taskTypes.filter(t =>- schedule.appImprovement[t].enabled &&- schedule.appImprovement[t].type === INTERVAL_TYPES.ROTATION+ schedule.tasks[t].enabled &&+ schedule.tasks[t].type === INTERVAL_TYPES.ROTATION);if (rotationTasks.length === 0) {@@ -1289,9 +927,10 @@ export async function getNextAppImprovementTaskType(appId, lastType) {return { taskType: rotationTasks[nextIndex], reason: 'rotation' };}-/**- * Add a template task that can be triggered on-demand- */+// ============================================================+// Templates+// ============================================================+export async function addTemplateTask(template) {const schedule = await loadSchedule();@@ -1300,7 +939,7 @@ export async function addTemplateTask(template) {createdAt: new Date().toISOString(),name: template.name,description: template.description,- category: template.category || 'custom', // 'selfImprovement', 'appImprovement', 'custom'+ category: template.category || 'custom',taskType: template.taskType,priority: template.priority || 'MEDIUM',metadata: template.metadata || {}@@ -1313,17 +952,11 @@ export async function addTemplateTask(template) {return newTemplate;}-/**- * Get all template tasks- */export async function getTemplateTasks() {const schedule = await loadSchedule();return schedule.templates;}-/**- * Delete a template task- */export async function deleteTemplateTask(templateId) {const schedule = await loadSchedule();const index = schedule.templates.findIndex(t => t.id === templateId);@@ -1339,13 +972,11 @@ export async function deleteTemplateTask(templateId) {return { success: true, deleted };}-/**- * Trigger an on-demand task by task type- * Creates an immediate task entry for the specified type- */-export async function triggerOnDemandTask(taskType, category = 'selfImprovement', appId = null) {- // This marks the task as requested for immediate execution- // The task generation will pick it up on the next evaluation+// ============================================================+// On-Demand Requests+// ============================================================++export async function triggerOnDemandTask(taskType, appId = null) {const schedule = await loadSchedule();if (!schedule.onDemandRequests) {@@ -1355,7 +986,6 @@ export async function triggerOnDemandTask(taskType, category = 'selfImprovement'const request = {id: `demand-${Date.now().toString(36)}`,taskType,- category,appId,requestedAt: new Date().toISOString()};@@ -1363,23 +993,17 @@ export async function triggerOnDemandTask(taskType, category = 'selfImprovement'schedule.onDemandRequests.push(request);await saveSchedule(schedule);- emitLog('info', `On-demand task requested: ${taskType}`, { category, appId }, '📅 TaskSchedule');+ emitLog('info', `On-demand task requested: ${taskType}`, { appId }, '📅 TaskSchedule');cosEvents.emit('task:on-demand-requested', request);return request;}-/**- * Get pending on-demand task requests- */export async function getOnDemandRequests() {const schedule = await loadSchedule();return schedule.onDemandRequests || [];}-/**- * Clear an on-demand request (after it's been processed)- */export async function clearOnDemandRequest(requestId) {const schedule = await loadSchedule();@@ -1394,64 +1018,35 @@ export async function clearOnDemandRequest(requestId) {return cleared;}-/**- * Get full schedule status for UI display- *- * Enhanced to include learning-based interval adjustments.- */+// ============================================================+// Schedule Status+// ============================================================+export async function getScheduleStatus() {const schedule = await loadSchedule();const status = {lastUpdated: schedule.lastUpdated,- selfImprovement: {},- appImprovement: {},+ tasks: {},templates: schedule.templates,onDemandRequests: schedule.onDemandRequests || [],- learningAdjustmentsActive: 0 // Count of task types with active learning adjustments+ learningAdjustmentsActive: 0};- // Add execution status to each self-improvement task type- for (const [taskType, interval] of Object.entries(schedule.selfImprovement)) {- const check = await shouldRunSelfImprovementTask(taskType);- const execution = schedule.executions[`self-improve:${taskType}`] || { lastRun: null, count: 0 };-- // Get learning adjustment info- const baseInterval = interval.type === 'daily' ? DAY : interval.type === 'weekly' ? WEEK : (interval.intervalMs || DAY);- const learningInfo = await getPerformanceAdjustedInterval(taskType, 'selfImprovement', baseInterval);-- status.selfImprovement[taskType] = {- ...interval,- lastRun: execution.lastRun,- runCount: execution.count,- status: check,- // Learning adjustment fields- learningAdjusted: learningInfo.adjusted,- learningMultiplier: learningInfo.multiplier,- successRate: learningInfo.successRate,- dataPoints: learningInfo.dataPoints,- adjustedIntervalMs: learningInfo.adjustedIntervalMs,- recommendation: learningInfo.recommendation- };-- if (learningInfo.adjusted) {- status.learningAdjustmentsActive++;- }- }-- // Add execution status to each app improvement task type// Fetch active apps once for per-app override aggregationconst activeApps = await getActiveApps().catch(() => []);const totalAppCount = activeApps.length;- for (const [taskType, interval] of Object.entries(schedule.appImprovement)) {- const execution = schedule.executions[`app-improve:${taskType}`] || { lastRun: null, count: 0, perApp: {} };+ for (const [taskType, interval] of Object.entries(schedule.tasks)) {+ const execution = schedule.executions[`task:${taskType}`] || { lastRun: null, count: 0, perApp: {} };// Get learning adjustment infoconst baseInterval = interval.type === 'daily' ? DAY : interval.type === 'weekly' ? WEEK : (interval.intervalMs || DAY);- const learningInfo = await getPerformanceAdjustedInterval(taskType, 'appImprovement', baseInterval);+ const learningInfo = await getPerformanceAdjustedInterval(taskType, baseInterval);++ // Check global shouldRun status+ const check = await shouldRunTask(taskType);// Build per-app overrides map and count enabled apps- // Preload all overrides in parallel to avoid sequential awaitsconst appOverrides = {};let enabledAppCount = 0;const allOverrides = await Promise.all(activeApps.map(app => getAppTaskTypeOverrides(app.id)));@@ -1463,21 +1058,22 @@ export async function getScheduleStatus() {interval: override.interval || null};}- // App is enabled if no override or override.enabled !== falseif (!override || override.enabled !== false) {enabledAppCount++;}}- status.appImprovement[taskType] = {+ status.tasks[taskType] = {...interval,+ lastRun: execution.lastRun,+ runCount: execution.count,globalLastRun: execution.lastRun,globalRunCount: execution.count,perAppCount: Object.keys(execution.perApp).length,appOverrides,enabledAppCount,totalAppCount,- // Learning adjustment fields+ status: check,learningAdjusted: learningInfo.adjusted,learningMultiplier: learningInfo.multiplier,successRate: learningInfo.successRate,@@ -1495,60 +1091,41 @@ export async function getScheduleStatus() {}/**- * Reset execution history for a task type (useful for re-running 'once' tasks)+ * Reset execution history for a task type*/-export async function resetExecutionHistory(taskType, category = 'selfImprovement', appId = null) {+export async function resetExecutionHistory(taskType, appId = null) {const schedule = await loadSchedule();- const key = category === 'selfImprovement' ? `self-improve:${taskType}` : `app-improve:${taskType}`;+ const key = `task:${taskType}`;if (!schedule.executions[key]) {return { error: 'No execution history found' };}if (appId) {- // Reset only for specific app- if (schedule.executions[key].perApp && schedule.executions[key].perApp[appId]) {+ if (schedule.executions[key].perApp?.[appId]) {delete schedule.executions[key].perApp[appId];}} else {- // Reset entire history for this task typedelete schedule.executions[key];}await saveSchedule(schedule);- emitLog('info', `Reset execution history for ${taskType}`, { category, appId }, '📅 TaskSchedule');+ emitLog('info', `Reset execution history for ${taskType}`, { appId }, '📅 TaskSchedule');return { success: true, taskType, appId };}-/**- * Get default prompt for a self-improvement task type- */-export function getDefaultSelfImprovementPrompt(taskType) {- return DEFAULT_SELF_IMPROVEMENT_PROMPTS[taskType] || null;-}--/**- * Get default prompt for an app improvement task type (with template variables)- */-export function getDefaultAppImprovementPrompt(taskType) {- return DEFAULT_APP_IMPROVEMENT_PROMPTS[taskType] || null;-}+// ============================================================+// Prompt getters+// ============================================================-/**- * Get the prompt for a self-improvement task type- */-export async function getSelfImprovementPrompt(taskType) {- const interval = await getSelfImprovementInterval(taskType);- return interval.prompt || `[Self-Improvement] ${taskType} analysis`;+export function getDefaultPrompt(taskType) {+ return DEFAULT_TASK_PROMPTS[taskType] || null;}-/**- * Get the prompt for an app improvement task type- */-export async function getAppImprovementPrompt(taskType) {- const interval = await getAppImprovementInterval(taskType);- return interval.prompt || `[App Improvement] ${taskType} analysis+export async function getTaskPrompt(taskType) {+ const interval = await getTaskInterval(taskType);+ return interval.prompt || DEFAULT_TASK_PROMPTS[taskType] || `[Improvement] ${taskType} analysisRepository: {repoPath}@@ -1556,48 +1133,42 @@ Perform ${taskType} analysis on {appName}.Analyze the codebase and make improvements. Commit changes with clear descriptions.`;}-/**- * Get upcoming tasks preview - what tasks will run next- * Returns a list of tasks sorted by when they'll be eligible to run- * @param {number} limit - Maximum number of upcoming tasks to return- * @returns {Array} Upcoming tasks with timing info- */+// ============================================================+// Upcoming Tasks Preview+// ============================================================+export async function getUpcomingTasks(limit = 10) {const schedule = await loadSchedule();const now = Date.now();const upcoming = [];- // Process self-improvement tasks- for (const [taskType, interval] of Object.entries(schedule.selfImprovement)) {+ for (const [taskType, interval] of Object.entries(schedule.tasks)) {if (!interval.enabled) continue;if (interval.type === INTERVAL_TYPES.ON_DEMAND) continue;- const check = await shouldRunSelfImprovementTask(taskType);- const execution = schedule.executions[`self-improve:${taskType}`] || { lastRun: null, count: 0 };- const lastRun = execution.lastRun ? new Date(execution.lastRun).getTime() : 0;+ const check = await shouldRunTask(taskType);+ const execution = schedule.executions[`task:${taskType}`] || { lastRun: null, count: 0 };- // Calculate when task becomes eligiblelet eligibleAt = now;- let status = 'ready';+ let taskStatus = 'ready';if (check.shouldRun) {eligibleAt = now;- status = 'ready';+ taskStatus = 'ready';} else if (check.nextRunAt) {eligibleAt = new Date(check.nextRunAt).getTime();- status = 'scheduled';+ taskStatus = 'scheduled';} else if (interval.type === INTERVAL_TYPES.ONCE && execution.count > 0) {- status = 'completed';+ taskStatus = 'completed';eligibleAt = Infinity;}- if (status === 'completed') continue;+ if (taskStatus === 'completed') continue;upcoming.push({taskType,- category: 'selfImprovement',intervalType: interval.type,- status,+ status: taskStatus,eligibleAt,eligibleIn: eligibleAt - now,eligibleInFormatted: formatTimeRemaining(eligibleAt - now),@@ -1611,7 +1182,6 @@ export async function getUpcomingTasks(limit = 10) {});}- // Sort by eligibility time (ready tasks first, then by time until eligible)upcoming.sort((a, b) => {if (a.status === 'ready' && b.status !== 'ready') return -1;if (b.status === 'ready' && a.status !== 'ready') return 1;@@ -1621,42 +1191,29 @@ export async function getUpcomingTasks(limit = 10) {return upcoming.slice(0, limit);}-/**- * Format time remaining in human-readable form- */function formatTimeRemaining(ms) {if (ms <= 0) return 'now';-const minutes = Math.floor(ms / 60000);const hours = Math.floor(minutes / 60);const days = Math.floor(hours / 24);-if (days > 0) return `${days}d ${hours % 24}h`;if (hours > 0) return `${hours}h ${minutes % 60}m`;if (minutes > 0) return `${minutes}m`;return '< 1m';}-/**- * Format relative time (e.g., "2h ago")- */function formatRelativeTime(timestamp) {const now = Date.now();const diff = now - timestamp;-const minutes = Math.floor(diff / 60000);const hours = Math.floor(minutes / 60);const days = Math.floor(hours / 24);-if (days > 0) return `${days}d ago`;if (hours > 0) return `${hours}h ago`;if (minutes > 0) return `${minutes}m ago`;return 'just now';}-/**- * Get human-readable description for task type- */function getTaskTypeDescription(taskType) {const descriptions = {'ui-bugs': 'Find and fix UI bugs',@@ -1665,13 +1222,74 @@ function getTaskTypeDescription(taskType) {'code-quality': 'Code quality improvements','console-errors': 'Fix console errors','performance': 'Performance optimization',- 'cos-enhancement': 'Enhance CoS capabilities','test-coverage': 'Improve test coverage','documentation': 'Update documentation','feature-ideas': 'Brainstorm and implement features','accessibility': 'Accessibility audit','dependency-updates': 'Update dependencies',- 'release-check': 'Check dev for release readiness'+ 'release-check': 'Check dev for release readiness',+ 'error-handling': 'Improve error handling',+ 'typing': 'Improve TypeScript types'};return descriptions[taskType] || taskType.replace(/-/g, ' ');}++// ============================================================+// Backward-compatible exports (delegate to unified functions)+// ============================================================++export async function getSelfImprovementInterval(taskType) {+ return getTaskInterval(taskType);+}++export async function getAppImprovementInterval(taskType) {+ return getTaskInterval(taskType);+}++export async function updateSelfImprovementInterval(taskType, settings) {+ return updateTaskInterval(taskType, settings);+}++export async function updateAppImprovementInterval(taskType, settings) {+ return updateTaskInterval(taskType, settings);+}++export async function shouldRunSelfImprovementTask(taskType) {+ return shouldRunTask(taskType);+}++export async function shouldRunAppImprovementTask(taskType, appId) {+ return shouldRunTask(taskType, appId);+}++export async function getDueSelfImprovementTasks() {+ return getDueTasks();+}++export async function getDueAppImprovementTasks(appId) {+ return getDueTasks(appId);+}++export async function getNextSelfImprovementTaskType(lastType) {+ return getNextTaskType(null, lastType);+}++export async function getNextAppImprovementTaskType(appId, lastType) {+ return getNextTaskType(appId, lastType);+}++export function getDefaultSelfImprovementPrompt(taskType) {+ return getDefaultPrompt(taskType);+}++export function getDefaultAppImprovementPrompt(taskType) {+ return getDefaultPrompt(taskType);+}++export async function getSelfImprovementPrompt(taskType) {+ return getTaskPrompt(taskType);+}++export async function getAppImprovementPrompt(taskType) {+ return getTaskPrompt(taskType);+}