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: add configurable task intervals for self-improvement tasks
Adam Eivydee3f6792054
diff --git a/PLAN.md b/PLAN.mdindex 007a145fb6..bc204ed11f 100644--- a/PLAN.md+++ b/PLAN.md@@ -55,6 +55,7 @@ pm2 logs- [x] M26: Scheduled Scripts (cron scheduling, agent triggers, command allowlist, run history)- [x] M28: Weekly Digest UI (visual digest tab with insights, accomplishments, week-over-week comparisons)- [x] M29: Comprehensive App Improvement (self-improvement operations extended to managed apps, 10 analysis types, rotation system)+- [x] M30: Configurable Task Intervals (per-task-type scheduling: daily, weekly, once, on-demand; schedule UI tab; execution history tracking)### Documentation- [Architecture Overview](./docs/ARCHITECTURE.md) - System design, data flowdiff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex f43556ace5..94d3c50378 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -5,13 +5,15 @@ import {Brain,Activity,Settings,- Calendar+ Calendar,+ Clock} from 'lucide-react';export const TABS = [{ id: 'tasks', label: 'Tasks', icon: FileText },{ id: 'agents', label: 'Agents', icon: Cpu },{ id: 'scripts', label: 'Scripts', icon: Terminal },+ { id: 'schedule', label: 'Schedule', icon: Clock },{ id: 'digest', label: 'Digest', icon: Calendar },{ id: 'memory', label: 'Memory', icon: Brain },{ id: 'health', label: 'Health', icon: Activity },diff --git a/client/src/components/cos/index.js b/client/src/components/cos/index.jsindex b24edb0a80..6abd54137e 100644--- a/client/src/components/cos/index.js+++ b/client/src/components/cos/index.js@@ -19,6 +19,7 @@ export { default as EventLog } from './EventLog';export { default as TasksTab } from './tabs/TasksTab';export { default as AgentsTab } from './tabs/AgentsTab';export { default as ScriptsTab } from './tabs/ScriptsTab';+export { default as ScheduleTab } from './tabs/ScheduleTab';export { default as MemoryTab } from './tabs/MemoryTab';export { default as HealthTab } from './tabs/HealthTab';export { default as ConfigTab } from './tabs/ConfigTab';diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsxnew file mode 100644index 0000000000..b6729284fa--- /dev/null+++ b/client/src/components/cos/tabs/ScheduleTab.jsx@@ -0,0 +1,402 @@+import { useState, useEffect, useCallback } from 'react';+import { Clock, Play, RotateCcw, ChevronDown, ChevronRight, CheckCircle, XCircle, AlertCircle, RefreshCw } from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';++const INTERVAL_LABELS = {+ rotation: 'Rotation',+ daily: 'Daily',+ weekly: 'Weekly',+ once: 'Once',+ 'on-demand': 'On Demand',+ custom: 'Custom'+};++const INTERVAL_DESCRIPTIONS = {+ rotation: 'Runs as part of normal task rotation',+ daily: 'Runs once per day',+ weekly: 'Runs once per week',+ once: 'Runs once then stops',+ 'on-demand': 'Only runs when manually triggered',+ custom: 'Custom interval'+};++function formatTimeRemaining(ms) {+ if (!ms || ms <= 0) return 'now';+ const hours = Math.floor(ms / (60 * 60 * 1000));+ const minutes = Math.floor((ms % (60 * 60 * 1000)) / (60 * 1000));+ if (hours > 24) {+ const days = Math.floor(hours / 24);+ return `${days}d ${hours % 24}h`;+ }+ if (hours > 0) return `${hours}h ${minutes}m`;+ return `${minutes}m`;+}++function TaskTypeRow({ taskType, config, onUpdate, onTrigger, onReset, category }) {+ const [expanded, setExpanded] = useState(false);+ const [updating, setUpdating] = useState(false);+ const [selectedType, setSelectedType] = useState(config.type);++ const handleTypeChange = async (newType) => {+ setUpdating(true);+ setSelectedType(newType);+ await onUpdate(taskType, { type: newType }).catch(() => {+ setSelectedType(config.type);+ });+ setUpdating(false);+ };++ const handleToggleEnabled = async () => {+ setUpdating(true);+ await onUpdate(taskType, { enabled: !config.enabled });+ setUpdating(false);+ };++ const status = config.status || {};+ const isEligible = status.shouldRun;+ const nextRunText = status.nextRunAt+ ? formatTimeRemaining(new Date(status.nextRunAt).getTime() - Date.now())+ : null;++ return (+ <div className="border border-port-border rounded-lg overflow-hidden">+ <div+ className="flex items-center gap-3 p-3 bg-port-card hover:bg-port-card/80 cursor-pointer"+ onClick={() => setExpanded(!expanded)}+ >+ <button+ className="text-gray-500 hover:text-white"+ onClick={(e) => { e.stopPropagation(); setExpanded(!expanded); }}+ aria-label={expanded ? 'Collapse' : 'Expand'}+ >+ {expanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ </button>++ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="font-mono text-sm text-white">{taskType}</span>+ {!config.enabled && (+ <span className="text-xs px-2 py-0.5 bg-gray-600/50 text-gray-400 rounded">Disabled</span>+ )}+ </div>+ {config.lastRun && (+ <div className="text-xs text-gray-500">+ Last run: {new Date(config.lastRun).toLocaleDateString()} ({config.runCount || 0} total)+ </div>+ )}+ </div>++ <div className="flex items-center gap-2">+ {isEligible ? (+ <span className="flex items-center gap-1 text-xs text-port-success">+ <CheckCircle size={12} />+ Ready+ </span>+ ) : status.reason === 'disabled' ? (+ <span className="flex items-center gap-1 text-xs text-gray-500">+ <XCircle size={12} />+ Disabled+ </span>+ ) : status.reason === 'on-demand-only' ? (+ <span className="flex items-center gap-1 text-xs text-port-accent">+ <Clock size={12} />+ On Demand+ </span>+ ) : status.reason === 'once-completed' ? (+ <span className="flex items-center gap-1 text-xs text-port-warning">+ <CheckCircle size={12} />+ Completed+ </span>+ ) : nextRunText ? (+ <span className="flex items-center gap-1 text-xs text-gray-400">+ <Clock size={12} />+ {nextRunText}+ </span>+ ) : null}++ <span className={`text-xs px-2 py-0.5 rounded ${+ config.type === 'daily' ? 'bg-port-accent/20 text-port-accent' :+ config.type === 'weekly' ? 'bg-purple-500/20 text-purple-400' :+ config.type === 'once' ? 'bg-port-warning/20 text-port-warning' :+ config.type === 'on-demand' ? 'bg-gray-500/20 text-gray-400' :+ 'bg-port-success/20 text-port-success'+ }`}>+ {INTERVAL_LABELS[config.type]}+ </span>+ </div>+ </div>++ {expanded && (+ <div className="p-4 border-t border-port-border bg-port-bg/50 space-y-4">+ <div className="flex items-center justify-between">+ <label className="text-sm text-gray-400">Enabled</label>+ <button+ onClick={handleToggleEnabled}+ disabled={updating}+ className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${+ config.enabled ? 'bg-port-accent' : 'bg-gray-600'+ }`}+ aria-label={config.enabled ? 'Disable task' : 'Enable task'}+ >+ <span+ className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${+ config.enabled ? 'translate-x-6' : 'translate-x-1'+ }`}+ />+ </button>+ </div>++ <div>+ <label className="text-sm text-gray-400 block mb-2">Interval Type</label>+ <select+ value={selectedType}+ onChange={(e) => handleTypeChange(e.target.value)}+ disabled={updating}+ className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-white text-sm"+ >+ <option value="rotation">Rotation (runs in task queue)</option>+ <option value="daily">Daily (once per day)</option>+ <option value="weekly">Weekly (once per week)</option>+ <option value="once">Once (run once then stop)</option>+ <option value="on-demand">On Demand (manual trigger only)</option>+ </select>+ <p className="text-xs text-gray-500 mt-1">{INTERVAL_DESCRIPTIONS[selectedType]}</p>+ </div>++ <div className="flex gap-2">+ <button+ onClick={() => onTrigger(taskType)}+ className="flex items-center gap-1 px-3 py-1.5 text-sm bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded transition-colors"+ title="Run this task immediately (bypasses schedule)"+ >+ <Play size={14} />+ Run Now+ </button>+ {(config.type === 'once' && status.reason === 'once-completed') && (+ <button+ onClick={() => onReset(taskType)}+ className="flex items-center gap-1 px-3 py-1.5 text-sm bg-port-warning/20 hover:bg-port-warning/30 text-port-warning rounded transition-colors"+ title="Reset execution history to run this task again"+ >+ <RotateCcw size={14} />+ Reset+ </button>+ )}+ </div>++ {status.completedAt && (+ <div className="text-xs text-gray-500">+ Completed: {new Date(status.completedAt).toLocaleString()}+ </div>+ )}+ </div>+ )}+ </div>+ );+}++function TaskTypeSection({ title, description, tasks, onUpdate, onTrigger, onReset, category }) {+ const [collapsed, setCollapsed] = useState(false);+ const taskEntries = Object.entries(tasks || {});++ if (taskEntries.length === 0) return null;++ const enabledCount = taskEntries.filter(([, config]) => config.enabled).length;+ const readyCount = taskEntries.filter(([, config]) => config.status?.shouldRun).length;++ return (+ <div className="space-y-3">+ <button+ onClick={() => setCollapsed(!collapsed)}+ className="flex items-center gap-2 w-full text-left"+ >+ {collapsed ? <ChevronRight size={18} /> : <ChevronDown size={18} />}+ <h3 className="text-lg font-semibold text-white">{title}</h3>+ <span className="text-xs text-gray-500">+ {enabledCount} enabled, {readyCount} ready+ </span>+ </button>+ {description && !collapsed && (+ <p className="text-sm text-gray-400 ml-6">{description}</p>+ )}+ {!collapsed && (+ <div className="space-y-2 ml-6">+ {taskEntries.map(([taskType, config]) => (+ <TaskTypeRow+ key={taskType}+ taskType={taskType}+ config={config}+ onUpdate={onUpdate}+ onTrigger={onTrigger}+ onReset={onReset}+ category={category}+ />+ ))}+ </div>+ )}+ </div>+ );+}++export default function ScheduleTab({ apps }) {+ const [schedule, setSchedule] = useState(null);+ const [loading, setLoading] = useState(true);++ const fetchSchedule = useCallback(async () => {+ const data = await api.getCosSchedule().catch(() => null);+ setSchedule(data);+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchSchedule();+ }, [fetchSchedule]);++ 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 => {+ toast.error(err.message);+ return null;+ });+ if (result?.success) {+ toast.success(`Updated ${taskType} interval`);+ fetchSchedule();+ }+ };++ const handleTriggerSelfImprovement = async (taskType) => {+ const result = await api.triggerCosOnDemandTask(taskType, 'selfImprovement').catch(err => {+ toast.error(err.message);+ return null;+ });+ if (result?.success) {+ toast.success(`Triggered ${taskType} task - 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 => {+ toast.error(err.message);+ return null;+ });+ if (result?.success) {+ toast.success(`Reset execution history for ${taskType}`);+ fetchSchedule();+ }+ };++ const handleResetAppImprovement = async (taskType, appId) => {+ const result = await api.resetCosTaskHistory(taskType, 'appImprovement', appId).catch(err => {+ toast.error(err.message);+ return null;+ });+ if (result?.success) {+ toast.success(`Reset execution history for ${taskType}`);+ fetchSchedule();+ }+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center h-64">+ <div className="text-gray-500">Loading schedule...</div>+ </div>+ );+ }++ if (!schedule) {+ return (+ <div className="text-center py-8 text-gray-500">+ <AlertCircle className="w-12 h-12 mx-auto mb-3 opacity-50" />+ <p>Failed to load task schedule</p>+ </div>+ );+ }++ return (+ <div className="space-y-8">+ <div className="flex items-center justify-between">+ <div>+ <h2 className="text-xl font-semibold text-white">Task Schedule</h2>+ <p className="text-sm text-gray-400 mt-1">+ Configure how often each task type runs. Set intervals to daily, weekly, once, or on-demand.+ </p>+ </div>+ <button+ onClick={fetchSchedule}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors"+ title="Refresh schedule"+ >+ <RefreshCw size={14} />+ Refresh+ </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()}+ </div>+ ))}+ </div>+ </div>+ )}++ <TaskTypeSection+ title="Self-Improvement Tasks"+ description="Tasks that analyze and improve PortOS itself"+ tasks={schedule.selfImprovement}+ onUpdate={handleUpdateSelfImprovement}+ onTrigger={handleTriggerSelfImprovement}+ onReset={handleResetSelfImprovement}+ category="selfImprovement"+ />++ <TaskTypeSection+ title="App Improvement Tasks"+ description="Tasks that analyze and improve managed applications"+ tasks={schedule.appImprovement}+ onUpdate={handleUpdateAppImprovement}+ onTrigger={(taskType) => {+ // For app improvement, we need to select an app first+ // For now, just trigger without app (will apply to next eligible app)+ handleTriggerAppImprovement(taskType, null);+ }}+ onReset={(taskType) => handleResetAppImprovement(taskType, null)}+ category="appImprovement"+ />++ {schedule.lastUpdated && (+ <div className="text-xs text-gray-500 text-right">+ Schedule last updated: {new Date(schedule.lastUpdated).toLocaleString()}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex ead5d531bf..88f80b134d 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -20,6 +20,7 @@ import {TasksTab,AgentsTab,ScriptsTab,+ ScheduleTab,DigestTab,MemoryTab,HealthTab,@@ -490,6 +491,11 @@ export default function ChiefOfStaff() {<ScriptsTab scripts={scripts} onRefresh={fetchData} /></div>)}+ {activeTab === 'schedule' && (+ <div role="tabpanel" id="tabpanel-schedule" aria-labelledby="tab-schedule">+ <ScheduleTab apps={apps} />+ </div>+ )}{activeTab === 'digest' && (<div role="tabpanel" id="tabpanel-digest" aria-labelledby="tab-digest"><DigestTab />diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 1066597476..3d87df1f87 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -294,6 +294,35 @@ export const generateCosDigest = (weekId = null) => request('/cos/digest/generat});export const compareCosWeeks = (week1, week2) => request(`/cos/digest/compare?week1=${week1}&week2=${week2}`);+// Task Schedule (Configurable Intervals)+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}`, {+ 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', {+ method: 'POST',+ body: JSON.stringify({ taskType, category, appId })+});+export const getCosOnDemandRequests = () => request('/cos/schedule/on-demand');+export const resetCosTaskHistory = (taskType, category = 'selfImprovement', appId = null) => request('/cos/schedule/reset', {+ method: 'POST',+ body: JSON.stringify({ taskType, category, appId })+});+export const getCosScheduleTemplates = () => request('/cos/schedule/templates');+export const addCosScheduleTemplate = (template) => request('/cos/schedule/templates', {+ method: 'POST',+ body: JSON.stringify(template)+});+export const deleteCosScheduleTemplate = (templateId) => request(`/cos/schedule/templates/${templateId}`, { method: 'DELETE' });+// Memoryexport const getMemories = (options = {}) => {const params = new URLSearchParams();diff --git a/server/routes/cos.js b/server/routes/cos.jsindex 4068c9eb94..28f8efd970 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -8,6 +8,7 @@ import * as taskWatcher from '../services/taskWatcher.js';import * as appActivity from '../services/appActivity.js';import * as taskLearning from '../services/taskLearning.js';import * as weeklyDigest from '../services/weeklyDigest.js';+import * as taskSchedule from '../services/taskSchedule.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();@@ -435,4 +436,163 @@ router.get('/digest/compare', asyncHandler(async (req, res) => {res.json(comparison);}));+// ============================================================+// Task Schedule Routes (Configurable Intervals)+// ============================================================++// GET /api/cos/schedule - Get full schedule status+router.get('/schedule', asyncHandler(async (req, res) => {+ const status = await taskSchedule.getScheduleStatus();+ res.json(status);+}));++// GET /api/cos/schedule/self-improvement/:taskType - Get interval for self-improvement task+router.get('/schedule/self-improvement/:taskType', asyncHandler(async (req, res) => {+ const { taskType } = req.params;+ const interval = await taskSchedule.getSelfImprovementInterval(taskType);+ const shouldRun = await taskSchedule.shouldRunSelfImprovementTask(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) => {+ const { taskType } = req.params;+ const { type, enabled, intervalMs } = req.body;++ const settings = {};+ if (type !== undefined) settings.type = type;+ if (enabled !== undefined) settings.enabled = enabled;+ if (intervalMs !== undefined) settings.intervalMs = intervalMs;++ const result = await taskSchedule.updateSelfImprovementInterval(taskType, settings);+ res.json({ success: true, taskType, interval: result });+}));++// GET /api/cos/schedule/app-improvement/:taskType - Get interval for app improvement task+router.get('/schedule/app-improvement/:taskType', asyncHandler(async (req, res) => {+ const { taskType } = req.params;+ const interval = await taskSchedule.getAppImprovementInterval(taskType);+ res.json({ taskType, interval });+}));++// PUT /api/cos/schedule/app-improvement/:taskType - Update interval for app improvement task+router.put('/schedule/app-improvement/:taskType', asyncHandler(async (req, res) => {+ const { taskType } = req.params;+ const { type, enabled, intervalMs } = req.body;++ const settings = {};+ if (type !== undefined) settings.type = type;+ if (enabled !== undefined) settings.enabled = enabled;+ if (intervalMs !== undefined) settings.intervalMs = intervalMs;++ const result = await taskSchedule.updateAppImprovementInterval(taskType, settings);+ res.json({ success: true, taskType, interval: result });+}));++// GET /api/cos/schedule/due - Get all tasks that are due to run+router.get('/schedule/due', asyncHandler(async (req, res) => {+ const selfImprovement = await taskSchedule.getDueSelfImprovementTasks();+ res.json({ selfImprovement, appImprovement: 'requires appId - use /schedule/due/:appId' });+}));++// GET /api/cos/schedule/due/:appId - Get app improvement tasks due for specific app+router.get('/schedule/due/:appId', asyncHandler(async (req, res) => {+ const { appId } = req.params;+ const appImprovement = await taskSchedule.getDueAppImprovementTasks(appId);+ res.json({ appId, appImprovement });+}));++// POST /api/cos/schedule/trigger - Trigger an on-demand task+router.post('/schedule/trigger', asyncHandler(async (req, res) => {+ const { taskType, category, 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);+ res.json({ success: true, request });+}));++// GET /api/cos/schedule/on-demand - Get pending on-demand requests+router.get('/schedule/on-demand', asyncHandler(async (req, res) => {+ const requests = await taskSchedule.getOnDemandRequests();+ res.json({ requests });+}));++// DELETE /api/cos/schedule/on-demand/:requestId - Clear an on-demand request+router.delete('/schedule/on-demand/:requestId', asyncHandler(async (req, res) => {+ const { requestId } = req.params;+ const cleared = await taskSchedule.clearOnDemandRequest(requestId);+ if (!cleared) {+ throw new ServerError('Request not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json({ success: true, cleared });+}));++// POST /api/cos/schedule/reset - Reset execution history for a task type+router.post('/schedule/reset', asyncHandler(async (req, res) => {+ const { taskType, category, 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);+ if (result.error) {+ throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });+ }+ res.json(result);+}));++// GET /api/cos/schedule/templates - Get all template tasks+router.get('/schedule/templates', asyncHandler(async (req, res) => {+ const templates = await taskSchedule.getTemplateTasks();+ res.json({ templates });+}));++// POST /api/cos/schedule/templates - Add a template task+router.post('/schedule/templates', asyncHandler(async (req, res) => {+ const { name, description, category, taskType, priority, metadata } = req.body;++ if (!name || !description) {+ throw new ServerError('name and description are required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ const template = await taskSchedule.addTemplateTask({+ name,+ description,+ category,+ taskType,+ priority,+ metadata+ });+ res.json({ success: true, template });+}));++// DELETE /api/cos/schedule/templates/:templateId - Delete a template task+router.delete('/schedule/templates/:templateId', asyncHandler(async (req, res) => {+ const { templateId } = req.params;+ const result = await taskSchedule.deleteTemplateTask(templateId);+ if (result.error) {+ throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });+ }+ res.json(result);+}));++// GET /api/cos/schedule/interval-types - Get available interval types+router.get('/schedule/interval-types', (req, res) => {+ res.json({+ types: taskSchedule.INTERVAL_TYPES,+ descriptions: {+ rotation: 'Runs as part of normal task rotation (default)',+ daily: 'Runs once per day',+ weekly: 'Runs once per week',+ once: 'Runs once per app or globally, then stops',+ 'on-demand': 'Only runs when manually triggered',+ custom: 'Custom interval in milliseconds'+ }+ });+});+export default router;diff --git a/server/services/cos.js b/server/services/cos.jsindex a407fb25b8..c0adb49ff3 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -746,70 +746,96 @@ const MANAGED_APP_IMPROVEMENT_TYPES = [* Generate a self-improvement task for PortOS itself* Uses Playwright and Opus to analyze and fix issues*- * Enhanced with adaptive learning:+ * Enhanced with adaptive learning and configurable intervals:+ * - Respects per-task-type interval settings (daily, weekly, once, etc.)* - Skips task types with consistently poor success rates* - Logs learning-based recommendations* - Falls back to next available task type if current is skipped+ * - Checks for on-demand task requests first*/async function generateSelfImprovementTask(state) {- // Get the next analysis type in rotation, but skip failing task types- const lastType = state.stats.lastSelfImprovementType || '';- let currentIndex = SELF_IMPROVEMENT_TYPES.indexOf(lastType);- let nextType = null;- let attempts = 0;- const maxAttempts = SELF_IMPROVEMENT_TYPES.length;-- // Find next task type that isn't being skipped due to poor performance- while (attempts < maxAttempts) {- currentIndex = (currentIndex + 1) % SELF_IMPROVEMENT_TYPES.length;- const candidateType = SELF_IMPROVEMENT_TYPES[currentIndex];- const taskTypeKey = `self-improve:${candidateType}`;-- // Check if this task type should be skipped based on learning data- const cooldownInfo = await getAdaptiveCooldownMultiplier(taskTypeKey).catch(() => ({ skip: false }));-- if (cooldownInfo.skip) {- emitLog('warn', `Skipping ${candidateType} - poor success rate (${cooldownInfo.successRate}% after ${cooldownInfo.completed} attempts)`, {- taskType: candidateType,- successRate: cooldownInfo.successRate,- completed: cooldownInfo.completed,- reason: cooldownInfo.reason- });- attempts++;- continue;- }+ // Import task schedule service dynamically to avoid circular dependency+ const taskSchedule = await import('./taskSchedule.js');++ // First, check for any on-demand task requests+ const onDemandRequests = await taskSchedule.getOnDemandRequests();+ const selfImprovementRequests = onDemandRequests.filter(r => r.category === 'selfImprovement');++ if (selfImprovementRequests.length > 0) {+ const request = selfImprovementRequests[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}`);++ // Update state+ await withStateLock(async () => {+ const s = await loadState();+ s.stats.lastSelfImprovement = new Date().toISOString();+ s.stats.lastSelfImprovementType = request.taskType;+ await saveState(s);+ });- // Log if there's a recommendation from learning system- if (cooldownInfo.recommendation) {- emitLog('info', `Learning insight for ${candidateType}: ${cooldownInfo.recommendation}`, {- taskType: candidateType,- multiplier: cooldownInfo.multiplier- });- }+ return generateSelfImprovementTaskForType(request.taskType, state);+ }++ // Use the schedule service to determine the next task type+ const lastType = state.stats.lastSelfImprovementType || '';+ const nextTypeResult = await taskSchedule.getNextSelfImprovementTaskType(lastType);- nextType = candidateType;- break;+ if (!nextTypeResult) {+ emitLog('info', 'No self-improvement tasks are eligible to run based on schedule');+ return null;}- // If all task types are failing, log warning and pick the one that's been failing longest- if (!nextType) {- const skippedTypes = await getSkippedTaskTypes().catch(() => []);- emitLog('warn', `All self-improvement task types are underperforming - selecting oldest failed type for retry`, {- skippedCount: skippedTypes.length+ let nextType = nextTypeResult.taskType;+ const selectionReason = nextTypeResult.reason;++ // Additional check: skip if learning data suggests poor performance+ const taskTypeKey = `self-improve:${nextType}`;+ const cooldownInfo = await getAdaptiveCooldownMultiplier(taskTypeKey).catch(() => ({ skip: false }));++ if (cooldownInfo.skip) {+ emitLog('warn', `Skipping ${nextType} - poor success rate (${cooldownInfo.successRate}% after ${cooldownInfo.completed} attempts)`, {+ taskType: nextType,+ successRate: cooldownInfo.successRate,+ completed: cooldownInfo.completed,+ reason: cooldownInfo.reason});- // Sort by lastCompleted ascending (oldest first) and pick that one- 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:', '');- nextType = oldestType;- emitLog('info', `Retrying ${oldestType} as it hasn't been attempted recently`);+ // Try to find another eligible task type+ const dueTasks = await taskSchedule.getDueSelfImprovementTasks();+ const alternativeTask = dueTasks.find(t => t.taskType !== nextType);++ if (alternativeTask) {+ nextType = alternativeTask.taskType;+ emitLog('info', `Switched to alternative task type: ${nextType}`);} else {- // Fallback to first type in rotation- nextType = SELF_IMPROVEMENT_TYPES[0];+ // Fall back to the skipped types logic+ const skippedTypes = await getSkippedTaskTypes().catch(() => []);+ if (skippedTypes.length > 0) {+ skippedTypes.sort((a, b) => new Date(a.lastCompleted || 0) - new Date(b.lastCompleted || 0));+ const oldestType = skippedTypes[0].taskType.replace('self-improve:', '');+ nextType = oldestType;+ emitLog('info', `Retrying ${oldestType} as it hasn't been attempted recently`);+ } else {+ nextType = SELF_IMPROVEMENT_TYPES[0];+ }}}+ // Log if there's a recommendation from learning system+ if (cooldownInfo.recommendation) {+ emitLog('info', `Learning insight for ${nextType}: ${cooldownInfo.recommendation}`, {+ taskType: nextType,+ multiplier: cooldownInfo.multiplier+ });+ }++ // Record execution in the schedule service+ await taskSchedule.recordExecution(`self-improve:${nextType}`);+// Update state with new timestamp and typeawait withStateLock(async () => {const s = await loadState();@@ -818,9 +844,48 @@ async function generateSelfImprovementTask(state) {await saveState(s);});- emitLog('info', `Generating self-improvement task: ${nextType}`);+ emitLog('info', `Generating self-improvement task: ${nextType} (${selectionReason})`);- const taskDescriptions = {+ // Get task descriptions from the centralized helper function+ const taskDescriptions = getSelfImprovementTaskDescriptions();++ return generateSelfImprovementTaskForType(nextType, state, taskDescriptions);+}++/**+ * Helper function to generate a self-improvement task for a specific type+ * Used by both normal rotation and on-demand task requests+ */+function generateSelfImprovementTaskForType(taskType, state, taskDescriptions = null) {+ // Use provided descriptions or generate default ones+ const descriptions = taskDescriptions || getSelfImprovementTaskDescriptions();+ const description = descriptions[taskType] || `[Self-Improvement] ${taskType} analysis`;++ const task = {+ id: `self-improve-${taskType}-${Date.now().toString(36)}`,+ status: 'pending',+ priority: 'MEDIUM',+ priorityValue: PRIORITY_VALUES['MEDIUM'],+ description,+ metadata: {+ analysisType: taskType,+ autoGenerated: true,+ selfImprovement: true,+ model: 'claude-opus-4-5-20251101'+ },+ taskType: 'internal',+ autoApproved: true+ };++ return task;+}++/**+ * Get task descriptions for all self-improvement types+ * Extracted for reuse by on-demand task generation+ */+function getSelfImprovementTaskDescriptions() {+ return {'ui-bugs': `[Self-Improvement] UI Bug AnalysisUse Playwright MCP (browser_navigate, browser_snapshot, browser_console_messages) to analyze PortOS UI:@@ -1109,54 +1174,66 @@ IMPORTANT: Only update one major version bump at a time. If multiple major updatUse model: claude-opus-4-5-20251101 for thorough security analysis`};-- const description = taskDescriptions[nextType];-- const task = {- id: `self-improve-${nextType}-${Date.now().toString(36)}`,- status: 'pending',- priority: 'MEDIUM',- priorityValue: PRIORITY_VALUES['MEDIUM'],- description,- metadata: {- analysisType: nextType,- autoGenerated: true,- selfImprovement: true,- model: 'claude-opus-4-5-20251101'- },- taskType: 'internal',- autoApproved: true- };-- return task;}/*** Generate a comprehensive self-improvement task for a managed app* Rotates through analysis types similar to PortOS self-improvement*+ * Enhanced with configurable intervals:+ * - Respects per-task-type interval settings (daily, weekly, once per app, etc.)+ * - Checks for on-demand task requests first+ * - Records execution history for interval tracking+ ** @param {Object} app - The managed app object* @param {Object} state - Current CoS state* @returns {Object} Generated task*/async function generateManagedAppImprovementTask(app, state) {const { getAppActivityById, updateAppActivity } = await import('./appActivity.js');+ const taskSchedule = await import('./taskSchedule.js');++ // First, check for any on-demand task requests for this app+ const onDemandRequests = await taskSchedule.getOnDemandRequests();+ const appRequests = onDemandRequests.filter(r =>+ r.category === 'appImprovement' && r.appId === app.id+ );++ let nextType;+ let selectionReason = 'rotation';++ if (appRequests.length > 0) {+ const request = appRequests[0];+ await taskSchedule.clearOnDemandRequest(request.id);+ nextType = request.taskType;+ selectionReason = 'on-demand';+ emitLog('info', `Processing on-demand app task request: ${nextType} for ${app.name}`, { requestId: request.id });+ } else {+ // Get last improvement type for this app+ const appActivity = await getAppActivityById(app.id);+ const lastType = appActivity?.lastImprovementType || '';++ // Use the schedule service to determine the next task type+ const nextTypeResult = await taskSchedule.getNextAppImprovementTaskType(app.id, lastType);++ if (!nextTypeResult) {+ emitLog('info', `No app improvement tasks are eligible for ${app.name} based on schedule`);+ return null;+ }- // Get last improvement type for this app- const appActivity = await getAppActivityById(app.id);- const lastType = appActivity?.lastImprovementType || '';+ nextType = nextTypeResult.taskType;+ selectionReason = nextTypeResult.reason;+ }- // Find next type in rotation- let currentIndex = MANAGED_APP_IMPROVEMENT_TYPES.indexOf(lastType);- currentIndex = (currentIndex + 1) % MANAGED_APP_IMPROVEMENT_TYPES.length;- const nextType = MANAGED_APP_IMPROVEMENT_TYPES[currentIndex];+ // Record execution in the schedule service+ await taskSchedule.recordExecution(`app-improve:${nextType}`, app.id);// Update app activity with new typeawait updateAppActivity(app.id, {lastImprovementType: nextType});- emitLog('info', `Generating comprehensive improvement task for ${app.name}: ${nextType}`, { appId: app.id, analysisType: nextType });+ emitLog('info', `Generating comprehensive improvement task for ${app.name}: ${nextType} (${selectionReason})`, { appId: app.id, analysisType: nextType });// Task descriptions for each analysis typeconst taskDescriptions = {diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsnew file mode 100644index 0000000000..2790f8aabc--- /dev/null+++ b/server/services/taskSchedule.js@@ -0,0 +1,679 @@+/**+ * Task Schedule Service+ *+ * 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+ *+ * Interval types:+ * - 'rotation': Run as part of normal rotation (default)+ * - 'daily': Run once per day+ * - 'weekly': Run once per week+ * - 'once': Run once per app/globally then stop+ * - 'on-demand': Only run when manually triggered+ * - 'custom': Custom interval in milliseconds+ */++import { readFile, writeFile, mkdir } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { cosEvents, emitLog } from './cos.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const DATA_DIR = join(__dirname, '../../data/cos');+const SCHEDULE_FILE = join(DATA_DIR, 'task-schedule.json');++// Interval type constants+export const INTERVAL_TYPES = {+ ROTATION: 'rotation', // Default: runs in normal task rotation+ DAILY: 'daily', // Runs once per day+ WEEKLY: 'weekly', // Runs once per week+ ONCE: 'once', // Runs once per app or globally+ ON_DEMAND: 'on-demand', // Only runs when manually triggered+ CUSTOM: 'custom' // Custom interval in milliseconds+};++// Time constants in milliseconds+const HOUR = 60 * 60 * 1000;+const DAY = 24 * HOUR;+const WEEK = 7 * DAY;++// Default interval settings for self-improvement task types+const DEFAULT_SELF_IMPROVEMENT_INTERVALS = {+ 'ui-bugs': { type: INTERVAL_TYPES.ROTATION, enabled: true },+ 'mobile-responsive': { type: INTERVAL_TYPES.WEEKLY, enabled: true },+ 'security': { type: INTERVAL_TYPES.WEEKLY, enabled: true },+ 'code-quality': { type: INTERVAL_TYPES.ROTATION, enabled: true },+ 'console-errors': { type: INTERVAL_TYPES.ROTATION, enabled: true },+ 'performance': { type: INTERVAL_TYPES.WEEKLY, enabled: true },+ 'cos-enhancement': { type: INTERVAL_TYPES.ROTATION, enabled: true },+ 'test-coverage': { type: INTERVAL_TYPES.WEEKLY, enabled: true },+ 'documentation': { type: INTERVAL_TYPES.WEEKLY, enabled: true },+ 'feature-ideas': { type: INTERVAL_TYPES.DAILY, enabled: true },+ 'accessibility': { type: INTERVAL_TYPES.WEEKLY, enabled: true },+ 'dependency-updates': { type: INTERVAL_TYPES.WEEKLY, enabled: true }+};++// Default interval settings for managed app improvement task types+const DEFAULT_APP_IMPROVEMENT_INTERVALS = {+ 'security-audit': { type: INTERVAL_TYPES.WEEKLY, enabled: true },+ 'code-quality': { type: INTERVAL_TYPES.ROTATION, enabled: true },+ 'test-coverage': { type: INTERVAL_TYPES.WEEKLY, enabled: true },+ 'performance': { type: INTERVAL_TYPES.WEEKLY, enabled: true },+ 'accessibility': { type: INTERVAL_TYPES.ONCE, enabled: true },+ 'console-errors': { type: INTERVAL_TYPES.ROTATION, enabled: true },+ 'dependency-updates': { type: INTERVAL_TYPES.WEEKLY, enabled: true },+ 'documentation': { type: INTERVAL_TYPES.ONCE, enabled: true },+ 'error-handling': { type: INTERVAL_TYPES.ROTATION, enabled: true },+ 'typing': { type: INTERVAL_TYPES.ONCE, enabled: true }+};++/**+ * Default schedule data structure+ */+const DEFAULT_SCHEDULE = {+ version: 1,+ lastUpdated: null,++ // Self-improvement task intervals (for PortOS)+ selfImprovement: {+ ...DEFAULT_SELF_IMPROVEMENT_INTERVALS+ },++ // Managed app task intervals+ appImprovement: {+ ...DEFAULT_APP_IMPROVEMENT_INTERVALS+ },++ // Track last execution times+ executions: {+ // Format: 'self-improve:ui-bugs': { lastRun: timestamp, count: number, perApp: {} }+ },++ // On-demand task templates that can be triggered manually+ templates: []+};++/**+ * Ensure data directory exists+ */+async function ensureDir() {+ if (!existsSync(DATA_DIR)) {+ await mkdir(DATA_DIR, { recursive: true });+ }+}++/**+ * Load schedule data+ */+export async function loadSchedule() {+ await ensureDir();++ if (!existsSync(SCHEDULE_FILE)) {+ return { ...DEFAULT_SCHEDULE };+ }++ const content = await readFile(SCHEDULE_FILE, 'utf-8');+ const loaded = JSON.parse(content);++ // Merge with defaults to ensure all task types have settings+ return {+ ...DEFAULT_SCHEDULE,+ ...loaded,+ selfImprovement: {+ ...DEFAULT_SELF_IMPROVEMENT_INTERVALS,+ ...loaded.selfImprovement+ },+ appImprovement: {+ ...DEFAULT_APP_IMPROVEMENT_INTERVALS,+ ...loaded.appImprovement+ },+ executions: loaded.executions || {},+ templates: loaded.templates || []+ };+}++/**+ * 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 };+}++/**+ * 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 };+}++/**+ * Update self-improvement interval for a task type+ */+export async function updateSelfImprovementInterval(taskType, settings) {+ const schedule = await loadSchedule();++ if (!schedule.selfImprovement[taskType]) {+ schedule.selfImprovement[taskType] = { type: INTERVAL_TYPES.ROTATION, enabled: true };+ }++ 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];+}++/**+ * Update app improvement interval for a task type+ */+export async function updateAppImprovementInterval(taskType, settings) {+ const schedule = await loadSchedule();++ if (!schedule.appImprovement[taskType]) {+ schedule.appImprovement[taskType] = { type: INTERVAL_TYPES.ROTATION, enabled: true };+ }++ schedule.appImprovement[taskType] = {+ ...schedule.appImprovement[taskType],+ ...settings+ };++ await saveSchedule(schedule);+ emitLog('info', `Updated app improvement interval for ${taskType}`, { taskType, settings }, '[TaskSchedule]');+ cosEvents.emit('schedule:changed', { category: 'appImprovement', taskType, settings });++ return schedule.appImprovement[taskType];+}++/**+ * Record a task execution+ */+export async function recordExecution(taskType, appId = null) {+ const schedule = await loadSchedule();+ const key = taskType;++ if (!schedule.executions[key]) {+ schedule.executions[key] = {+ lastRun: null,+ count: 0,+ perApp: {}+ };+ }++ schedule.executions[key].lastRun = new Date().toISOString();+ schedule.executions[key].count = (schedule.executions[key].count || 0) + 1;++ if (appId) {+ if (!schedule.executions[key].perApp[appId]) {+ schedule.executions[key].perApp[appId] = {+ lastRun: null,+ count: 0+ };+ }+ schedule.executions[key].perApp[appId].lastRun = new Date().toISOString();+ schedule.executions[key].perApp[appId].count++;+ }++ await saveSchedule(schedule);+ 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: {} };+}++/**+ * Check if a self-improvement task type should run based on its interval+ */+export async function shouldRunSelfImprovementTask(taskType) {+ const schedule = await loadSchedule();+ const interval = schedule.selfImprovement[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;++ switch (interval.type) {+ case INTERVAL_TYPES.ROTATION:+ // Always eligible in rotation+ return { shouldRun: true, reason: 'rotation' };++ case INTERVAL_TYPES.DAILY:+ if (timeSinceLastRun >= DAY) {+ return { shouldRun: true, reason: 'daily-due' };+ }+ return {+ shouldRun: false,+ reason: 'daily-cooldown',+ nextRunIn: DAY - timeSinceLastRun,+ nextRunAt: new Date(lastRun + DAY).toISOString()+ };++ case INTERVAL_TYPES.WEEKLY:+ if (timeSinceLastRun >= WEEK) {+ return { shouldRun: true, reason: 'weekly-due' };+ }+ return {+ shouldRun: false,+ reason: 'weekly-cooldown',+ nextRunIn: WEEK - timeSinceLastRun,+ nextRunAt: new Date(lastRun + WEEK).toISOString()+ };++ 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 customInterval = interval.intervalMs || DAY;+ if (timeSinceLastRun >= customInterval) {+ return { shouldRun: true, reason: 'custom-due' };+ }+ return {+ shouldRun: false,+ reason: 'custom-cooldown',+ nextRunIn: customInterval - timeSinceLastRun,+ nextRunAt: new Date(lastRun + customInterval).toISOString()+ };++ default:+ return { shouldRun: true, reason: 'unknown-default-rotation' };+ }+}++/**+ * Check if an app improvement task type should run for a specific app+ */+export async function shouldRunAppImprovementTask(taskType, appId) {+ const schedule = await loadSchedule();+ const interval = schedule.appImprovement[taskType];++ if (!interval || !interval.enabled) {+ return { shouldRun: false, reason: 'disabled' };+ }++ const key = `app-improve:${taskType}`;+ const execution = schedule.executions[key] || { lastRun: null, count: 0, perApp: {} };+ const appExecution = execution.perApp[appId] || { lastRun: null, count: 0 };+ const now = Date.now();+ const lastRun = appExecution.lastRun ? new Date(appExecution.lastRun).getTime() : 0;+ const timeSinceLastRun = now - lastRun;++ switch (interval.type) {+ case INTERVAL_TYPES.ROTATION:+ return { shouldRun: true, reason: 'rotation' };++ case INTERVAL_TYPES.DAILY:+ if (timeSinceLastRun >= DAY) {+ return { shouldRun: true, reason: 'daily-due' };+ }+ return {+ shouldRun: false,+ reason: 'daily-cooldown',+ nextRunIn: DAY - timeSinceLastRun,+ nextRunAt: new Date(lastRun + DAY).toISOString()+ };++ case INTERVAL_TYPES.WEEKLY:+ if (timeSinceLastRun >= WEEK) {+ return { shouldRun: true, reason: 'weekly-due' };+ }+ return {+ shouldRun: false,+ reason: 'weekly-cooldown',+ nextRunIn: WEEK - timeSinceLastRun,+ nextRunAt: new Date(lastRun + WEEK).toISOString()+ };++ case INTERVAL_TYPES.ONCE:+ if (appExecution.count === 0) {+ return { shouldRun: true, reason: 'once-first-run' };+ }+ return { shouldRun: false, reason: 'once-completed', completedAt: appExecution.lastRun };++ case INTERVAL_TYPES.ON_DEMAND:+ return { shouldRun: false, reason: 'on-demand-only' };++ case INTERVAL_TYPES.CUSTOM:+ const customInterval = interval.intervalMs || DAY;+ if (timeSinceLastRun >= customInterval) {+ return { shouldRun: true, reason: 'custom-due' };+ }+ return {+ shouldRun: false,+ reason: 'custom-cooldown',+ nextRunIn: customInterval - timeSinceLastRun,+ nextRunAt: new Date(lastRun + customInterval).toISOString()+ };++ default:+ return { shouldRun: true, reason: 'unknown-default-rotation' };+ }+}++/**+ * 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+ */+export async function getDueAppImprovementTasks(appId) {+ const schedule = await loadSchedule();+ const due = [];++ for (const [taskType, interval] of Object.entries(schedule.appImprovement)) {+ if (!interval.enabled) continue;++ const check = await shouldRunAppImprovementTask(taskType, appId);+ if (check.shouldRun) {+ due.push({ taskType, reason: check.reason, interval });+ }+ }++ return due;+}++/**+ * 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+ */+export async function getNextAppImprovementTaskType(appId, lastType) {+ const schedule = await loadSchedule();+ const taskTypes = Object.keys(schedule.appImprovement);++ // First, check for daily/weekly tasks that are due+ const dueTasks = await getDueAppImprovementTasks(appId);++ // Prioritize daily tasks first, then weekly, then once+ 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' };+ }++ const onceDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.ONCE);+ if (onceDue.length > 0) {+ return { taskType: onceDue[0].taskType, reason: 'once-first-run' };+ }++ // Fall back to rotation+ const rotationTasks = taskTypes.filter(t =>+ schedule.appImprovement[t].enabled &&+ schedule.appImprovement[t].type === INTERVAL_TYPES.ROTATION+ );++ if (rotationTasks.length === 0) {+ return null;+ }++ const currentIndex = rotationTasks.indexOf(lastType);+ const nextIndex = (currentIndex + 1) % rotationTasks.length;++ return { taskType: rotationTasks[nextIndex], reason: 'rotation' };+}++/**+ * Add a template task that can be triggered on-demand+ */+export async function addTemplateTask(template) {+ const schedule = await loadSchedule();++ const newTemplate = {+ id: `template-${Date.now().toString(36)}`,+ createdAt: new Date().toISOString(),+ name: template.name,+ description: template.description,+ category: template.category || 'custom', // 'selfImprovement', 'appImprovement', 'custom'+ taskType: template.taskType,+ priority: template.priority || 'MEDIUM',+ metadata: template.metadata || {}+ };++ schedule.templates.push(newTemplate);+ await saveSchedule(schedule);++ emitLog('info', `Added template task: ${newTemplate.name}`, { templateId: newTemplate.id }, '[TaskSchedule]');+ 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);++ if (index === -1) {+ return { error: 'Template not found' };+ }++ const deleted = schedule.templates.splice(index, 1)[0];+ await saveSchedule(schedule);++ emitLog('info', `Deleted template task: ${deleted.name}`, { templateId }, '[TaskSchedule]');+ 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+ const schedule = await loadSchedule();++ if (!schedule.onDemandRequests) {+ schedule.onDemandRequests = [];+ }++ const request = {+ id: `demand-${Date.now().toString(36)}`,+ taskType,+ category,+ appId,+ requestedAt: new Date().toISOString()+ };++ schedule.onDemandRequests.push(request);+ await saveSchedule(schedule);++ emitLog('info', `On-demand task requested: ${taskType}`, { category, 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();++ if (!schedule.onDemandRequests) return null;++ const index = schedule.onDemandRequests.findIndex(r => r.id === requestId);+ if (index === -1) return null;++ const cleared = schedule.onDemandRequests.splice(index, 1)[0];+ await saveSchedule(schedule);++ return cleared;+}++/**+ * Get full schedule status for UI display+ */+export async function getScheduleStatus() {+ const schedule = await loadSchedule();+ const status = {+ lastUpdated: schedule.lastUpdated,+ selfImprovement: {},+ appImprovement: {},+ templates: schedule.templates,+ onDemandRequests: schedule.onDemandRequests || []+ };++ // 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 };++ status.selfImprovement[taskType] = {+ ...interval,+ lastRun: execution.lastRun,+ runCount: execution.count,+ status: check+ };+ }++ // Add execution status to each app improvement task type+ for (const [taskType, interval] of Object.entries(schedule.appImprovement)) {+ const execution = schedule.executions[`app-improve:${taskType}`] || { lastRun: null, count: 0, perApp: {} };++ status.appImprovement[taskType] = {+ ...interval,+ globalLastRun: execution.lastRun,+ globalRunCount: execution.count,+ perAppCount: Object.keys(execution.perApp).length+ };+ }++ return status;+}++/**+ * Reset execution history for a task type (useful for re-running 'once' tasks)+ */+export async function resetExecutionHistory(taskType, category = 'selfImprovement', appId = null) {+ const schedule = await loadSchedule();+ const key = category === 'selfImprovement' ? `self-improve:${taskType}` : `app-improve:${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]) {+ delete schedule.executions[key].perApp[appId];+ }+ } else {+ // Reset entire history for this task type+ delete schedule.executions[key];+ }++ await saveSchedule(schedule);+ emitLog('info', `Reset execution history for ${taskType}`, { category, appId }, '[TaskSchedule]');++ return { success: true, taskType, appId };+}